blob: a8e88a9785c59151865ad68447feebe817e38291 [file] [log] [blame]
Lang Hames68c9b8d2018-06-18 18:01:43 +00001//===----- CompileOnDemandLayer.cpp - Lazily emit IR on first call --------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Lang Hames68c9b8d2018-06-18 18:01:43 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h"
Lang Hames1df947a2020-02-22 09:49:55 -080010
11#include "llvm/ADT/Hashing.h"
Lang Hames85fb9972019-12-16 02:50:40 -080012#include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
Lang Hames68c9b8d2018-06-18 18:01:43 +000013#include "llvm/IR/Mangler.h"
14#include "llvm/IR/Module.h"
Lang Hames1df947a2020-02-22 09:49:55 -080015#include "llvm/Support/FormatVariadic.h"
Lang Hames68c9b8d2018-06-18 18:01:43 +000016
17using namespace llvm;
18using namespace llvm::orc;
19
Lang Hames98440292018-09-29 23:49:57 +000020static ThreadSafeModule extractSubModule(ThreadSafeModule &TSM,
21 StringRef Suffix,
22 GVPredicate ShouldExtract) {
Lang Hames6a941342018-06-26 21:35:48 +000023
Lang Hames98440292018-09-29 23:49:57 +000024 auto DeleteExtractedDefs = [](GlobalValue &GV) {
25 // Bump the linkage: this global will be provided by the external module.
26 GV.setLinkage(GlobalValue::ExternalLinkage);
Lang Hames6a941342018-06-26 21:35:48 +000027
Lang Hames98440292018-09-29 23:49:57 +000028 // Delete the definition in the source module.
Lang Hames8d76c712018-09-26 01:24:12 +000029 if (isa<Function>(GV)) {
30 auto &F = cast<Function>(GV);
31 F.deleteBody();
32 F.setPersonalityFn(nullptr);
33 } else if (isa<GlobalVariable>(GV)) {
34 cast<GlobalVariable>(GV).setInitializer(nullptr);
Lang Hames98440292018-09-29 23:49:57 +000035 } else if (isa<GlobalAlias>(GV)) {
36 // We need to turn deleted aliases into function or variable decls based
37 // on the type of their aliasee.
38 auto &A = cast<GlobalAlias>(GV);
39 Constant *Aliasee = A.getAliasee();
40 assert(A.hasName() && "Anonymous alias?");
41 assert(Aliasee->hasName() && "Anonymous aliasee");
Benjamin Krameradcd0262020-01-28 20:23:46 +010042 std::string AliasName = std::string(A.getName());
Lang Hames98440292018-09-29 23:49:57 +000043
44 if (isa<Function>(Aliasee)) {
45 auto *F = cloneFunctionDecl(*A.getParent(), *cast<Function>(Aliasee));
46 A.replaceAllUsesWith(F);
47 A.eraseFromParent();
48 F->setName(AliasName);
49 } else if (isa<GlobalVariable>(Aliasee)) {
50 auto *G = cloneGlobalVariableDecl(*A.getParent(),
51 *cast<GlobalVariable>(Aliasee));
52 A.replaceAllUsesWith(G);
53 A.eraseFromParent();
54 G->setName(AliasName);
55 } else
56 llvm_unreachable("Alias to unsupported type");
Lang Hames8d76c712018-09-26 01:24:12 +000057 } else
58 llvm_unreachable("Unsupported global type");
Lang Hames8d76c712018-09-26 01:24:12 +000059 };
Lang Hames68c9b8d2018-06-18 18:01:43 +000060
Lang Hames809e9d12019-08-02 15:21:37 +000061 auto NewTSM = cloneToNewContext(TSM, ShouldExtract, DeleteExtractedDefs);
62 NewTSM.withModuleDo([&](Module &M) {
63 M.setModuleIdentifier((M.getModuleIdentifier() + Suffix).str());
64 });
Lang Hames68c9b8d2018-06-18 18:01:43 +000065
Lang Hames809e9d12019-08-02 15:21:37 +000066 return NewTSM;
Lang Hames7bd89702018-07-05 19:01:27 +000067}
68
Lang Hames68c9b8d2018-06-18 18:01:43 +000069namespace llvm {
70namespace orc {
71
Lang Hames98440292018-09-29 23:49:57 +000072class PartitioningIRMaterializationUnit : public IRMaterializationUnit {
Lang Hames68c9b8d2018-06-18 18:01:43 +000073public:
Lang Hamesce2207a2020-01-21 16:28:30 -080074 PartitioningIRMaterializationUnit(ExecutionSession &ES,
Lang Hames85fb9972019-12-16 02:50:40 -080075 const IRSymbolMapper::ManglingOptions &MO,
Lang Hamesce2207a2020-01-21 16:28:30 -080076 ThreadSafeModule TSM, VModuleKey K,
77 CompileOnDemandLayer &Parent)
78 : IRMaterializationUnit(ES, MO, std::move(TSM), std::move(K)),
Lang Hames8b942742018-10-16 20:13:06 +000079 Parent(Parent) {}
Lang Hames68c9b8d2018-06-18 18:01:43 +000080
Lang Hames98440292018-09-29 23:49:57 +000081 PartitioningIRMaterializationUnit(
Lang Hames85fb9972019-12-16 02:50:40 -080082 ThreadSafeModule TSM, VModuleKey K, SymbolFlagsMap SymbolFlags,
83 SymbolStringPtr InitSymbol, SymbolNameToDefinitionMap SymbolToDefinition,
Lang Hames079df9a2018-10-15 22:56:10 +000084 CompileOnDemandLayer &Parent)
Lang Hames8b942742018-10-16 20:13:06 +000085 : IRMaterializationUnit(std::move(TSM), std::move(K),
Lang Hames85fb9972019-12-16 02:50:40 -080086 std::move(SymbolFlags), std::move(InitSymbol),
Lang Hames68c9b8d2018-06-18 18:01:43 +000087 std::move(SymbolToDefinition)),
Lang Hamesfd0c1e712018-07-20 18:31:50 +000088 Parent(Parent) {}
Lang Hames68c9b8d2018-06-18 18:01:43 +000089
90private:
91 void materialize(MaterializationResponsibility R) override {
Lang Hames98440292018-09-29 23:49:57 +000092 Parent.emitPartition(std::move(R), std::move(TSM),
93 std::move(SymbolToDefinition));
Lang Hames68c9b8d2018-06-18 18:01:43 +000094 }
95
Lang Hamescb5702c32018-10-06 23:02:06 +000096 void discard(const JITDylib &V, const SymbolStringPtr &Name) override {
Lang Hames68c9b8d2018-06-18 18:01:43 +000097 // All original symbols were materialized by the CODLayer and should be
98 // final. The function bodies provided by M should never be overridden.
99 llvm_unreachable("Discard should never be called on an "
100 "ExtractingIRMaterializationUnit");
101 }
102
Lang Hames7bd89702018-07-05 19:01:27 +0000103 mutable std::mutex SourceModuleMutex;
Lang Hames079df9a2018-10-15 22:56:10 +0000104 CompileOnDemandLayer &Parent;
Lang Hames68c9b8d2018-06-18 18:01:43 +0000105};
106
Lang Hames079df9a2018-10-15 22:56:10 +0000107Optional<CompileOnDemandLayer::GlobalValueSet>
108CompileOnDemandLayer::compileRequested(GlobalValueSet Requested) {
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800109 return std::move(Requested);
Lang Hames98440292018-09-29 23:49:57 +0000110}
111
Lang Hames079df9a2018-10-15 22:56:10 +0000112Optional<CompileOnDemandLayer::GlobalValueSet>
113CompileOnDemandLayer::compileWholeModule(GlobalValueSet Requested) {
Lang Hames98440292018-09-29 23:49:57 +0000114 return None;
115}
116
Lang Hames079df9a2018-10-15 22:56:10 +0000117CompileOnDemandLayer::CompileOnDemandLayer(
Lang Hamesd8048672018-09-26 05:08:29 +0000118 ExecutionSession &ES, IRLayer &BaseLayer, LazyCallThroughManager &LCTMgr,
Lang Hames8d76c712018-09-26 01:24:12 +0000119 IndirectStubsManagerBuilder BuildIndirectStubsManager)
Lang Hamesce2207a2020-01-21 16:28:30 -0800120 : IRLayer(ES, BaseLayer.getManglingOptions()), BaseLayer(BaseLayer),
121 LCTMgr(LCTMgr),
Lang Hames8d76c712018-09-26 01:24:12 +0000122 BuildIndirectStubsManager(std::move(BuildIndirectStubsManager)) {}
Lang Hames68c9b8d2018-06-18 18:01:43 +0000123
Lang Hames079df9a2018-10-15 22:56:10 +0000124void CompileOnDemandLayer::setPartitionFunction(PartitionFunction Partition) {
Lang Hames98440292018-09-29 23:49:57 +0000125 this->Partition = std::move(Partition);
Lang Hames68c9b8d2018-06-18 18:01:43 +0000126}
127
Praveen Velliengirif5c40cb2019-08-03 14:42:13 +0000128void CompileOnDemandLayer::setImplMap(ImplSymbolMap *Imp) {
129 this->AliaseeImpls = Imp;
130}
Lang Hames8b942742018-10-16 20:13:06 +0000131void CompileOnDemandLayer::emit(MaterializationResponsibility R,
132 ThreadSafeModule TSM) {
Lang Hames809e9d12019-08-02 15:21:37 +0000133 assert(TSM && "Null module");
Lang Hames98440292018-09-29 23:49:57 +0000134
Lang Hames68c9b8d2018-06-18 18:01:43 +0000135 auto &ES = getExecutionSession();
Lang Hames68c9b8d2018-06-18 18:01:43 +0000136
Lang Hames809e9d12019-08-02 15:21:37 +0000137 // Sort the callables and non-callables, build re-exports and lodge the
Lang Hames98440292018-09-29 23:49:57 +0000138 // actual module with the implementation dylib.
139 auto &PDR = getPerDylibResources(R.getTargetJITDylib());
Lang Hames68c9b8d2018-06-18 18:01:43 +0000140
Lang Hames98440292018-09-29 23:49:57 +0000141 SymbolAliasMap NonCallables;
142 SymbolAliasMap Callables;
Lang Hames809e9d12019-08-02 15:21:37 +0000143 TSM.withModuleDo([&](Module &M) {
144 // First, do some cleanup on the module:
145 cleanUpModule(M);
Lang Hames809e9d12019-08-02 15:21:37 +0000146 });
Lang Hames68c9b8d2018-06-18 18:01:43 +0000147
Lang Hamesce2207a2020-01-21 16:28:30 -0800148 for (auto &KV : R.getSymbols()) {
149 auto &Name = KV.first;
150 auto &Flags = KV.second;
151 if (Flags.isCallable())
152 Callables[Name] = SymbolAliasMapEntry(Name, Flags);
153 else
154 NonCallables[Name] = SymbolAliasMapEntry(Name, Flags);
155 }
156
Lang Hames98440292018-09-29 23:49:57 +0000157 // Create a partitioning materialization unit and lodge it with the
158 // implementation dylib.
159 if (auto Err = PDR.getImplDylib().define(
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000160 std::make_unique<PartitioningIRMaterializationUnit>(
Lang Hamesce2207a2020-01-21 16:28:30 -0800161 ES, *getManglingOptions(), std::move(TSM), R.getVModuleKey(),
162 *this))) {
Lang Hames68c9b8d2018-06-18 18:01:43 +0000163 ES.reportError(std::move(Err));
164 R.failMaterialization();
165 return;
166 }
167
Lang Hamesa7b83932020-03-18 20:09:11 -0700168 if (!NonCallables.empty())
169 R.replace(reexports(PDR.getImplDylib(), std::move(NonCallables),
170 JITDylibLookupFlags::MatchAllSymbols));
171 if (!Callables.empty())
172 R.replace(lazyReexports(LCTMgr, PDR.getISManager(), PDR.getImplDylib(),
173 std::move(Callables), AliaseeImpls));
Lang Hames68c9b8d2018-06-18 18:01:43 +0000174}
175
Lang Hames079df9a2018-10-15 22:56:10 +0000176CompileOnDemandLayer::PerDylibResources &
177CompileOnDemandLayer::getPerDylibResources(JITDylib &TargetD) {
Lang Hamesd8048672018-09-26 05:08:29 +0000178 auto I = DylibResources.find(&TargetD);
179 if (I == DylibResources.end()) {
Lang Hames4fc68b92019-12-04 22:45:38 -0800180 auto &ImplD =
Lang Hames85fb9972019-12-16 02:50:40 -0800181 getExecutionSession().createBareJITDylib(TargetD.getName() + ".impl");
182 JITDylibSearchOrder NewSearchOrder;
Lang Hames674df132019-11-25 21:57:27 -0800183 TargetD.withSearchOrderDo(
184 [&](const JITDylibSearchOrder &TargetSearchOrder) {
Lang Hames85fb9972019-12-16 02:50:40 -0800185 NewSearchOrder = TargetSearchOrder;
Lang Hames674df132019-11-25 21:57:27 -0800186 });
Lang Hames85fb9972019-12-16 02:50:40 -0800187
188 assert(
189 !NewSearchOrder.empty() && NewSearchOrder.front().first == &TargetD &&
190 NewSearchOrder.front().second == JITDylibLookupFlags::MatchAllSymbols &&
191 "TargetD must be at the front of its own search order and match "
192 "non-exported symbol");
193 NewSearchOrder.insert(std::next(NewSearchOrder.begin()),
194 {&ImplD, JITDylibLookupFlags::MatchAllSymbols});
195 ImplD.setSearchOrder(NewSearchOrder, false);
196 TargetD.setSearchOrder(std::move(NewSearchOrder), false);
197
Lang Hamesd8048672018-09-26 05:08:29 +0000198 PerDylibResources PDR(ImplD, BuildIndirectStubsManager());
199 I = DylibResources.insert(std::make_pair(&TargetD, std::move(PDR))).first;
200 }
201
202 return I->second;
Lang Hames68c9b8d2018-06-18 18:01:43 +0000203}
204
Lang Hames079df9a2018-10-15 22:56:10 +0000205void CompileOnDemandLayer::cleanUpModule(Module &M) {
Lang Hames98440292018-09-29 23:49:57 +0000206 for (auto &F : M.functions()) {
207 if (F.isDeclaration())
208 continue;
209
210 if (F.hasAvailableExternallyLinkage()) {
211 F.deleteBody();
212 F.setPersonalityFn(nullptr);
213 continue;
214 }
215 }
216}
217
Lang Hames079df9a2018-10-15 22:56:10 +0000218void CompileOnDemandLayer::expandPartition(GlobalValueSet &Partition) {
Lang Hames98440292018-09-29 23:49:57 +0000219 // Expands the partition to ensure the following rules hold:
220 // (1) If any alias is in the partition, its aliasee is also in the partition.
221 // (2) If any aliasee is in the partition, its aliases are also in the
222 // partiton.
223 // (3) If any global variable is in the partition then all global variables
224 // are in the partition.
225 assert(!Partition.empty() && "Unexpected empty partition");
226
227 const Module &M = *(*Partition.begin())->getParent();
228 bool ContainsGlobalVariables = false;
229 std::vector<const GlobalValue *> GVsToAdd;
230
231 for (auto *GV : Partition)
232 if (isa<GlobalAlias>(GV))
233 GVsToAdd.push_back(
234 cast<GlobalValue>(cast<GlobalAlias>(GV)->getAliasee()));
235 else if (isa<GlobalVariable>(GV))
236 ContainsGlobalVariables = true;
237
238 for (auto &A : M.aliases())
239 if (Partition.count(cast<GlobalValue>(A.getAliasee())))
240 GVsToAdd.push_back(&A);
241
242 if (ContainsGlobalVariables)
243 for (auto &G : M.globals())
244 GVsToAdd.push_back(&G);
245
246 for (auto *GV : GVsToAdd)
247 Partition.insert(GV);
248}
249
Lang Hames079df9a2018-10-15 22:56:10 +0000250void CompileOnDemandLayer::emitPartition(
Lang Hames98440292018-09-29 23:49:57 +0000251 MaterializationResponsibility R, ThreadSafeModule TSM,
252 IRMaterializationUnit::SymbolNameToDefinitionMap Defs) {
253
254 // FIXME: Need a 'notify lazy-extracting/emitting' callback to tie the
255 // extracted module key, extracted module, and source module key
256 // together. This could be used, for example, to provide a specific
257 // memory manager instance to the linking layer.
258
259 auto &ES = getExecutionSession();
Lang Hames98440292018-09-29 23:49:57 +0000260 GlobalValueSet RequestedGVs;
261 for (auto &Name : R.getRequestedSymbols()) {
Lang Hames85fb9972019-12-16 02:50:40 -0800262 if (Name == R.getInitializerSymbol())
263 TSM.withModuleDo([&](Module &M) {
264 for (auto &GV : getStaticInitGVs(M))
265 RequestedGVs.insert(&GV);
266 });
267 else {
268 assert(Defs.count(Name) && "No definition for symbol");
269 RequestedGVs.insert(Defs[Name]);
270 }
Lang Hames98440292018-09-29 23:49:57 +0000271 }
272
Lang Hames809e9d12019-08-02 15:21:37 +0000273 /// Perform partitioning with the context lock held, since the partition
274 /// function is allowed to access the globals to compute the partition.
275 auto GVsToExtract =
276 TSM.withModuleDo([&](Module &M) { return Partition(RequestedGVs); });
Lang Hames98440292018-09-29 23:49:57 +0000277
278 // Take a 'None' partition to mean the whole module (as opposed to an empty
279 // partition, which means "materialize nothing"). Emit the whole module
280 // unmodified to the base layer.
281 if (GVsToExtract == None) {
282 Defs.clear();
Lang Hames8b942742018-10-16 20:13:06 +0000283 BaseLayer.emit(std::move(R), std::move(TSM));
Lang Hames98440292018-09-29 23:49:57 +0000284 return;
285 }
286
287 // If the partition is empty, return the whole module to the symbol table.
288 if (GVsToExtract->empty()) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000289 R.replace(std::make_unique<PartitioningIRMaterializationUnit>(
Lang Hames85fb9972019-12-16 02:50:40 -0800290 std::move(TSM), R.getVModuleKey(), R.getSymbols(),
291 R.getInitializerSymbol(), std::move(Defs), *this));
Lang Hames98440292018-09-29 23:49:57 +0000292 return;
293 }
294
Lang Hamesbf6603e2018-10-09 20:44:32 +0000295 // Ok -- we actually need to partition the symbols. Promote the symbol
Lang Hames809e9d12019-08-02 15:21:37 +0000296 // linkages/names, expand the partition to include any required symbols
297 // (i.e. symbols that can't be separated from our partition), and
298 // then extract the partition.
299 //
300 // FIXME: We apply this promotion once per partitioning. It's safe, but
301 // overkill.
Lang Hames809e9d12019-08-02 15:21:37 +0000302 auto ExtractedTSM =
303 TSM.withModuleDo([&](Module &M) -> Expected<ThreadSafeModule> {
304 auto PromotedGlobals = PromoteSymbols(M);
305 if (!PromotedGlobals.empty()) {
Lang Hames1df947a2020-02-22 09:49:55 -0800306
Lang Hames809e9d12019-08-02 15:21:37 +0000307 MangleAndInterner Mangle(ES, M.getDataLayout());
308 SymbolFlagsMap SymbolFlags;
Lang Hames1df947a2020-02-22 09:49:55 -0800309 IRSymbolMapper::add(ES, *getManglingOptions(),
310 PromotedGlobals, SymbolFlags);
311
Lang Hames809e9d12019-08-02 15:21:37 +0000312 if (auto Err = R.defineMaterializing(SymbolFlags))
Bill Wendlingc55cf4a2020-02-10 07:06:45 -0800313 return std::move(Err);
Lang Hames809e9d12019-08-02 15:21:37 +0000314 }
315
316 expandPartition(*GVsToExtract);
317
Lang Hames1df947a2020-02-22 09:49:55 -0800318 // Submodule name is given by hashing the names of the globals.
319 std::string SubModuleName;
320 {
321 std::vector<const GlobalValue*> HashGVs;
322 HashGVs.reserve(GVsToExtract->size());
323 for (auto *GV : *GVsToExtract)
324 HashGVs.push_back(GV);
325 llvm::sort(HashGVs, [](const GlobalValue *LHS, const GlobalValue *RHS) {
326 return LHS->getName() < RHS->getName();
327 });
328 hash_code HC(0);
329 for (auto *GV : HashGVs) {
330 assert(GV->hasName() && "All GVs to extract should be named by now");
331 auto GVName = GV->getName();
332 HC = hash_combine(HC, hash_combine_range(GVName.begin(), GVName.end()));
333 }
334 raw_string_ostream(SubModuleName)
335 << ".submodule."
336 << formatv(sizeof(size_t) == 8 ? "{0:x16}" : "{0:x8}",
337 static_cast<size_t>(HC))
338 << ".ll";
339 }
340
Lang Hames809e9d12019-08-02 15:21:37 +0000341 // Extract the requested partiton (plus any necessary aliases) and
342 // put the rest back into the impl dylib.
343 auto ShouldExtract = [&](const GlobalValue &GV) -> bool {
344 return GVsToExtract->count(&GV);
345 };
346
Lang Hames1df947a2020-02-22 09:49:55 -0800347 return extractSubModule(TSM, SubModuleName , ShouldExtract);
Lang Hames809e9d12019-08-02 15:21:37 +0000348 });
349
350 if (!ExtractedTSM) {
351 ES.reportError(ExtractedTSM.takeError());
352 R.failMaterialization();
353 return;
Lang Hamesbf6603e2018-10-09 20:44:32 +0000354 }
355
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000356 R.replace(std::make_unique<PartitioningIRMaterializationUnit>(
Lang Hamesce2207a2020-01-21 16:28:30 -0800357 ES, *getManglingOptions(), std::move(TSM), R.getVModuleKey(), *this));
Lang Hames809e9d12019-08-02 15:21:37 +0000358 BaseLayer.emit(std::move(R), std::move(*ExtractedTSM));
Lang Hames68c9b8d2018-06-18 18:01:43 +0000359}
360
361} // end namespace orc
362} // end namespace llvm