LLVM 24.0.0git
ReOptimizeLayer.cpp
Go to the documentation of this file.
7
8using namespace llvm;
9using namespace orc;
10
11// Spec for the call-controller handler that the ORC runtime calls to
12// request reoptimization.
14struct Reoptimize : sps::HandlerSpec<shared::SPSError(uint64_t, uint32_t)> {
15 static constexpr SymbolNameSpec Name =
16 SymbolNameSpec::c("__orc_rt_reoptimize_tag");
17};
18} // namespace llvm::orc::reoptimize_sps_handlers
19
20bool ReOptimizeLayer::ReOptMaterializationUnitState::tryStartReoptimize() {
21 std::unique_lock<std::mutex> Lock(Mutex);
22 if (Reoptimizing)
23 return false;
24
25 Reoptimizing = true;
26 return true;
27}
28
29void ReOptimizeLayer::ReOptMaterializationUnitState::reoptimizeSucceeded() {
30 std::unique_lock<std::mutex> Lock(Mutex);
31 assert(Reoptimizing && "Tried to mark unstarted reoptimization as done");
32 Reoptimizing = false;
33 CurVersion++;
34}
35
36void ReOptimizeLayer::ReOptMaterializationUnitState::reoptimizeFailed() {
37 std::unique_lock<std::mutex> Lock(Mutex);
38 assert(Reoptimizing && "Tried to mark unstarted reoptimization as done");
39 Reoptimizing = false;
40}
41
43 shared::CWrapperFunctionBuffer (*JITDispatch)(void *Ctx, const void *Tag,
44 const char *Data,
45 size_t Size),
46 void *JITDispatchCtx, const void *Tag, uint64_t MUID, uint32_t CurVersion) {
47 // Serialize the arguments into a WrapperFunctionBuffer and call dispatch.
49 auto ArgBytes =
50 shared::WrapperFunctionBuffer::allocate(SPSArgs::size(MUID, CurVersion));
51 shared::SPSOutputBuffer OB(ArgBytes.data(), ArgBytes.size());
52 if (!SPSArgs::serialize(OB, MUID, CurVersion)) {
53 errs()
54 << "Reoptimization error: could not serialize reoptimization arguments";
55 abort();
56 }
58 JITDispatch(JITDispatchCtx, Tag, ArgBytes.data(), ArgBytes.size())};
59
60 if (const char *ErrMsg = Buf.getOutOfBandError()) {
61 errs() << "Reoptimization error: " << ErrMsg << "\naborting.\n";
62 abort();
63 }
64}
65
67 const DataLayout &DL) {
68 auto Ctx = std::make_unique<LLVMContext>();
69 auto Mod = std::make_unique<Module>("orc-rt-lite-reoptimize.ll", *Ctx);
70 Mod->setDataLayout(DL);
71 Mod->setTargetTriple(ES.getTargetTriple());
72
73 IRBuilder<> Builder(*Mod);
74
75 // Create basic types portably
76 Type *VoidTy = Type::getVoidTy(*Ctx);
77 Type *Int8Ty = Type::getInt8Ty(*Ctx);
78 Type *Int32Ty = Type::getInt32Ty(*Ctx);
79 Type *Int64Ty = Type::getInt64Ty(*Ctx);
80 Type *VoidPtrTy = PointerType::getUnqual(*Ctx);
81
82 // Helper function type: void (void*, void*, void*, uint64_t, uint32_t)
83 FunctionType *HelperFnTy = FunctionType::get(
84 VoidTy, {VoidPtrTy, VoidPtrTy, VoidPtrTy, Int64Ty, Int32Ty}, false);
85
86 // Define ReoptimizeTag with initializer = 0
87 GlobalVariable *ReoptimizeTag = new GlobalVariable(
88 *Mod, Int8Ty, false, GlobalValue::ExternalLinkage,
89 ConstantInt::get(Int8Ty, 0), "__orc_rt_reoptimize_tag");
90
91 // Define orc_rt_lite_reoptimize function: void (uint64_t, uint32_t)
92 FunctionType *ReOptimizeFnTy =
93 FunctionType::get(VoidTy, {Int64Ty, Int32Ty}, false);
94
95 Function *ReOptimizeFn =
97 "__orc_rt_reoptimize", Mod.get());
98
99 // Set parameter names
100 auto ArgIt = ReOptimizeFn->arg_begin();
101 Value *MUID = &*ArgIt++;
102 MUID->setName("MUID");
103 Value *CurVersion = &*ArgIt;
104 CurVersion->setName("CurVersion");
105
106 // Build function body
107 BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", ReOptimizeFn);
108 Builder.SetInsertPoint(Entry);
109
110 ExecutorAddr JITDispatchSym, JITDispatchCtxSym;
111 if (auto Err =
112 lookupAndApply(ES.getBootstrapJITDylib(),
113 {recordAddr(rt::DispatchName, &JITDispatchSym),
114 recordAddr(rt::DispatchCtxName, &JITDispatchCtxSym)}))
115 return Err;
116
117 Type *IntPtrTy = DL.getIntPtrType(*Ctx);
118 Constant *JITDispatchPtr = ConstantExpr::getIntToPtr(
119 ConstantInt::get(IntPtrTy, JITDispatchSym.getValue()), VoidPtrTy);
120 Constant *JITDispatchCtxPtr = ConstantExpr::getIntToPtr(
121 ConstantInt::get(IntPtrTy, JITDispatchCtxSym.getValue()), VoidPtrTy);
122 Constant *HelperFnAddr = ConstantExpr::getIntToPtr(
123 ConstantInt::get(IntPtrTy, reinterpret_cast<uintptr_t>(
126
127 // Cast ReoptimizeTag to void*
128 Value *ReoptimizeTagPtr = Builder.CreatePointerCast(ReoptimizeTag, VoidPtrTy);
129
130 // Call the helper function
131 Builder.CreateCall(
132 HelperFnTy, HelperFnAddr,
133 {JITDispatchPtr, JITDispatchCtxPtr, ReoptimizeTagPtr, MUID, CurVersion});
134
135 // Return void
136 Builder.CreateRetVoid();
137
138 return BaseLayer.add(PlatformJD,
139 ThreadSafeModule(std::move(Mod), std::move(Ctx)));
140}
141
143 return ES.registerCallControllerHandlers(
144 PlatformJD,
146 this, &ReOptimizeLayer::rt_reoptimize));
147}
148
149void ReOptimizeLayer::emit(std::unique_ptr<MaterializationResponsibility> R,
150 ThreadSafeModule TSM) {
151 auto &JD = R->getTargetJITDylib();
152
153 bool HasNonCallable = false;
154 for (auto &KV : R->getSymbols()) {
155 auto &Flags = KV.second;
156 if (!Flags.isCallable())
157 HasNonCallable = true;
158 }
159
160 if (HasNonCallable) {
161 BaseLayer.emit(std::move(R), std::move(TSM));
162 return;
163 }
164
165 auto &MUState = createMaterializationUnitState(TSM);
166
167 if (auto Err = R->withResourceKeyDo([&](ResourceKey Key) {
168 registerMaterializationUnitResource(Key, MUState);
169 })) {
170 ES.reportError(std::move(Err));
171 R->failMaterialization();
172 return;
173 }
174
175 if (auto Err =
176 ProfilerFunc(*this, MUState.getID(), MUState.getCurVersion(), TSM)) {
177 ES.reportError(std::move(Err));
178 R->failMaterialization();
179 return;
180 }
181
182 auto InitialDests =
183 emitMUImplSymbols(MUState, MUState.getCurVersion(), JD, std::move(TSM));
184 if (!InitialDests) {
185 ES.reportError(InitialDests.takeError());
186 R->failMaterialization();
187 return;
188 }
189
190 RSManager.emitRedirectableSymbols(std::move(R), std::move(*InitialDests));
191}
192
195 unsigned CurVersion,
196 ThreadSafeModule &TSM) {
197 return TSM.withModuleDo([&](Module &M) -> Error {
198 Type *I64Ty = Type::getInt64Ty(M.getContext());
199 GlobalVariable *Counter = new GlobalVariable(
200 M, I64Ty, false, GlobalValue::InternalLinkage,
201 Constant::getNullValue(I64Ty), "__orc_reopt_counter");
202 for (auto &F : M) {
203 if (F.isDeclaration())
204 continue;
205 auto &BB = F.getEntryBlock();
206 auto *IP = &*BB.getFirstInsertionPt();
207 IRBuilder<> IRB(IP);
208 Value *Threshold = ConstantInt::get(I64Ty, CallCountThreshold, true);
209 Value *Cnt = IRB.CreateLoad(I64Ty, Counter);
210 // Use EQ to prevent further reoptimize calls.
211 Value *Cmp = IRB.CreateICmpEQ(Cnt, Threshold);
212 Value *Added = IRB.CreateAdd(Cnt, ConstantInt::get(I64Ty, 1));
213 (void)IRB.CreateStore(Added, Counter);
214 Instruction *SplitTerminator = SplitBlockAndInsertIfThen(Cmp, IP, false);
215 createReoptimizeCall(M, *SplitTerminator, MUID, CurVersion);
216 }
217 return Error::success();
218 });
219}
220
222ReOptimizeLayer::emitMUImplSymbols(ReOptMaterializationUnitState &MUState,
224 ThreadSafeModule TSM) {
226 cantFail(TSM.withModuleDo([&](Module &M) -> Error {
227 MangleAndInterner Mangle(ES, M.getDataLayout());
228 for (auto &F : M)
229 if (!F.isDeclaration()) {
230 std::string NewName =
231 (F.getName() + ".__def__." + Twine(Version)).str();
232 RenamedMap[Mangle(F.getName())] = Mangle(NewName);
233 F.setName(NewName);
234 }
235 return Error::success();
236 }));
237
238 auto RT = JD.createResourceTracker();
239 if (auto Err =
240 JD.define(std::make_unique<BasicIRLayerMaterializationUnit>(
241 BaseLayer, *getManglingOptions(), std::move(TSM)),
242 RT))
243 return Err;
244 MUState.setResourceTracker(RT);
245
246 SymbolLookupSet LookupSymbols;
247 for (auto [K, V] : RenamedMap)
248 LookupSymbols.add(V);
249
250 auto ImplSymbols =
251 ES.lookup({{&JD, JITDylibLookupFlags::MatchAllSymbols}}, LookupSymbols,
253 if (auto Err = ImplSymbols.takeError())
254 return Err;
255
257 for (auto [K, V] : RenamedMap)
258 Result[K] = (*ImplSymbols)[V];
259
260 return Result;
261}
262
263void ReOptimizeLayer::rt_reoptimize(SendErrorFn SendResult,
265 uint32_t CurVersion) {
266 auto &MUState = getMaterializationUnitState(MUID);
267 if (CurVersion < MUState.getCurVersion() || !MUState.tryStartReoptimize()) {
268 SendResult(Error::success());
269 return;
270 }
271
272 ThreadSafeModule TSM = cloneToNewContext(MUState.getThreadSafeModule());
273 auto OldRT = MUState.getResourceTracker();
274 auto &JD = OldRT->getJITDylib();
275
276 if (auto Err = ReOptFunc(*this, MUID, CurVersion + 1, OldRT, TSM)) {
277 ES.reportError(std::move(Err));
278 MUState.reoptimizeFailed();
279 SendResult(Error::success());
280 return;
281 }
282
283 auto SymbolDests =
284 emitMUImplSymbols(MUState, CurVersion + 1, JD, std::move(TSM));
285 if (!SymbolDests) {
286 ES.reportError(SymbolDests.takeError());
287 MUState.reoptimizeFailed();
288 SendResult(Error::success());
289 return;
290 }
291
292 if (auto Err = RSManager.redirect(JD, std::move(*SymbolDests))) {
293 ES.reportError(std::move(Err));
294 MUState.reoptimizeFailed();
295 SendResult(Error::success());
296 return;
297 }
298
299 MUState.reoptimizeSucceeded();
300 SendResult(Error::success());
301}
302
305 uint32_t CurVersion) {
306 Type *MUIDTy = IntegerType::get(M.getContext(), 64);
307 Type *VersionTy = IntegerType::get(M.getContext(), 32);
308 Function *ReoptimizeFunc = M.getFunction("__orc_rt_reoptimize");
309 if (!ReoptimizeFunc) {
310 std::vector<Type *> ArgTys = {MUIDTy, VersionTy};
311 FunctionType *FuncTy =
312 FunctionType::get(Type::getVoidTy(M.getContext()), ArgTys, false);
313 ReoptimizeFunc = Function::Create(FuncTy, GlobalValue::ExternalLinkage,
314 "__orc_rt_reoptimize", &M);
315 }
316 Constant *MUIDArg = ConstantInt::get(MUIDTy, MUID, false);
317 Constant *CurVersionArg = ConstantInt::get(VersionTy, CurVersion, false);
318 IRBuilder<> IRB(&IP);
319 (void)IRB.CreateCall(ReoptimizeFunc, {MUIDArg, CurVersionArg});
320}
321
322ReOptimizeLayer::ReOptMaterializationUnitState &
323ReOptimizeLayer::createMaterializationUnitState(const ThreadSafeModule &TSM) {
324 std::unique_lock<std::mutex> Lock(Mutex);
325 ReOptMaterializationUnitID MUID = NextID;
326 MUStates.emplace(MUID,
327 ReOptMaterializationUnitState(MUID, cloneToNewContext(TSM)));
328 ++NextID;
329 return MUStates.at(MUID);
330}
331
332ReOptimizeLayer::ReOptMaterializationUnitState &
333ReOptimizeLayer::getMaterializationUnitState(ReOptMaterializationUnitID MUID) {
334 std::unique_lock<std::mutex> Lock(Mutex);
335 return MUStates.at(MUID);
336}
337
338void ReOptimizeLayer::registerMaterializationUnitResource(
339 ResourceKey Key, ReOptMaterializationUnitState &State) {
340 std::unique_lock<std::mutex> Lock(Mutex);
341 MUResources[Key].insert(State.getID());
342}
343
345 std::unique_lock<std::mutex> Lock(Mutex);
346 for (auto MUID : MUResources[K])
347 MUStates.erase(MUID);
348
349 MUResources.erase(K);
350 return Error::success();
351}
352
354 ResourceKey SrcK) {
355 std::unique_lock<std::mutex> Lock(Mutex);
356 MUResources[DstK].insert_range(MUResources[SrcK]);
357 MUResources.erase(SrcK);
358}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define F(x, y, z)
Definition MD5.cpp:54
static void orc_rt_lite_reoptimize_helper(shared::CWrapperFunctionBuffer(*JITDispatch)(void *Ctx, const void *Tag, const char *Data, size_t Size), void *JITDispatchCtx, const void *Tag, uint64_t MUID, uint32_t CurVersion)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Class to represent function types.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
const Function & getFunction() const
Definition Function.h:167
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2458
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1913
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1931
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1424
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2637
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2987
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
LLVM_ABI void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete, RegisterDependenciesFunction RegisterDependencies)
Search the given JITDylibs for the given symbols.
Definition Core.cpp:1783
Represents an address in the executor process.
uint64_t getValue() const
const IRSymbolMapper::ManglingOptions *& getManglingOptions() const
Get the mangling options for this layer.
Definition Layer.h:76
Represents a JIT'd dynamic library.
Definition Core.h:675
Error registerRuntimeFunctions(JITDylib &PlatformJD)
Registers reoptimize runtime dispatch handlers to given PlatformJD.
ReOptimizeLayer(ExecutionSession &ES, DataLayout &DL, IRLayer &BaseLayer, RedirectableSymbolManager &RM)
void emit(std::unique_ptr< MaterializationResponsibility > R, ThreadSafeModule TSM) override
Emits the given module.
static void createReoptimizeCall(Module &M, Instruction &IP, ReOptMaterializationUnitID MUID, unsigned CurVersion)
void handleTransferResources(JITDylib &JD, ResourceKey DstK, ResourceKey SrcK) override
This function will be called inside the session lock.
Error addOrcRTLiteSupport(JITDylib &PlatformJD, const DataLayout &DL)
Add ORC Runtime-lite support for reoptimization to PlatformJD.
static Error reoptimizeIfCallFrequent(ReOptimizeLayer &Parent, ReOptMaterializationUnitID MUID, unsigned CurVersion, ThreadSafeModule &TSM)
Basic AddProfilerFunc that reoptimizes the function when the call count exceeds CallCountThreshold.
Error handleRemoveResources(JITDylib &JD, ResourceKey K) override
This function will be called outside the session lock.
static const uint64_t CallCountThreshold
A set of symbols to look up, each associated with a SymbolLookupFlags value.
SymbolLookupSet & add(SymbolStringPtr Name, SymbolLookupFlags Flags=SymbolLookupFlags::RequiredSymbol)
Add an element to the set.
A symbol name together with the naming level (SymbolNameKind) it is expressed in, so that a Mangler /...
static constexpr SymbolNameSpec c(StringRef Name)
An LLVM Module together with a shared ThreadSafeContext.
decltype(auto) withModuleDo(Func &&F)
Locks the associated ThreadSafeContext and calls the given function on the contained Module.
A utility class for serializing to a blob from a variadic list.
Output char buffer with overflow check.
C++ wrapper function buffer: Same as CWrapperFunctionBuffer but auto-releases memory.
const char * getOutOfBandError() const
If this value is an out-of-band error then this returns the error message, otherwise returns nullptr.
static WrapperFunctionBuffer allocate(size_t Size)
Create a WrapperFunctionBuffer with the given size and return a pointer to the underlying memory.
Base class for specs that bind handlers for calls with the SPS signature SPSSigT.
ExecutionSession::CallControllerHandlerBinding bindCallControllerHandler(HandlerT &&H, SymbolLookupFlags LF=SymbolLookupFlags::RequiredSymbol)
Bind H, using the given spec, to the tag with the spec's default name.
uintptr_t ResourceKey
Definition Core.h:61
LLVM_ABI void lookupAndApply(unique_function< void(Error)> OnApplied, LookupKind K, const JITDylibSearchOrder &SearchOrder, ArrayRef< LookupPrepareFn > PrepareFns)
Resolve the symbols contributed by every prepare function with a single lookup, then let each of thei...
DenseMap< SymbolStringPtr, ExecutorSymbolDef > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
LLVM_ABI ThreadSafeModule cloneToNewContext(const ThreadSafeModule &TSMW, GVPredicate ShouldCloneDef=GVPredicate(), GVModifier UpdateClonedDefSource=GVModifier())
Clones the given module on to a new context.
@ Resolved
Queried, materialization begun.
Definition Core.h:550
SmartMutex< false > Mutex
Mutex - A standard, always enforced mutex.
Definition Mutex.h:66
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
IntPtrTy
Definition InstrProf.h:82
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...