llvm.org GIT mirror llvm / 582b119
[ORC] Rename ORC layers to make the "new" ORC layers the default. This commit adds a 'Legacy' prefix to old ORC layers and utilities, and removes the '2' suffix from the new ORC layers. If you wish to continue using the old ORC layers you will need to add a 'Legacy' prefix to your classes. If you were already using the new ORC layers you will need to drop the '2' suffix. The legacy layers will remain in-tree until the new layers reach feature parity with them. This will involve adding support for removing code from the new layers, and ensuring that performance is comperable. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@344572 91177308-0d34-0410-b5e6-96231b3b80d8 Lang Hames 8 months ago
31 changed file(s) with 672 addition(s) and 672 deletion(s). Raw diff Collapse all Expand all
4141 std::shared_ptr Resolver;
4242 std::unique_ptr TM;
4343 const DataLayout DL;
44 RTDyldObjectLinkingLayer ObjectLayer;
45 IRCompileLayer CompileLayer;
44 LegacyRTDyldObjectLinkingLayer ObjectLayer;
45 LegacyIRCompileLayer CompileLayer;
4646
4747 public:
4848 KaleidoscopeJIT()
6262 TM(EngineBuilder().selectTarget()), DL(TM->createDataLayout()),
6363 ObjectLayer(ES,
6464 [this](VModuleKey) {
65 return RTDyldObjectLinkingLayer::Resources{
65 return LegacyRTDyldObjectLinkingLayer::Resources{
6666 std::make_shared(), Resolver};
6767 }),
6868 CompileLayer(ObjectLayer, SimpleCompiler(*TM)) {
4646 std::shared_ptr Resolver;
4747 std::unique_ptr TM;
4848 const DataLayout DL;
49 RTDyldObjectLinkingLayer ObjectLayer;
50 IRCompileLayer CompileLayer;
49 LegacyRTDyldObjectLinkingLayer ObjectLayer;
50 LegacyIRCompileLayer CompileLayer;
5151
5252 using OptimizeFunction =
5353 std::function(std::unique_ptr)>;
5454
55 IRTransformLayer OptimizeLayer;
55 LegacyIRTransformLayer OptimizeLayer;
5656
5757 public:
5858 KaleidoscopeJIT()
7272 TM(EngineBuilder().selectTarget()), DL(TM->createDataLayout()),
7373 ObjectLayer(ES,
7474 [this](VModuleKey) {
75 return RTDyldObjectLinkingLayer::Resources{
75 return LegacyRTDyldObjectLinkingLayer::Resources{
7676 std::make_shared(), Resolver};
7777 }),
7878 CompileLayer(ObjectLayer, SimpleCompiler(*TM)),
5050 std::map> Resolvers;
5151 std::unique_ptr TM;
5252 const DataLayout DL;
53 RTDyldObjectLinkingLayer ObjectLayer;
54 IRCompileLayer CompileLayer;
53 LegacyRTDyldObjectLinkingLayer ObjectLayer;
54 LegacyIRCompileLayer CompileLayer;
5555
5656 using OptimizeFunction =
5757 std::function(std::unique_ptr)>;
5858
59 IRTransformLayer OptimizeLayer;
59 LegacyIRTransformLayer OptimizeLayer;
6060
6161 std::unique_ptr CompileCallbackManager;
62 CompileOnDemandLayer CODLayer;
62 LegacyCompileOnDemandLayer CODLayer;
6363
6464 public:
6565 KaleidoscopeJIT()
6666 : TM(EngineBuilder().selectTarget()), DL(TM->createDataLayout()),
6767 ObjectLayer(ES,
6868 [this](VModuleKey K) {
69 return RTDyldObjectLinkingLayer::Resources{
69 return LegacyRTDyldObjectLinkingLayer::Resources{
7070 std::make_shared(),
7171 Resolvers[K]};
7272 }),
7676 std::shared_ptr Resolver;
7777 std::unique_ptr TM;
7878 const DataLayout DL;
79 RTDyldObjectLinkingLayer ObjectLayer;
80 IRCompileLayer CompileLayer;
79 LegacyRTDyldObjectLinkingLayer ObjectLayer;
80 LegacyIRCompileLayer CompileLayer;
8181
8282 using OptimizeFunction =
8383 std::function(std::unique_ptr)>;
8484
85 IRTransformLayer OptimizeLayer;
85 LegacyIRTransformLayer OptimizeLayer;
8686
8787 std::unique_ptr CompileCallbackMgr;
8888 std::unique_ptr IndirectStubsMgr;
107107 TM(EngineBuilder().selectTarget()), DL(TM->createDataLayout()),
108108 ObjectLayer(ES,
109109 [this](VModuleKey K) {
110 return RTDyldObjectLinkingLayer::Resources{
110 return LegacyRTDyldObjectLinkingLayer::Resources{
111111 std::make_shared(), Resolver};
112112 }),
113113 CompileLayer(ObjectLayer, SimpleCompiler(*TM)),
8181 std::shared_ptr Resolver;
8282 std::unique_ptr TM;
8383 const DataLayout DL;
84 RTDyldObjectLinkingLayer ObjectLayer;
85 IRCompileLayer CompileLayer;
84 LegacyRTDyldObjectLinkingLayer ObjectLayer;
85 LegacyIRCompileLayer CompileLayer;
8686
8787 using OptimizeFunction =
8888 std::function(std::unique_ptr)>;
8989
90 IRTransformLayer OptimizeLayer;
90 LegacyIRTransformLayer OptimizeLayer;
9191
9292 JITCompileCallbackManager *CompileCallbackMgr;
9393 std::unique_ptr IndirectStubsMgr;
115115 DL(TM->createDataLayout()),
116116 ObjectLayer(ES,
117117 [this](VModuleKey K) {
118 return RTDyldObjectLinkingLayer::Resources{
118 return LegacyRTDyldObjectLinkingLayer::Resources{
119119 cantFail(this->Remote.createRemoteMemoryManager()),
120120 Resolver};
121121 }),
3939
4040 class KaleidoscopeJIT {
4141 public:
42 using ObjLayerT = RTDyldObjectLinkingLayer;
43 using CompileLayerT = IRCompileLayer;
42 using ObjLayerT = LegacyRTDyldObjectLinkingLayer;
43 using CompileLayerT = LegacyIRCompileLayer;
4444
4545 KaleidoscopeJIT()
4646 : Resolver(createLegacyLookupResolver(
6161
6262 class ExtractingIRMaterializationUnit;
6363
64 class CompileOnDemandLayer2 : public IRLayer {
64 class CompileOnDemandLayer : public IRLayer {
6565 friend class PartitioningIRMaterializationUnit;
6666
6767 public:
8383 /// symbol in them is requested.
8484 static Optional compileWholeModule(GlobalValueSet Requested);
8585
86 /// Construct a CompileOnDemandLayer2.
87 CompileOnDemandLayer2(ExecutionSession &ES, IRLayer &BaseLayer,
86 /// Construct a CompileOnDemandLayer.
87 CompileOnDemandLayer(ExecutionSession &ES, IRLayer &BaseLayer,
8888 LazyCallThroughManager &LCTMgr,
8989 IndirectStubsManagerBuilder BuildIndirectStubsManager);
9090
141141 template
142142 typename CompileCallbackMgrT = JITCompileCallbackManager,
143143 typename IndirectStubsMgrT = IndirectStubsManager>
144 class CompileOnDemandLayer {
144 class LegacyCompileOnDemandLayer {
145145 private:
146146 template
147147 class LambdaMaterializer final : public ValueMaterializer {
265265 std::function R)>;
266266
267267 /// Construct a compile-on-demand layer instance.
268 CompileOnDemandLayer(ExecutionSession &ES, BaseLayerT &BaseLayer,
269 SymbolResolverGetter GetSymbolResolver,
270 SymbolResolverSetter SetSymbolResolver,
271 PartitioningFtor Partition,
272 CompileCallbackMgrT &CallbackMgr,
273 IndirectStubsManagerBuilderT CreateIndirectStubsManager,
274 bool CloneStubsIntoPartitions = true)
268 LegacyCompileOnDemandLayer(ExecutionSession &ES, BaseLayerT &BaseLayer,
269 SymbolResolverGetter GetSymbolResolver,
270 SymbolResolverSetter SetSymbolResolver,
271 PartitioningFtor Partition,
272 CompileCallbackMgrT &CallbackMgr,
273 IndirectStubsManagerBuilderT CreateIndirectStubsManager,
274 bool CloneStubsIntoPartitions = true)
275275 : ES(ES), BaseLayer(BaseLayer),
276276 GetSymbolResolver(std::move(GetSymbolResolver)),
277277 SetSymbolResolver(std::move(SetSymbolResolver)),
279279 CreateIndirectStubsManager(std::move(CreateIndirectStubsManager)),
280280 CloneStubsIntoPartitions(CloneStubsIntoPartitions) {}
281281
282 ~CompileOnDemandLayer() {
282 ~LegacyCompileOnDemandLayer() {
283283 // FIXME: Report error on log.
284284 while (!LogicalDylibs.empty())
285285 consumeError(removeModule(LogicalDylibs.begin()->first));
9393 /// Convenience class for recording constructor/destructor names for
9494 /// later execution.
9595 template
96 class CtorDtorRunner {
96 class LegacyCtorDtorRunner {
9797 public:
9898 /// Construct a CtorDtorRunner for the given range using the given
9999 /// name mangling function.
100 CtorDtorRunner(std::vector CtorDtorNames, VModuleKey K)
100 LegacyCtorDtorRunner(std::vector CtorDtorNames, VModuleKey K)
101101 : CtorDtorNames(std::move(CtorDtorNames)), K(K) {}
102102
103103 /// Run the recorded constructors/destructors through the given JIT
128128 orc::VModuleKey K;
129129 };
130130
131 class CtorDtorRunner2 {
132 public:
133 CtorDtorRunner2(JITDylib &JD) : JD(JD) {}
131 class CtorDtorRunner {
132 public:
133 CtorDtorRunner(JITDylib &JD) : JD(JD) {}
134134 void add(iterator_range CtorDtors);
135135 Error run();
136136
176176 void *DSOHandle);
177177 };
178178
179 class LocalCXXRuntimeOverrides : public LocalCXXRuntimeOverridesBase {
179 class LegacyLocalCXXRuntimeOverrides : public LocalCXXRuntimeOverridesBase {
180180 public:
181181 /// Create a runtime-overrides class.
182182 template
183 LocalCXXRuntimeOverrides(const MangleFtorT &Mangle) {
183 LegacyLocalCXXRuntimeOverrides(const MangleFtorT &Mangle) {
184184 addOverride(Mangle("__dso_handle"), toTargetAddress(&DSOHandleOverride));
185185 addOverride(Mangle("__cxa_atexit"), toTargetAddress(&CXAAtExitOverride));
186186 }
201201 StringMap CXXRuntimeOverrides;
202202 };
203203
204 class LocalCXXRuntimeOverrides2 : public LocalCXXRuntimeOverridesBase {
204 class LocalCXXRuntimeOverrides : public LocalCXXRuntimeOverridesBase {
205205 public:
206206 Error enable(JITDylib &JD, MangleAndInterner &Mangler);
207207 };
2727
2828 namespace orc {
2929
30 class IRCompileLayer2 : public IRLayer {
30 class IRCompileLayer : public IRLayer {
3131 public:
3232 using CompileFunction =
3333 std::function>(Module &)>;
3535 using NotifyCompiledFunction =
3636 std::function;
3737
38 IRCompileLayer2(ExecutionSession &ES, ObjectLayer &BaseLayer,
39 CompileFunction Compile);
38 IRCompileLayer(ExecutionSession &ES, ObjectLayer &BaseLayer,
39 CompileFunction Compile);
4040
4141 void setNotifyCompiled(NotifyCompiledFunction NotifyCompiled);
4242
5656 /// object file and adds this module file to the layer below, which must
5757 /// implement the object layer concept.
5858 template
59 class IRCompileLayer {
59 class LegacyIRCompileLayer {
6060 public:
6161 /// Callback type for notifications when modules are compiled.
6262 using NotifyCompiledCallback =
6363 std::function)>;
6464
65 /// Construct an IRCompileLayer with the given BaseLayer, which must
65 /// Construct an LegacyIRCompileLayer with the given BaseLayer, which must
6666 /// implement the ObjectLayer concept.
67 IRCompileLayer(
67 LegacyIRCompileLayer(
6868 BaseLayerT &BaseLayer, CompileFtor Compile,
6969 NotifyCompiledCallback NotifyCompiled = NotifyCompiledCallback())
7070 : BaseLayer(BaseLayer), Compile(std::move(Compile)),
2222 class Module;
2323 namespace orc {
2424
25 class IRTransformLayer2 : public IRLayer {
25 class IRTransformLayer : public IRLayer {
2626 public:
2727 using TransformFunction = std::function(
2828 ThreadSafeModule, const MaterializationResponsibility &R)>;
2929
30 IRTransformLayer2(ExecutionSession &ES, IRLayer &BaseLayer,
31 TransformFunction Transform = identityTransform);
30 IRTransformLayer(ExecutionSession &ES, IRLayer &BaseLayer,
31 TransformFunction Transform = identityTransform);
3232
3333 void setTransform(TransformFunction Transform) {
3434 this->Transform = std::move(Transform);
5353 /// This layer applies a user supplied transform to each module that is added,
5454 /// then adds the transformed module to the layer below.
5555 template
56 class IRTransformLayer {
56 class LegacyIRTransformLayer {
5757 public:
5858
59 /// Construct an IRTransformLayer with the given BaseLayer
60 IRTransformLayer(BaseLayerT &BaseLayer,
59 /// Construct an LegacyIRTransformLayer with the given BaseLayer
60 LegacyIRTransformLayer(BaseLayerT &BaseLayer,
6161 TransformFtor Transform = TransformFtor())
6262 : BaseLayer(BaseLayer), Transform(std::move(Transform)) {}
6363
9898 Error runDestructors() { return DtorRunner.run(); }
9999
100100 /// Returns a reference to the ObjLinkingLayer
101 RTDyldObjectLinkingLayer2 &getObjLinkingLayer() { return ObjLinkingLayer; }
101 RTDyldObjectLinkingLayer &getObjLinkingLayer() { return ObjLinkingLayer; }
102102
103103 protected:
104104
124124 DataLayout DL;
125125 std::unique_ptr CompileThreads;
126126
127 RTDyldObjectLinkingLayer2 ObjLinkingLayer;
128 IRCompileLayer2 CompileLayer;
127 RTDyldObjectLinkingLayer ObjLinkingLayer;
128 IRCompileLayer CompileLayer;
129129
130 CtorDtorRunner2 CtorRunner, DtorRunner;
130 CtorDtorRunner CtorRunner, DtorRunner;
131131 };
132132
133133 /// An extended version of LLJIT that supports lazy function-at-a-time
144144
145145 /// Set an IR transform (e.g. pass manager pipeline) to run on each function
146146 /// when it is compiled.
147 void setLazyCompileTransform(IRTransformLayer2::TransformFunction Transform) {
147 void setLazyCompileTransform(IRTransformLayer::TransformFunction Transform) {
148148 TransformLayer.setTransform(std::move(Transform));
149149 }
150150
151151 /// Sets the partition function.
152152 void
153 setPartitionFunction(CompileOnDemandLayer2::PartitionFunction Partition) {
153 setPartitionFunction(CompileOnDemandLayer::PartitionFunction Partition) {
154154 CODLayer.setPartitionFunction(std::move(Partition));
155155 }
156156
179179 std::unique_ptr LCTMgr;
180180 std::function()> ISMBuilder;
181181
182 IRTransformLayer2 TransformLayer;
183 CompileOnDemandLayer2 CODLayer;
182 IRTransformLayer TransformLayer;
183 CompileOnDemandLayer CODLayer;
184184 };
185185
186186 } // End namespace orc
2222 namespace llvm {
2323 namespace orc {
2424
25 class ObjectTransformLayer2 : public ObjectLayer {
25 class ObjectTransformLayer : public ObjectLayer {
2626 public:
2727 using TransformFunction =
2828 std::function>(
2929 std::unique_ptr)>;
3030
31 ObjectTransformLayer2(ExecutionSession &ES, ObjectLayer &BaseLayer,
32 TransformFunction Transform);
31 ObjectTransformLayer(ExecutionSession &ES, ObjectLayer &BaseLayer,
32 TransformFunction Transform);
3333
3434 void emit(MaterializationResponsibility R, VModuleKey K,
3535 std::unique_ptr O) override;
4545 /// immediately applies the user supplied functor to each object, then adds
4646 /// the set of transformed objects to the layer below.
4747 template
48 class ObjectTransformLayer {
48 class LegacyObjectTransformLayer {
4949 public:
5050 /// Construct an ObjectTransformLayer with the given BaseLayer
51 ObjectTransformLayer(BaseLayerT &BaseLayer,
52 TransformFtor Transform = TransformFtor())
51 LegacyObjectTransformLayer(BaseLayerT &BaseLayer,
52 TransformFtor Transform = TransformFtor())
5353 : BaseLayer(BaseLayer), Transform(std::move(Transform)) {}
5454
5555 /// Apply the transform functor to each object in the object set, then
3535 namespace llvm {
3636 namespace orc {
3737
38 class RTDyldObjectLinkingLayer2 : public ObjectLayer {
38 class RTDyldObjectLinkingLayer : public ObjectLayer {
3939 public:
4040 /// Functor for receiving object-loaded notifications.
4141 using NotifyLoadedFunction =
5050
5151 /// Construct an ObjectLinkingLayer with the given NotifyLoaded,
5252 /// and NotifyEmitted functors.
53 RTDyldObjectLinkingLayer2(
53 RTDyldObjectLinkingLayer(
5454 ExecutionSession &ES, GetMemoryManagerFunction GetMemoryManager,
5555 NotifyLoadedFunction NotifyLoaded = NotifyLoadedFunction(),
5656 NotifyEmittedFunction NotifyEmitted = NotifyEmittedFunction());
6565 /// the memory manager, rather than just the sections required for execution.
6666 ///
6767 /// This is kludgy, and may be removed in the future.
68 RTDyldObjectLinkingLayer2 &setProcessAllSections(bool ProcessAllSections) {
68 RTDyldObjectLinkingLayer &setProcessAllSections(bool ProcessAllSections) {
6969 this->ProcessAllSections = ProcessAllSections;
7070 return *this;
7171 }
7878 ///
7979 /// FIXME: We should be able to remove this if/when COFF properly tracks
8080 /// exported symbols.
81 RTDyldObjectLinkingLayer2 &
81 RTDyldObjectLinkingLayer &
8282 setOverrideObjectFlagsWithResponsibilityFlags(bool OverrideObjectFlags) {
8383 this->OverrideObjectFlags = OverrideObjectFlags;
8484 return *this;
8585 }
8686
87 /// If set, this RTDyldObjectLinkingLayer2 instance will claim responsibility
87 /// If set, this RTDyldObjectLinkingLayer instance will claim responsibility
8888 /// for any symbols provided by a given object file that were not already in
8989 /// the MaterializationResponsibility instance. Setting this flag allows
9090 /// higher-level program representations (e.g. LLVM IR) to be added based on
9595 /// deterministically). If this option is set, clashes for the additional
9696 /// symbols may not be detected until late, and detection may depend on
9797 /// the flow of control through JIT'd code. Use with care.
98 RTDyldObjectLinkingLayer2 &
98 RTDyldObjectLinkingLayer &
9999 setAutoClaimResponsibilityForObjectSymbols(bool AutoClaimObjectSymbols) {
100100 this->AutoClaimObjectSymbols = AutoClaimObjectSymbols;
101101 return *this;
120120 std::map> MemMgrs;
121121 };
122122
123 class RTDyldObjectLinkingLayerBase {
123 class LegacyRTDyldObjectLinkingLayerBase {
124124 public:
125125 using ObjectPtr = std::unique_ptr;
126126
172172 /// object files to be loaded into memory, linked, and the addresses of their
173173 /// symbols queried. All objects added to this layer can see each other's
174174 /// symbols.
175 class RTDyldObjectLinkingLayer : public RTDyldObjectLinkingLayerBase {
175 class LegacyRTDyldObjectLinkingLayer : public LegacyRTDyldObjectLinkingLayerBase {
176176 public:
177177
178 using RTDyldObjectLinkingLayerBase::ObjectPtr;
178 using LegacyRTDyldObjectLinkingLayerBase::ObjectPtr;
179179
180180 /// Functor for receiving object-loaded notifications.
181181 using NotifyLoadedFtor =
196196 template
197197 class ConcreteLinkedObject : public LinkedObject {
198198 public:
199 ConcreteLinkedObject(RTDyldObjectLinkingLayer &Parent, VModuleKey K,
199 ConcreteLinkedObject(LegacyRTDyldObjectLinkingLayer &Parent, VModuleKey K,
200200 OwnedObject Obj, MemoryManagerPtrT MemMgr,
201201 std::shared_ptr Resolver,
202202 bool ProcessAllSections)
312312 };
313313
314314 VModuleKey K;
315 RTDyldObjectLinkingLayer &Parent;
315 LegacyRTDyldObjectLinkingLayer &Parent;
316316 MemoryManagerPtrT MemMgr;
317317 OwnedObject ObjForNotify;
318318 std::unique_ptr PFC;
320320
321321 template
322322 std::unique_ptr>
323 createLinkedObject(RTDyldObjectLinkingLayer &Parent, VModuleKey K,
323 createLinkedObject(LegacyRTDyldObjectLinkingLayer &Parent, VModuleKey K,
324324 OwnedObject Obj, MemoryManagerPtrT MemMgr,
325325 std::shared_ptr Resolver,
326326 bool ProcessAllSections) {
340340
341341 /// Construct an ObjectLinkingLayer with the given NotifyLoaded,
342342 /// and NotifyFinalized functors.
343 RTDyldObjectLinkingLayer(
343 LegacyRTDyldObjectLinkingLayer(
344344 ExecutionSession &ES, ResourcesGetter GetResources,
345345 NotifyLoadedFtor NotifyLoaded = NotifyLoadedFtor(),
346346 NotifyFinalizedFtor NotifyFinalized = NotifyFinalizedFtor(),
6767 class PartitioningIRMaterializationUnit : public IRMaterializationUnit {
6868 public:
6969 PartitioningIRMaterializationUnit(ExecutionSession &ES, ThreadSafeModule TSM,
70 CompileOnDemandLayer2 &Parent)
70 CompileOnDemandLayer &Parent)
7171 : IRMaterializationUnit(ES, std::move(TSM)), Parent(Parent) {}
7272
7373 PartitioningIRMaterializationUnit(
7474 ThreadSafeModule TSM, SymbolFlagsMap SymbolFlags,
7575 SymbolNameToDefinitionMap SymbolToDefinition,
76 CompileOnDemandLayer2 &Parent)
76 CompileOnDemandLayer &Parent)
7777 : IRMaterializationUnit(std::move(TSM), std::move(SymbolFlags),
7878 std::move(SymbolToDefinition)),
7979 Parent(Parent) {}
9292 }
9393
9494 mutable std::mutex SourceModuleMutex;
95 CompileOnDemandLayer2 &Parent;
95 CompileOnDemandLayer &Parent;
9696 };
9797
98 Optional
99 CompileOnDemandLayer2::compileRequested(GlobalValueSet Requested) {
98 Optional
99 CompileOnDemandLayer::compileRequested(GlobalValueSet Requested) {
100100 return std::move(Requested);
101101 }
102102
103 Optional
104 CompileOnDemandLayer2::compileWholeModule(GlobalValueSet Requested) {
103 Optional
104 CompileOnDemandLayer::compileWholeModule(GlobalValueSet Requested) {
105105 return None;
106106 }
107107
108 CompileOnDemandLayer2::CompileOnDemandLayer2(
108 CompileOnDemandLayer::CompileOnDemandLayer(
109109 ExecutionSession &ES, IRLayer &BaseLayer, LazyCallThroughManager &LCTMgr,
110110 IndirectStubsManagerBuilder BuildIndirectStubsManager)
111111 : IRLayer(ES), BaseLayer(BaseLayer), LCTMgr(LCTMgr),
112112 BuildIndirectStubsManager(std::move(BuildIndirectStubsManager)) {}
113113
114 void CompileOnDemandLayer2::setPartitionFunction(PartitionFunction Partition) {
114 void CompileOnDemandLayer::setPartitionFunction(PartitionFunction Partition) {
115115 this->Partition = std::move(Partition);
116116 }
117117
118 void CompileOnDemandLayer2::emit(MaterializationResponsibility R, VModuleKey K,
118 void CompileOnDemandLayer::emit(MaterializationResponsibility R, VModuleKey K,
119119 ThreadSafeModule TSM) {
120120 assert(TSM.getModule() && "Null module");
121121
159159 std::move(Callables)));
160160 }
161161
162 CompileOnDemandLayer2::PerDylibResources &
163 CompileOnDemandLayer2::getPerDylibResources(JITDylib &TargetD) {
162 CompileOnDemandLayer::PerDylibResources &
163 CompileOnDemandLayer::getPerDylibResources(JITDylib &TargetD) {
164164 auto I = DylibResources.find(&TargetD);
165165 if (I == DylibResources.end()) {
166166 auto &ImplD =
175175 return I->second;
176176 }
177177
178 void CompileOnDemandLayer2::cleanUpModule(Module &M) {
178 void CompileOnDemandLayer::cleanUpModule(Module &M) {
179179 for (auto &F : M.functions()) {
180180 if (F.isDeclaration())
181181 continue;
188188 }
189189 }
190190
191 void CompileOnDemandLayer2::expandPartition(GlobalValueSet &Partition) {
191 void CompileOnDemandLayer::expandPartition(GlobalValueSet &Partition) {
192192 // Expands the partition to ensure the following rules hold:
193193 // (1) If any alias is in the partition, its aliasee is also in the partition.
194194 // (2) If any aliasee is in the partition, its aliases are also in the
220220 Partition.insert(GV);
221221 }
222222
223 void CompileOnDemandLayer2::emitPartition(
223 void CompileOnDemandLayer::emitPartition(
224224 MaterializationResponsibility R, ThreadSafeModule TSM,
225225 IRMaterializationUnit::SymbolNameToDefinitionMap Defs) {
226226
8686 CtorDtorIterator(DtorsList, true));
8787 }
8888
89 void CtorDtorRunner2::add(iterator_range CtorDtors) {
89 void CtorDtorRunner::add(iterator_range CtorDtors) {
9090 if (CtorDtors.begin() == CtorDtors.end())
9191 return;
9292
114114 }
115115 }
116116
117 Error CtorDtorRunner2::run() {
117 Error CtorDtorRunner::run() {
118118 using CtorDtorTy = void (*)();
119119
120120 SymbolNameSet Names;
164164 return 0;
165165 }
166166
167 Error LocalCXXRuntimeOverrides2::enable(JITDylib &JD,
167 Error LocalCXXRuntimeOverrides::enable(JITDylib &JD,
168168 MangleAndInterner &Mangle) {
169169 SymbolMap RuntimeInterposes;
170170 RuntimeInterposes[Mangle("__dso_handle")] =
1111 namespace llvm {
1212 namespace orc {
1313
14 IRCompileLayer2::IRCompileLayer2(ExecutionSession &ES, ObjectLayer &BaseLayer,
14 IRCompileLayer::IRCompileLayer(ExecutionSession &ES, ObjectLayer &BaseLayer,
1515 CompileFunction Compile)
1616 : IRLayer(ES), BaseLayer(BaseLayer), Compile(std::move(Compile)) {}
1717
18 void IRCompileLayer2::setNotifyCompiled(NotifyCompiledFunction NotifyCompiled) {
18 void IRCompileLayer::setNotifyCompiled(NotifyCompiledFunction NotifyCompiled) {
1919 std::lock_guard Lock(IRLayerMutex);
2020 this->NotifyCompiled = std::move(NotifyCompiled);
2121 }
2222
23 void IRCompileLayer2::emit(MaterializationResponsibility R, VModuleKey K,
23 void IRCompileLayer::emit(MaterializationResponsibility R, VModuleKey K,
2424 ThreadSafeModule TSM) {
2525 assert(TSM.getModule() && "Module must not be null");
2626
1212 namespace llvm {
1313 namespace orc {
1414
15 IRTransformLayer2::IRTransformLayer2(ExecutionSession &ES,
15 IRTransformLayer::IRTransformLayer(ExecutionSession &ES,
1616 IRLayer &BaseLayer,
1717 TransformFunction Transform)
1818 : IRLayer(ES), BaseLayer(BaseLayer), Transform(std::move(Transform)) {}
1919
20 void IRTransformLayer2::emit(MaterializationResponsibility R, VModuleKey K,
20 void IRTransformLayer::emit(MaterializationResponsibility R, VModuleKey K,
2121 ThreadSafeModule TSM) {
2222 assert(TSM.getModule() && "Module must not be null");
2323
2020 : llvm::orc::SimpleCompiler(*TM), TM(std::move(TM)) {}
2121 private:
2222 // FIXME: shared because std::functions (and thus
23 // IRCompileLayer2::CompileFunction) are not moveable.
23 // IRCompileLayer::CompileFunction) are not moveable.
2424 std::shared_ptr TM;
2525 };
2626
1212 namespace llvm {
1313 namespace orc {
1414
15 ObjectTransformLayer2::ObjectTransformLayer2(ExecutionSession &ES,
16 ObjectLayer &BaseLayer,
17 TransformFunction Transform)
15 ObjectTransformLayer::ObjectTransformLayer(ExecutionSession &ES,
16 ObjectLayer &BaseLayer,
17 TransformFunction Transform)
1818 : ObjectLayer(ES), BaseLayer(BaseLayer), Transform(std::move(Transform)) {}
1919
20 void ObjectTransformLayer2::emit(MaterializationResponsibility R, VModuleKey K,
21 std::unique_ptr O) {
20 void ObjectTransformLayer::emit(MaterializationResponsibility R, VModuleKey K,
21 std::unique_ptr O) {
2222 assert(O && "Module must not be null");
2323
2424 if (auto TransformedObj = Transform(std::move(O)))
7676 };
7777
7878 template <>
79 class GenericLayerImplRTDyldObjectLinkingLayer> : public GenericLayer {
79 class GenericLayerImplLegacyRTDyldObjectLinkingLayer> : public GenericLayer {
8080 private:
81 using LayerT = orc::RTDyldObjectLinkingLayer;
81 using LayerT = orc::LegacyRTDyldObjectLinkingLayer;
8282 public:
8383 GenericLayerImpl(LayerT &Layer) : Layer(Layer) {}
8484
106106 public:
107107
108108 using CompileCallbackMgr = orc::JITCompileCallbackManager;
109 using ObjLayerT = orc::RTDyldObjectLinkingLayer;
110 using CompileLayerT = orc::IRCompileLayer;
109 using ObjLayerT = orc::LegacyRTDyldObjectLinkingLayer;
110 using CompileLayerT = orc::LegacyIRCompileLayer;
111111 using CODLayerT =
112 orc::CompileOnDemandLayer;
112 orc::LegacyCompileOnDemandLayer;
113113
114114 using CallbackManagerBuilder =
115115 std::function()>;
311311
312312 // Run the static constructors, and save the static destructor runner for
313313 // execution when the JIT is torn down.
314 orc::CtorDtorRunner CtorRunner(std::move(CtorNames), K);
314 orc::LegacyCtorDtorRunner CtorRunner(std::move(CtorNames), K);
315315 if (auto Err = CtorRunner.runViaLayer(*this))
316316 return std::move(Err);
317317
516516
517517 std::map> KeyLayers;
518518
519 orc::LocalCXXRuntimeOverrides CXXRuntimeOverrides;
520 std::vector> IRStaticDestructorRunners;
519 orc::LegacyLocalCXXRuntimeOverrides CXXRuntimeOverrides;
520 std::vector> IRStaticDestructorRunners;
521521 std::string ErrMsg;
522522
523523 ResolverMap Resolvers;
127127 auto &CtorDtorsMap = isDtors ? UnexecutedDestructors : UnexecutedConstructors;
128128
129129 for (auto &KV : CtorDtorsMap)
130 cantFail(CtorDtorRunner(std::move(KV.second), KV.first)
130 cantFail(LegacyCtorDtorRunner(std::move(KV.second), KV.first)
131131 .runViaLayer(LazyEmitLayer));
132132
133133 CtorDtorsMap.clear();
460460 return MangledName;
461461 }
462462
463 using ObjectLayerT = RTDyldObjectLinkingLayer;
464 using CompileLayerT = IRCompileLayer;
463 using ObjectLayerT = LegacyRTDyldObjectLinkingLayer;
464 using CompileLayerT = LegacyIRCompileLayer;
465465 using LazyEmitLayerT = LazyEmittingLayer;
466466
467467 ExecutionSession ES;
7575 namespace llvm {
7676 namespace orc {
7777
78 RTDyldObjectLinkingLayer2::RTDyldObjectLinkingLayer2(
78 RTDyldObjectLinkingLayer::RTDyldObjectLinkingLayer(
7979 ExecutionSession &ES, GetMemoryManagerFunction GetMemoryManager,
8080 NotifyLoadedFunction NotifyLoaded, NotifyEmittedFunction NotifyEmitted)
8181 : ObjectLayer(ES), GetMemoryManager(GetMemoryManager),
8282 NotifyLoaded(std::move(NotifyLoaded)),
8383 NotifyEmitted(std::move(NotifyEmitted)) {}
8484
85 void RTDyldObjectLinkingLayer2::emit(MaterializationResponsibility R,
85 void RTDyldObjectLinkingLayer::emit(MaterializationResponsibility R,
8686 VModuleKey K,
8787 std::unique_ptr O) {
8888 assert(O && "Object must not be null");
152152 });
153153 }
154154
155 Error RTDyldObjectLinkingLayer2::onObjLoad(
155 Error RTDyldObjectLinkingLayer::onObjLoad(
156156 VModuleKey K, MaterializationResponsibility &R, object::ObjectFile &Obj,
157157 std::unique_ptr LoadedObjInfo,
158158 std::map Resolved,
195195 return Error::success();
196196 }
197197
198 void RTDyldObjectLinkingLayer2::onObjEmit(VModuleKey K,
198 void RTDyldObjectLinkingLayer::onObjEmit(VModuleKey K,
199199 MaterializationResponsibility &R,
200200 Error Err) {
201201 if (Err) {
695695 return Result;
696696 }
697697
698 static orc::IRTransformLayer2::TransformFunction createDebugDumper() {
698 static orc::IRTransformLayer::TransformFunction createDebugDumper() {
699699 switch (OrcDumpKind) {
700700 case DumpKind::NoDump:
701701 return [](orc::ThreadSafeModule TSM,
780780 auto J = ExitOnErr(orc::LLLazyJIT::Create(std::move(JTMB), DL, LazyJITCompileThreads));
781781
782782 if (PerModuleLazy)
783 J->setPartitionFunction(orc::CompileOnDemandLayer2::compileWholeModule);
783 J->setPartitionFunction(orc::CompileOnDemandLayer::compileWholeModule);
784784
785785 auto Dump = createDebugDumper();
786786
796796 ExitOnErr(orc::DynamicLibrarySearchGenerator::GetForCurrentProcess(DL)));
797797
798798 orc::MangleAndInterner Mangle(J->getExecutionSession(), DL);
799 orc::LocalCXXRuntimeOverrides2 CXXRuntimeOverrides;
799 orc::LocalCXXRuntimeOverrides CXXRuntimeOverrides;
800800 ExitOnErr(CXXRuntimeOverrides.enable(J->getMainJITDylib(), Mangle));
801801
802802 // Add the main module.
99 )
1010
1111 add_llvm_unittest(OrcJITTests
12 CompileOnDemandLayerTest.cpp
1312 CoreAPIsTest.cpp
1413 IndirectionUtilsTest.cpp
1514 GlobalMappingLayerTest.cpp
1716 LazyCallThroughAndReexportsTest.cpp
1817 LazyEmittingLayerTest.cpp
1918 LegacyAPIInteropTest.cpp
19 LegacyCompileOnDemandLayerTest.cpp
20 LegacyRTDyldObjectLinkingLayerTest.cpp
2021 ObjectTransformLayerTest.cpp
2122 OrcCAPITest.cpp
2223 OrcTestCommon.cpp
2425 RemoteObjectLayerTest.cpp
2526 RPCUtilsTest.cpp
2627 RTDyldObjectLinkingLayerTest.cpp
27 RTDyldObjectLinkingLayer2Test.cpp
2828 SymbolStringPoolTest.cpp
2929 ThreadSafeModuleTest.cpp
3030 )
+0
-89
unittests/ExecutionEngine/Orc/CompileOnDemandLayerTest.cpp less more
None //===----- CompileOnDemandLayerTest.cpp - Unit tests for the COD layer ----===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h"
10 #include "OrcTestCommon.h"
11 #include "gtest/gtest.h"
12
13 using namespace llvm;
14 using namespace llvm::orc;
15
16 namespace {
17
18 class DummyTrampolinePool : public orc::TrampolinePool {
19 public:
20 Expected getTrampoline() {
21 llvm_unreachable("Unimplemented");
22 }
23 };
24
25 class DummyCallbackManager : public JITCompileCallbackManager {
26 public:
27 DummyCallbackManager(ExecutionSession &ES)
28 : JITCompileCallbackManager(llvm::make_unique(), ES,
29 0) {}
30 };
31
32 class DummyStubsManager : public orc::IndirectStubsManager {
33 public:
34 Error createStub(StringRef StubName, JITTargetAddress InitAddr,
35 JITSymbolFlags Flags) override {
36 llvm_unreachable("Not implemented");
37 }
38
39 Error createStubs(const StubInitsMap &StubInits) override {
40 llvm_unreachable("Not implemented");
41 }
42
43 JITEvaluatedSymbol findStub(StringRef Name, bool ExportedStubsOnly) override {
44 llvm_unreachable("Not implemented");
45 }
46
47 JITEvaluatedSymbol findPointer(StringRef Name) override {
48 llvm_unreachable("Not implemented");
49 }
50
51 Error updatePointer(StringRef Name, JITTargetAddress NewAddr) override {
52 llvm_unreachable("Not implemented");
53 }
54 };
55
56 TEST(CompileOnDemandLayerTest, FindSymbol) {
57 MockBaseLayer> TestBaseLayer;
58 TestBaseLayer.findSymbolImpl =
59 [](const std::string &Name, bool) {
60 if (Name == "foo")
61 return JITSymbol(1, JITSymbolFlags::Exported);
62 return JITSymbol(nullptr);
63 };
64
65
66 ExecutionSession ES(std::make_shared());
67 DummyCallbackManager CallbackMgr(ES);
68
69 auto GetResolver =
70 [](orc::VModuleKey) -> std::shared_ptr {
71 llvm_unreachable("Should never be called");
72 };
73
74 auto SetResolver = [](orc::VModuleKey, std::shared_ptr) {
75 llvm_unreachable("Should never be called");
76 };
77
78 llvm::orc::CompileOnDemandLayer COD(
79 ES, TestBaseLayer, GetResolver, SetResolver,
80 [](Function &F) { return std::set{&F}; }, CallbackMgr,
81 [] { return llvm::make_unique(); }, true);
82
83 auto Sym = COD.findSymbol("foo", true);
84
85 EXPECT_TRUE(!!Sym) << "CompileOnDemand::findSymbol should call findSymbol in "
86 "the base layer.";
87 }
88 }
0 //===----- CompileOnDemandLayerTest.cpp - Unit tests for the COD layer ----===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h"
10 #include "OrcTestCommon.h"
11 #include "gtest/gtest.h"
12
13 using namespace llvm;
14 using namespace llvm::orc;
15
16 namespace {
17
18 class DummyTrampolinePool : public orc::TrampolinePool {
19 public:
20 Expected getTrampoline() {
21 llvm_unreachable("Unimplemented");
22 }
23 };
24
25 class DummyCallbackManager : public JITCompileCallbackManager {
26 public:
27 DummyCallbackManager(ExecutionSession &ES)
28 : JITCompileCallbackManager(llvm::make_unique(), ES,
29 0) {}
30 };
31
32 class DummyStubsManager : public orc::IndirectStubsManager {
33 public:
34 Error createStub(StringRef StubName, JITTargetAddress InitAddr,
35 JITSymbolFlags Flags) override {
36 llvm_unreachable("Not implemented");
37 }
38
39 Error createStubs(const StubInitsMap &StubInits) override {
40 llvm_unreachable("Not implemented");
41 }
42
43 JITEvaluatedSymbol findStub(StringRef Name, bool ExportedStubsOnly) override {
44 llvm_unreachable("Not implemented");
45 }
46
47 JITEvaluatedSymbol findPointer(StringRef Name) override {
48 llvm_unreachable("Not implemented");
49 }
50
51 Error updatePointer(StringRef Name, JITTargetAddress NewAddr) override {
52 llvm_unreachable("Not implemented");
53 }
54 };
55
56 TEST(LegacyCompileOnDemandLayerTest, FindSymbol) {
57 MockBaseLayer> TestBaseLayer;
58 TestBaseLayer.findSymbolImpl =
59 [](const std::string &Name, bool) {
60 if (Name == "foo")
61 return JITSymbol(1, JITSymbolFlags::Exported);
62 return JITSymbol(nullptr);
63 };
64
65
66 ExecutionSession ES(std::make_shared());
67 DummyCallbackManager CallbackMgr(ES);
68
69 auto GetResolver =
70 [](orc::VModuleKey) -> std::shared_ptr {
71 llvm_unreachable("Should never be called");
72 };
73
74 auto SetResolver = [](orc::VModuleKey, std::shared_ptr) {
75 llvm_unreachable("Should never be called");
76 };
77
78 llvm::orc::LegacyCompileOnDemandLayer COD(
79 ES, TestBaseLayer, GetResolver, SetResolver,
80 [](Function &F) { return std::set{&F}; }, CallbackMgr,
81 [] { return llvm::make_unique(); }, true);
82
83 auto Sym = COD.findSymbol("foo", true);
84
85 EXPECT_TRUE(!!Sym) << "CompileOnDemand::findSymbol should call findSymbol in "
86 "the base layer.";
87 }
88 }
0 //===- RTDyldObjectLinkingLayerTest.cpp - RTDyld linking layer unit tests -===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
10 #include "OrcTestCommon.h"
11 #include "llvm/ExecutionEngine/ExecutionEngine.h"
12 #include "llvm/ExecutionEngine/Orc/CompileUtils.h"
13 #include "llvm/ExecutionEngine/Orc/LambdaResolver.h"
14 #include "llvm/ExecutionEngine/Orc/Legacy.h"
15 #include "llvm/ExecutionEngine/Orc/NullResolver.h"
16 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "gtest/gtest.h"
20
21 using namespace llvm;
22 using namespace llvm::orc;
23
24 namespace {
25
26 class LegacyRTDyldObjectLinkingLayerExecutionTest : public testing::Test,
27 public OrcExecutionTest {
28
29 };
30
31 class SectionMemoryManagerWrapper : public SectionMemoryManager {
32 public:
33 int FinalizationCount = 0;
34 int NeedsToReserveAllocationSpaceCount = 0;
35
36 bool needsToReserveAllocationSpace() override {
37 ++NeedsToReserveAllocationSpaceCount;
38 return SectionMemoryManager::needsToReserveAllocationSpace();
39 }
40
41 bool finalizeMemory(std::string *ErrMsg = nullptr) override {
42 ++FinalizationCount;
43 return SectionMemoryManager::finalizeMemory(ErrMsg);
44 }
45 };
46
47 TEST(LegacyRTDyldObjectLinkingLayerTest, TestSetProcessAllSections) {
48 class MemoryManagerWrapper : public SectionMemoryManager {
49 public:
50 MemoryManagerWrapper(bool &DebugSeen) : DebugSeen(DebugSeen) {}
51 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
52 unsigned SectionID,
53 StringRef SectionName,
54 bool IsReadOnly) override {
55 if (SectionName == ".debug_str")
56 DebugSeen = true;
57 return SectionMemoryManager::allocateDataSection(Size, Alignment,
58 SectionID,
59 SectionName,
60 IsReadOnly);
61 }
62 private:
63 bool &DebugSeen;
64 };
65
66 bool DebugSectionSeen = false;
67 auto MM = std::make_shared(DebugSectionSeen);
68
69 ExecutionSession ES;
70
71 LegacyRTDyldObjectLinkingLayer ObjLayer(ES, [&MM](VModuleKey) {
72 return LegacyRTDyldObjectLinkingLayer::Resources{
73 MM, std::make_shared()};
74 });
75
76 LLVMContext Context;
77 auto M = llvm::make_unique("", Context);
78 M->setTargetTriple("x86_64-unknown-linux-gnu");
79 Type *Int32Ty = IntegerType::get(Context, 32);
80 GlobalVariable *GV =
81 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
82 ConstantInt::get(Int32Ty, 42), "foo");
83
84 GV->setSection(".debug_str");
85
86
87 // Initialize the native target in case this is the first unit test
88 // to try to build a TM.
89 OrcNativeTarget::initialize();
90 std::unique_ptr TM(
91 EngineBuilder().selectTarget(Triple(M->getTargetTriple()), "", "",
92 SmallVector()));
93 if (!TM)
94 return;
95
96 auto Obj = SimpleCompiler(*TM)(*M);
97
98 {
99 // Test with ProcessAllSections = false (the default).
100 auto K = ES.allocateVModule();
101 cantFail(ObjLayer.addObject(
102 K, MemoryBuffer::getMemBufferCopy(Obj->getBuffer())));
103 cantFail(ObjLayer.emitAndFinalize(K));
104 EXPECT_EQ(DebugSectionSeen, false)
105 << "Unexpected debug info section";
106 cantFail(ObjLayer.removeObject(K));
107 }
108
109 {
110 // Test with ProcessAllSections = true.
111 ObjLayer.setProcessAllSections(true);
112 auto K = ES.allocateVModule();
113 cantFail(ObjLayer.addObject(K, std::move(Obj)));
114 cantFail(ObjLayer.emitAndFinalize(K));
115 EXPECT_EQ(DebugSectionSeen, true)
116 << "Expected debug info section not seen";
117 cantFail(ObjLayer.removeObject(K));
118 }
119 }
120
121 TEST_F(LegacyRTDyldObjectLinkingLayerExecutionTest, NoDuplicateFinalization) {
122 if (!SupportsJIT)
123 return;
124
125 ExecutionSession ES;
126
127 auto MM = std::make_shared();
128
129 std::map> Resolvers;
130
131 LegacyRTDyldObjectLinkingLayer ObjLayer(ES, [&](VModuleKey K) {
132 auto I = Resolvers.find(K);
133 assert(I != Resolvers.end() && "Missing resolver");
134 auto R = std::move(I->second);
135 Resolvers.erase(I);
136 return LegacyRTDyldObjectLinkingLayer::Resources{MM, std::move(R)};
137 });
138 SimpleCompiler Compile(*TM);
139
140 // Create a pair of modules that will trigger recursive finalization:
141 // Module 1:
142 // int bar() { return 42; }
143 // Module 2:
144 // int bar();
145 // int foo() { return bar(); }
146 //
147 // Verify that the memory manager is only finalized once (for Module 2).
148 // Failure suggests that finalize is being called on the inner RTDyld
149 // instance (for Module 1) which is unsafe, as it will prevent relocation of
150 // Module 2.
151
152 ModuleBuilder MB1(Context, "", "dummy");
153 {
154 MB1.getModule()->setDataLayout(TM->createDataLayout());
155 Function *BarImpl = MB1.createFunctionDecl("bar");
156 BasicBlock *BarEntry = BasicBlock::Create(Context, "entry", BarImpl);
157 IRBuilder<> Builder(BarEntry);
158 IntegerType *Int32Ty = IntegerType::get(Context, 32);
159 Value *FourtyTwo = ConstantInt::getSigned(Int32Ty, 42);
160 Builder.CreateRet(FourtyTwo);
161 }
162
163 auto Obj1 = Compile(*MB1.getModule());
164
165 ModuleBuilder MB2(Context, "", "dummy");
166 {
167 MB2.getModule()->setDataLayout(TM->createDataLayout());
168 Function *BarDecl = MB2.createFunctionDecl("bar");
169 Function *FooImpl = MB2.createFunctionDecl("foo");
170 BasicBlock *FooEntry = BasicBlock::Create(Context, "entry", FooImpl);
171 IRBuilder<> Builder(FooEntry);
172 Builder.CreateRet(Builder.CreateCall(BarDecl));
173 }
174 auto Obj2 = Compile(*MB2.getModule());
175
176 auto K1 = ES.allocateVModule();
177 Resolvers[K1] = std::make_shared();
178 cantFail(ObjLayer.addObject(K1, std::move(Obj1)));
179
180 auto K2 = ES.allocateVModule();
181 auto LegacyLookup = [&](const std::string &Name) {
182 return ObjLayer.findSymbol(Name, true);
183 };
184
185 Resolvers[K2] = createSymbolResolver(
186 [&](const SymbolNameSet &Symbols) {
187 return cantFail(
188 getResponsibilitySetWithLegacyFn(Symbols, LegacyLookup));
189 },
190 [&](std::shared_ptr Query,
191 const SymbolNameSet &Symbols) {
192 return lookupWithLegacyFn(ES, *Query, Symbols, LegacyLookup);
193 });
194
195 cantFail(ObjLayer.addObject(K2, std::move(Obj2)));
196 cantFail(ObjLayer.emitAndFinalize(K2));
197 cantFail(ObjLayer.removeObject(K2));
198
199 // Finalization of module 2 should trigger finalization of module 1.
200 // Verify that finalize on SMMW is only called once.
201 EXPECT_EQ(MM->FinalizationCount, 1)
202 << "Extra call to finalize";
203 }
204
205 TEST_F(LegacyRTDyldObjectLinkingLayerExecutionTest, NoPrematureAllocation) {
206 if (!SupportsJIT)
207 return;
208
209 ExecutionSession ES;
210
211 auto MM = std::make_shared();
212
213 LegacyRTDyldObjectLinkingLayer ObjLayer(ES, [&MM](VModuleKey K) {
214 return LegacyRTDyldObjectLinkingLayer::Resources{
215 MM, std::make_shared()};
216 });
217 SimpleCompiler Compile(*TM);
218
219 // Create a pair of unrelated modules:
220 //
221 // Module 1:
222 // int foo() { return 42; }
223 // Module 2:
224 // int bar() { return 7; }
225 //
226 // Both modules will share a memory manager. We want to verify that the
227 // second object is not loaded before the first one is finalized. To do this
228 // in a portable way, we abuse the
229 // RuntimeDyld::MemoryManager::needsToReserveAllocationSpace hook, which is
230 // called once per object before any sections are allocated.
231
232 ModuleBuilder MB1(Context, "", "dummy");
233 {
234 MB1.getModule()->setDataLayout(TM->createDataLayout());
235 Function *BarImpl = MB1.createFunctionDecl("foo");
236 BasicBlock *BarEntry = BasicBlock::Create(Context, "entry", BarImpl);
237 IRBuilder<> Builder(BarEntry);
238 IntegerType *Int32Ty = IntegerType::get(Context, 32);
239 Value *FourtyTwo = ConstantInt::getSigned(Int32Ty, 42);
240 Builder.CreateRet(FourtyTwo);
241 }
242
243 auto Obj1 = Compile(*MB1.getModule());
244
245 ModuleBuilder MB2(Context, "", "dummy");
246 {
247 MB2.getModule()->setDataLayout(TM->createDataLayout());
248 Function *BarImpl = MB2.createFunctionDecl("bar");
249 BasicBlock *BarEntry = BasicBlock::Create(Context, "entry", BarImpl);
250 IRBuilder<> Builder(BarEntry);
251 IntegerType *Int32Ty = IntegerType::get(Context, 32);
252 Value *Seven = ConstantInt::getSigned(Int32Ty, 7);
253 Builder.CreateRet(Seven);
254 }
255 auto Obj2 = Compile(*MB2.getModule());
256
257 auto K = ES.allocateVModule();
258 cantFail(ObjLayer.addObject(K, std::move(Obj1)));
259 cantFail(ObjLayer.addObject(ES.allocateVModule(), std::move(Obj2)));
260 cantFail(ObjLayer.emitAndFinalize(K));
261 cantFail(ObjLayer.removeObject(K));
262
263 // Only one call to needsToReserveAllocationSpace should have been made.
264 EXPECT_EQ(MM->NeedsToReserveAllocationSpaceCount, 1)
265 << "More than one call to needsToReserveAllocationSpace "
266 "(multiple unrelated objects loaded prior to finalization)";
267 }
268
269 TEST_F(LegacyRTDyldObjectLinkingLayerExecutionTest, TestNotifyLoadedSignature) {
270 ExecutionSession ES;
271 LegacyRTDyldObjectLinkingLayer ObjLayer(
272 ES,
273 [](VModuleKey) {
274 return LegacyRTDyldObjectLinkingLayer::Resources{
275 nullptr, std::make_shared()};
276 },
277 [](VModuleKey, const object::ObjectFile &obj,
278 const RuntimeDyld::LoadedObjectInfo &info) {});
279 }
280
281 } // end anonymous namespace
174174 }
175175 };
176176
177 // Test each operation on ObjectTransformLayer.
178 TEST(ObjectTransformLayerTest, Main) {
177 // Test each operation on LegacyObjectTransformLayer.
178 TEST(LegacyObjectTransformLayerTest, Main) {
179179 MockBaseLayer M;
180180
181181 ExecutionSession ES(std::make_shared());
182182
183183 // Create one object transform layer using a transform (as a functor)
184184 // that allocates new objects, and deals in unique pointers.
185 ObjectTransformLayer T1(M);
185 LegacyObjectTransformLayer T1(M);
186186
187187 // Create a second object transform layer using a transform (as a lambda)
188188 // that mutates objects in place, and deals in naked pointers
189 ObjectTransformLayer
189 LegacyObjectTransformLayer
190190 std::function(
191191 std::shared_ptr)>>
192192 T2(M, [](std::shared_ptr Obj) {
256256 if (!RunStaticChecks)
257257 return;
258258
259 // Make sure that ObjectTransformLayer implements the object layer concept
259 // Make sure that LegacyObjectTransformLayer implements the object layer concept
260260 // correctly by sandwitching one between an ObjectLinkingLayer and an
261 // IRCompileLayer, verifying that it compiles if we have a call to the
261 // LegacyIRCompileLayer, verifying that it compiles if we have a call to the
262262 // IRComileLayer's addModule that should call the transform layer's
263263 // addObject, and also calling the other public transform layer methods
264264 // directly to make sure the methods they intend to forward to exist on
281281 };
282282
283283 // Construct the jit layers.
284 RTDyldObjectLinkingLayer BaseLayer(ES, [](VModuleKey) {
285 return RTDyldObjectLinkingLayer::Resources{
284 LegacyRTDyldObjectLinkingLayer BaseLayer(ES, [](VModuleKey) {
285 return LegacyRTDyldObjectLinkingLayer::Resources{
286286 std::make_shared(),
287287 std::make_shared()};
288288 });
290290 auto IdentityTransform = [](std::unique_ptr Obj) {
291291 return Obj;
292292 };
293 ObjectTransformLayer
293 LegacyObjectTransformLayer
294294 TransformLayer(BaseLayer, IdentityTransform);
295295 auto NullCompiler = [](llvm::Module &) {
296296 return std::unique_ptr(nullptr);
297297 };
298 IRCompileLayer
298 LegacyIRCompileLayer
299299 CompileLayer(TransformLayer, NullCompiler);
300300
301 // Make sure that the calls from IRCompileLayer to ObjectTransformLayer
301 // Make sure that the calls from LegacyIRCompileLayer to LegacyObjectTransformLayer
302302 // compile.
303303 cantFail(CompileLayer.addModule(ES.allocateVModule(),
304304 std::unique_ptr()));
305305
306 // Make sure that the calls from ObjectTransformLayer to ObjectLinkingLayer
306 // Make sure that the calls from LegacyObjectTransformLayer to ObjectLinkingLayer
307307 // compile.
308308 VModuleKey DummyKey = ES.allocateVModule();
309309 cantFail(TransformLayer.emitAndFinalize(DummyKey));
+0
-228
unittests/ExecutionEngine/Orc/RTDyldObjectLinkingLayer2Test.cpp less more
None //===--- RTDyldObjectLinkingLayer2Test.cpp - RTDyld linking layer tests ---===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "OrcTestCommon.h"
10 #include "llvm/ExecutionEngine/ExecutionEngine.h"
11 #include "llvm/ExecutionEngine/Orc/CompileUtils.h"
12 #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
13 #include "llvm/ExecutionEngine/Orc/LambdaResolver.h"
14 #include "llvm/ExecutionEngine/Orc/Legacy.h"
15 #include "llvm/ExecutionEngine/Orc/NullResolver.h"
16 #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
17 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "gtest/gtest.h"
21
22 using namespace llvm;
23 using namespace llvm::orc;
24
25 namespace {
26
27 class RTDyldObjectLinkingLayer2ExecutionTest : public testing::Test,
28 public OrcExecutionTest {};
29
30 // Adds an object with a debug section to RuntimeDyld and then returns whether
31 // the debug section was passed to the memory manager.
32 static bool testSetProcessAllSections(std::unique_ptr Obj,
33 bool ProcessAllSections) {
34 class MemoryManagerWrapper : public SectionMemoryManager {
35 public:
36 MemoryManagerWrapper(bool &DebugSeen) : DebugSeen(DebugSeen) {}
37 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
38 unsigned SectionID, StringRef SectionName,
39 bool IsReadOnly) override {
40 if (SectionName == ".debug_str")
41 DebugSeen = true;
42 return SectionMemoryManager::allocateDataSection(
43 Size, Alignment, SectionID, SectionName, IsReadOnly);
44 }
45
46 private:
47 bool &DebugSeen;
48 };
49
50 bool DebugSectionSeen = false;
51
52 ExecutionSession ES;
53 auto &JD = ES.createJITDylib("main");
54 auto Foo = ES.intern("foo");
55
56 RTDyldObjectLinkingLayer2 ObjLayer(ES, [&DebugSectionSeen](VModuleKey) {
57 return llvm::make_unique(DebugSectionSeen);
58 });
59
60 auto OnResolveDoNothing = [](Expected R) {
61 cantFail(std::move(R));
62 };
63
64 auto OnReadyDoNothing = [](Error Err) { cantFail(std::move(Err)); };
65
66 ObjLayer.setProcessAllSections(ProcessAllSections);
67 auto K = ES.allocateVModule();
68 cantFail(ObjLayer.add(JD, K, std::move(Obj)));
69 ES.lookup({&JD}, {Foo}, OnResolveDoNothing, OnReadyDoNothing,
70 NoDependenciesToRegister);
71 return DebugSectionSeen;
72 }
73
74 TEST(RTDyldObjectLinkingLayer2Test, TestSetProcessAllSections) {
75 LLVMContext Context;
76 auto M = llvm::make_unique("", Context);
77 M->setTargetTriple("x86_64-unknown-linux-gnu");
78 Type *Int32Ty = IntegerType::get(Context, 32);
79 GlobalVariable *GV =
80 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
81 ConstantInt::get(Int32Ty, 42), "foo");
82
83 GV->setSection(".debug_str");
84
85 // Initialize the native target in case this is the first unit test
86 // to try to build a TM.
87 OrcNativeTarget::initialize();
88 std::unique_ptr TM(EngineBuilder().selectTarget(
89 Triple(M->getTargetTriple()), "", "", SmallVector()));
90 if (!TM)
91 return;
92
93 auto Obj = SimpleCompiler(*TM)(*M);
94
95 EXPECT_FALSE(testSetProcessAllSections(
96 MemoryBuffer::getMemBufferCopy(Obj->getBuffer()), false))
97 << "Debug section seen despite ProcessAllSections being false";
98 EXPECT_TRUE(testSetProcessAllSections(std::move(Obj), true))
99 << "Expected to see debug section when ProcessAllSections is true";
100 }
101
102 TEST(RTDyldObjectLinkingLayer2Test, TestOverrideObjectFlags) {
103
104 OrcNativeTarget::initialize();
105
106 std::unique_ptr TM(
107 EngineBuilder().selectTarget(Triple("x86_64-unknown-linux-gnu"), "", "",
108 SmallVector()));
109
110 if (!TM)
111 return;
112
113 // Our compiler is going to modify symbol visibility settings without telling
114 // ORC. This will test our ability to override the flags later.
115 class FunkySimpleCompiler : public SimpleCompiler {
116 public:
117 FunkySimpleCompiler(TargetMachine &TM) : SimpleCompiler(TM) {}
118
119 CompileResult operator()(Module &M) {
120 auto *Foo = M.getFunction("foo");
121 assert(Foo && "Expected function Foo not found");
122 Foo->setVisibility(GlobalValue::HiddenVisibility);
123 return SimpleCompiler::operator()(M);
124 }
125 };
126
127 // Create a module with two void() functions: foo and bar.
128 ThreadSafeContext TSCtx(llvm::make_unique());
129 ThreadSafeModule M;
130 {
131 ModuleBuilder MB(*TSCtx.getContext(), TM->getTargetTriple().str(), "dummy");
132 MB.getModule()->setDataLayout(TM->createDataLayout());
133
134 Function *FooImpl = MB.createFunctionDecl("foo");
135 BasicBlock *FooEntry =
136 BasicBlock::Create(*TSCtx.getContext(), "entry", FooImpl);
137 IRBuilder<> B1(FooEntry);
138 B1.CreateRetVoid();
139
140 Function *BarImpl = MB.createFunctionDecl("bar");
141 BasicBlock *BarEntry =
142 BasicBlock::Create(*TSCtx.getContext(), "entry", BarImpl);
143 IRBuilder<> B2(BarEntry);
144 B2.CreateRetVoid();
145
146 M = ThreadSafeModule(MB.takeModule(), std::move(TSCtx));
147 }
148
149 // Create a simple stack and set the override flags option.
150 ExecutionSession ES;
151 auto &JD = ES.createJITDylib("main");
152 auto Foo = ES.intern("foo");
153 RTDyldObjectLinkingLayer2 ObjLayer(
154 ES, [](VModuleKey) { return llvm::make_unique(); });
155 IRCompileLayer2 CompileLayer(ES, ObjLayer, FunkySimpleCompiler(*TM));
156
157 ObjLayer.setOverrideObjectFlagsWithResponsibilityFlags(true);
158
159 cantFail(CompileLayer.add(JD, ES.allocateVModule(), std::move(M)));
160 ES.lookup({&JD}, {Foo}, [](Expected R) { cantFail(std::move(R)); },
161 [](Error Err) { cantFail(std::move(Err)); },
162 NoDependenciesToRegister);
163 }
164
165 TEST(RTDyldObjectLinkingLayer2Test, TestAutoClaimResponsibilityForSymbols) {
166
167 OrcNativeTarget::initialize();
168
169 std::unique_ptr TM(
170 EngineBuilder().selectTarget(Triple("x86_64-unknown-linux-gnu"), "", "",
171 SmallVector()));
172
173 if (!TM)
174 return;
175
176 // Our compiler is going to add a new symbol without telling ORC.
177 // This will test our ability to auto-claim responsibility later.
178 class FunkySimpleCompiler : public SimpleCompiler {
179 public:
180 FunkySimpleCompiler(TargetMachine &TM) : SimpleCompiler(TM) {}
181
182 CompileResult operator()(Module &M) {
183 Function *BarImpl =
184 Function::Create(TypeBuilder::get(M.getContext()),
185 GlobalValue::ExternalLinkage, "bar", &M);
186 BasicBlock *BarEntry =
187 BasicBlock::Create(M.getContext(), "entry", BarImpl);
188 IRBuilder<> B(BarEntry);
189 B.CreateRetVoid();
190
191 return SimpleCompiler::operator()(M);
192 }
193 };
194
195 // Create a module with two void() functions: foo and bar.
196 ThreadSafeContext TSCtx(llvm::make_unique());
197 ThreadSafeModule M;
198 {
199 ModuleBuilder MB(*TSCtx.getContext(), TM->getTargetTriple().str(), "dummy");
200 MB.getModule()->setDataLayout(TM->createDataLayout());
201
202 Function *FooImpl = MB.createFunctionDecl("foo");
203 BasicBlock *FooEntry =
204 BasicBlock::Create(*TSCtx.getContext(), "entry", FooImpl);
205 IRBuilder<> B(FooEntry);
206 B.CreateRetVoid();
207
208 M = ThreadSafeModule(MB.takeModule(), std::move(TSCtx));
209 }
210
211 // Create a simple stack and set the override flags option.
212 ExecutionSession ES;
213 auto &JD = ES.createJITDylib("main");
214 auto Foo = ES.intern("foo");
215 RTDyldObjectLinkingLayer2 ObjLayer(
216 ES, [](VModuleKey) { return llvm::make_unique(); });
217 IRCompileLayer2 CompileLayer(ES, ObjLayer, FunkySimpleCompiler(*TM));
218
219 ObjLayer.setAutoClaimResponsibilityForObjectSymbols(true);
220
221 cantFail(CompileLayer.add(JD, ES.allocateVModule(), std::move(M)));
222 ES.lookup({&JD}, {Foo}, [](Expected R) { cantFail(std::move(R)); },
223 [](Error Err) { cantFail(std::move(Err)); },
224 NoDependenciesToRegister);
225 }
226
227 } // end anonymous namespace
None //===- RTDyldObjectLinkingLayerTest.cpp - RTDyld linking layer unit tests -===//
0 //===--- RTDyldObjectLinkingLayerTest.cpp - RTDyld linking layer tests ---===//
11 //
22 // The LLVM Compiler Infrastructure
33 //
66 //
77 //===----------------------------------------------------------------------===//
88
9 #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
109 #include "OrcTestCommon.h"
1110 #include "llvm/ExecutionEngine/ExecutionEngine.h"
1211 #include "llvm/ExecutionEngine/Orc/CompileUtils.h"
12 #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
1313 #include "llvm/ExecutionEngine/Orc/LambdaResolver.h"
1414 #include "llvm/ExecutionEngine/Orc/Legacy.h"
1515 #include "llvm/ExecutionEngine/Orc/NullResolver.h"
16 #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
1617 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
1718 #include "llvm/IR/Constants.h"
1819 #include "llvm/IR/LLVMContext.h"
2425 namespace {
2526
2627 class RTDyldObjectLinkingLayerExecutionTest : public testing::Test,
27 public OrcExecutionTest {
28
29 };
30
31 class SectionMemoryManagerWrapper : public SectionMemoryManager {
32 public:
33 int FinalizationCount = 0;
34 int NeedsToReserveAllocationSpaceCount = 0;
35
36 bool needsToReserveAllocationSpace() override {
37 ++NeedsToReserveAllocationSpaceCount;
38 return SectionMemoryManager::needsToReserveAllocationSpace();
39 }
40
41 bool finalizeMemory(std::string *ErrMsg = nullptr) override {
42 ++FinalizationCount;
43 return SectionMemoryManager::finalizeMemory(ErrMsg);
44 }
45 };
46
47 TEST(RTDyldObjectLinkingLayerTest, TestSetProcessAllSections) {
28 public OrcExecutionTest {};
29
30 // Adds an object with a debug section to RuntimeDyld and then returns whether
31 // the debug section was passed to the memory manager.
32 static bool testSetProcessAllSections(std::unique_ptr Obj,
33 bool ProcessAllSections) {
4834 class MemoryManagerWrapper : public SectionMemoryManager {
4935 public:
5036 MemoryManagerWrapper(bool &DebugSeen) : DebugSeen(DebugSeen) {}
5137 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
52 unsigned SectionID,
53 StringRef SectionName,
38 unsigned SectionID, StringRef SectionName,
5439 bool IsReadOnly) override {
5540 if (SectionName == ".debug_str")
5641 DebugSeen = true;
57 return SectionMemoryManager::allocateDataSection(Size, Alignment,
58 SectionID,
59 SectionName,
60 IsReadOnly);
42 return SectionMemoryManager::allocateDataSection(
43 Size, Alignment, SectionID, SectionName, IsReadOnly);
6144 }
45
6246 private:
6347 bool &DebugSeen;
6448 };
6549
6650 bool DebugSectionSeen = false;
67 auto MM = std::make_shared(DebugSectionSeen);
6851
6952 ExecutionSession ES;
70
71 RTDyldObjectLinkingLayer ObjLayer(ES, [&MM](VModuleKey) {
72 return RTDyldObjectLinkingLayer::Resources{
73 MM, std::make_shared()};
53 auto &JD = ES.createJITDylib("main");
54 auto Foo = ES.intern("foo");
55
56 RTDyldObjectLinkingLayer ObjLayer(ES, [&DebugSectionSeen](VModuleKey) {
57 return llvm::make_unique(DebugSectionSeen);
7458 });
7559
60 auto OnResolveDoNothing = [](Expected R) {
61 cantFail(std::move(R));
62 };
63
64 auto OnReadyDoNothing = [](Error Err) { cantFail(std::move(Err)); };
65
66 ObjLayer.setProcessAllSections(ProcessAllSections);
67 auto K = ES.allocateVModule();
68 cantFail(ObjLayer.add(JD, K, std::move(Obj)));
69 ES.lookup({&JD}, {Foo}, OnResolveDoNothing, OnReadyDoNothing,
70 NoDependenciesToRegister);
71 return DebugSectionSeen;
72 }
73
74 TEST(RTDyldObjectLinkingLayerTest, TestSetProcessAllSections) {
7675 LLVMContext Context;
7776 auto M = llvm::make_unique("", Context);
7877 M->setTargetTriple("x86_64-unknown-linux-gnu");
7978 Type *Int32Ty = IntegerType::get(Context, 32);
8079 GlobalVariable *GV =
81 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
80 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
8281 ConstantInt::get(Int32Ty, 42), "foo");
8382
8483 GV->setSection(".debug_str");
85
8684
8785 // Initialize the native target in case this is the first unit test
8886 // to try to build a TM.
8987 OrcNativeTarget::initialize();
90 std::unique_ptr TM(
91 EngineBuilder().selectTarget(Triple(M->getTargetTriple()), "", "",
92 SmallVector()));
88 std::unique_ptr TM(EngineBuilder().selectTarget(
89 Triple(M->getTargetTriple()), "", "", SmallVector()));
9390 if (!TM)
9491 return;
9592
9693 auto Obj = SimpleCompiler(*TM)(*M);
9794
95 EXPECT_FALSE(testSetProcessAllSections(
96 MemoryBuffer::getMemBufferCopy(Obj->getBuffer()), false))
97 << "Debug section seen despite ProcessAllSections being false";
98 EXPECT_TRUE(testSetProcessAllSections(std::move(Obj), true))
99 << "Expected to see debug section when ProcessAllSections is true";
100 }
101
102 TEST(RTDyldObjectLinkingLayerTest, TestOverrideObjectFlags) {
103
104 OrcNativeTarget::initialize();
105
106 std::unique_ptr TM(
107 EngineBuilder().selectTarget(Triple("x86_64-unknown-linux-gnu"), "", "",
108 SmallVector()));
109
110 if (!TM)
111 return;
112
113 // Our compiler is going to modify symbol visibility settings without telling
114 // ORC. This will test our ability to override the flags later.
115 class FunkySimpleCompiler : public SimpleCompiler {
116 public:
117 FunkySimpleCompiler(TargetMachine &TM) : SimpleCompiler(TM) {}
118
119 CompileResult operator()(Module &M) {
120 auto *Foo = M.getFunction("foo");
121 assert(Foo && "Expected function Foo not found");
122 Foo->setVisibility(GlobalValue::HiddenVisibility);
123 return SimpleCompiler::operator()(M);
124 }
125 };
126
127 // Create a module with two void() functions: foo and bar.
128 ThreadSafeContext TSCtx(llvm::make_unique());
129 ThreadSafeModule M;
98130 {
99 // Test with ProcessAllSections = false (the default).
100 auto K = ES.allocateVModule();
101 cantFail(ObjLayer.addObject(
102 K, MemoryBuffer::getMemBufferCopy(Obj->getBuffer())));
103 cantFail(ObjLayer.emitAndFinalize(K));
104 EXPECT_EQ(DebugSectionSeen, false)
105 << "Unexpected debug info section";
106 cantFail(ObjLayer.removeObject(K));
131 ModuleBuilder MB(*TSCtx.getContext(), TM->getTargetTriple().str(), "dummy");
132 MB.getModule()->setDataLayout(TM->createDataLayout());
133
134 Function *FooImpl = MB.createFunctionDecl("foo");
135 BasicBlock *FooEntry =
136 BasicBlock::Create(*TSCtx.getContext(), "entry", FooImpl);
137 IRBuilder<> B1(FooEntry);
138 B1.CreateRetVoid();
139
140 Function *BarImpl = MB.createFunctionDecl("bar");
141 BasicBlock *BarEntry =
142 BasicBlock::Create(*TSCtx.getContext(), "entry", BarImpl);
143 IRBuilder<> B2(BarEntry);
144 B2.CreateRetVoid();
145
146 M = ThreadSafeModule(MB.takeModule(), std::move(TSCtx));
107147 }
108148
149 // Create a simple stack and set the override flags option.
150 ExecutionSession ES;
151 auto &JD = ES.createJITDylib("main");
152 auto Foo = ES.intern("foo");
153 RTDyldObjectLinkingLayer ObjLayer(
154 ES, [](VModuleKey) { return llvm::make_unique(); });
155 IRCompileLayer CompileLayer(ES, ObjLayer, FunkySimpleCompiler(*TM));
156
157 ObjLayer.setOverrideObjectFlagsWithResponsibilityFlags(true);
158
159 cantFail(CompileLayer.add(JD, ES.allocateVModule(), std::move(M)));
160 ES.lookup({&JD}, {Foo}, [](Expected R) { cantFail(std::move(R)); },
161 [](Error Err) { cantFail(std::move(Err)); },
162 NoDependenciesToRegister);
163 }
164
165 TEST(RTDyldObjectLinkingLayerTest, TestAutoClaimResponsibilityForSymbols) {
166
167 OrcNativeTarget::initialize();
168
169 std::unique_ptr TM(
170 EngineBuilder().selectTarget(Triple("x86_64-unknown-linux-gnu"), "", "",
171 SmallVector()));
172
173 if (!TM)
174 return;
175
176 // Our compiler is going to add a new symbol without telling ORC.
177 // This will test our ability to auto-claim responsibility later.
178 class FunkySimpleCompiler : public SimpleCompiler {
179 public:
180 FunkySimpleCompiler(TargetMachine &TM) : SimpleCompiler(TM) {}
181
182 CompileResult operator()(Module &M) {
183 Function *BarImpl =
184 Function::Create(TypeBuilder::get(M.getContext()),
185 GlobalValue::ExternalLinkage, "bar", &M);
186 BasicBlock *BarEntry =
187 BasicBlock::Create(M.getContext(), "entry", BarImpl);
188 IRBuilder<> B(BarEntry);
189 B.CreateRetVoid();
190
191 return SimpleCompiler::operator()(M);
192 }
193 };
194
195 // Create a module with two void() functions: foo and bar.
196 ThreadSafeContext TSCtx(llvm::make_unique());
197 ThreadSafeModule M;
109198 {
110 // Test with ProcessAllSections = true.
111 ObjLayer.setProcessAllSections(true);
112 auto K = ES.allocateVModule();
113 cantFail(ObjLayer.addObject(K, std::move(Obj)));
114 cantFail(ObjLayer.emitAndFinalize(K));
115 EXPECT_EQ(DebugSectionSeen, true)
116 << "Expected debug info section not seen";
117 cantFail(ObjLayer.removeObject(K));
199 ModuleBuilder MB(*TSCtx.getContext(), TM->getTargetTriple().str(), "dummy");
200 MB.getModule()->setDataLayout(TM->createDataLayout());
201
202 Function *FooImpl = MB.createFunctionDecl("foo");
203 BasicBlock *FooEntry =
204 BasicBlock::Create(*TSCtx.getContext(), "entry", FooImpl);
205 IRBuilder<> B(FooEntry);
206 B.CreateRetVoid();
207
208 M = ThreadSafeModule(MB.takeModule(), std::move(TSCtx));
118209 }
119 }
120
121 TEST_F(RTDyldObjectLinkingLayerExecutionTest, NoDuplicateFinalization) {
122 if (!SupportsJIT)
123 return;
124
210
211 // Create a simple stack and set the override flags option.
125212 ExecutionSession ES;
126
127 auto MM = std::make_shared();
128
129 std::map> Resolvers;
130
131 RTDyldObjectLinkingLayer ObjLayer(ES, [&](VModuleKey K) {
132 auto I = Resolvers.find(K);
133 assert(I != Resolvers.end() && "Missing resolver");
134 auto R = std::move(I->second);
135 Resolvers.erase(I);
136 return RTDyldObjectLinkingLayer::Resources{MM, std::move(R)};
137 });
138 SimpleCompiler Compile(*TM);
139
140 // Create a pair of modules that will trigger recursive finalization:
141 // Module 1:
142 // int bar() { return 42; }
143 // Module 2:
144 // int bar();
145 // int foo() { return bar(); }
146 //
147 // Verify that the memory manager is only finalized once (for Module 2).
148 // Failure suggests that finalize is being called on the inner RTDyld
149 // instance (for Module 1) which is unsafe, as it will prevent relocation of
150 // Module 2.
151
152 ModuleBuilder MB1(Context, "", "dummy");
153 {
154 MB1.getModule()->setDataLayout(TM->createDataLayout());
155 Function *BarImpl = MB1.createFunctionDecl("bar");
156 BasicBlock *BarEntry = BasicBlock::Create(Context, "entry", BarImpl);
157 IRBuilder<> Builder(BarEntry);
158 IntegerType *Int32Ty = IntegerType::get(Context, 32);
159 Value *FourtyTwo = ConstantInt::getSigned(Int32Ty, 42);
160 Builder.CreateRet(FourtyTwo);
161 }
162
163 auto Obj1 = Compile(*MB1.getModule());
164
165 ModuleBuilder MB2(Context, "", "dummy");
166 {
167 MB2.getModule()->setDataLayout(TM->createDataLayout());
168 Function *BarDecl = MB2.createFunctionDecl("bar");
169 Function *FooImpl = MB2.createFunctionDecl("foo");
170 BasicBlock *FooEntry = BasicBlock::Create(Context, "entry", FooImpl);
171 IRBuilder<> Builder(FooEntry);
172 Builder.CreateRet(Builder.CreateCall(BarDecl));
173 }
174 auto Obj2 = Compile(*MB2.getModule());
175
176 auto K1 = ES.allocateVModule();
177 Resolvers[K1] = std::make_shared();
178 cantFail(ObjLayer.addObject(K1, std::move(Obj1)));
179
180 auto K2 = ES.allocateVModule();
181 auto LegacyLookup = [&](const std::string &Name) {
182 return ObjLayer.findSymbol(Name, true);
183 };
184
185 Resolvers[K2] = createSymbolResolver(
186 [&](const SymbolNameSet &Symbols) {
187 return cantFail(
188 getResponsibilitySetWithLegacyFn(Symbols, LegacyLookup));
189 },
190 [&](std::shared_ptr Query,
191 const SymbolNameSet &Symbols) {
192 return lookupWithLegacyFn(ES, *Query, Symbols, LegacyLookup);
193 });
194
195 cantFail(ObjLayer.addObject(K2, std::move(Obj2)));
196 cantFail(ObjLayer.emitAndFinalize(K2));
197 cantFail(ObjLayer.removeObject(K2));
198
199 // Finalization of module 2 should trigger finalization of module 1.
200 // Verify that finalize on SMMW is only called once.
201 EXPECT_EQ(MM->FinalizationCount, 1)
202 << "Extra call to finalize";
203 }
204
205 TEST_F(RTDyldObjectLinkingLayerExecutionTest, NoPrematureAllocation) {
206 if (!SupportsJIT)
207 return;
208
209 ExecutionSession ES;
210
211 auto MM = std::make_shared();
212
213 RTDyldObjectLinkingLayer ObjLayer(ES, [&MM](VModuleKey K) {
214 return RTDyldObjectLinkingLayer::Resources{
215 MM, std::make_shared()};
216 });
217 SimpleCompiler Compile(*TM);
218
219 // Create a pair of unrelated modules:
220 //
221 // Module 1:
222 // int foo() { return 42; }
223 // Module 2:
224 // int bar() { return 7; }
225 //
226 // Both modules will share a memory manager. We want to verify that the
227 // second object is not loaded before the first one is finalized. To do this
228 // in a portable way, we abuse the
229 // RuntimeDyld::MemoryManager::needsToReserveAllocationSpace hook, which is
230 // called once per object before any sections are allocated.
231
232 ModuleBuilder MB1(Context, "", "dummy");
233 {
234 MB1.getModule()->setDataLayout(TM->createDataLayout());
235 Function *BarImpl = MB1.createFunctionDecl("foo");
236 BasicBlock *BarEntry = BasicBlock::Create(Context, "entry", BarImpl);
237 IRBuilder<> Builder(BarEntry);
238 IntegerType *Int32Ty = IntegerType::get(Context, 32);
239 Value *FourtyTwo = ConstantInt::getSigned(Int32Ty, 42);
240 Builder.CreateRet(FourtyTwo);
241 }
242
243 auto Obj1 = Compile(*MB1.getModule());
244
245 ModuleBuilder MB2(Context, "", "dummy");
246 {
247 MB2.getModule()->setDataLayout(TM->createDataLayout());
248 Function *BarImpl = MB2.createFunctionDecl("bar");
249 BasicBlock *BarEntry = BasicBlock::Create(Context, "entry", BarImpl);
250 IRBuilder<> Builder(BarEntry);
251 IntegerType *Int32Ty = IntegerType::get(Context, 32);
252 Value *Seven = ConstantInt::getSigned(Int32Ty, 7);
253 Builder.CreateRet(Seven);
254 }
255 auto Obj2 = Compile(*MB2.getModule());
256
257 auto K = ES.allocateVModule();
258 cantFail(ObjLayer.addObject(K, std::move(Obj1)));
259 cantFail(ObjLayer.addObject(ES.allocateVModule(), std::move(Obj2)));
260 cantFail(ObjLayer.emitAndFinalize(K));
261 cantFail(ObjLayer.removeObject(K));
262
263 // Only one call to needsToReserveAllocationSpace should have been made.
264 EXPECT_EQ(MM->NeedsToReserveAllocationSpaceCount, 1)
265 << "More than one call to needsToReserveAllocationSpace "
266 "(multiple unrelated objects loaded prior to finalization)";
267 }
268
269 TEST_F(RTDyldObjectLinkingLayerExecutionTest, TestNotifyLoadedSignature) {
270 ExecutionSession ES;
213 auto &JD = ES.createJITDylib("main");
214 auto Foo = ES.intern("foo");
271215 RTDyldObjectLinkingLayer ObjLayer(
272 ES,
273 [](VModuleKey) {
274 return RTDyldObjectLinkingLayer::Resources{
275 nullptr, std::make_shared()};
276 },
277 [](VModuleKey, const object::ObjectFile &obj,
278 const RuntimeDyld::LoadedObjectInfo &info) {});
216 ES, [](VModuleKey) { return llvm::make_unique(); });
217 IRCompileLayer CompileLayer(ES, ObjLayer, FunkySimpleCompiler(*TM));
218
219 ObjLayer.setAutoClaimResponsibilityForObjectSymbols(true);
220
221 cantFail(CompileLayer.add(JD, ES.allocateVModule(), std::move(M)));
222 ES.lookup({&JD}, {Foo}, [](Expected R) { cantFail(std::move(R)); },
223 [](Error Err) { cantFail(std::move(Err)); },
224 NoDependenciesToRegister);
279225 }
280226
281227 } // end anonymous namespace