Andrew Scull | 5e1ddfa | 2018-08-14 10:06:54 +0100 | [diff] [blame^] | 1 | //===- CompileOnDemandLayer.h - Compile each function on demand -*- C++ -*-===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // JIT layer for breaking up modules and inserting callbacks to allow |
| 11 | // individual functions to be compiled on demand. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
| 15 | #ifndef LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H |
| 16 | #define LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H |
| 17 | |
| 18 | #include "llvm/ADT/APInt.h" |
| 19 | #include "llvm/ADT/STLExtras.h" |
| 20 | #include "llvm/ADT/StringRef.h" |
| 21 | #include "llvm/ADT/Twine.h" |
| 22 | #include "llvm/ExecutionEngine/JITSymbol.h" |
| 23 | #include "llvm/ExecutionEngine/Orc/Core.h" |
| 24 | #include "llvm/ExecutionEngine/Orc/IndirectionUtils.h" |
| 25 | #include "llvm/ExecutionEngine/Orc/LambdaResolver.h" |
| 26 | #include "llvm/ExecutionEngine/Orc/OrcError.h" |
| 27 | #include "llvm/ExecutionEngine/RuntimeDyld.h" |
| 28 | #include "llvm/IR/Attributes.h" |
| 29 | #include "llvm/IR/Constant.h" |
| 30 | #include "llvm/IR/Constants.h" |
| 31 | #include "llvm/IR/DataLayout.h" |
| 32 | #include "llvm/IR/Function.h" |
| 33 | #include "llvm/IR/GlobalAlias.h" |
| 34 | #include "llvm/IR/GlobalValue.h" |
| 35 | #include "llvm/IR/GlobalVariable.h" |
| 36 | #include "llvm/IR/Instruction.h" |
| 37 | #include "llvm/IR/Mangler.h" |
| 38 | #include "llvm/IR/Module.h" |
| 39 | #include "llvm/IR/Type.h" |
| 40 | #include "llvm/Support/Casting.h" |
| 41 | #include "llvm/Support/raw_ostream.h" |
| 42 | #include "llvm/Transforms/Utils/ValueMapper.h" |
| 43 | #include <algorithm> |
| 44 | #include <cassert> |
| 45 | #include <functional> |
| 46 | #include <iterator> |
| 47 | #include <list> |
| 48 | #include <memory> |
| 49 | #include <set> |
| 50 | #include <string> |
| 51 | #include <utility> |
| 52 | #include <vector> |
| 53 | |
| 54 | namespace llvm { |
| 55 | |
| 56 | class Value; |
| 57 | |
| 58 | namespace orc { |
| 59 | |
| 60 | /// @brief Compile-on-demand layer. |
| 61 | /// |
| 62 | /// When a module is added to this layer a stub is created for each of its |
| 63 | /// function definitions. The stubs and other global values are immediately |
| 64 | /// added to the layer below. When a stub is called it triggers the extraction |
| 65 | /// of the function body from the original module. The extracted body is then |
| 66 | /// compiled and executed. |
| 67 | template <typename BaseLayerT, |
| 68 | typename CompileCallbackMgrT = JITCompileCallbackManager, |
| 69 | typename IndirectStubsMgrT = IndirectStubsManager> |
| 70 | class CompileOnDemandLayer { |
| 71 | private: |
| 72 | template <typename MaterializerFtor> |
| 73 | class LambdaMaterializer final : public ValueMaterializer { |
| 74 | public: |
| 75 | LambdaMaterializer(MaterializerFtor M) : M(std::move(M)) {} |
| 76 | |
| 77 | Value *materialize(Value *V) final { return M(V); } |
| 78 | |
| 79 | private: |
| 80 | MaterializerFtor M; |
| 81 | }; |
| 82 | |
| 83 | template <typename MaterializerFtor> |
| 84 | LambdaMaterializer<MaterializerFtor> |
| 85 | createLambdaMaterializer(MaterializerFtor M) { |
| 86 | return LambdaMaterializer<MaterializerFtor>(std::move(M)); |
| 87 | } |
| 88 | |
| 89 | // Provide type-erasure for the Modules and MemoryManagers. |
| 90 | template <typename ResourceT> |
| 91 | class ResourceOwner { |
| 92 | public: |
| 93 | ResourceOwner() = default; |
| 94 | ResourceOwner(const ResourceOwner &) = delete; |
| 95 | ResourceOwner &operator=(const ResourceOwner &) = delete; |
| 96 | virtual ~ResourceOwner() = default; |
| 97 | |
| 98 | virtual ResourceT& getResource() const = 0; |
| 99 | }; |
| 100 | |
| 101 | template <typename ResourceT, typename ResourcePtrT> |
| 102 | class ResourceOwnerImpl : public ResourceOwner<ResourceT> { |
| 103 | public: |
| 104 | ResourceOwnerImpl(ResourcePtrT ResourcePtr) |
| 105 | : ResourcePtr(std::move(ResourcePtr)) {} |
| 106 | |
| 107 | ResourceT& getResource() const override { return *ResourcePtr; } |
| 108 | |
| 109 | private: |
| 110 | ResourcePtrT ResourcePtr; |
| 111 | }; |
| 112 | |
| 113 | template <typename ResourceT, typename ResourcePtrT> |
| 114 | std::unique_ptr<ResourceOwner<ResourceT>> |
| 115 | wrapOwnership(ResourcePtrT ResourcePtr) { |
| 116 | using RO = ResourceOwnerImpl<ResourceT, ResourcePtrT>; |
| 117 | return llvm::make_unique<RO>(std::move(ResourcePtr)); |
| 118 | } |
| 119 | |
| 120 | class StaticGlobalRenamer { |
| 121 | public: |
| 122 | StaticGlobalRenamer() = default; |
| 123 | StaticGlobalRenamer(StaticGlobalRenamer &&) = default; |
| 124 | StaticGlobalRenamer &operator=(StaticGlobalRenamer &&) = default; |
| 125 | |
| 126 | void rename(Module &M) { |
| 127 | for (auto &F : M) |
| 128 | if (F.hasLocalLinkage()) |
| 129 | F.setName("$static." + Twine(NextId++)); |
| 130 | for (auto &G : M.globals()) |
| 131 | if (G.hasLocalLinkage()) |
| 132 | G.setName("$static." + Twine(NextId++)); |
| 133 | } |
| 134 | |
| 135 | private: |
| 136 | unsigned NextId = 0; |
| 137 | }; |
| 138 | |
| 139 | struct LogicalDylib { |
| 140 | struct SourceModuleEntry { |
| 141 | std::unique_ptr<Module> SourceMod; |
| 142 | std::set<Function*> StubsToClone; |
| 143 | }; |
| 144 | |
| 145 | using SourceModulesList = std::vector<SourceModuleEntry>; |
| 146 | using SourceModuleHandle = typename SourceModulesList::size_type; |
| 147 | |
| 148 | LogicalDylib() = default; |
| 149 | |
| 150 | LogicalDylib(VModuleKey K, std::shared_ptr<SymbolResolver> BackingResolver, |
| 151 | std::unique_ptr<IndirectStubsMgrT> StubsMgr) |
| 152 | : K(std::move(K)), BackingResolver(std::move(BackingResolver)), |
| 153 | StubsMgr(std::move(StubsMgr)) {} |
| 154 | |
| 155 | SourceModuleHandle addSourceModule(std::unique_ptr<Module> M) { |
| 156 | SourceModuleHandle H = SourceModules.size(); |
| 157 | SourceModules.push_back(SourceModuleEntry()); |
| 158 | SourceModules.back().SourceMod = std::move(M); |
| 159 | return H; |
| 160 | } |
| 161 | |
| 162 | Module& getSourceModule(SourceModuleHandle H) { |
| 163 | return *SourceModules[H].SourceMod; |
| 164 | } |
| 165 | |
| 166 | std::set<Function*>& getStubsToClone(SourceModuleHandle H) { |
| 167 | return SourceModules[H].StubsToClone; |
| 168 | } |
| 169 | |
| 170 | JITSymbol findSymbol(BaseLayerT &BaseLayer, const std::string &Name, |
| 171 | bool ExportedSymbolsOnly) { |
| 172 | if (auto Sym = StubsMgr->findStub(Name, ExportedSymbolsOnly)) |
| 173 | return Sym; |
| 174 | for (auto BLK : BaseLayerVModuleKeys) |
| 175 | if (auto Sym = BaseLayer.findSymbolIn(BLK, Name, ExportedSymbolsOnly)) |
| 176 | return Sym; |
| 177 | else if (auto Err = Sym.takeError()) |
| 178 | return std::move(Err); |
| 179 | return nullptr; |
| 180 | } |
| 181 | |
| 182 | Error removeModulesFromBaseLayer(BaseLayerT &BaseLayer) { |
| 183 | for (auto &BLK : BaseLayerVModuleKeys) |
| 184 | if (auto Err = BaseLayer.removeModule(BLK)) |
| 185 | return Err; |
| 186 | return Error::success(); |
| 187 | } |
| 188 | |
| 189 | VModuleKey K; |
| 190 | std::shared_ptr<SymbolResolver> BackingResolver; |
| 191 | std::unique_ptr<IndirectStubsMgrT> StubsMgr; |
| 192 | StaticGlobalRenamer StaticRenamer; |
| 193 | SourceModulesList SourceModules; |
| 194 | std::vector<VModuleKey> BaseLayerVModuleKeys; |
| 195 | }; |
| 196 | |
| 197 | public: |
| 198 | |
| 199 | /// @brief Module partitioning functor. |
| 200 | using PartitioningFtor = std::function<std::set<Function*>(Function&)>; |
| 201 | |
| 202 | /// @brief Builder for IndirectStubsManagers. |
| 203 | using IndirectStubsManagerBuilderT = |
| 204 | std::function<std::unique_ptr<IndirectStubsMgrT>()>; |
| 205 | |
| 206 | using SymbolResolverGetter = |
| 207 | std::function<std::shared_ptr<SymbolResolver>(VModuleKey K)>; |
| 208 | |
| 209 | using SymbolResolverSetter = |
| 210 | std::function<void(VModuleKey K, std::shared_ptr<SymbolResolver> R)>; |
| 211 | |
| 212 | /// @brief Construct a compile-on-demand layer instance. |
| 213 | CompileOnDemandLayer(ExecutionSession &ES, BaseLayerT &BaseLayer, |
| 214 | SymbolResolverGetter GetSymbolResolver, |
| 215 | SymbolResolverSetter SetSymbolResolver, |
| 216 | PartitioningFtor Partition, |
| 217 | CompileCallbackMgrT &CallbackMgr, |
| 218 | IndirectStubsManagerBuilderT CreateIndirectStubsManager, |
| 219 | bool CloneStubsIntoPartitions = true) |
| 220 | : ES(ES), BaseLayer(BaseLayer), |
| 221 | GetSymbolResolver(std::move(GetSymbolResolver)), |
| 222 | SetSymbolResolver(std::move(SetSymbolResolver)), |
| 223 | Partition(std::move(Partition)), CompileCallbackMgr(CallbackMgr), |
| 224 | CreateIndirectStubsManager(std::move(CreateIndirectStubsManager)), |
| 225 | CloneStubsIntoPartitions(CloneStubsIntoPartitions) {} |
| 226 | |
| 227 | ~CompileOnDemandLayer() { |
| 228 | // FIXME: Report error on log. |
| 229 | while (!LogicalDylibs.empty()) |
| 230 | consumeError(removeModule(LogicalDylibs.begin()->first)); |
| 231 | } |
| 232 | |
| 233 | /// @brief Add a module to the compile-on-demand layer. |
| 234 | Error addModule(VModuleKey K, std::unique_ptr<Module> M) { |
| 235 | |
| 236 | assert(!LogicalDylibs.count(K) && "VModuleKey K already in use"); |
| 237 | auto I = LogicalDylibs.insert( |
| 238 | LogicalDylibs.end(), |
| 239 | std::make_pair(K, LogicalDylib(K, GetSymbolResolver(K), |
| 240 | CreateIndirectStubsManager()))); |
| 241 | |
| 242 | return addLogicalModule(I->second, std::move(M)); |
| 243 | } |
| 244 | |
| 245 | /// @brief Add extra modules to an existing logical module. |
| 246 | Error addExtraModule(VModuleKey K, std::unique_ptr<Module> M) { |
| 247 | return addLogicalModule(LogicalDylibs[K], std::move(M)); |
| 248 | } |
| 249 | |
| 250 | /// @brief Remove the module represented by the given key. |
| 251 | /// |
| 252 | /// This will remove all modules in the layers below that were derived from |
| 253 | /// the module represented by K. |
| 254 | Error removeModule(VModuleKey K) { |
| 255 | auto I = LogicalDylibs.find(K); |
| 256 | assert(I != LogicalDylibs.end() && "VModuleKey K not valid here"); |
| 257 | auto Err = I->second.removeModulesFromBaseLayer(BaseLayer); |
| 258 | LogicalDylibs.erase(I); |
| 259 | return Err; |
| 260 | } |
| 261 | |
| 262 | /// @brief Search for the given named symbol. |
| 263 | /// @param Name The name of the symbol to search for. |
| 264 | /// @param ExportedSymbolsOnly If true, search only for exported symbols. |
| 265 | /// @return A handle for the given named symbol, if it exists. |
| 266 | JITSymbol findSymbol(StringRef Name, bool ExportedSymbolsOnly) { |
| 267 | for (auto &KV : LogicalDylibs) { |
| 268 | if (auto Sym = KV.second.StubsMgr->findStub(Name, ExportedSymbolsOnly)) |
| 269 | return Sym; |
| 270 | if (auto Sym = findSymbolIn(KV.first, Name, ExportedSymbolsOnly)) |
| 271 | return Sym; |
| 272 | else if (auto Err = Sym.takeError()) |
| 273 | return std::move(Err); |
| 274 | } |
| 275 | return BaseLayer.findSymbol(Name, ExportedSymbolsOnly); |
| 276 | } |
| 277 | |
| 278 | /// @brief Get the address of a symbol provided by this layer, or some layer |
| 279 | /// below this one. |
| 280 | JITSymbol findSymbolIn(VModuleKey K, const std::string &Name, |
| 281 | bool ExportedSymbolsOnly) { |
| 282 | assert(LogicalDylibs.count(K) && "VModuleKey K is not valid here"); |
| 283 | return LogicalDylibs[K].findSymbol(BaseLayer, Name, ExportedSymbolsOnly); |
| 284 | } |
| 285 | |
| 286 | /// @brief Update the stub for the given function to point at FnBodyAddr. |
| 287 | /// This can be used to support re-optimization. |
| 288 | /// @return true if the function exists and the stub is updated, false |
| 289 | /// otherwise. |
| 290 | // |
| 291 | // FIXME: We should track and free associated resources (unused compile |
| 292 | // callbacks, uncompiled IR, and no-longer-needed/reachable function |
| 293 | // implementations). |
| 294 | Error updatePointer(std::string FuncName, JITTargetAddress FnBodyAddr) { |
| 295 | //Find out which logical dylib contains our symbol |
| 296 | auto LDI = LogicalDylibs.begin(); |
| 297 | for (auto LDE = LogicalDylibs.end(); LDI != LDE; ++LDI) { |
| 298 | if (auto LMResources = |
| 299 | LDI->getLogicalModuleResourcesForSymbol(FuncName, false)) { |
| 300 | Module &SrcM = LMResources->SourceModule->getResource(); |
| 301 | std::string CalledFnName = mangle(FuncName, SrcM.getDataLayout()); |
| 302 | if (auto Err = LMResources->StubsMgr->updatePointer(CalledFnName, |
| 303 | FnBodyAddr)) |
| 304 | return Err; |
| 305 | return Error::success(); |
| 306 | } |
| 307 | } |
| 308 | return make_error<JITSymbolNotFound>(FuncName); |
| 309 | } |
| 310 | |
| 311 | private: |
| 312 | Error addLogicalModule(LogicalDylib &LD, std::unique_ptr<Module> SrcMPtr) { |
| 313 | |
| 314 | // Rename all static functions / globals to $static.X : |
| 315 | // This will unique the names across all modules in the logical dylib, |
| 316 | // simplifying symbol lookup. |
| 317 | LD.StaticRenamer.rename(*SrcMPtr); |
| 318 | |
| 319 | // Bump the linkage and rename any anonymous/privote members in SrcM to |
| 320 | // ensure that everything will resolve properly after we partition SrcM. |
| 321 | makeAllSymbolsExternallyAccessible(*SrcMPtr); |
| 322 | |
| 323 | // Create a logical module handle for SrcM within the logical dylib. |
| 324 | Module &SrcM = *SrcMPtr; |
| 325 | auto LMId = LD.addSourceModule(std::move(SrcMPtr)); |
| 326 | |
| 327 | // Create stub functions. |
| 328 | const DataLayout &DL = SrcM.getDataLayout(); |
| 329 | { |
| 330 | typename IndirectStubsMgrT::StubInitsMap StubInits; |
| 331 | for (auto &F : SrcM) { |
| 332 | // Skip declarations. |
| 333 | if (F.isDeclaration()) |
| 334 | continue; |
| 335 | |
| 336 | // Skip weak functions for which we already have definitions. |
| 337 | auto MangledName = mangle(F.getName(), DL); |
| 338 | if (F.hasWeakLinkage() || F.hasLinkOnceLinkage()) { |
| 339 | if (auto Sym = LD.findSymbol(BaseLayer, MangledName, false)) |
| 340 | continue; |
| 341 | else if (auto Err = Sym.takeError()) |
| 342 | return std::move(Err); |
| 343 | } |
| 344 | |
| 345 | // Record all functions defined by this module. |
| 346 | if (CloneStubsIntoPartitions) |
| 347 | LD.getStubsToClone(LMId).insert(&F); |
| 348 | |
| 349 | // Create a callback, associate it with the stub for the function, |
| 350 | // and set the compile action to compile the partition containing the |
| 351 | // function. |
| 352 | if (auto CCInfoOrErr = CompileCallbackMgr.getCompileCallback()) { |
| 353 | auto &CCInfo = *CCInfoOrErr; |
| 354 | StubInits[MangledName] = |
| 355 | std::make_pair(CCInfo.getAddress(), |
| 356 | JITSymbolFlags::fromGlobalValue(F)); |
| 357 | CCInfo.setCompileAction([this, &LD, LMId, &F]() -> JITTargetAddress { |
| 358 | if (auto FnImplAddrOrErr = this->extractAndCompile(LD, LMId, F)) |
| 359 | return *FnImplAddrOrErr; |
| 360 | else { |
| 361 | // FIXME: Report error, return to 'abort' or something similar. |
| 362 | consumeError(FnImplAddrOrErr.takeError()); |
| 363 | return 0; |
| 364 | } |
| 365 | }); |
| 366 | } else |
| 367 | return CCInfoOrErr.takeError(); |
| 368 | } |
| 369 | |
| 370 | if (auto Err = LD.StubsMgr->createStubs(StubInits)) |
| 371 | return Err; |
| 372 | } |
| 373 | |
| 374 | // If this module doesn't contain any globals, aliases, or module flags then |
| 375 | // we can bail out early and avoid the overhead of creating and managing an |
| 376 | // empty globals module. |
| 377 | if (SrcM.global_empty() && SrcM.alias_empty() && |
| 378 | !SrcM.getModuleFlagsMetadata()) |
| 379 | return Error::success(); |
| 380 | |
| 381 | // Create the GlobalValues module. |
| 382 | auto GVsM = llvm::make_unique<Module>((SrcM.getName() + ".globals").str(), |
| 383 | SrcM.getContext()); |
| 384 | GVsM->setDataLayout(DL); |
| 385 | |
| 386 | ValueToValueMapTy VMap; |
| 387 | |
| 388 | // Clone global variable decls. |
| 389 | for (auto &GV : SrcM.globals()) |
| 390 | if (!GV.isDeclaration() && !VMap.count(&GV)) |
| 391 | cloneGlobalVariableDecl(*GVsM, GV, &VMap); |
| 392 | |
| 393 | // And the aliases. |
| 394 | for (auto &A : SrcM.aliases()) |
| 395 | if (!VMap.count(&A)) |
| 396 | cloneGlobalAliasDecl(*GVsM, A, VMap); |
| 397 | |
| 398 | // Clone the module flags. |
| 399 | cloneModuleFlagsMetadata(*GVsM, SrcM, VMap); |
| 400 | |
| 401 | // Now we need to clone the GV and alias initializers. |
| 402 | |
| 403 | // Initializers may refer to functions declared (but not defined) in this |
| 404 | // module. Build a materializer to clone decls on demand. |
| 405 | Error MaterializerErrors = Error::success(); |
| 406 | auto Materializer = createLambdaMaterializer( |
| 407 | [&LD, &GVsM, &MaterializerErrors](Value *V) -> Value* { |
| 408 | if (auto *F = dyn_cast<Function>(V)) { |
| 409 | // Decls in the original module just get cloned. |
| 410 | if (F->isDeclaration()) |
| 411 | return cloneFunctionDecl(*GVsM, *F); |
| 412 | |
| 413 | // Definitions in the original module (which we have emitted stubs |
| 414 | // for at this point) get turned into a constant alias to the stub |
| 415 | // instead. |
| 416 | const DataLayout &DL = GVsM->getDataLayout(); |
| 417 | std::string FName = mangle(F->getName(), DL); |
| 418 | unsigned PtrBitWidth = DL.getPointerTypeSizeInBits(F->getType()); |
| 419 | JITTargetAddress StubAddr = 0; |
| 420 | |
| 421 | // Get the address for the stub. If we encounter an error while |
| 422 | // doing so, stash it in the MaterializerErrors variable and use a |
| 423 | // null address as a placeholder. |
| 424 | if (auto StubSym = LD.StubsMgr->findStub(FName, false)) { |
| 425 | if (auto StubAddrOrErr = StubSym.getAddress()) |
| 426 | StubAddr = *StubAddrOrErr; |
| 427 | else |
| 428 | MaterializerErrors = joinErrors(std::move(MaterializerErrors), |
| 429 | StubAddrOrErr.takeError()); |
| 430 | } |
| 431 | |
| 432 | ConstantInt *StubAddrCI = |
| 433 | ConstantInt::get(GVsM->getContext(), APInt(PtrBitWidth, StubAddr)); |
| 434 | Constant *Init = ConstantExpr::getCast(Instruction::IntToPtr, |
| 435 | StubAddrCI, F->getType()); |
| 436 | return GlobalAlias::create(F->getFunctionType(), |
| 437 | F->getType()->getAddressSpace(), |
| 438 | F->getLinkage(), F->getName(), |
| 439 | Init, GVsM.get()); |
| 440 | } |
| 441 | // else.... |
| 442 | return nullptr; |
| 443 | }); |
| 444 | |
| 445 | // Clone the global variable initializers. |
| 446 | for (auto &GV : SrcM.globals()) |
| 447 | if (!GV.isDeclaration()) |
| 448 | moveGlobalVariableInitializer(GV, VMap, &Materializer); |
| 449 | |
| 450 | // Clone the global alias initializers. |
| 451 | for (auto &A : SrcM.aliases()) { |
| 452 | auto *NewA = cast<GlobalAlias>(VMap[&A]); |
| 453 | assert(NewA && "Alias not cloned?"); |
| 454 | Value *Init = MapValue(A.getAliasee(), VMap, RF_None, nullptr, |
| 455 | &Materializer); |
| 456 | NewA->setAliasee(cast<Constant>(Init)); |
| 457 | } |
| 458 | |
| 459 | if (MaterializerErrors) |
| 460 | return MaterializerErrors; |
| 461 | |
| 462 | // Build a resolver for the globals module and add it to the base layer. |
| 463 | auto LegacyLookup = [this, &LD](const std::string &Name) -> JITSymbol { |
| 464 | if (auto Sym = LD.StubsMgr->findStub(Name, false)) |
| 465 | return Sym; |
| 466 | else if (auto Err = Sym.takeError()) |
| 467 | return std::move(Err); |
| 468 | |
| 469 | if (auto Sym = LD.findSymbol(BaseLayer, Name, false)) |
| 470 | return Sym; |
| 471 | else if (auto Err = Sym.takeError()) |
| 472 | return std::move(Err); |
| 473 | |
| 474 | return nullptr; |
| 475 | }; |
| 476 | |
| 477 | auto GVsResolver = createSymbolResolver( |
| 478 | [&LD, LegacyLookup](SymbolFlagsMap &SymbolFlags, |
| 479 | const SymbolNameSet &Symbols) { |
| 480 | auto NotFoundViaLegacyLookup = |
| 481 | lookupFlagsWithLegacyFn(SymbolFlags, Symbols, LegacyLookup); |
| 482 | |
| 483 | if (!NotFoundViaLegacyLookup) { |
| 484 | logAllUnhandledErrors(NotFoundViaLegacyLookup.takeError(), errs(), |
| 485 | "CODLayer/GVsResolver flags lookup failed: "); |
| 486 | SymbolFlags.clear(); |
| 487 | return SymbolNameSet(); |
| 488 | } |
| 489 | |
| 490 | return LD.BackingResolver->lookupFlags(SymbolFlags, |
| 491 | *NotFoundViaLegacyLookup); |
| 492 | }, |
| 493 | [&LD, LegacyLookup](std::shared_ptr<AsynchronousSymbolQuery> Query, |
| 494 | SymbolNameSet Symbols) { |
| 495 | auto NotFoundViaLegacyLookup = |
| 496 | lookupWithLegacyFn(*Query, Symbols, LegacyLookup); |
| 497 | return LD.BackingResolver->lookup(Query, NotFoundViaLegacyLookup); |
| 498 | }); |
| 499 | |
| 500 | SetSymbolResolver(LD.K, std::move(GVsResolver)); |
| 501 | |
| 502 | if (auto Err = BaseLayer.addModule(LD.K, std::move(GVsM))) |
| 503 | return Err; |
| 504 | |
| 505 | LD.BaseLayerVModuleKeys.push_back(LD.K); |
| 506 | |
| 507 | return Error::success(); |
| 508 | } |
| 509 | |
| 510 | static std::string mangle(StringRef Name, const DataLayout &DL) { |
| 511 | std::string MangledName; |
| 512 | { |
| 513 | raw_string_ostream MangledNameStream(MangledName); |
| 514 | Mangler::getNameWithPrefix(MangledNameStream, Name, DL); |
| 515 | } |
| 516 | return MangledName; |
| 517 | } |
| 518 | |
| 519 | Expected<JITTargetAddress> |
| 520 | extractAndCompile(LogicalDylib &LD, |
| 521 | typename LogicalDylib::SourceModuleHandle LMId, |
| 522 | Function &F) { |
| 523 | Module &SrcM = LD.getSourceModule(LMId); |
| 524 | |
| 525 | // If F is a declaration we must already have compiled it. |
| 526 | if (F.isDeclaration()) |
| 527 | return 0; |
| 528 | |
| 529 | // Grab the name of the function being called here. |
| 530 | std::string CalledFnName = mangle(F.getName(), SrcM.getDataLayout()); |
| 531 | |
| 532 | JITTargetAddress CalledAddr = 0; |
| 533 | auto Part = Partition(F); |
| 534 | if (auto PartKeyOrErr = emitPartition(LD, LMId, Part)) { |
| 535 | auto &PartKey = *PartKeyOrErr; |
| 536 | for (auto *SubF : Part) { |
| 537 | std::string FnName = mangle(SubF->getName(), SrcM.getDataLayout()); |
| 538 | if (auto FnBodySym = BaseLayer.findSymbolIn(PartKey, FnName, false)) { |
| 539 | if (auto FnBodyAddrOrErr = FnBodySym.getAddress()) { |
| 540 | JITTargetAddress FnBodyAddr = *FnBodyAddrOrErr; |
| 541 | |
| 542 | // If this is the function we're calling record the address so we can |
| 543 | // return it from this function. |
| 544 | if (SubF == &F) |
| 545 | CalledAddr = FnBodyAddr; |
| 546 | |
| 547 | // Update the function body pointer for the stub. |
| 548 | if (auto EC = LD.StubsMgr->updatePointer(FnName, FnBodyAddr)) |
| 549 | return 0; |
| 550 | |
| 551 | } else |
| 552 | return FnBodyAddrOrErr.takeError(); |
| 553 | } else if (auto Err = FnBodySym.takeError()) |
| 554 | return std::move(Err); |
| 555 | else |
| 556 | llvm_unreachable("Function not emitted for partition"); |
| 557 | } |
| 558 | |
| 559 | LD.BaseLayerVModuleKeys.push_back(PartKey); |
| 560 | } else |
| 561 | return PartKeyOrErr.takeError(); |
| 562 | |
| 563 | return CalledAddr; |
| 564 | } |
| 565 | |
| 566 | template <typename PartitionT> |
| 567 | Expected<VModuleKey> |
| 568 | emitPartition(LogicalDylib &LD, |
| 569 | typename LogicalDylib::SourceModuleHandle LMId, |
| 570 | const PartitionT &Part) { |
| 571 | Module &SrcM = LD.getSourceModule(LMId); |
| 572 | |
| 573 | // Create the module. |
| 574 | std::string NewName = SrcM.getName(); |
| 575 | for (auto *F : Part) { |
| 576 | NewName += "."; |
| 577 | NewName += F->getName(); |
| 578 | } |
| 579 | |
| 580 | auto M = llvm::make_unique<Module>(NewName, SrcM.getContext()); |
| 581 | M->setDataLayout(SrcM.getDataLayout()); |
| 582 | ValueToValueMapTy VMap; |
| 583 | |
| 584 | auto Materializer = createLambdaMaterializer([&LD, &LMId, |
| 585 | &M](Value *V) -> Value * { |
| 586 | if (auto *GV = dyn_cast<GlobalVariable>(V)) |
| 587 | return cloneGlobalVariableDecl(*M, *GV); |
| 588 | |
| 589 | if (auto *F = dyn_cast<Function>(V)) { |
| 590 | // Check whether we want to clone an available_externally definition. |
| 591 | if (!LD.getStubsToClone(LMId).count(F)) |
| 592 | return cloneFunctionDecl(*M, *F); |
| 593 | |
| 594 | // Ok - we want an inlinable stub. For that to work we need a decl |
| 595 | // for the stub pointer. |
| 596 | auto *StubPtr = createImplPointer(*F->getType(), *M, |
| 597 | F->getName() + "$stub_ptr", nullptr); |
| 598 | auto *ClonedF = cloneFunctionDecl(*M, *F); |
| 599 | makeStub(*ClonedF, *StubPtr); |
| 600 | ClonedF->setLinkage(GlobalValue::AvailableExternallyLinkage); |
| 601 | ClonedF->addFnAttr(Attribute::AlwaysInline); |
| 602 | return ClonedF; |
| 603 | } |
| 604 | |
| 605 | if (auto *A = dyn_cast<GlobalAlias>(V)) { |
| 606 | auto *Ty = A->getValueType(); |
| 607 | if (Ty->isFunctionTy()) |
| 608 | return Function::Create(cast<FunctionType>(Ty), |
| 609 | GlobalValue::ExternalLinkage, A->getName(), |
| 610 | M.get()); |
| 611 | |
| 612 | return new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, |
| 613 | nullptr, A->getName(), nullptr, |
| 614 | GlobalValue::NotThreadLocal, |
| 615 | A->getType()->getAddressSpace()); |
| 616 | } |
| 617 | |
| 618 | return nullptr; |
| 619 | }); |
| 620 | |
| 621 | // Create decls in the new module. |
| 622 | for (auto *F : Part) |
| 623 | cloneFunctionDecl(*M, *F, &VMap); |
| 624 | |
| 625 | // Move the function bodies. |
| 626 | for (auto *F : Part) |
| 627 | moveFunctionBody(*F, VMap, &Materializer); |
| 628 | |
| 629 | auto K = ES.allocateVModule(); |
| 630 | |
| 631 | auto LegacyLookup = [this, &LD](const std::string &Name) -> JITSymbol { |
| 632 | return LD.findSymbol(BaseLayer, Name, false); |
| 633 | }; |
| 634 | |
| 635 | // Create memory manager and symbol resolver. |
| 636 | auto Resolver = createSymbolResolver( |
| 637 | [&LD, LegacyLookup](SymbolFlagsMap &SymbolFlags, |
| 638 | const SymbolNameSet &Symbols) { |
| 639 | auto NotFoundViaLegacyLookup = |
| 640 | lookupFlagsWithLegacyFn(SymbolFlags, Symbols, LegacyLookup); |
| 641 | if (!NotFoundViaLegacyLookup) { |
| 642 | logAllUnhandledErrors(NotFoundViaLegacyLookup.takeError(), errs(), |
| 643 | "CODLayer/SubResolver flags lookup failed: "); |
| 644 | SymbolFlags.clear(); |
| 645 | return SymbolNameSet(); |
| 646 | } |
| 647 | return LD.BackingResolver->lookupFlags(SymbolFlags, |
| 648 | *NotFoundViaLegacyLookup); |
| 649 | }, |
| 650 | [&LD, LegacyLookup](std::shared_ptr<AsynchronousSymbolQuery> Q, |
| 651 | SymbolNameSet Symbols) { |
| 652 | auto NotFoundViaLegacyLookup = |
| 653 | lookupWithLegacyFn(*Q, Symbols, LegacyLookup); |
| 654 | return LD.BackingResolver->lookup(Q, |
| 655 | std::move(NotFoundViaLegacyLookup)); |
| 656 | }); |
| 657 | SetSymbolResolver(K, std::move(Resolver)); |
| 658 | |
| 659 | if (auto Err = BaseLayer.addModule(std::move(K), std::move(M))) |
| 660 | return std::move(Err); |
| 661 | |
| 662 | return K; |
| 663 | } |
| 664 | |
| 665 | ExecutionSession &ES; |
| 666 | BaseLayerT &BaseLayer; |
| 667 | SymbolResolverGetter GetSymbolResolver; |
| 668 | SymbolResolverSetter SetSymbolResolver; |
| 669 | PartitioningFtor Partition; |
| 670 | CompileCallbackMgrT &CompileCallbackMgr; |
| 671 | IndirectStubsManagerBuilderT CreateIndirectStubsManager; |
| 672 | |
| 673 | std::map<VModuleKey, LogicalDylib> LogicalDylibs; |
| 674 | bool CloneStubsIntoPartitions; |
| 675 | }; |
| 676 | |
| 677 | } // end namespace orc |
| 678 | |
| 679 | } // end namespace llvm |
| 680 | |
| 681 | #endif // LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H |