LLVM 22.0.0git
Speculation.h
Go to the documentation of this file.
1//===-- Speculation.h - Speculative Compilation --*- C++ -*-===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// Contains the definition to support speculative compilation when laziness is
10// enabled.
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_EXECUTIONENGINE_ORC_SPECULATION_H
14#define LLVM_EXECUTIONENGINE_ORC_SPECULATION_H
15
16#include "llvm/ADT/DenseMap.h"
21#include "llvm/Support/Debug.h"
22#include <mutex>
23#include <type_traits>
24#include <utility>
25
26namespace llvm {
27namespace orc {
28
29class Speculator;
30
31// Track the Impls (JITDylib,Symbols) of Symbols while lazy call through
32// trampolines are created. Operations are guarded by locks tp ensure that Imap
33// stays in consistent state after read/write
34
36 friend class Speculator;
37
38public:
39 using AliaseeDetails = std::pair<SymbolStringPtr, JITDylib *>;
42 LLVM_ABI void trackImpls(SymbolAliasMap ImplMaps, JITDylib *SrcJD);
43
44private:
45 // FIX ME: find a right way to distinguish the pre-compile Symbols, and update
46 // the callsite
47 std::optional<AliaseeDetails> getImplFor(const SymbolStringPtr &StubSymbol) {
48 std::lock_guard<std::mutex> Lockit(ConcurrentAccess);
49 auto Position = Maps.find(StubSymbol);
50 if (Position != Maps.end())
51 return Position->getSecond();
52 else
53 return std::nullopt;
54 }
55
56 std::mutex ConcurrentAccess;
57 ImapTy Maps;
58};
59
60// Defines Speculator Concept,
62public:
66
67private:
68 void registerSymbolsWithAddr(TargetFAddr ImplAddr,
69 SymbolNameSet likelySymbols) {
70 std::lock_guard<std::mutex> Lockit(ConcurrentAccess);
71 GlobalSpecMap.insert({ImplAddr, std::move(likelySymbols)});
72 }
73
74 void launchCompile(ExecutorAddr FAddr) {
75 SymbolNameSet CandidateSet;
76 // Copy CandidateSet is necessary, to avoid unsynchronized access to
77 // the datastructure.
78 {
79 std::lock_guard<std::mutex> Lockit(ConcurrentAccess);
80 auto It = GlobalSpecMap.find(FAddr);
81 if (It == GlobalSpecMap.end())
82 return;
83 CandidateSet = It->getSecond();
84 }
85
86 SymbolDependenceMap SpeculativeLookUpImpls;
87
88 for (auto &Callee : CandidateSet) {
89 auto ImplSymbol = AliaseeImplTable.getImplFor(Callee);
90 // try to distinguish already compiled & library symbols
91 if (!ImplSymbol)
92 continue;
93 const auto &ImplSymbolName = ImplSymbol->first;
94 JITDylib *ImplJD = ImplSymbol->second;
95 auto &SymbolsInJD = SpeculativeLookUpImpls[ImplJD];
96 SymbolsInJD.insert(ImplSymbolName);
97 }
98
99 DEBUG_WITH_TYPE("orc", {
100 for (auto &I : SpeculativeLookUpImpls) {
101 llvm::dbgs() << "\n In " << I.first->getName() << " JITDylib ";
102 for (auto &N : I.second)
103 llvm::dbgs() << "\n Likely Symbol : " << N;
104 }
105 });
106
107 // for a given symbol, there may be no symbol qualified for speculatively
108 // compile try to fix this before jumping to this code if possible.
109 for (auto &LookupPair : SpeculativeLookUpImpls)
110 ES.lookup(
112 makeJITDylibSearchOrder(LookupPair.first,
114 SymbolLookupSet(LookupPair.second), SymbolState::Ready,
115 [this](Expected<SymbolMap> Result) {
116 if (auto Err = Result.takeError())
117 ES.reportError(std::move(Err));
118 },
120 }
121
122public:
124 : AliaseeImplTable(Impl), ES(ref), GlobalSpecMap(0) {}
125 Speculator(const Speculator &) = delete;
126 Speculator(Speculator &&) = delete;
127 Speculator &operator=(const Speculator &) = delete;
129
130 /// Define symbols for this Speculator object (__orc_speculator) and the
131 /// speculation runtime entry point symbol (__orc_speculate_for) in the
132 /// given JITDylib.
134
135 // Speculatively compile likely functions for the given Stub Address.
136 // destination of __orc_speculate_for jump
137 void speculateFor(TargetFAddr StubAddr) { launchCompile(StubAddr); }
138
139 // FIXME : Register with Stub Address, after JITLink Fix.
141 for (auto &SymPair : Candidates) {
142 auto Target = SymPair.first;
143 auto Likely = SymPair.second;
144
145 auto OnReadyFixUp = [Likely, Target,
146 this](Expected<SymbolMap> ReadySymbol) {
147 if (ReadySymbol) {
148 auto RDef = (*ReadySymbol)[Target];
149 registerSymbolsWithAddr(RDef.getAddress(), std::move(Likely));
150 } else
151 this->getES().reportError(ReadySymbol.takeError());
152 };
153 // Include non-exported symbols also.
154 ES.lookup(
159 }
160 }
161
162 ExecutionSession &getES() { return ES; }
163
164private:
165 static void speculateForEntryPoint(Speculator *Ptr, uint64_t StubId);
166 std::mutex ConcurrentAccess;
167 ImplSymbolMap &AliaseeImplTable;
169 StubAddrLikelies GlobalSpecMap;
170};
171
173public:
175 std::optional<DenseMap<StringRef, DenseSet<StringRef>>>;
176 using ResultEval = std::function<IRlikiesStrRef(Function &)>;
178
181 : IRLayer(ES, BaseLayer.getManglingOptions()), NextLayer(BaseLayer),
182 S(Spec), Mangle(Mangle), QueryAnalysis(Interpreter) {}
183
184 void emit(std::unique_ptr<MaterializationResponsibility> R,
185 ThreadSafeModule TSM) override;
186
187private:
188 TargetAndLikelies
189 internToJITSymbols(DenseMap<StringRef, DenseSet<StringRef>> IRNames) {
190 assert(!IRNames.empty() && "No IRNames received to Intern?");
191 TargetAndLikelies InternedNames;
192 for (auto &NamePair : IRNames) {
193 DenseSet<SymbolStringPtr> TargetJITNames;
194 for (auto &TargetNames : NamePair.second)
195 TargetJITNames.insert(Mangle(TargetNames));
196 InternedNames[Mangle(NamePair.first)] = std::move(TargetJITNames);
197 }
198 return InternedNames;
199 }
200
201 IRLayer &NextLayer;
202 Speculator &S;
203 MangleAndInterner &Mangle;
204 ResultEval QueryAnalysis;
205};
206
207} // namespace orc
208} // namespace llvm
209
210#endif // LLVM_EXECUTIONENGINE_ORC_SPECULATION_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:213
This file defines the DenseMap class.
#define I(x, y, z)
Definition MD5.cpp:58
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition Debug.h:77
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h:187
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:165
iterator end()
Definition DenseMap.h:81
Implements a dense probed hash-table based set.
Definition DenseSet.h:261
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Tagged union holding either a T or a Error.
Definition Error.h:485
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Target - Wrapper for Target specific information.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:194
An ExecutionSession represents a running JIT program.
Definition Core.h:1355
void reportError(Error Err)
Report a error for this execution session.
Definition Core.h:1490
Represents an address in the executor process.
IRLayer(ExecutionSession &ES, const IRSymbolMapper::ManglingOptions *&MO)
Definition Layer.h:70
const IRSymbolMapper::ManglingOptions *& getManglingOptions() const
Get the mangling options for this layer.
Definition Layer.h:79
IRSpeculationLayer(ExecutionSession &ES, IRLayer &BaseLayer, Speculator &Spec, MangleAndInterner &Mangle, ResultEval Interpreter)
std::function< IRlikiesStrRef(Function &)> ResultEval
std::optional< DenseMap< StringRef, DenseSet< StringRef > > > IRlikiesStrRef
DenseMap< SymbolStringPtr, SymbolNameSet > TargetAndLikelies
LLVM_ABI void trackImpls(SymbolAliasMap ImplMaps, JITDylib *SrcJD)
SymbolStringPtr Alias
Definition Speculation.h:40
DenseMap< Alias, AliaseeDetails > ImapTy
Definition Speculation.h:41
std::pair< SymbolStringPtr, JITDylib * > AliaseeDetails
Definition Speculation.h:39
Represents a JIT'd dynamic library.
Definition Core.h:902
Mangles symbol names then uniques them in the context of an ExecutionSession.
Definition Mangling.h:27
Speculator(ImplSymbolMap &Impl, ExecutionSession &ref)
ExecutionSession & getES()
Speculator & operator=(const Speculator &)=delete
Speculator & operator=(Speculator &&)=delete
DenseMap< TargetFAddr, SymbolNameSet > StubAddrLikelies
Definition Speculation.h:65
Speculator(Speculator &&)=delete
LLVM_ABI Error addSpeculationRuntime(JITDylib &JD, MangleAndInterner &Mangle)
Define symbols for this Speculator object (__orc_speculator) and the speculation runtime entry point ...
ExecutorAddr TargetFAddr
Definition Speculation.h:63
DenseMap< SymbolStringPtr, SymbolNameSet > FunctionCandidatesMap
Definition Speculation.h:64
Speculator(const Speculator &)=delete
void registerSymbols(FunctionCandidatesMap Candidates, JITDylib *JD)
void speculateFor(TargetFAddr StubAddr)
A set of symbols to look up, each associated with a SymbolLookupFlags value.
Definition Core.h:195
Pointer to a pooled string representing a symbol name.
An LLVM Module together with a shared ThreadSafeContext.
JITDylibSearchOrder makeJITDylibSearchOrder(ArrayRef< JITDylib * > JDs, JITDylibLookupFlags Flags=JITDylibLookupFlags::MatchExportedSymbolsOnly)
Convenience function for creating a search order from an ArrayRef of JITDylib*, all with the same fla...
Definition Core.h:178
LLVM_ABI RegisterDependenciesFunction NoDependenciesToRegister
This can be used as the value for a RegisterDependenciesFunction if there are no dependants to regist...
Definition Core.cpp:38
DenseMap< JITDylib *, SymbolNameSet > SymbolDependenceMap
A map from JITDylibs to sets of symbols.
DenseSet< SymbolStringPtr > SymbolNameSet
A set of symbol names (represented by SymbolStringPtrs for.
@ Ready
Emitted to memory, but waiting on transitive dependencies.
Definition Core.h:778
DenseMap< SymbolStringPtr, SymbolAliasMapEntry > SymbolAliasMap
A map of Symbols to (Symbol, Flags) pairs.
Definition Core.h:413
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
#define N