Orc: Drop some else-after-return, reflow a few spots, and avoid use of pointee types
[oota-llvm.git] / include / llvm / ExecutionEngine / Orc / CompileOnDemandLayer.h
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 "IndirectionUtils.h"
19 #include "LambdaResolver.h"
20 #include "LogicalDylib.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
23 #include "llvm/Transforms/Utils/Cloning.h"
24 #include <list>
25 #include <memory>
26 #include <set>
27
28 #include "llvm/Support/Debug.h"
29
30 namespace llvm {
31 namespace orc {
32
33 /// @brief Compile-on-demand layer.
34 ///
35 ///   When a module is added to this layer a stub is created for each of its
36 /// function definitions. The stubs and other global values are immediately
37 /// added to the layer below. When a stub is called it triggers the extraction
38 /// of the function body from the original module. The extracted body is then
39 /// compiled and executed.
40 template <typename BaseLayerT,
41           typename CompileCallbackMgrT = JITCompileCallbackManagerBase,
42           typename IndirectStubsMgrT = IndirectStubsManagerBase>
43 class CompileOnDemandLayer {
44 private:
45
46   template <typename MaterializerFtor>
47   class LambdaMaterializer final : public ValueMaterializer {
48   public:
49     LambdaMaterializer(MaterializerFtor M) : M(std::move(M)) {}
50     Value* materializeValueFor(Value *V) final {
51       return M(V);
52     }
53   private:
54     MaterializerFtor M;
55   };
56
57   template <typename MaterializerFtor>
58   LambdaMaterializer<MaterializerFtor>
59   createLambdaMaterializer(MaterializerFtor M) {
60     return LambdaMaterializer<MaterializerFtor>(std::move(M));
61   }
62
63   typedef typename BaseLayerT::ModuleSetHandleT BaseLayerModuleSetHandleT;
64
65   class ModuleOwner {
66   public:
67     ModuleOwner() = default;
68     ModuleOwner(const ModuleOwner&) = delete;
69     ModuleOwner& operator=(const ModuleOwner&) = delete;
70     virtual ~ModuleOwner() { }
71     virtual Module& getModule() const = 0;
72   };
73
74   template <typename ModulePtrT>
75   class ModuleOwnerImpl : public ModuleOwner {
76   public:
77     ModuleOwnerImpl(ModulePtrT ModulePtr) : ModulePtr(std::move(ModulePtr)) {}
78     Module& getModule() const override { return *ModulePtr; }
79   private:
80     ModulePtrT ModulePtr;
81   };
82
83   template <typename ModulePtrT>
84   std::unique_ptr<ModuleOwner> wrapOwnership(ModulePtrT ModulePtr) {
85     return llvm::make_unique<ModuleOwnerImpl<ModulePtrT>>(std::move(ModulePtr));
86   }
87
88   struct LogicalModuleResources {
89     std::unique_ptr<ModuleOwner> SourceModuleOwner;
90     std::set<const Function*> StubsToClone;
91     std::unique_ptr<IndirectStubsMgrT> StubsMgr;
92
93     LogicalModuleResources() = default;
94
95     // Explicit move constructor to make MSVC happy.
96     LogicalModuleResources(LogicalModuleResources &&Other)
97         : SourceModuleOwner(std::move(Other.SourceModuleOwner)),
98           StubsToClone(std::move(Other.StubsToClone)),
99           StubsMgr(std::move(Other.StubsMgr)) {}
100
101     // Explicit move assignment to make MSVC happy.
102     LogicalModuleResources& operator=(LogicalModuleResources &&Other) {
103       SourceModuleOwner = std::move(Other.SourceModuleOwner);
104       StubsToClone = std::move(Other.StubsToClone);
105       StubsMgr = std::move(Other.StubsMgr);
106     }
107
108     JITSymbol findSymbol(StringRef Name, bool ExportedSymbolsOnly) {
109       if (Name.endswith("$stub_ptr") && !ExportedSymbolsOnly) {
110         assert(!ExportedSymbolsOnly && "Stubs are never exported");
111         return StubsMgr->findPointer(Name.drop_back(9));
112       }
113       return StubsMgr->findStub(Name, ExportedSymbolsOnly);
114     }
115
116   };
117
118
119
120   struct LogicalDylibResources {
121     typedef std::function<RuntimeDyld::SymbolInfo(const std::string&)>
122       SymbolResolverFtor;
123     SymbolResolverFtor ExternalSymbolResolver;
124   };
125
126   typedef LogicalDylib<BaseLayerT, LogicalModuleResources,
127                        LogicalDylibResources> CODLogicalDylib;
128
129   typedef typename CODLogicalDylib::LogicalModuleHandle LogicalModuleHandle;
130   typedef std::list<CODLogicalDylib> LogicalDylibList;
131
132 public:
133
134   /// @brief Handle to a set of loaded modules.
135   typedef typename LogicalDylibList::iterator ModuleSetHandleT;
136
137   /// @brief Module partitioning functor.
138   typedef std::function<std::set<Function*>(Function&)> PartitioningFtor;
139
140   /// @brief Builder for IndirectStubsManagers.
141   typedef std::function<std::unique_ptr<IndirectStubsMgrT>()>
142     IndirectStubsManagerBuilderT;
143
144   /// @brief Construct a compile-on-demand layer instance.
145   CompileOnDemandLayer(BaseLayerT &BaseLayer, PartitioningFtor Partition,
146                        CompileCallbackMgrT &CallbackMgr,
147                        IndirectStubsManagerBuilderT CreateIndirectStubsManager,
148                        bool CloneStubsIntoPartitions = true)
149       : BaseLayer(BaseLayer),  Partition(Partition),
150         CompileCallbackMgr(CallbackMgr),
151         CreateIndirectStubsManager(std::move(CreateIndirectStubsManager)),
152         CloneStubsIntoPartitions(CloneStubsIntoPartitions) {}
153
154   /// @brief Add a module to the compile-on-demand layer.
155   template <typename ModuleSetT, typename MemoryManagerPtrT,
156             typename SymbolResolverPtrT>
157   ModuleSetHandleT addModuleSet(ModuleSetT Ms,
158                                 MemoryManagerPtrT MemMgr,
159                                 SymbolResolverPtrT Resolver) {
160
161     assert(MemMgr == nullptr &&
162            "User supplied memory managers not supported with COD yet.");
163
164     LogicalDylibs.push_back(CODLogicalDylib(BaseLayer));
165     auto &LDResources = LogicalDylibs.back().getDylibResources();
166
167     LDResources.ExternalSymbolResolver =
168       [Resolver](const std::string &Name) {
169         return Resolver->findSymbol(Name);
170       };
171
172     // Process each of the modules in this module set.
173     for (auto &M : Ms)
174       addLogicalModule(LogicalDylibs.back(), std::move(M));
175
176     return std::prev(LogicalDylibs.end());
177   }
178
179   /// @brief Remove the module represented by the given handle.
180   ///
181   ///   This will remove all modules in the layers below that were derived from
182   /// the module represented by H.
183   void removeModuleSet(ModuleSetHandleT H) {
184     LogicalDylibs.erase(H);
185   }
186
187   /// @brief Search for the given named symbol.
188   /// @param Name The name of the symbol to search for.
189   /// @param ExportedSymbolsOnly If true, search only for exported symbols.
190   /// @return A handle for the given named symbol, if it exists.
191   JITSymbol findSymbol(StringRef Name, bool ExportedSymbolsOnly) {
192     for (auto LDI = LogicalDylibs.begin(), LDE = LogicalDylibs.end();
193          LDI != LDE; ++LDI)
194       if (auto Symbol = findSymbolIn(LDI, Name, ExportedSymbolsOnly))
195         return Symbol;
196     return BaseLayer.findSymbol(Name, ExportedSymbolsOnly);
197   }
198
199   /// @brief Get the address of a symbol provided by this layer, or some layer
200   ///        below this one.
201   JITSymbol findSymbolIn(ModuleSetHandleT H, const std::string &Name,
202                          bool ExportedSymbolsOnly) {
203     return H->findSymbol(Name, ExportedSymbolsOnly);
204   }
205
206 private:
207
208   template <typename ModulePtrT>
209   void addLogicalModule(CODLogicalDylib &LD, ModulePtrT SrcMPtr) {
210
211     // Bump the linkage and rename any anonymous/privote members in SrcM to
212     // ensure that everything will resolve properly after we partition SrcM.
213     makeAllSymbolsExternallyAccessible(*SrcMPtr);
214
215     // Create a logical module handle for SrcM within the logical dylib.
216     auto LMH = LD.createLogicalModule();
217     auto &LMResources =  LD.getLogicalModuleResources(LMH);
218
219     LMResources.SourceModuleOwner = wrapOwnership(std::move(SrcMPtr));
220
221     Module &SrcM = LMResources.SourceModuleOwner->getModule();
222
223     // Create the GlobalValues module.
224     const DataLayout &DL = SrcM.getDataLayout();
225     auto GVsM = llvm::make_unique<Module>((SrcM.getName() + ".globals").str(),
226                                           SrcM.getContext());
227     GVsM->setDataLayout(DL);
228
229     // Create function stubs.
230     ValueToValueMapTy VMap;
231     {
232       typename IndirectStubsMgrT::StubInitsMap StubInits;
233       for (auto &F : SrcM) {
234         // Skip declarations.
235         if (F.isDeclaration())
236           continue;
237
238         // Record all functions defined by this module.
239         if (CloneStubsIntoPartitions)
240           LMResources.StubsToClone.insert(&F);
241
242         // Create a callback, associate it with the stub for the function,
243         // and set the compile action to compile the partition containing the
244         // function.
245         auto CCInfo = CompileCallbackMgr.getCompileCallback(SrcM.getContext());
246         StubInits[mangle(F.getName(), DL)] =
247           std::make_pair(CCInfo.getAddress(),
248                          JITSymbolBase::flagsFromGlobalValue(F));
249         CCInfo.setCompileAction([this, &LD, LMH, &F]() {
250           return this->extractAndCompile(LD, LMH, F);
251         });
252       }
253
254       LMResources.StubsMgr = CreateIndirectStubsManager();
255       auto EC = LMResources.StubsMgr->createStubs(StubInits);
256       (void)EC;
257       // FIXME: This should be propagated back to the user. Stub creation may
258       //        fail for remote JITs.
259       assert(!EC && "Error generating stubs");
260     }
261
262     // Clone global variable decls.
263     for (auto &GV : SrcM.globals())
264       if (!GV.isDeclaration() && !VMap.count(&GV))
265         cloneGlobalVariableDecl(*GVsM, GV, &VMap);
266
267     // And the aliases.
268     for (auto &A : SrcM.aliases())
269       if (!VMap.count(&A))
270         cloneGlobalAliasDecl(*GVsM, A, VMap);
271
272     // Now we need to clone the GV and alias initializers.
273
274     // Initializers may refer to functions declared (but not defined) in this
275     // module. Build a materializer to clone decls on demand.
276     auto Materializer = createLambdaMaterializer(
277       [this, &GVsM, &LMResources](Value *V) -> Value* {
278         if (auto *F = dyn_cast<Function>(V)) {
279           // Decls in the original module just get cloned.
280           if (F->isDeclaration())
281             return cloneFunctionDecl(*GVsM, *F);
282
283           // Definitions in the original module (which we have emitted stubs
284           // for at this point) get turned into a constant alias to the stub
285           // instead.
286           const DataLayout &DL = GVsM->getDataLayout();
287           std::string FName = mangle(F->getName(), DL);
288           auto StubSym = LMResources.StubsMgr->findStub(FName, false);
289           unsigned PtrBitWidth = DL.getPointerTypeSizeInBits(F->getType());
290           ConstantInt *StubAddr =
291             ConstantInt::get(GVsM->getContext(),
292                              APInt(PtrBitWidth, StubSym.getAddress()));
293           Constant *Init = ConstantExpr::getCast(Instruction::IntToPtr,
294                                                  StubAddr, F->getType());
295           return GlobalAlias::create(F->getFunctionType(),
296                                      F->getType()->getAddressSpace(),
297                                      F->getLinkage(), F->getName(),
298                                      Init, GVsM.get());
299         }
300         // else....
301         return nullptr;
302       });
303
304     // Clone the global variable initializers.
305     for (auto &GV : SrcM.globals())
306       if (!GV.isDeclaration())
307         moveGlobalVariableInitializer(GV, VMap, &Materializer);
308
309     // Clone the global alias initializers.
310     for (auto &A : SrcM.aliases()) {
311       auto *NewA = cast<GlobalAlias>(VMap[&A]);
312       assert(NewA && "Alias not cloned?");
313       Value *Init = MapValue(A.getAliasee(), VMap, RF_None, nullptr,
314                              &Materializer);
315       NewA->setAliasee(cast<Constant>(Init));
316     }
317
318     // Build a resolver for the globals module and add it to the base layer.
319     auto GVsResolver = createLambdaResolver(
320         [&LD, LMH](const std::string &Name) {
321           auto &LMResources = LD.getLogicalModuleResources(LMH);
322           if (auto Sym = LMResources.StubsMgr->findStub(Name, false))
323             return RuntimeDyld::SymbolInfo(Sym.getAddress(), Sym.getFlags());
324           return LD.getDylibResources().ExternalSymbolResolver(Name);
325         },
326         [](const std::string &Name) {
327           return RuntimeDyld::SymbolInfo(nullptr);
328         });
329
330     std::vector<std::unique_ptr<Module>> GVsMSet;
331     GVsMSet.push_back(std::move(GVsM));
332     auto GVsH =
333       BaseLayer.addModuleSet(std::move(GVsMSet),
334                              llvm::make_unique<SectionMemoryManager>(),
335                              std::move(GVsResolver));
336     LD.addToLogicalModule(LMH, GVsH);
337   }
338
339   static std::string mangle(StringRef Name, const DataLayout &DL) {
340     std::string MangledName;
341     Mangler::getNameWithPrefix(raw_string_ostream(MangledName), Name, DL);
342     return MangledName;
343   }
344
345   TargetAddress extractAndCompile(CODLogicalDylib &LD,
346                                   LogicalModuleHandle LMH,
347                                   Function &F) {
348     auto &LMResources = LD.getLogicalModuleResources(LMH);
349     Module &SrcM = LMResources.SourceModuleOwner->getModule();
350
351     // If F is a declaration we must already have compiled it.
352     if (F.isDeclaration())
353       return 0;
354
355     // Grab the name of the function being called here.
356     std::string CalledFnName = mangle(F.getName(), SrcM.getDataLayout());
357
358     auto Part = Partition(F);
359     auto PartH = emitPartition(LD, LMH, Part);
360
361     TargetAddress CalledAddr = 0;
362     for (auto *SubF : Part) {
363       std::string FnName = mangle(SubF->getName(), SrcM.getDataLayout());
364       auto FnBodySym = BaseLayer.findSymbolIn(PartH, FnName, false);
365       assert(FnBodySym && "Couldn't find function body.");
366
367       TargetAddress FnBodyAddr = FnBodySym.getAddress();
368
369       // If this is the function we're calling record the address so we can
370       // return it from this function.
371       if (SubF == &F)
372         CalledAddr = FnBodyAddr;
373
374       // Update the function body pointer for the stub.
375       if (auto EC = LMResources.StubsMgr->updatePointer(FnName, FnBodyAddr))
376         return 0;
377     }
378
379     return CalledAddr;
380   }
381
382   template <typename PartitionT>
383   BaseLayerModuleSetHandleT emitPartition(CODLogicalDylib &LD,
384                                           LogicalModuleHandle LMH,
385                                           const PartitionT &Part) {
386     auto &LMResources = LD.getLogicalModuleResources(LMH);
387     Module &SrcM = LMResources.SourceModuleOwner->getModule();
388
389     // Create the module.
390     std::string NewName = SrcM.getName();
391     for (auto *F : Part) {
392       NewName += ".";
393       NewName += F->getName();
394     }
395
396     auto M = llvm::make_unique<Module>(NewName, SrcM.getContext());
397     M->setDataLayout(SrcM.getDataLayout());
398     ValueToValueMapTy VMap;
399
400     auto Materializer = createLambdaMaterializer([this, &LMResources, &M,
401                                                   &VMap](Value *V) -> Value * {
402       if (auto *GV = dyn_cast<GlobalVariable>(V))
403         return cloneGlobalVariableDecl(*M, *GV);
404
405       if (auto *F = dyn_cast<Function>(V)) {
406         // Check whether we want to clone an available_externally definition.
407         if (!LMResources.StubsToClone.count(F))
408           return cloneFunctionDecl(*M, *F);
409
410         // Ok - we want an inlinable stub. For that to work we need a decl
411         // for the stub pointer.
412         auto *StubPtr = createImplPointer(*F->getType(), *M,
413                                           F->getName() + "$stub_ptr", nullptr);
414         auto *ClonedF = cloneFunctionDecl(*M, *F);
415         makeStub(*ClonedF, *StubPtr);
416         ClonedF->setLinkage(GlobalValue::AvailableExternallyLinkage);
417         ClonedF->addFnAttr(Attribute::AlwaysInline);
418         return ClonedF;
419       }
420
421       if (auto *A = dyn_cast<GlobalAlias>(V)) {
422         auto *Ty = A->getValueType();
423         if (Ty->isFunctionTy())
424           return Function::Create(cast<FunctionType>(Ty),
425                                   GlobalValue::ExternalLinkage, A->getName(),
426                                   M.get());
427
428         return new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage,
429                                   nullptr, A->getName(), nullptr,
430                                   GlobalValue::NotThreadLocal,
431                                   A->getType()->getAddressSpace());
432       }
433
434       return nullptr;
435     });
436
437     // Create decls in the new module.
438     for (auto *F : Part)
439       cloneFunctionDecl(*M, *F, &VMap);
440
441     // Move the function bodies.
442     for (auto *F : Part)
443       moveFunctionBody(*F, VMap, &Materializer);
444
445     // Create memory manager and symbol resolver.
446     auto MemMgr = llvm::make_unique<SectionMemoryManager>();
447     auto Resolver = createLambdaResolver(
448         [this, &LD, LMH](const std::string &Name) {
449           if (auto Symbol = LD.findSymbolInternally(LMH, Name))
450             return RuntimeDyld::SymbolInfo(Symbol.getAddress(),
451                                            Symbol.getFlags());
452           return LD.getDylibResources().ExternalSymbolResolver(Name);
453         },
454         [this, &LD, LMH](const std::string &Name) {
455           if (auto Symbol = LD.findSymbolInternally(LMH, Name))
456             return RuntimeDyld::SymbolInfo(Symbol.getAddress(),
457                                            Symbol.getFlags());
458           return RuntimeDyld::SymbolInfo(nullptr);
459         });
460     std::vector<std::unique_ptr<Module>> PartMSet;
461     PartMSet.push_back(std::move(M));
462     return BaseLayer.addModuleSet(std::move(PartMSet), std::move(MemMgr),
463                                   std::move(Resolver));
464   }
465
466   BaseLayerT &BaseLayer;
467   PartitioningFtor Partition;
468   CompileCallbackMgrT &CompileCallbackMgr;
469   IndirectStubsManagerBuilderT CreateIndirectStubsManager;
470
471   LogicalDylibList LogicalDylibs;
472   bool CloneStubsIntoPartitions;
473 };
474
475 } // End namespace orc.
476 } // End namespace llvm.
477
478 #endif // LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H