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