ThinLtoJIT.cpp
12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
#include "ThinLtoJIT.h"
#include "llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h"
#include "llvm/ExecutionEngine/Orc/CompileUtils.h"
#include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
#include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
#include "llvm/ExecutionEngine/Orc/IndirectionUtils.h"
#include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
#include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
#include "llvm/ExecutionEngine/SectionMemoryManager.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Host.h"
#include "ThinLtoDiscoveryThread.h"
#include "ThinLtoInstrumentationLayer.h"
#include "ThinLtoModuleIndex.h"
#include <set>
#include <string>
#include <thread>
#ifndef NDEBUG
#include <chrono>
#endif
#define DEBUG_TYPE "thinltojit"
namespace llvm {
namespace orc {
class ThinLtoDefinitionGenerator : public JITDylib::DefinitionGenerator {
public:
ThinLtoDefinitionGenerator(ThinLtoModuleIndex &GlobalIndex,
ThinLtoInstrumentationLayer &InstrumentationLayer,
ThinLtoJIT::AddModuleFunction AddModule,
char Prefix, bool AllowNudge, bool PrintStats)
: GlobalIndex(GlobalIndex), InstrumentationLayer(InstrumentationLayer),
AddModule(std::move(AddModule)), ManglePrefix(Prefix),
AllowNudgeIntoDiscovery(AllowNudge), PrintStats(PrintStats) {}
~ThinLtoDefinitionGenerator() {
if (PrintStats)
dump(errs());
}
Error tryToGenerate(LookupKind K, JITDylib &JD,
JITDylibLookupFlags JDLookupFlags,
const SymbolLookupSet &Symbols) override;
void dump(raw_ostream &OS) {
OS << format("Modules submitted synchronously: %d\n", NumModulesMissed);
}
private:
ThinLtoModuleIndex &GlobalIndex;
ThinLtoInstrumentationLayer &InstrumentationLayer;
ThinLtoJIT::AddModuleFunction AddModule;
char ManglePrefix;
bool AllowNudgeIntoDiscovery;
bool PrintStats;
unsigned NumModulesMissed{0};
// ThinLTO summaries encode unprefixed names.
StringRef stripGlobalManglePrefix(StringRef Symbol) const {
bool Strip = (ManglePrefix != '\0' && Symbol[0] == ManglePrefix);
return Strip ? StringRef(Symbol.data() + 1, Symbol.size() - 1) : Symbol;
}
};
Error ThinLtoDefinitionGenerator::tryToGenerate(
LookupKind K, JITDylib &JD, JITDylibLookupFlags JDLookupFlags,
const SymbolLookupSet &Symbols) {
std::set<StringRef> ModulePaths;
std::vector<GlobalValue::GUID> NewDiscoveryRoots;
for (const auto &KV : Symbols) {
StringRef UnmangledName = stripGlobalManglePrefix(*KV.first);
auto Guid = GlobalValue::getGUID(UnmangledName);
if (GlobalValueSummary *S = GlobalIndex.getSummary(Guid)) {
// We could have discovered it ahead of time.
LLVM_DEBUG(dbgs() << format("Failed to discover symbol: %s\n",
UnmangledName.str().c_str()));
ModulePaths.insert(S->modulePath());
if (AllowNudgeIntoDiscovery && isa<FunctionSummary>(S)) {
NewDiscoveryRoots.push_back(Guid);
}
}
}
NumModulesMissed += ModulePaths.size();
// Parse the requested modules if it hasn't happened yet.
GlobalIndex.scheduleModuleParsing(ModulePaths);
for (StringRef Path : ModulePaths) {
ThreadSafeModule TSM = GlobalIndex.takeModule(Path);
assert(TSM && "We own the session lock, no asynchronous access possible");
if (Error LoadErr = AddModule(std::move(TSM)))
// Failed to add the module to the session.
return LoadErr;
LLVM_DEBUG(dbgs() << "Generator: added " << Path << " synchronously\n");
}
// Requested functions that we failed to discover ahead of time, are likely
// close to the execution front. We can anticipate to run into them as soon
// as execution continues and trigger their discovery flags already now. This
// behavior is enabled with the 'allow-nudge' option and implemented below.
// On the one hand, it may give us a head start in a moment where discovery
// was lacking behind. On the other hand, we may bet on the wrong horse and
// waste extra time speculating in the wrong direction.
if (!NewDiscoveryRoots.empty()) {
assert(AllowNudgeIntoDiscovery);
InstrumentationLayer.nudgeIntoDiscovery(std::move(NewDiscoveryRoots));
}
return Error::success();
}
ThinLtoJIT::ThinLtoJIT(ArrayRef<std::string> InputFiles,
StringRef MainFunctionName, unsigned LookaheadLevels,
unsigned NumCompileThreads, unsigned NumLoadThreads,
unsigned DiscoveryFlagsPerBucket,
ExplicitMemoryBarrier MemFence,
bool AllowNudgeIntoDiscovery, bool PrintStats,
Error &Err) {
ErrorAsOutParameter ErrAsOutParam(&Err);
// Populate the module index, so we know which modules exist and we can find
// the one that defines the main function.
GlobalIndex = std::make_unique<ThinLtoModuleIndex>(ES, NumLoadThreads);
for (StringRef F : InputFiles) {
if (auto Err = GlobalIndex->add(F))
ES.reportError(std::move(Err));
}
// Load the module that defines the main function.
auto TSM = setupMainModule(MainFunctionName);
if (!TSM) {
Err = TSM.takeError();
return;
}
// Infer target-specific utils from the main module.
ThreadSafeModule MainModule = std::move(*TSM);
auto JTMB = setupTargetUtils(MainModule.getModuleUnlocked());
if (!JTMB) {
Err = JTMB.takeError();
return;
}
// Set up the JIT compile pipeline.
setupLayers(std::move(*JTMB), NumCompileThreads, DiscoveryFlagsPerBucket,
MemFence);
// We can use the mangler now. Remember the mangled name of the main function.
MainFunctionMangled = (*Mangle)(MainFunctionName);
// We are restricted to a single dylib currently. Add runtime overrides and
// symbol generators.
MainJD = &ES.createBareJITDylib("main");
Err = setupJITDylib(MainJD, AllowNudgeIntoDiscovery, PrintStats);
if (Err)
return;
// Spawn discovery thread and let it add newly discovered modules to the JIT.
setupDiscovery(MainJD, LookaheadLevels, PrintStats);
Err = AddModule(std::move(MainModule));
if (Err)
return;
if (AllowNudgeIntoDiscovery) {
auto MainFunctionGuid = GlobalValue::getGUID(MainFunctionName);
InstrumentationLayer->nudgeIntoDiscovery({MainFunctionGuid});
}
}
Expected<ThreadSafeModule> ThinLtoJIT::setupMainModule(StringRef MainFunction) {
Optional<StringRef> M = GlobalIndex->getModulePathForSymbol(MainFunction);
if (!M) {
std::string Buffer;
raw_string_ostream OS(Buffer);
OS << "No ValueInfo for symbol '" << MainFunction;
OS << "' in provided modules: ";
for (StringRef P : GlobalIndex->getAllModulePaths())
OS << P << " ";
OS << "\n";
return createStringError(inconvertibleErrorCode(), OS.str());
}
if (auto TSM = GlobalIndex->parseModuleFromFile(*M))
return std::move(TSM); // Not a redundant move: fix build on gcc-7.5
return createStringError(inconvertibleErrorCode(),
"Failed to parse main module");
}
Expected<JITTargetMachineBuilder> ThinLtoJIT::setupTargetUtils(Module *M) {
std::string T = M->getTargetTriple();
JITTargetMachineBuilder JTMB(Triple(T.empty() ? sys::getProcessTriple() : T));
// CallThroughManager is ABI-specific
auto LCTM = createLocalLazyCallThroughManager(
JTMB.getTargetTriple(), ES,
pointerToJITTargetAddress(exitOnLazyCallThroughFailure));
if (!LCTM)
return LCTM.takeError();
CallThroughManager = std::move(*LCTM);
// Use DataLayout or the given module or fall back to the host's default.
DL = DataLayout(M);
if (DL.getStringRepresentation().empty()) {
auto HostDL = JTMB.getDefaultDataLayoutForTarget();
if (!HostDL)
return HostDL.takeError();
DL = std::move(*HostDL);
if (Error Err = applyDataLayout(M))
return std::move(Err);
}
// Now that we know the target data layout we can setup the mangler.
Mangle = std::make_unique<MangleAndInterner>(ES, DL);
return JTMB;
}
Error ThinLtoJIT::applyDataLayout(Module *M) {
if (M->getDataLayout().isDefault())
M->setDataLayout(DL);
if (M->getDataLayout() != DL)
return make_error<StringError>(
"Added modules have incompatible data layouts",
inconvertibleErrorCode());
return Error::success();
}
static bool IsTrivialModule(MaterializationUnit *MU) {
StringRef ModuleName = MU->getName();
return ModuleName == "<Lazy Reexports>" || ModuleName == "<Reexports>" ||
ModuleName == "<Absolute Symbols>";
}
void ThinLtoJIT::setupLayers(JITTargetMachineBuilder JTMB,
unsigned NumCompileThreads,
unsigned DiscoveryFlagsPerBucket,
ExplicitMemoryBarrier MemFence) {
ObjLinkingLayer = std::make_unique<RTDyldObjectLinkingLayer>(
ES, []() { return std::make_unique<SectionMemoryManager>(); });
CompileLayer = std::make_unique<IRCompileLayer>(
ES, *ObjLinkingLayer, std::make_unique<ConcurrentIRCompiler>(JTMB));
InstrumentationLayer = std::make_unique<ThinLtoInstrumentationLayer>(
ES, *CompileLayer, MemFence, DiscoveryFlagsPerBucket);
OnDemandLayer = std::make_unique<CompileOnDemandLayer>(
ES, *InstrumentationLayer, *CallThroughManager,
createLocalIndirectStubsManagerBuilder(JTMB.getTargetTriple()));
// Don't break up modules. Insert stubs on module boundaries.
OnDemandLayer->setPartitionFunction(CompileOnDemandLayer::compileWholeModule);
// Delegate compilation to the thread pool.
CompileThreads = std::make_unique<ThreadPool>(
llvm::hardware_concurrency(NumCompileThreads));
ES.setDispatchMaterialization(
[this](std::unique_ptr<MaterializationUnit> MU,
MaterializationResponsibility MR) {
if (IsTrivialModule(MU.get())) {
// This should be quick and we may save a few session locks.
MU->materialize(std::move(MR));
} else {
// FIXME: Drop the std::shared_ptr workaround once ThreadPool::async()
// accepts llvm::unique_function to define jobs.
auto SharedMU = std::shared_ptr<MaterializationUnit>(std::move(MU));
auto SharedMR =
std::make_shared<MaterializationResponsibility>(std::move(MR));
CompileThreads->async(
[MU = std::move(SharedMU), MR = std::move(SharedMR)]() {
MU->materialize(std::move(*MR));
});
}
});
AddModule = [this](ThreadSafeModule TSM) -> Error {
assert(MainJD && "Setup MainJD JITDylib before calling");
Module *M = TSM.getModuleUnlocked();
if (Error Err = applyDataLayout(M))
return Err;
VModuleKey Id = GlobalIndex->getModuleId(M->getName());
return OnDemandLayer->add(*MainJD, std::move(TSM), Id);
};
}
void ThinLtoJIT::setupDiscovery(JITDylib *MainJD, unsigned LookaheadLevels,
bool PrintStats) {
JitRunning.store(true);
DiscoveryThreadWorker = std::make_unique<ThinLtoDiscoveryThread>(
JitRunning, ES, MainJD, *InstrumentationLayer, *GlobalIndex, AddModule,
LookaheadLevels, PrintStats);
DiscoveryThread = std::thread(std::ref(*DiscoveryThreadWorker));
}
Error ThinLtoJIT::setupJITDylib(JITDylib *JD, bool AllowNudge,
bool PrintStats) {
// Register symbols for C++ static destructors.
LocalCXXRuntimeOverrides CXXRuntimeoverrides;
Error Err = CXXRuntimeoverrides.enable(*JD, *Mangle);
if (Err)
return Err;
// Lookup symbol names in the global ThinLTO module index first
char Prefix = DL.getGlobalPrefix();
JD->addGenerator(std::make_unique<ThinLtoDefinitionGenerator>(
*GlobalIndex, *InstrumentationLayer, AddModule, Prefix, AllowNudge,
PrintStats));
// Then try lookup in the host process.
auto HostLookup = DynamicLibrarySearchGenerator::GetForCurrentProcess(Prefix);
if (!HostLookup)
return HostLookup.takeError();
JD->addGenerator(std::move(*HostLookup));
return Error::success();
}
ThinLtoJIT::~ThinLtoJIT() {
// Signal the DiscoveryThread to shut down.
JitRunning.store(false);
DiscoveryThread.join();
// Wait for potential compile actions to finish.
CompileThreads->wait();
}
} // namespace orc
} // namespace llvm