1 //===- CompileOnDemandLayer.h - Compile each function on demand -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // JIT layer for breaking up modules and inserting callbacks to allow
11 // individual functions to be compiled on demand.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H
16 #define LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H
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"
27 #include "llvm/Support/Debug.h"
32 /// @brief Compile-on-demand layer.
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, typename CompileCallbackMgrT,
40 typename PartitioningFtor =
41 std::function<std::set<Function*>(Function&)>>
42 class CompileOnDemandLayer {
45 // Utility class for MapValue. Only materializes declarations for global
47 class GlobalDeclMaterializer : public ValueMaterializer {
49 typedef std::set<const Function*> StubSet;
51 GlobalDeclMaterializer(Module &Dst, const StubSet *StubsToClone = nullptr)
52 : Dst(Dst), StubsToClone(StubsToClone) {}
54 Value* materializeValueFor(Value *V) final {
55 if (auto *GV = dyn_cast<GlobalVariable>(V))
56 return cloneGlobalVariableDecl(Dst, *GV);
57 else if (auto *F = dyn_cast<Function>(V)) {
58 auto *ClonedF = cloneFunctionDecl(Dst, *F);
59 if (StubsToClone && StubsToClone->count(F)) {
60 GlobalVariable *FnBodyPtr =
61 createImplPointer(*ClonedF->getType(), *ClonedF->getParent(),
62 ClonedF->getName() + "$orc_addr", nullptr);
63 makeStub(*ClonedF, *FnBodyPtr);
64 ClonedF->setLinkage(GlobalValue::AvailableExternallyLinkage);
65 ClonedF->addFnAttr(Attribute::AlwaysInline);
74 const StubSet *StubsToClone;
77 typedef typename BaseLayerT::ModuleSetHandleT BaseLayerModuleSetHandleT;
79 struct LogicalModuleResources {
80 std::shared_ptr<Module> SourceModule;
81 std::set<const Function*> StubsToClone;
84 struct LogicalDylibResources {
85 typedef std::function<RuntimeDyld::SymbolInfo(const std::string&)>
87 SymbolResolverFtor ExternalSymbolResolver;
90 typedef LogicalDylib<BaseLayerT, LogicalModuleResources,
91 LogicalDylibResources> CODLogicalDylib;
93 typedef typename CODLogicalDylib::LogicalModuleHandle LogicalModuleHandle;
94 typedef std::list<CODLogicalDylib> LogicalDylibList;
97 /// @brief Handle to a set of loaded modules.
98 typedef typename LogicalDylibList::iterator ModuleSetHandleT;
100 /// @brief Construct a compile-on-demand layer instance.
101 CompileOnDemandLayer(BaseLayerT &BaseLayer, CompileCallbackMgrT &CallbackMgr,
102 PartitioningFtor Partition,
103 bool CloneStubsIntoPartitions = true)
104 : BaseLayer(BaseLayer), CompileCallbackMgr(CallbackMgr),
105 Partition(Partition),
106 CloneStubsIntoPartitions(CloneStubsIntoPartitions) {}
108 /// @brief Add a module to the compile-on-demand layer.
109 template <typename ModuleSetT, typename MemoryManagerPtrT,
110 typename SymbolResolverPtrT>
111 ModuleSetHandleT addModuleSet(ModuleSetT Ms,
112 MemoryManagerPtrT MemMgr,
113 SymbolResolverPtrT Resolver) {
115 assert(MemMgr == nullptr &&
116 "User supplied memory managers not supported with COD yet.");
118 LogicalDylibs.push_back(CODLogicalDylib(BaseLayer));
119 auto &LDResources = LogicalDylibs.back().getDylibResources();
121 LDResources.ExternalSymbolResolver =
122 [Resolver](const std::string &Name) {
123 return Resolver->findSymbol(Name);
126 // Process each of the modules in this module set.
128 addLogicalModule(LogicalDylibs.back(),
129 std::shared_ptr<Module>(std::move(M)));
131 return std::prev(LogicalDylibs.end());
134 /// @brief Remove the module represented by the given handle.
136 /// This will remove all modules in the layers below that were derived from
137 /// the module represented by H.
138 void removeModuleSet(ModuleSetHandleT H) {
139 LogicalDylibs.erase(H);
142 /// @brief Search for the given named symbol.
143 /// @param Name The name of the symbol to search for.
144 /// @param ExportedSymbolsOnly If true, search only for exported symbols.
145 /// @return A handle for the given named symbol, if it exists.
146 JITSymbol findSymbol(StringRef Name, bool ExportedSymbolsOnly) {
147 return BaseLayer.findSymbol(Name, ExportedSymbolsOnly);
150 /// @brief Get the address of a symbol provided by this layer, or some layer
152 JITSymbol findSymbolIn(ModuleSetHandleT H, const std::string &Name,
153 bool ExportedSymbolsOnly) {
154 return H->findSymbol(Name, ExportedSymbolsOnly);
159 void addLogicalModule(CODLogicalDylib &LD, std::shared_ptr<Module> SrcM) {
161 // Bump the linkage and rename any anonymous/privote members in SrcM to
162 // ensure that everything will resolve properly after we partition SrcM.
163 makeAllSymbolsExternallyAccessible(*SrcM);
165 // Create a logical module handle for SrcM within the logical dylib.
166 auto LMH = LD.createLogicalModule();
167 auto &LMResources = LD.getLogicalModuleResources(LMH);
168 LMResources.SourceModule = SrcM;
170 // Create the GVs-and-stubs module.
171 auto GVsAndStubsM = llvm::make_unique<Module>(
172 (SrcM->getName() + ".globals_and_stubs").str(),
174 GVsAndStubsM->setDataLayout(SrcM->getDataLayout());
175 ValueToValueMapTy VMap;
177 // Process module and create stubs.
178 // We create the stubs before copying the global variables as we know the
179 // stubs won't refer to any globals (they only refer to their implementation
180 // pointer) so there's no ordering/value-mapping issues.
181 for (auto &F : *SrcM) {
183 // Skip declarations.
184 if (F.isDeclaration())
187 // Record all functions defined by this module.
188 if (CloneStubsIntoPartitions)
189 LMResources.StubsToClone.insert(&F);
191 // For each definition: create a callback, a stub, and a function body
192 // pointer. Initialize the function body pointer to point at the callback,
193 // and set the callback to compile the function body.
194 auto CCInfo = CompileCallbackMgr.getCompileCallback(SrcM->getContext());
195 Function *StubF = cloneFunctionDecl(*GVsAndStubsM, F, &VMap);
196 GlobalVariable *FnBodyPtr =
197 createImplPointer(*StubF->getType(), *StubF->getParent(),
198 StubF->getName() + "$orc_addr",
199 createIRTypedAddress(*StubF->getFunctionType(),
200 CCInfo.getAddress()));
201 makeStub(*StubF, *FnBodyPtr);
202 CCInfo.setCompileAction(
203 [this, &LD, LMH, &F]() {
204 return this->extractAndCompile(LD, LMH, F);
208 // Now clone the global variable declarations.
209 GlobalDeclMaterializer GDMat(*GVsAndStubsM);
210 for (auto &GV : SrcM->globals())
211 if (!GV.isDeclaration())
212 cloneGlobalVariableDecl(*GVsAndStubsM, GV, &VMap);
215 for (auto &Alias : SrcM->aliases())
216 cloneGlobalAlias(*GVsAndStubsM, Alias, VMap, &GDMat);
218 // Then clone the initializers.
219 for (auto &GV : SrcM->globals())
220 if (!GV.isDeclaration())
221 moveGlobalVariableInitializer(GV, VMap, &GDMat);
223 // Build a resolver for the stubs module and add it to the base layer.
224 auto GVsAndStubsResolver = createLambdaResolver(
225 [&LD](const std::string &Name) {
226 return LD.getDylibResources().ExternalSymbolResolver(Name);
228 [](const std::string &Name) {
229 return RuntimeDyld::SymbolInfo(nullptr);
232 std::vector<std::unique_ptr<Module>> GVsAndStubsMSet;
233 GVsAndStubsMSet.push_back(std::move(GVsAndStubsM));
235 BaseLayer.addModuleSet(std::move(GVsAndStubsMSet),
236 llvm::make_unique<SectionMemoryManager>(),
237 std::move(GVsAndStubsResolver));
238 LD.addToLogicalModule(LMH, GVsAndStubsH);
241 static std::string Mangle(StringRef Name, const DataLayout &DL) {
242 std::string MangledName;
244 raw_string_ostream MangledNameStream(MangledName);
245 Mangler::getNameWithPrefix(MangledNameStream, Name, DL);
250 TargetAddress extractAndCompile(CODLogicalDylib &LD,
251 LogicalModuleHandle LMH,
253 Module &SrcM = *LD.getLogicalModuleResources(LMH).SourceModule;
255 // If F is a declaration we must already have compiled it.
256 if (F.isDeclaration())
259 // Grab the name of the function being called here.
260 std::string CalledFnName = Mangle(F.getName(), SrcM.getDataLayout());
262 auto Part = Partition(F);
263 auto PartH = emitPartition(LD, LMH, Part);
265 TargetAddress CalledAddr = 0;
266 for (auto *SubF : Part) {
267 std::string FName = SubF->getName();
269 BaseLayer.findSymbolIn(PartH, Mangle(FName, SrcM.getDataLayout()),
272 BaseLayer.findSymbolIn(*LD.moduleHandlesBegin(LMH),
273 Mangle(FName + "$orc_addr",
274 SrcM.getDataLayout()),
276 assert(FnBodySym && "Couldn't find function body.");
277 assert(FnPtrSym && "Couldn't find function body pointer.");
279 TargetAddress FnBodyAddr = FnBodySym.getAddress();
280 void *FnPtrAddr = reinterpret_cast<void*>(
281 static_cast<uintptr_t>(FnPtrSym.getAddress()));
283 // If this is the function we're calling record the address so we can
284 // return it from this function.
286 CalledAddr = FnBodyAddr;
288 memcpy(FnPtrAddr, &FnBodyAddr, sizeof(uintptr_t));
294 template <typename PartitionT>
295 BaseLayerModuleSetHandleT emitPartition(CODLogicalDylib &LD,
296 LogicalModuleHandle LMH,
297 const PartitionT &Part) {
298 auto &LMResources = LD.getLogicalModuleResources(LMH);
299 Module &SrcM = *LMResources.SourceModule;
301 // Create the module.
302 std::string NewName = SrcM.getName();
303 for (auto *F : Part) {
305 NewName += F->getName();
308 auto M = llvm::make_unique<Module>(NewName, SrcM.getContext());
309 M->setDataLayout(SrcM.getDataLayout());
310 ValueToValueMapTy VMap;
311 GlobalDeclMaterializer GDM(*M, &LMResources.StubsToClone);
313 // Create decls in the new module.
315 cloneFunctionDecl(*M, *F, &VMap);
317 // Move the function bodies.
319 moveFunctionBody(*F, VMap, &GDM);
321 // Create memory manager and symbol resolver.
322 auto MemMgr = llvm::make_unique<SectionMemoryManager>();
323 auto Resolver = createLambdaResolver(
324 [this, &LD, LMH](const std::string &Name) {
325 if (auto Symbol = LD.findSymbolInternally(LMH, Name))
326 return RuntimeDyld::SymbolInfo(Symbol.getAddress(),
328 return LD.getDylibResources().ExternalSymbolResolver(Name);
330 [this, &LD, LMH](const std::string &Name) {
331 if (auto Symbol = LD.findSymbolInternally(LMH, Name))
332 return RuntimeDyld::SymbolInfo(Symbol.getAddress(),
334 return RuntimeDyld::SymbolInfo(nullptr);
336 std::vector<std::unique_ptr<Module>> PartMSet;
337 PartMSet.push_back(std::move(M));
338 return BaseLayer.addModuleSet(std::move(PartMSet), std::move(MemMgr),
339 std::move(Resolver));
342 BaseLayerT &BaseLayer;
343 CompileCallbackMgrT &CompileCallbackMgr;
344 LogicalDylibList LogicalDylibs;
345 PartitioningFtor Partition;
346 bool CloneStubsIntoPartitions;
349 } // End namespace orc.
350 } // End namespace llvm.
352 #endif // LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H