xref: /llvm-project/llvm/lib/ExecutionEngine/Orc/ObjectLinkingLayer.cpp (revision 84b07c9b3aa79e073a97290bdd30d98b1941a536)
1 //===------- ObjectLinkingLayer.cpp - JITLink backed ORC ObjectLayer ------===//
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 #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
10 #include "llvm/ADT/Optional.h"
11 #include "llvm/ExecutionEngine/JITLink/EHFrameSupport.h"
12 #include "llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h"
13 #include "llvm/Support/MemoryBuffer.h"
14 #include <string>
15 #include <vector>
16 
17 #define DEBUG_TYPE "orc"
18 
19 using namespace llvm;
20 using namespace llvm::jitlink;
21 using namespace llvm::orc;
22 
23 namespace {
24 
25 class LinkGraphMaterializationUnit : public MaterializationUnit {
26 private:
27   struct LinkGraphInterface {
28     SymbolFlagsMap SymbolFlags;
29     SymbolStringPtr InitSymbol;
30   };
31 
32 public:
33   static std::unique_ptr<LinkGraphMaterializationUnit>
34   Create(ObjectLinkingLayer &ObjLinkingLayer, std::unique_ptr<LinkGraph> G) {
35     auto LGI = scanLinkGraph(ObjLinkingLayer.getExecutionSession(), *G);
36     return std::unique_ptr<LinkGraphMaterializationUnit>(
37         new LinkGraphMaterializationUnit(ObjLinkingLayer, std::move(G),
38                                          std::move(LGI)));
39   }
40 
41   StringRef getName() const override { return G->getName(); }
42   void materialize(std::unique_ptr<MaterializationResponsibility> MR) override {
43     ObjLinkingLayer.emit(std::move(MR), std::move(G));
44   }
45 
46 private:
47   static LinkGraphInterface scanLinkGraph(ExecutionSession &ES, LinkGraph &G) {
48 
49     LinkGraphInterface LGI;
50 
51     for (auto *Sym : G.defined_symbols()) {
52       // Skip local symbols.
53       if (Sym->getScope() == Scope::Local)
54         continue;
55       assert(Sym->hasName() && "Anonymous non-local symbol?");
56 
57       JITSymbolFlags Flags;
58       if (Sym->getScope() == Scope::Default)
59         Flags |= JITSymbolFlags::Exported;
60 
61       if (Sym->isCallable())
62         Flags |= JITSymbolFlags::Callable;
63 
64       LGI.SymbolFlags[ES.intern(Sym->getName())] = Flags;
65     }
66 
67     if ((G.getTargetTriple().isOSBinFormatMachO() && hasMachOInitSection(G)) ||
68         (G.getTargetTriple().isOSBinFormatELF() && hasELFInitSection(G)))
69       LGI.InitSymbol = makeInitSymbol(ES, G);
70 
71     return LGI;
72   }
73 
74   static bool hasMachOInitSection(LinkGraph &G) {
75     for (auto &Sec : G.sections())
76       if (Sec.getName() == "__DATA,__obj_selrefs" ||
77           Sec.getName() == "__DATA,__objc_classlist" ||
78           Sec.getName() == "__TEXT,__swift5_protos" ||
79           Sec.getName() == "__TEXT,__swift5_proto" ||
80           Sec.getName() == "__DATA,__mod_init_func")
81         return true;
82     return false;
83   }
84 
85   static bool hasELFInitSection(LinkGraph &G) {
86     for (auto &Sec : G.sections())
87       if (Sec.getName() == ".init_array")
88         return true;
89     return false;
90   }
91 
92   static SymbolStringPtr makeInitSymbol(ExecutionSession &ES, LinkGraph &G) {
93     std::string InitSymString;
94     raw_string_ostream(InitSymString)
95         << "$." << G.getName() << ".__inits" << Counter++;
96     return ES.intern(InitSymString);
97   }
98 
99   LinkGraphMaterializationUnit(ObjectLinkingLayer &ObjLinkingLayer,
100                                std::unique_ptr<LinkGraph> G,
101                                LinkGraphInterface LGI)
102       : MaterializationUnit(std::move(LGI.SymbolFlags),
103                             std::move(LGI.InitSymbol)),
104         ObjLinkingLayer(ObjLinkingLayer), G(std::move(G)) {}
105 
106   void discard(const JITDylib &JD, const SymbolStringPtr &Name) override {
107     for (auto *Sym : G->defined_symbols())
108       if (Sym->getName() == *Name) {
109         assert(Sym->getLinkage() == Linkage::Weak &&
110                "Discarding non-weak definition");
111         G->makeExternal(*Sym);
112         break;
113       }
114   }
115 
116   ObjectLinkingLayer &ObjLinkingLayer;
117   std::unique_ptr<LinkGraph> G;
118   static std::atomic<uint64_t> Counter;
119 };
120 
121 std::atomic<uint64_t> LinkGraphMaterializationUnit::Counter{0};
122 
123 } // end anonymous namespace
124 
125 namespace llvm {
126 namespace orc {
127 
128 class ObjectLinkingLayerJITLinkContext final : public JITLinkContext {
129 public:
130   ObjectLinkingLayerJITLinkContext(
131       ObjectLinkingLayer &Layer,
132       std::unique_ptr<MaterializationResponsibility> MR,
133       std::unique_ptr<MemoryBuffer> ObjBuffer)
134       : JITLinkContext(&MR->getTargetJITDylib()), Layer(Layer),
135         MR(std::move(MR)), ObjBuffer(std::move(ObjBuffer)) {}
136 
137   ~ObjectLinkingLayerJITLinkContext() {
138     // If there is an object buffer return function then use it to
139     // return ownership of the buffer.
140     if (Layer.ReturnObjectBuffer && ObjBuffer)
141       Layer.ReturnObjectBuffer(std::move(ObjBuffer));
142   }
143 
144   JITLinkMemoryManager &getMemoryManager() override { return Layer.MemMgr; }
145 
146   void notifyMaterializing(LinkGraph &G) {
147     for (auto &P : Layer.Plugins)
148       P->notifyMaterializing(*MR, G, *this,
149                              ObjBuffer ? ObjBuffer->getMemBufferRef()
150                              : MemoryBufferRef());
151   }
152 
153   void notifyFailed(Error Err) override {
154     for (auto &P : Layer.Plugins)
155       Err = joinErrors(std::move(Err), P->notifyFailed(*MR));
156     Layer.getExecutionSession().reportError(std::move(Err));
157     MR->failMaterialization();
158   }
159 
160   void lookup(const LookupMap &Symbols,
161               std::unique_ptr<JITLinkAsyncLookupContinuation> LC) override {
162 
163     JITDylibSearchOrder LinkOrder;
164     MR->getTargetJITDylib().withLinkOrderDo(
165         [&](const JITDylibSearchOrder &LO) { LinkOrder = LO; });
166 
167     auto &ES = Layer.getExecutionSession();
168 
169     SymbolLookupSet LookupSet;
170     for (auto &KV : Symbols) {
171       orc::SymbolLookupFlags LookupFlags;
172       switch (KV.second) {
173       case jitlink::SymbolLookupFlags::RequiredSymbol:
174         LookupFlags = orc::SymbolLookupFlags::RequiredSymbol;
175         break;
176       case jitlink::SymbolLookupFlags::WeaklyReferencedSymbol:
177         LookupFlags = orc::SymbolLookupFlags::WeaklyReferencedSymbol;
178         break;
179       }
180       LookupSet.add(ES.intern(KV.first), LookupFlags);
181     }
182 
183     // OnResolve -- De-intern the symbols and pass the result to the linker.
184     auto OnResolve = [LookupContinuation =
185                           std::move(LC)](Expected<SymbolMap> Result) mutable {
186       if (!Result)
187         LookupContinuation->run(Result.takeError());
188       else {
189         AsyncLookupResult LR;
190         for (auto &KV : *Result)
191           LR[*KV.first] = KV.second;
192         LookupContinuation->run(std::move(LR));
193       }
194     };
195 
196     for (auto &KV : InternalNamedSymbolDeps) {
197       SymbolDependenceMap InternalDeps;
198       InternalDeps[&MR->getTargetJITDylib()] = std::move(KV.second);
199       MR->addDependencies(KV.first, InternalDeps);
200     }
201 
202     ES.lookup(LookupKind::Static, LinkOrder, std::move(LookupSet),
203               SymbolState::Resolved, std::move(OnResolve),
204               [this](const SymbolDependenceMap &Deps) {
205                 registerDependencies(Deps);
206               });
207   }
208 
209   Error notifyResolved(LinkGraph &G) override {
210     auto &ES = Layer.getExecutionSession();
211 
212     SymbolFlagsMap ExtraSymbolsToClaim;
213     bool AutoClaim = Layer.AutoClaimObjectSymbols;
214 
215     SymbolMap InternedResult;
216     for (auto *Sym : G.defined_symbols())
217       if (Sym->hasName() && Sym->getScope() != Scope::Local) {
218         auto InternedName = ES.intern(Sym->getName());
219         JITSymbolFlags Flags;
220 
221         if (Sym->isCallable())
222           Flags |= JITSymbolFlags::Callable;
223         if (Sym->getScope() == Scope::Default)
224           Flags |= JITSymbolFlags::Exported;
225 
226         InternedResult[InternedName] =
227             JITEvaluatedSymbol(Sym->getAddress(), Flags);
228         if (AutoClaim && !MR->getSymbols().count(InternedName)) {
229           assert(!ExtraSymbolsToClaim.count(InternedName) &&
230                  "Duplicate symbol to claim?");
231           ExtraSymbolsToClaim[InternedName] = Flags;
232         }
233       }
234 
235     for (auto *Sym : G.absolute_symbols())
236       if (Sym->hasName()) {
237         auto InternedName = ES.intern(Sym->getName());
238         JITSymbolFlags Flags;
239         Flags |= JITSymbolFlags::Absolute;
240         if (Sym->isCallable())
241           Flags |= JITSymbolFlags::Callable;
242         if (Sym->getLinkage() == Linkage::Weak)
243           Flags |= JITSymbolFlags::Weak;
244         InternedResult[InternedName] =
245             JITEvaluatedSymbol(Sym->getAddress(), Flags);
246         if (AutoClaim && !MR->getSymbols().count(InternedName)) {
247           assert(!ExtraSymbolsToClaim.count(InternedName) &&
248                  "Duplicate symbol to claim?");
249           ExtraSymbolsToClaim[InternedName] = Flags;
250         }
251       }
252 
253     if (!ExtraSymbolsToClaim.empty())
254       if (auto Err = MR->defineMaterializing(ExtraSymbolsToClaim))
255         return Err;
256 
257     {
258 
259       // Check that InternedResult matches up with MR->getSymbols().
260       // This guards against faulty transformations / compilers / object caches.
261 
262       // First check that there aren't any missing symbols.
263       size_t NumMaterializationSideEffectsOnlySymbols = 0;
264       SymbolNameVector ExtraSymbols;
265       SymbolNameVector MissingSymbols;
266       for (auto &KV : MR->getSymbols()) {
267 
268         // If this is a materialization-side-effects only symbol then bump
269         // the counter and make sure it's *not* defined, otherwise make
270         // sure that it is defined.
271         if (KV.second.hasMaterializationSideEffectsOnly()) {
272           ++NumMaterializationSideEffectsOnlySymbols;
273           if (InternedResult.count(KV.first))
274             ExtraSymbols.push_back(KV.first);
275           continue;
276         } else if (!InternedResult.count(KV.first))
277           MissingSymbols.push_back(KV.first);
278       }
279 
280       // If there were missing symbols then report the error.
281       if (!MissingSymbols.empty())
282         return make_error<MissingSymbolDefinitions>(G.getName(),
283                                                     std::move(MissingSymbols));
284 
285       // If there are more definitions than expected, add them to the
286       // ExtraSymbols vector.
287       if (InternedResult.size() >
288           MR->getSymbols().size() - NumMaterializationSideEffectsOnlySymbols) {
289         for (auto &KV : InternedResult)
290           if (!MR->getSymbols().count(KV.first))
291             ExtraSymbols.push_back(KV.first);
292       }
293 
294       // If there were extra definitions then report the error.
295       if (!ExtraSymbols.empty())
296         return make_error<UnexpectedSymbolDefinitions>(G.getName(),
297                                                        std::move(ExtraSymbols));
298     }
299 
300     if (auto Err = MR->notifyResolved(InternedResult))
301       return Err;
302 
303     Layer.notifyLoaded(*MR);
304     return Error::success();
305   }
306 
307   void notifyFinalized(
308       std::unique_ptr<JITLinkMemoryManager::Allocation> A) override {
309     if (auto Err = Layer.notifyEmitted(*MR, std::move(A))) {
310       Layer.getExecutionSession().reportError(std::move(Err));
311       MR->failMaterialization();
312       return;
313     }
314     if (auto Err = MR->notifyEmitted()) {
315       Layer.getExecutionSession().reportError(std::move(Err));
316       MR->failMaterialization();
317     }
318   }
319 
320   LinkGraphPassFunction getMarkLivePass(const Triple &TT) const override {
321     return [this](LinkGraph &G) { return markResponsibilitySymbolsLive(G); };
322   }
323 
324   Error modifyPassConfig(LinkGraph &LG, PassConfiguration &Config) override {
325     // Add passes to mark duplicate defs as should-discard, and to walk the
326     // link graph to build the symbol dependence graph.
327     Config.PrePrunePasses.push_back([this](LinkGraph &G) {
328       return claimOrExternalizeWeakAndCommonSymbols(G);
329     });
330 
331     Layer.modifyPassConfig(*MR, LG, Config);
332 
333     Config.PostPrunePasses.push_back(
334         [this](LinkGraph &G) { return computeNamedSymbolDependencies(G); });
335 
336     return Error::success();
337   }
338 
339 private:
340   // Symbol name dependencies:
341   // Internal: Defined in this graph.
342   // External: Defined externally.
343   struct BlockSymbolDependencies {
344     SymbolNameSet Internal, External;
345   };
346 
347   // Lazily populated map of blocks to BlockSymbolDependencies values.
348   class BlockDependenciesMap {
349   public:
350     BlockDependenciesMap(ExecutionSession &ES,
351                          DenseMap<const Block *, DenseSet<Block *>> BlockDeps)
352         : ES(ES), BlockDeps(std::move(BlockDeps)) {}
353 
354     const BlockSymbolDependencies &operator[](const Block &B) {
355       // Check the cache first.
356       auto I = BlockTransitiveDepsCache.find(&B);
357       if (I != BlockTransitiveDepsCache.end())
358         return I->second;
359 
360       // No value. Populate the cache.
361       BlockSymbolDependencies BTDCacheVal;
362       auto BDI = BlockDeps.find(&B);
363       assert(BDI != BlockDeps.end() && "No block dependencies");
364 
365       for (auto *BDep : BDI->second) {
366         auto &BID = getBlockImmediateDeps(*BDep);
367         for (auto &ExternalDep : BID.External)
368           BTDCacheVal.External.insert(ExternalDep);
369         for (auto &InternalDep : BID.Internal)
370           BTDCacheVal.Internal.insert(InternalDep);
371       }
372 
373       return BlockTransitiveDepsCache
374           .insert(std::make_pair(&B, std::move(BTDCacheVal)))
375           .first->second;
376     }
377 
378     SymbolStringPtr &getInternedName(Symbol &Sym) {
379       auto I = NameCache.find(&Sym);
380       if (I != NameCache.end())
381         return I->second;
382 
383       return NameCache.insert(std::make_pair(&Sym, ES.intern(Sym.getName())))
384           .first->second;
385     }
386 
387   private:
388     BlockSymbolDependencies &getBlockImmediateDeps(Block &B) {
389       // Check the cache first.
390       auto I = BlockImmediateDepsCache.find(&B);
391       if (I != BlockImmediateDepsCache.end())
392         return I->second;
393 
394       BlockSymbolDependencies BIDCacheVal;
395       for (auto &E : B.edges()) {
396         auto &Tgt = E.getTarget();
397         if (Tgt.getScope() != Scope::Local) {
398           if (Tgt.isExternal())
399             BIDCacheVal.External.insert(getInternedName(Tgt));
400           else
401             BIDCacheVal.Internal.insert(getInternedName(Tgt));
402         }
403       }
404 
405       return BlockImmediateDepsCache
406           .insert(std::make_pair(&B, std::move(BIDCacheVal)))
407           .first->second;
408     }
409 
410     ExecutionSession &ES;
411     DenseMap<const Block *, DenseSet<Block *>> BlockDeps;
412     DenseMap<const Symbol *, SymbolStringPtr> NameCache;
413     DenseMap<const Block *, BlockSymbolDependencies> BlockImmediateDepsCache;
414     DenseMap<const Block *, BlockSymbolDependencies> BlockTransitiveDepsCache;
415   };
416 
417   Error claimOrExternalizeWeakAndCommonSymbols(LinkGraph &G) {
418     auto &ES = Layer.getExecutionSession();
419 
420     SymbolFlagsMap NewSymbolsToClaim;
421     std::vector<std::pair<SymbolStringPtr, Symbol *>> NameToSym;
422 
423     auto ProcessSymbol = [&](Symbol *Sym) {
424       if (Sym->hasName() && Sym->getLinkage() == Linkage::Weak) {
425         auto Name = ES.intern(Sym->getName());
426         if (!MR->getSymbols().count(ES.intern(Sym->getName()))) {
427           JITSymbolFlags SF = JITSymbolFlags::Weak;
428           if (Sym->getScope() == Scope::Default)
429             SF |= JITSymbolFlags::Exported;
430           NewSymbolsToClaim[Name] = SF;
431           NameToSym.push_back(std::make_pair(std::move(Name), Sym));
432         }
433       }
434     };
435 
436     for (auto *Sym : G.defined_symbols())
437       ProcessSymbol(Sym);
438     for (auto *Sym : G.absolute_symbols())
439       ProcessSymbol(Sym);
440 
441     // Attempt to claim all weak defs that we're not already responsible for.
442     // This cannot fail -- any clashes will just result in rejection of our
443     // claim, at which point we'll externalize that symbol.
444     cantFail(MR->defineMaterializing(std::move(NewSymbolsToClaim)));
445 
446     for (auto &KV : NameToSym)
447       if (!MR->getSymbols().count(KV.first))
448         G.makeExternal(*KV.second);
449 
450     return Error::success();
451   }
452 
453   Error markResponsibilitySymbolsLive(LinkGraph &G) const {
454     auto &ES = Layer.getExecutionSession();
455     for (auto *Sym : G.defined_symbols())
456       if (Sym->hasName() && MR->getSymbols().count(ES.intern(Sym->getName())))
457         Sym->setLive(true);
458     return Error::success();
459   }
460 
461   Error computeNamedSymbolDependencies(LinkGraph &G) {
462     auto &ES = MR->getTargetJITDylib().getExecutionSession();
463     auto BlockDeps = computeBlockNonLocalDeps(G);
464 
465     // Compute dependencies for symbols defined in the JITLink graph.
466     for (auto *Sym : G.defined_symbols()) {
467 
468       // Skip local symbols: we do not track dependencies for these.
469       if (Sym->getScope() == Scope::Local)
470         continue;
471       assert(Sym->hasName() &&
472              "Defined non-local jitlink::Symbol should have a name");
473 
474       auto &SymDeps = BlockDeps[Sym->getBlock()];
475       if (SymDeps.External.empty() && SymDeps.Internal.empty())
476         continue;
477 
478       auto SymName = ES.intern(Sym->getName());
479       if (!SymDeps.External.empty())
480         ExternalNamedSymbolDeps[SymName] = SymDeps.External;
481       if (!SymDeps.Internal.empty())
482         InternalNamedSymbolDeps[SymName] = SymDeps.Internal;
483     }
484 
485     for (auto &P : Layer.Plugins) {
486       auto SynthDeps = P->getSyntheticSymbolDependencies(*MR);
487       if (SynthDeps.empty())
488         continue;
489 
490       DenseSet<Block *> BlockVisited;
491       for (auto &KV : SynthDeps) {
492         auto &Name = KV.first;
493         auto &DepsForName = KV.second;
494         for (auto *Sym : DepsForName) {
495           if (Sym->getScope() == Scope::Local) {
496             auto &BDeps = BlockDeps[Sym->getBlock()];
497             for (auto &S : BDeps.Internal)
498               InternalNamedSymbolDeps[Name].insert(S);
499             for (auto &S : BDeps.External)
500               ExternalNamedSymbolDeps[Name].insert(S);
501           } else {
502             if (Sym->isExternal())
503               ExternalNamedSymbolDeps[Name].insert(
504                   BlockDeps.getInternedName(*Sym));
505             else
506               InternalNamedSymbolDeps[Name].insert(
507                   BlockDeps.getInternedName(*Sym));
508           }
509         }
510       }
511     }
512 
513     return Error::success();
514   }
515 
516   BlockDependenciesMap computeBlockNonLocalDeps(LinkGraph &G) {
517     // First calculate the reachable-via-non-local-symbol blocks for each block.
518     struct BlockInfo {
519       DenseSet<Block *> Dependencies;
520       DenseSet<Block *> Dependants;
521       bool DependenciesChanged = true;
522     };
523     DenseMap<Block *, BlockInfo> BlockInfos;
524     SmallVector<Block *> WorkList;
525 
526     // Pre-allocate map entries. This prevents any iterator/reference
527     // invalidation in the next loop.
528     for (auto *B : G.blocks())
529       (void)BlockInfos[B];
530 
531     // Build initial worklist, record block dependencies/dependants and
532     // non-local symbol dependencies.
533     for (auto *B : G.blocks()) {
534       auto &BI = BlockInfos[B];
535       for (auto &E : B->edges()) {
536         if (E.getTarget().getScope() == Scope::Local) {
537           auto &TgtB = E.getTarget().getBlock();
538           if (&TgtB != B) {
539             BI.Dependencies.insert(&TgtB);
540             BlockInfos[&TgtB].Dependants.insert(B);
541           }
542         }
543       }
544 
545       // If this node has both dependants and dependencies then add it to the
546       // worklist to propagate the dependencies to the dependants.
547       if (!BI.Dependants.empty() && !BI.Dependencies.empty())
548         WorkList.push_back(B);
549     }
550 
551     // Propagate block-level dependencies through the block-dependence graph.
552     while (!WorkList.empty()) {
553       auto *B = WorkList.pop_back_val();
554 
555       auto &BI = BlockInfos[B];
556       assert(BI.DependenciesChanged &&
557              "Block in worklist has unchanged dependencies");
558       BI.DependenciesChanged = false;
559       for (auto *Dependant : BI.Dependants) {
560         auto &DependantBI = BlockInfos[Dependant];
561         for (auto *Dependency : BI.Dependencies) {
562           if (Dependant != Dependency &&
563               DependantBI.Dependencies.insert(Dependency).second)
564             if (!DependantBI.DependenciesChanged) {
565               DependantBI.DependenciesChanged = true;
566               WorkList.push_back(Dependant);
567             }
568         }
569       }
570     }
571 
572     DenseMap<const Block *, DenseSet<Block *>> BlockDeps;
573     for (auto &KV : BlockInfos)
574       BlockDeps[KV.first] = std::move(KV.second.Dependencies);
575 
576     return BlockDependenciesMap(Layer.getExecutionSession(),
577                                 std::move(BlockDeps));
578   }
579 
580   void registerDependencies(const SymbolDependenceMap &QueryDeps) {
581     for (auto &NamedDepsEntry : ExternalNamedSymbolDeps) {
582       auto &Name = NamedDepsEntry.first;
583       auto &NameDeps = NamedDepsEntry.second;
584       SymbolDependenceMap SymbolDeps;
585 
586       for (const auto &QueryDepsEntry : QueryDeps) {
587         JITDylib &SourceJD = *QueryDepsEntry.first;
588         const SymbolNameSet &Symbols = QueryDepsEntry.second;
589         auto &DepsForJD = SymbolDeps[&SourceJD];
590 
591         for (const auto &S : Symbols)
592           if (NameDeps.count(S))
593             DepsForJD.insert(S);
594 
595         if (DepsForJD.empty())
596           SymbolDeps.erase(&SourceJD);
597       }
598 
599       MR->addDependencies(Name, SymbolDeps);
600     }
601   }
602 
603   ObjectLinkingLayer &Layer;
604   std::unique_ptr<MaterializationResponsibility> MR;
605   std::unique_ptr<MemoryBuffer> ObjBuffer;
606   DenseMap<SymbolStringPtr, SymbolNameSet> ExternalNamedSymbolDeps;
607   DenseMap<SymbolStringPtr, SymbolNameSet> InternalNamedSymbolDeps;
608 };
609 
610 ObjectLinkingLayer::Plugin::~Plugin() {}
611 
612 char ObjectLinkingLayer::ID;
613 
614 using BaseT = RTTIExtends<ObjectLinkingLayer, ObjectLayer>;
615 
616 ObjectLinkingLayer::ObjectLinkingLayer(ExecutionSession &ES)
617     : BaseT(ES), MemMgr(ES.getExecutorProcessControl().getMemMgr()) {
618   ES.registerResourceManager(*this);
619 }
620 
621 ObjectLinkingLayer::ObjectLinkingLayer(ExecutionSession &ES,
622                                        JITLinkMemoryManager &MemMgr)
623     : BaseT(ES), MemMgr(MemMgr) {
624   ES.registerResourceManager(*this);
625 }
626 
627 ObjectLinkingLayer::ObjectLinkingLayer(
628     ExecutionSession &ES, std::unique_ptr<JITLinkMemoryManager> MemMgr)
629     : BaseT(ES), MemMgr(*MemMgr), MemMgrOwnership(std::move(MemMgr)) {
630   ES.registerResourceManager(*this);
631 }
632 
633 ObjectLinkingLayer::~ObjectLinkingLayer() {
634   assert(Allocs.empty() && "Layer destroyed with resources still attached");
635   getExecutionSession().deregisterResourceManager(*this);
636 }
637 
638 Error ObjectLinkingLayer::add(ResourceTrackerSP RT,
639                               std::unique_ptr<LinkGraph> G) {
640   auto &JD = RT->getJITDylib();
641   return JD.define(LinkGraphMaterializationUnit::Create(*this, std::move(G)),
642                    std::move(RT));
643 }
644 
645 void ObjectLinkingLayer::emit(std::unique_ptr<MaterializationResponsibility> R,
646                               std::unique_ptr<MemoryBuffer> O) {
647   assert(O && "Object must not be null");
648   MemoryBufferRef ObjBuffer = O->getMemBufferRef();
649 
650   auto Ctx = std::make_unique<ObjectLinkingLayerJITLinkContext>(
651       *this, std::move(R), std::move(O));
652   if (auto G = createLinkGraphFromObject(ObjBuffer)) {
653     Ctx->notifyMaterializing(**G);
654     link(std::move(*G), std::move(Ctx));
655   } else {
656     Ctx->notifyFailed(G.takeError());
657   }
658 }
659 
660 void ObjectLinkingLayer::emit(std::unique_ptr<MaterializationResponsibility> R,
661                               std::unique_ptr<LinkGraph> G) {
662   auto Ctx = std::make_unique<ObjectLinkingLayerJITLinkContext>(
663       *this, std::move(R), nullptr);
664   Ctx->notifyMaterializing(*G);
665   link(std::move(G), std::move(Ctx));
666 }
667 
668 void ObjectLinkingLayer::modifyPassConfig(MaterializationResponsibility &MR,
669                                           LinkGraph &G,
670                                           PassConfiguration &PassConfig) {
671   for (auto &P : Plugins)
672     P->modifyPassConfig(MR, G, PassConfig);
673 }
674 
675 void ObjectLinkingLayer::notifyLoaded(MaterializationResponsibility &MR) {
676   for (auto &P : Plugins)
677     P->notifyLoaded(MR);
678 }
679 
680 Error ObjectLinkingLayer::notifyEmitted(MaterializationResponsibility &MR,
681                                         AllocPtr Alloc) {
682   Error Err = Error::success();
683   for (auto &P : Plugins)
684     Err = joinErrors(std::move(Err), P->notifyEmitted(MR));
685 
686   if (Err)
687     return Err;
688 
689   return MR.withResourceKeyDo(
690       [&](ResourceKey K) { Allocs[K].push_back(std::move(Alloc)); });
691 }
692 
693 Error ObjectLinkingLayer::handleRemoveResources(ResourceKey K) {
694 
695   Error Err = Error::success();
696 
697   for (auto &P : Plugins)
698     Err = joinErrors(std::move(Err), P->notifyRemovingResources(K));
699 
700   std::vector<AllocPtr> AllocsToRemove;
701   getExecutionSession().runSessionLocked([&] {
702     auto I = Allocs.find(K);
703     if (I != Allocs.end()) {
704       std::swap(AllocsToRemove, I->second);
705       Allocs.erase(I);
706     }
707   });
708 
709   while (!AllocsToRemove.empty()) {
710     Err = joinErrors(std::move(Err), AllocsToRemove.back()->deallocate());
711     AllocsToRemove.pop_back();
712   }
713 
714   return Err;
715 }
716 
717 void ObjectLinkingLayer::handleTransferResources(ResourceKey DstKey,
718                                                  ResourceKey SrcKey) {
719   auto I = Allocs.find(SrcKey);
720   if (I != Allocs.end()) {
721     auto &SrcAllocs = I->second;
722     auto &DstAllocs = Allocs[DstKey];
723     DstAllocs.reserve(DstAllocs.size() + SrcAllocs.size());
724     for (auto &Alloc : SrcAllocs)
725       DstAllocs.push_back(std::move(Alloc));
726 
727     // Erase SrcKey entry using value rather than iterator I: I may have been
728     // invalidated when we looked up DstKey.
729     Allocs.erase(SrcKey);
730   }
731 
732   for (auto &P : Plugins)
733     P->notifyTransferringResources(DstKey, SrcKey);
734 }
735 
736 EHFrameRegistrationPlugin::EHFrameRegistrationPlugin(
737     ExecutionSession &ES, std::unique_ptr<EHFrameRegistrar> Registrar)
738     : ES(ES), Registrar(std::move(Registrar)) {}
739 
740 void EHFrameRegistrationPlugin::modifyPassConfig(
741     MaterializationResponsibility &MR, LinkGraph &G,
742     PassConfiguration &PassConfig) {
743 
744   PassConfig.PostFixupPasses.push_back(createEHFrameRecorderPass(
745       G.getTargetTriple(), [this, &MR](JITTargetAddress Addr, size_t Size) {
746         if (Addr) {
747           std::lock_guard<std::mutex> Lock(EHFramePluginMutex);
748           assert(!InProcessLinks.count(&MR) &&
749                  "Link for MR already being tracked?");
750           InProcessLinks[&MR] = {Addr, Size};
751         }
752       }));
753 }
754 
755 Error EHFrameRegistrationPlugin::notifyEmitted(
756     MaterializationResponsibility &MR) {
757 
758   EHFrameRange EmittedRange;
759   {
760     std::lock_guard<std::mutex> Lock(EHFramePluginMutex);
761 
762     auto EHFrameRangeItr = InProcessLinks.find(&MR);
763     if (EHFrameRangeItr == InProcessLinks.end())
764       return Error::success();
765 
766     EmittedRange = EHFrameRangeItr->second;
767     assert(EmittedRange.Addr && "eh-frame addr to register can not be null");
768     InProcessLinks.erase(EHFrameRangeItr);
769   }
770 
771   if (auto Err = MR.withResourceKeyDo(
772           [&](ResourceKey K) { EHFrameRanges[K].push_back(EmittedRange); }))
773     return Err;
774 
775   return Registrar->registerEHFrames(EmittedRange.Addr, EmittedRange.Size);
776 }
777 
778 Error EHFrameRegistrationPlugin::notifyFailed(
779     MaterializationResponsibility &MR) {
780   std::lock_guard<std::mutex> Lock(EHFramePluginMutex);
781   InProcessLinks.erase(&MR);
782   return Error::success();
783 }
784 
785 Error EHFrameRegistrationPlugin::notifyRemovingResources(ResourceKey K) {
786   std::vector<EHFrameRange> RangesToRemove;
787 
788   ES.runSessionLocked([&] {
789     auto I = EHFrameRanges.find(K);
790     if (I != EHFrameRanges.end()) {
791       RangesToRemove = std::move(I->second);
792       EHFrameRanges.erase(I);
793     }
794   });
795 
796   Error Err = Error::success();
797   while (!RangesToRemove.empty()) {
798     auto RangeToRemove = RangesToRemove.back();
799     RangesToRemove.pop_back();
800     assert(RangeToRemove.Addr && "Untracked eh-frame range must not be null");
801     Err = joinErrors(
802         std::move(Err),
803         Registrar->deregisterEHFrames(RangeToRemove.Addr, RangeToRemove.Size));
804   }
805 
806   return Err;
807 }
808 
809 void EHFrameRegistrationPlugin::notifyTransferringResources(
810     ResourceKey DstKey, ResourceKey SrcKey) {
811   auto SI = EHFrameRanges.find(SrcKey);
812   if (SI == EHFrameRanges.end())
813     return;
814 
815   auto DI = EHFrameRanges.find(DstKey);
816   if (DI != EHFrameRanges.end()) {
817     auto &SrcRanges = SI->second;
818     auto &DstRanges = DI->second;
819     DstRanges.reserve(DstRanges.size() + SrcRanges.size());
820     for (auto &SrcRange : SrcRanges)
821       DstRanges.push_back(std::move(SrcRange));
822     EHFrameRanges.erase(SI);
823   } else {
824     // We need to move SrcKey's ranges over without invalidating the SI
825     // iterator.
826     auto Tmp = std::move(SI->second);
827     EHFrameRanges.erase(SI);
828     EHFrameRanges[DstKey] = std::move(Tmp);
829   }
830 }
831 
832 } // End namespace orc.
833 } // End namespace llvm.
834