1 //===------------ JITLink.h - JIT linker functionality ----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Contains generic JIT-linker types.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_EXECUTIONENGINE_JITLINK_JITLINK_H
14 #define LLVM_EXECUTIONENGINE_JITLINK_JITLINK_H
15
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h"
22 #include "llvm/ExecutionEngine/JITLink/MemoryFlags.h"
23 #include "llvm/ExecutionEngine/JITSymbol.h"
24 #include "llvm/Support/Allocator.h"
25 #include "llvm/Support/Endian.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/FormatVariadic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/MemoryBuffer.h"
30
31 #include <map>
32 #include <string>
33 #include <system_error>
34
35 namespace llvm {
36 namespace jitlink {
37
38 class LinkGraph;
39 class Symbol;
40 class Section;
41
42 /// Base class for errors originating in JIT linker, e.g. missing relocation
43 /// support.
44 class JITLinkError : public ErrorInfo<JITLinkError> {
45 public:
46 static char ID;
47
JITLinkError(Twine ErrMsg)48 JITLinkError(Twine ErrMsg) : ErrMsg(ErrMsg.str()) {}
49
50 void log(raw_ostream &OS) const override;
getErrorMessage()51 const std::string &getErrorMessage() const { return ErrMsg; }
52 std::error_code convertToErrorCode() const override;
53
54 private:
55 std::string ErrMsg;
56 };
57
58 /// Represents fixups and constraints in the LinkGraph.
59 class Edge {
60 public:
61 using Kind = uint8_t;
62
63 enum GenericEdgeKind : Kind {
64 Invalid, // Invalid edge value.
65 FirstKeepAlive, // Keeps target alive. Offset/addend zero.
66 KeepAlive = FirstKeepAlive, // Tag first edge kind that preserves liveness.
67 FirstRelocation // First architecture specific relocation.
68 };
69
70 using OffsetT = uint32_t;
71 using AddendT = int64_t;
72
Edge(Kind K,OffsetT Offset,Symbol & Target,AddendT Addend)73 Edge(Kind K, OffsetT Offset, Symbol &Target, AddendT Addend)
74 : Target(&Target), Offset(Offset), Addend(Addend), K(K) {}
75
getOffset()76 OffsetT getOffset() const { return Offset; }
setOffset(OffsetT Offset)77 void setOffset(OffsetT Offset) { this->Offset = Offset; }
getKind()78 Kind getKind() const { return K; }
setKind(Kind K)79 void setKind(Kind K) { this->K = K; }
isRelocation()80 bool isRelocation() const { return K >= FirstRelocation; }
getRelocation()81 Kind getRelocation() const {
82 assert(isRelocation() && "Not a relocation edge");
83 return K - FirstRelocation;
84 }
isKeepAlive()85 bool isKeepAlive() const { return K >= FirstKeepAlive; }
getTarget()86 Symbol &getTarget() const { return *Target; }
setTarget(Symbol & Target)87 void setTarget(Symbol &Target) { this->Target = &Target; }
getAddend()88 AddendT getAddend() const { return Addend; }
setAddend(AddendT Addend)89 void setAddend(AddendT Addend) { this->Addend = Addend; }
90
91 private:
92 Symbol *Target = nullptr;
93 OffsetT Offset = 0;
94 AddendT Addend = 0;
95 Kind K = 0;
96 };
97
98 /// Returns the string name of the given generic edge kind, or "unknown"
99 /// otherwise. Useful for debugging.
100 const char *getGenericEdgeKindName(Edge::Kind K);
101
102 /// Base class for Addressable entities (externals, absolutes, blocks).
103 class Addressable {
104 friend class LinkGraph;
105
106 protected:
Addressable(orc::ExecutorAddr Address,bool IsDefined)107 Addressable(orc::ExecutorAddr Address, bool IsDefined)
108 : Address(Address), IsDefined(IsDefined), IsAbsolute(false) {}
109
Addressable(orc::ExecutorAddr Address)110 Addressable(orc::ExecutorAddr Address)
111 : Address(Address), IsDefined(false), IsAbsolute(true) {
112 assert(!(IsDefined && IsAbsolute) &&
113 "Block cannot be both defined and absolute");
114 }
115
116 public:
117 Addressable(const Addressable &) = delete;
118 Addressable &operator=(const Addressable &) = default;
119 Addressable(Addressable &&) = delete;
120 Addressable &operator=(Addressable &&) = default;
121
getAddress()122 orc::ExecutorAddr getAddress() const { return Address; }
setAddress(orc::ExecutorAddr Address)123 void setAddress(orc::ExecutorAddr Address) { this->Address = Address; }
124
125 /// Returns true if this is a defined addressable, in which case you
126 /// can downcast this to a Block.
isDefined()127 bool isDefined() const { return static_cast<bool>(IsDefined); }
isAbsolute()128 bool isAbsolute() const { return static_cast<bool>(IsAbsolute); }
129
130 private:
setAbsolute(bool IsAbsolute)131 void setAbsolute(bool IsAbsolute) {
132 assert(!IsDefined && "Cannot change the Absolute flag on a defined block");
133 this->IsAbsolute = IsAbsolute;
134 }
135
136 orc::ExecutorAddr Address;
137 uint64_t IsDefined : 1;
138 uint64_t IsAbsolute : 1;
139
140 protected:
141 // bitfields for Block, allocated here to improve packing.
142 uint64_t ContentMutable : 1;
143 uint64_t P2Align : 5;
144 uint64_t AlignmentOffset : 56;
145 };
146
147 using SectionOrdinal = unsigned;
148
149 /// An Addressable with content and edges.
150 class Block : public Addressable {
151 friend class LinkGraph;
152
153 private:
154 /// Create a zero-fill defined addressable.
Block(Section & Parent,orc::ExecutorAddrDiff Size,orc::ExecutorAddr Address,uint64_t Alignment,uint64_t AlignmentOffset)155 Block(Section &Parent, orc::ExecutorAddrDiff Size, orc::ExecutorAddr Address,
156 uint64_t Alignment, uint64_t AlignmentOffset)
157 : Addressable(Address, true), Parent(&Parent), Size(Size) {
158 assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
159 assert(AlignmentOffset < Alignment &&
160 "Alignment offset cannot exceed alignment");
161 assert(AlignmentOffset <= MaxAlignmentOffset &&
162 "Alignment offset exceeds maximum");
163 ContentMutable = false;
164 P2Align = Alignment ? countTrailingZeros(Alignment) : 0;
165 this->AlignmentOffset = AlignmentOffset;
166 }
167
168 /// Create a defined addressable for the given content.
169 /// The Content is assumed to be non-writable, and will be copied when
170 /// mutations are required.
Block(Section & Parent,ArrayRef<char> Content,orc::ExecutorAddr Address,uint64_t Alignment,uint64_t AlignmentOffset)171 Block(Section &Parent, ArrayRef<char> Content, orc::ExecutorAddr Address,
172 uint64_t Alignment, uint64_t AlignmentOffset)
173 : Addressable(Address, true), Parent(&Parent), Data(Content.data()),
174 Size(Content.size()) {
175 assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
176 assert(AlignmentOffset < Alignment &&
177 "Alignment offset cannot exceed alignment");
178 assert(AlignmentOffset <= MaxAlignmentOffset &&
179 "Alignment offset exceeds maximum");
180 ContentMutable = false;
181 P2Align = Alignment ? countTrailingZeros(Alignment) : 0;
182 this->AlignmentOffset = AlignmentOffset;
183 }
184
185 /// Create a defined addressable for the given content.
186 /// The content is assumed to be writable, and the caller is responsible
187 /// for ensuring that it lives for the duration of the Block's lifetime.
188 /// The standard way to achieve this is to allocate it on the Graph's
189 /// allocator.
Block(Section & Parent,MutableArrayRef<char> Content,orc::ExecutorAddr Address,uint64_t Alignment,uint64_t AlignmentOffset)190 Block(Section &Parent, MutableArrayRef<char> Content,
191 orc::ExecutorAddr Address, uint64_t Alignment, uint64_t AlignmentOffset)
192 : Addressable(Address, true), Parent(&Parent), Data(Content.data()),
193 Size(Content.size()) {
194 assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
195 assert(AlignmentOffset < Alignment &&
196 "Alignment offset cannot exceed alignment");
197 assert(AlignmentOffset <= MaxAlignmentOffset &&
198 "Alignment offset exceeds maximum");
199 ContentMutable = true;
200 P2Align = Alignment ? countTrailingZeros(Alignment) : 0;
201 this->AlignmentOffset = AlignmentOffset;
202 }
203
204 public:
205 using EdgeVector = std::vector<Edge>;
206 using edge_iterator = EdgeVector::iterator;
207 using const_edge_iterator = EdgeVector::const_iterator;
208
209 Block(const Block &) = delete;
210 Block &operator=(const Block &) = delete;
211 Block(Block &&) = delete;
212 Block &operator=(Block &&) = delete;
213
214 /// Return the parent section for this block.
getSection()215 Section &getSection() const { return *Parent; }
216
217 /// Returns true if this is a zero-fill block.
218 ///
219 /// If true, getSize is callable but getContent is not (the content is
220 /// defined to be a sequence of zero bytes of length Size).
isZeroFill()221 bool isZeroFill() const { return !Data; }
222
223 /// Returns the size of this defined addressable.
getSize()224 size_t getSize() const { return Size; }
225
226 /// Returns the address range of this defined addressable.
getRange()227 orc::ExecutorAddrRange getRange() const {
228 return orc::ExecutorAddrRange(getAddress(), getSize());
229 }
230
231 /// Get the content for this block. Block must not be a zero-fill block.
getContent()232 ArrayRef<char> getContent() const {
233 assert(Data && "Block does not contain content");
234 return ArrayRef<char>(Data, Size);
235 }
236
237 /// Set the content for this block.
238 /// Caller is responsible for ensuring the underlying bytes are not
239 /// deallocated while pointed to by this block.
setContent(ArrayRef<char> Content)240 void setContent(ArrayRef<char> Content) {
241 assert(Content.data() && "Setting null content");
242 Data = Content.data();
243 Size = Content.size();
244 ContentMutable = false;
245 }
246
247 /// Get mutable content for this block.
248 ///
249 /// If this Block's content is not already mutable this will trigger a copy
250 /// of the existing immutable content to a new, mutable buffer allocated using
251 /// LinkGraph::allocateContent.
252 MutableArrayRef<char> getMutableContent(LinkGraph &G);
253
254 /// Get mutable content for this block.
255 ///
256 /// This block's content must already be mutable. It is a programmatic error
257 /// to call this on a block with immutable content -- consider using
258 /// getMutableContent instead.
getAlreadyMutableContent()259 MutableArrayRef<char> getAlreadyMutableContent() {
260 assert(Data && "Block does not contain content");
261 assert(ContentMutable && "Content is not mutable");
262 return MutableArrayRef<char>(const_cast<char *>(Data), Size);
263 }
264
265 /// Set mutable content for this block.
266 ///
267 /// The caller is responsible for ensuring that the memory pointed to by
268 /// MutableContent is not deallocated while pointed to by this block.
setMutableContent(MutableArrayRef<char> MutableContent)269 void setMutableContent(MutableArrayRef<char> MutableContent) {
270 assert(MutableContent.data() && "Setting null content");
271 Data = MutableContent.data();
272 Size = MutableContent.size();
273 ContentMutable = true;
274 }
275
276 /// Returns true if this block's content is mutable.
277 ///
278 /// This is primarily useful for asserting that a block is already in a
279 /// mutable state prior to modifying the content. E.g. when applying
280 /// fixups we expect the block to already be mutable as it should have been
281 /// copied to working memory.
isContentMutable()282 bool isContentMutable() const { return ContentMutable; }
283
284 /// Get the alignment for this content.
getAlignment()285 uint64_t getAlignment() const { return 1ull << P2Align; }
286
287 /// Set the alignment for this content.
setAlignment(uint64_t Alignment)288 void setAlignment(uint64_t Alignment) {
289 assert(isPowerOf2_64(Alignment) && "Alignment must be a power of two");
290 P2Align = Alignment ? countTrailingZeros(Alignment) : 0;
291 }
292
293 /// Get the alignment offset for this content.
getAlignmentOffset()294 uint64_t getAlignmentOffset() const { return AlignmentOffset; }
295
296 /// Set the alignment offset for this content.
setAlignmentOffset(uint64_t AlignmentOffset)297 void setAlignmentOffset(uint64_t AlignmentOffset) {
298 assert(AlignmentOffset < (1ull << P2Align) &&
299 "Alignment offset can't exceed alignment");
300 this->AlignmentOffset = AlignmentOffset;
301 }
302
303 /// Add an edge to this block.
addEdge(Edge::Kind K,Edge::OffsetT Offset,Symbol & Target,Edge::AddendT Addend)304 void addEdge(Edge::Kind K, Edge::OffsetT Offset, Symbol &Target,
305 Edge::AddendT Addend) {
306 assert(!isZeroFill() && "Adding edge to zero-fill block?");
307 Edges.push_back(Edge(K, Offset, Target, Addend));
308 }
309
310 /// Add an edge by copying an existing one. This is typically used when
311 /// moving edges between blocks.
addEdge(const Edge & E)312 void addEdge(const Edge &E) { Edges.push_back(E); }
313
314 /// Return the list of edges attached to this content.
edges()315 iterator_range<edge_iterator> edges() {
316 return make_range(Edges.begin(), Edges.end());
317 }
318
319 /// Returns the list of edges attached to this content.
edges()320 iterator_range<const_edge_iterator> edges() const {
321 return make_range(Edges.begin(), Edges.end());
322 }
323
324 /// Return the size of the edges list.
edges_size()325 size_t edges_size() const { return Edges.size(); }
326
327 /// Returns true if the list of edges is empty.
edges_empty()328 bool edges_empty() const { return Edges.empty(); }
329
330 /// Remove the edge pointed to by the given iterator.
331 /// Returns an iterator to the new next element.
removeEdge(edge_iterator I)332 edge_iterator removeEdge(edge_iterator I) { return Edges.erase(I); }
333
334 /// Returns the address of the fixup for the given edge, which is equal to
335 /// this block's address plus the edge's offset.
getFixupAddress(const Edge & E)336 orc::ExecutorAddr getFixupAddress(const Edge &E) const {
337 return getAddress() + E.getOffset();
338 }
339
340 private:
341 static constexpr uint64_t MaxAlignmentOffset = (1ULL << 56) - 1;
342
setSection(Section & Parent)343 void setSection(Section &Parent) { this->Parent = &Parent; }
344
345 Section *Parent;
346 const char *Data = nullptr;
347 size_t Size = 0;
348 std::vector<Edge> Edges;
349 };
350
351 // Align an address to conform with block alignment requirements.
alignToBlock(uint64_t Addr,Block & B)352 inline uint64_t alignToBlock(uint64_t Addr, Block &B) {
353 uint64_t Delta = (B.getAlignmentOffset() - Addr) % B.getAlignment();
354 return Addr + Delta;
355 }
356
357 // Align a orc::ExecutorAddr to conform with block alignment requirements.
alignToBlock(orc::ExecutorAddr Addr,Block & B)358 inline orc::ExecutorAddr alignToBlock(orc::ExecutorAddr Addr, Block &B) {
359 return orc::ExecutorAddr(alignToBlock(Addr.getValue(), B));
360 }
361
362 /// Describes symbol linkage. This can be used to make resolve definition
363 /// clashes.
364 enum class Linkage : uint8_t {
365 Strong,
366 Weak,
367 };
368
369 /// For errors and debugging output.
370 const char *getLinkageName(Linkage L);
371
372 /// Defines the scope in which this symbol should be visible:
373 /// Default -- Visible in the public interface of the linkage unit.
374 /// Hidden -- Visible within the linkage unit, but not exported from it.
375 /// Local -- Visible only within the LinkGraph.
376 enum class Scope : uint8_t {
377 Default,
378 Hidden,
379 Local
380 };
381
382 /// For debugging output.
383 const char *getScopeName(Scope S);
384
385 raw_ostream &operator<<(raw_ostream &OS, const Block &B);
386
387 /// Symbol representation.
388 ///
389 /// Symbols represent locations within Addressable objects.
390 /// They can be either Named or Anonymous.
391 /// Anonymous symbols have neither linkage nor visibility, and must point at
392 /// ContentBlocks.
393 /// Named symbols may be in one of four states:
394 /// - Null: Default initialized. Assignable, but otherwise unusable.
395 /// - Defined: Has both linkage and visibility and points to a ContentBlock
396 /// - Common: Has both linkage and visibility, points to a null Addressable.
397 /// - External: Has neither linkage nor visibility, points to an external
398 /// Addressable.
399 ///
400 class Symbol {
401 friend class LinkGraph;
402
403 private:
Symbol(Addressable & Base,orc::ExecutorAddrDiff Offset,StringRef Name,orc::ExecutorAddrDiff Size,Linkage L,Scope S,bool IsLive,bool IsCallable)404 Symbol(Addressable &Base, orc::ExecutorAddrDiff Offset, StringRef Name,
405 orc::ExecutorAddrDiff Size, Linkage L, Scope S, bool IsLive,
406 bool IsCallable)
407 : Name(Name), Base(&Base), Offset(Offset), Size(Size) {
408 assert(Offset <= MaxOffset && "Offset out of range");
409 setLinkage(L);
410 setScope(S);
411 setLive(IsLive);
412 setCallable(IsCallable);
413 }
414
constructCommon(void * SymStorage,Block & Base,StringRef Name,orc::ExecutorAddrDiff Size,Scope S,bool IsLive)415 static Symbol &constructCommon(void *SymStorage, Block &Base, StringRef Name,
416 orc::ExecutorAddrDiff Size, Scope S,
417 bool IsLive) {
418 assert(SymStorage && "Storage cannot be null");
419 assert(!Name.empty() && "Common symbol name cannot be empty");
420 assert(Base.isDefined() &&
421 "Cannot create common symbol from undefined block");
422 assert(static_cast<Block &>(Base).getSize() == Size &&
423 "Common symbol size should match underlying block size");
424 auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
425 new (Sym) Symbol(Base, 0, Name, Size, Linkage::Weak, S, IsLive, false);
426 return *Sym;
427 }
428
constructExternal(void * SymStorage,Addressable & Base,StringRef Name,orc::ExecutorAddrDiff Size,Linkage L)429 static Symbol &constructExternal(void *SymStorage, Addressable &Base,
430 StringRef Name, orc::ExecutorAddrDiff Size,
431 Linkage L) {
432 assert(SymStorage && "Storage cannot be null");
433 assert(!Base.isDefined() &&
434 "Cannot create external symbol from defined block");
435 assert(!Name.empty() && "External symbol name cannot be empty");
436 auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
437 new (Sym) Symbol(Base, 0, Name, Size, L, Scope::Default, false, false);
438 return *Sym;
439 }
440
constructAbsolute(void * SymStorage,Addressable & Base,StringRef Name,orc::ExecutorAddrDiff Size,Linkage L,Scope S,bool IsLive)441 static Symbol &constructAbsolute(void *SymStorage, Addressable &Base,
442 StringRef Name, orc::ExecutorAddrDiff Size,
443 Linkage L, Scope S, bool IsLive) {
444 assert(SymStorage && "Storage cannot be null");
445 assert(!Base.isDefined() &&
446 "Cannot create absolute symbol from a defined block");
447 auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
448 new (Sym) Symbol(Base, 0, Name, Size, L, S, IsLive, false);
449 return *Sym;
450 }
451
constructAnonDef(void * SymStorage,Block & Base,orc::ExecutorAddrDiff Offset,orc::ExecutorAddrDiff Size,bool IsCallable,bool IsLive)452 static Symbol &constructAnonDef(void *SymStorage, Block &Base,
453 orc::ExecutorAddrDiff Offset,
454 orc::ExecutorAddrDiff Size, bool IsCallable,
455 bool IsLive) {
456 assert(SymStorage && "Storage cannot be null");
457 assert((Offset + Size) <= Base.getSize() &&
458 "Symbol extends past end of block");
459 auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
460 new (Sym) Symbol(Base, Offset, StringRef(), Size, Linkage::Strong,
461 Scope::Local, IsLive, IsCallable);
462 return *Sym;
463 }
464
constructNamedDef(void * SymStorage,Block & Base,orc::ExecutorAddrDiff Offset,StringRef Name,orc::ExecutorAddrDiff Size,Linkage L,Scope S,bool IsLive,bool IsCallable)465 static Symbol &constructNamedDef(void *SymStorage, Block &Base,
466 orc::ExecutorAddrDiff Offset, StringRef Name,
467 orc::ExecutorAddrDiff Size, Linkage L,
468 Scope S, bool IsLive, bool IsCallable) {
469 assert(SymStorage && "Storage cannot be null");
470 assert((Offset + Size) <= Base.getSize() &&
471 "Symbol extends past end of block");
472 assert(!Name.empty() && "Name cannot be empty");
473 auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
474 new (Sym) Symbol(Base, Offset, Name, Size, L, S, IsLive, IsCallable);
475 return *Sym;
476 }
477
478 public:
479 /// Create a null Symbol. This allows Symbols to be default initialized for
480 /// use in containers (e.g. as map values). Null symbols are only useful for
481 /// assigning to.
482 Symbol() = default;
483
484 // Symbols are not movable or copyable.
485 Symbol(const Symbol &) = delete;
486 Symbol &operator=(const Symbol &) = delete;
487 Symbol(Symbol &&) = delete;
488 Symbol &operator=(Symbol &&) = delete;
489
490 /// Returns true if this symbol has a name.
hasName()491 bool hasName() const { return !Name.empty(); }
492
493 /// Returns the name of this symbol (empty if the symbol is anonymous).
getName()494 StringRef getName() const {
495 assert((!Name.empty() || getScope() == Scope::Local) &&
496 "Anonymous symbol has non-local scope");
497 return Name;
498 }
499
500 /// Rename this symbol. The client is responsible for updating scope and
501 /// linkage if this name-change requires it.
setName(StringRef Name)502 void setName(StringRef Name) { this->Name = Name; }
503
504 /// Returns true if this Symbol has content (potentially) defined within this
505 /// object file (i.e. is anything but an external or absolute symbol).
isDefined()506 bool isDefined() const {
507 assert(Base && "Attempt to access null symbol");
508 return Base->isDefined();
509 }
510
511 /// Returns true if this symbol is live (i.e. should be treated as a root for
512 /// dead stripping).
isLive()513 bool isLive() const {
514 assert(Base && "Attempting to access null symbol");
515 return IsLive;
516 }
517
518 /// Set this symbol's live bit.
setLive(bool IsLive)519 void setLive(bool IsLive) { this->IsLive = IsLive; }
520
521 /// Returns true is this symbol is callable.
isCallable()522 bool isCallable() const { return IsCallable; }
523
524 /// Set this symbol's callable bit.
setCallable(bool IsCallable)525 void setCallable(bool IsCallable) { this->IsCallable = IsCallable; }
526
527 /// Returns true if the underlying addressable is an unresolved external.
isExternal()528 bool isExternal() const {
529 assert(Base && "Attempt to access null symbol");
530 return !Base->isDefined() && !Base->isAbsolute();
531 }
532
533 /// Returns true if the underlying addressable is an absolute symbol.
isAbsolute()534 bool isAbsolute() const {
535 assert(Base && "Attempt to access null symbol");
536 return Base->isAbsolute();
537 }
538
539 /// Return the addressable that this symbol points to.
getAddressable()540 Addressable &getAddressable() {
541 assert(Base && "Cannot get underlying addressable for null symbol");
542 return *Base;
543 }
544
545 /// Return the addressable that thsi symbol points to.
getAddressable()546 const Addressable &getAddressable() const {
547 assert(Base && "Cannot get underlying addressable for null symbol");
548 return *Base;
549 }
550
551 /// Return the Block for this Symbol (Symbol must be defined).
getBlock()552 Block &getBlock() {
553 assert(Base && "Cannot get block for null symbol");
554 assert(Base->isDefined() && "Not a defined symbol");
555 return static_cast<Block &>(*Base);
556 }
557
558 /// Return the Block for this Symbol (Symbol must be defined).
getBlock()559 const Block &getBlock() const {
560 assert(Base && "Cannot get block for null symbol");
561 assert(Base->isDefined() && "Not a defined symbol");
562 return static_cast<const Block &>(*Base);
563 }
564
565 /// Returns the offset for this symbol within the underlying addressable.
getOffset()566 orc::ExecutorAddrDiff getOffset() const { return Offset; }
567
568 /// Returns the address of this symbol.
getAddress()569 orc::ExecutorAddr getAddress() const { return Base->getAddress() + Offset; }
570
571 /// Returns the size of this symbol.
getSize()572 orc::ExecutorAddrDiff getSize() const { return Size; }
573
574 /// Set the size of this symbol.
setSize(orc::ExecutorAddrDiff Size)575 void setSize(orc::ExecutorAddrDiff Size) {
576 assert(Base && "Cannot set size for null Symbol");
577 assert((Size == 0 || Base->isDefined()) &&
578 "Non-zero size can only be set for defined symbols");
579 assert((Offset + Size <= static_cast<const Block &>(*Base).getSize()) &&
580 "Symbol size cannot extend past the end of its containing block");
581 this->Size = Size;
582 }
583
584 /// Returns the address range of this symbol.
getRange()585 orc::ExecutorAddrRange getRange() const {
586 return orc::ExecutorAddrRange(getAddress(), getSize());
587 }
588
589 /// Returns true if this symbol is backed by a zero-fill block.
590 /// This method may only be called on defined symbols.
isSymbolZeroFill()591 bool isSymbolZeroFill() const { return getBlock().isZeroFill(); }
592
593 /// Returns the content in the underlying block covered by this symbol.
594 /// This method may only be called on defined non-zero-fill symbols.
getSymbolContent()595 ArrayRef<char> getSymbolContent() const {
596 return getBlock().getContent().slice(Offset, Size);
597 }
598
599 /// Get the linkage for this Symbol.
getLinkage()600 Linkage getLinkage() const { return static_cast<Linkage>(L); }
601
602 /// Set the linkage for this Symbol.
setLinkage(Linkage L)603 void setLinkage(Linkage L) {
604 assert((L == Linkage::Strong || (!Base->isAbsolute() && !Name.empty())) &&
605 "Linkage can only be applied to defined named symbols");
606 this->L = static_cast<uint8_t>(L);
607 }
608
609 /// Get the visibility for this Symbol.
getScope()610 Scope getScope() const { return static_cast<Scope>(S); }
611
612 /// Set the visibility for this Symbol.
setScope(Scope S)613 void setScope(Scope S) {
614 assert((!Name.empty() || S == Scope::Local) &&
615 "Can not set anonymous symbol to non-local scope");
616 assert((S == Scope::Default || Base->isDefined() || Base->isAbsolute()) &&
617 "Invalid visibility for symbol type");
618 this->S = static_cast<uint8_t>(S);
619 }
620
621 private:
makeExternal(Addressable & A)622 void makeExternal(Addressable &A) {
623 assert(!A.isDefined() && !A.isAbsolute() &&
624 "Attempting to make external with defined or absolute block");
625 Base = &A;
626 Offset = 0;
627 setScope(Scope::Default);
628 IsLive = 0;
629 // note: Size, Linkage and IsCallable fields left unchanged.
630 }
631
makeAbsolute(Addressable & A)632 void makeAbsolute(Addressable &A) {
633 assert(!A.isDefined() && A.isAbsolute() &&
634 "Attempting to make absolute with defined or external block");
635 Base = &A;
636 Offset = 0;
637 }
638
setBlock(Block & B)639 void setBlock(Block &B) { Base = &B; }
640
setOffset(orc::ExecutorAddrDiff NewOffset)641 void setOffset(orc::ExecutorAddrDiff NewOffset) {
642 assert(NewOffset <= MaxOffset && "Offset out of range");
643 Offset = NewOffset;
644 }
645
646 static constexpr uint64_t MaxOffset = (1ULL << 59) - 1;
647
648 // FIXME: A char* or SymbolStringPtr may pack better.
649 StringRef Name;
650 Addressable *Base = nullptr;
651 uint64_t Offset : 59;
652 uint64_t L : 1;
653 uint64_t S : 2;
654 uint64_t IsLive : 1;
655 uint64_t IsCallable : 1;
656 orc::ExecutorAddrDiff Size = 0;
657 };
658
659 raw_ostream &operator<<(raw_ostream &OS, const Symbol &A);
660
661 void printEdge(raw_ostream &OS, const Block &B, const Edge &E,
662 StringRef EdgeKindName);
663
664 /// Represents an object file section.
665 class Section {
666 friend class LinkGraph;
667
668 private:
Section(StringRef Name,MemProt Prot,SectionOrdinal SecOrdinal)669 Section(StringRef Name, MemProt Prot, SectionOrdinal SecOrdinal)
670 : Name(Name), Prot(Prot), SecOrdinal(SecOrdinal) {}
671
672 using SymbolSet = DenseSet<Symbol *>;
673 using BlockSet = DenseSet<Block *>;
674
675 public:
676 using symbol_iterator = SymbolSet::iterator;
677 using const_symbol_iterator = SymbolSet::const_iterator;
678
679 using block_iterator = BlockSet::iterator;
680 using const_block_iterator = BlockSet::const_iterator;
681
682 ~Section();
683
684 // Sections are not movable or copyable.
685 Section(const Section &) = delete;
686 Section &operator=(const Section &) = delete;
687 Section(Section &&) = delete;
688 Section &operator=(Section &&) = delete;
689
690 /// Returns the name of this section.
getName()691 StringRef getName() const { return Name; }
692
693 /// Returns the protection flags for this section.
getMemProt()694 MemProt getMemProt() const { return Prot; }
695
696 /// Set the protection flags for this section.
setMemProt(MemProt Prot)697 void setMemProt(MemProt Prot) { this->Prot = Prot; }
698
699 /// Get the deallocation policy for this section.
getMemDeallocPolicy()700 MemDeallocPolicy getMemDeallocPolicy() const { return MDP; }
701
702 /// Set the deallocation policy for this section.
setMemDeallocPolicy(MemDeallocPolicy MDP)703 void setMemDeallocPolicy(MemDeallocPolicy MDP) { this->MDP = MDP; }
704
705 /// Returns the ordinal for this section.
getOrdinal()706 SectionOrdinal getOrdinal() const { return SecOrdinal; }
707
708 /// Returns an iterator over the blocks defined in this section.
blocks()709 iterator_range<block_iterator> blocks() {
710 return make_range(Blocks.begin(), Blocks.end());
711 }
712
713 /// Returns an iterator over the blocks defined in this section.
blocks()714 iterator_range<const_block_iterator> blocks() const {
715 return make_range(Blocks.begin(), Blocks.end());
716 }
717
718 /// Returns the number of blocks in this section.
blocks_size()719 BlockSet::size_type blocks_size() const { return Blocks.size(); }
720
721 /// Returns an iterator over the symbols defined in this section.
symbols()722 iterator_range<symbol_iterator> symbols() {
723 return make_range(Symbols.begin(), Symbols.end());
724 }
725
726 /// Returns an iterator over the symbols defined in this section.
symbols()727 iterator_range<const_symbol_iterator> symbols() const {
728 return make_range(Symbols.begin(), Symbols.end());
729 }
730
731 /// Return the number of symbols in this section.
symbols_size()732 SymbolSet::size_type symbols_size() const { return Symbols.size(); }
733
734 private:
addSymbol(Symbol & Sym)735 void addSymbol(Symbol &Sym) {
736 assert(!Symbols.count(&Sym) && "Symbol is already in this section");
737 Symbols.insert(&Sym);
738 }
739
removeSymbol(Symbol & Sym)740 void removeSymbol(Symbol &Sym) {
741 assert(Symbols.count(&Sym) && "symbol is not in this section");
742 Symbols.erase(&Sym);
743 }
744
addBlock(Block & B)745 void addBlock(Block &B) {
746 assert(!Blocks.count(&B) && "Block is already in this section");
747 Blocks.insert(&B);
748 }
749
removeBlock(Block & B)750 void removeBlock(Block &B) {
751 assert(Blocks.count(&B) && "Block is not in this section");
752 Blocks.erase(&B);
753 }
754
transferContentTo(Section & DstSection)755 void transferContentTo(Section &DstSection) {
756 if (&DstSection == this)
757 return;
758 for (auto *S : Symbols)
759 DstSection.addSymbol(*S);
760 for (auto *B : Blocks)
761 DstSection.addBlock(*B);
762 Symbols.clear();
763 Blocks.clear();
764 }
765
766 StringRef Name;
767 MemProt Prot;
768 MemDeallocPolicy MDP = MemDeallocPolicy::Standard;
769 SectionOrdinal SecOrdinal = 0;
770 BlockSet Blocks;
771 SymbolSet Symbols;
772 };
773
774 /// Represents a section address range via a pair of Block pointers
775 /// to the first and last Blocks in the section.
776 class SectionRange {
777 public:
778 SectionRange() = default;
SectionRange(const Section & Sec)779 SectionRange(const Section &Sec) {
780 if (llvm::empty(Sec.blocks()))
781 return;
782 First = Last = *Sec.blocks().begin();
783 for (auto *B : Sec.blocks()) {
784 if (B->getAddress() < First->getAddress())
785 First = B;
786 if (B->getAddress() > Last->getAddress())
787 Last = B;
788 }
789 }
getFirstBlock()790 Block *getFirstBlock() const {
791 assert((!Last || First) && "First can not be null if end is non-null");
792 return First;
793 }
getLastBlock()794 Block *getLastBlock() const {
795 assert((First || !Last) && "Last can not be null if start is non-null");
796 return Last;
797 }
empty()798 bool empty() const {
799 assert((First || !Last) && "Last can not be null if start is non-null");
800 return !First;
801 }
getStart()802 orc::ExecutorAddr getStart() const {
803 return First ? First->getAddress() : orc::ExecutorAddr();
804 }
getEnd()805 orc::ExecutorAddr getEnd() const {
806 return Last ? Last->getAddress() + Last->getSize() : orc::ExecutorAddr();
807 }
getSize()808 orc::ExecutorAddrDiff getSize() const { return getEnd() - getStart(); }
809
getRange()810 orc::ExecutorAddrRange getRange() const {
811 return orc::ExecutorAddrRange(getStart(), getEnd());
812 }
813
814 private:
815 Block *First = nullptr;
816 Block *Last = nullptr;
817 };
818
819 class LinkGraph {
820 private:
821 using SectionList = std::vector<std::unique_ptr<Section>>;
822 using ExternalSymbolSet = DenseSet<Symbol *>;
823 using BlockSet = DenseSet<Block *>;
824
825 template <typename... ArgTs>
createAddressable(ArgTs &&...Args)826 Addressable &createAddressable(ArgTs &&... Args) {
827 Addressable *A =
828 reinterpret_cast<Addressable *>(Allocator.Allocate<Addressable>());
829 new (A) Addressable(std::forward<ArgTs>(Args)...);
830 return *A;
831 }
832
destroyAddressable(Addressable & A)833 void destroyAddressable(Addressable &A) {
834 A.~Addressable();
835 Allocator.Deallocate(&A);
836 }
837
createBlock(ArgTs &&...Args)838 template <typename... ArgTs> Block &createBlock(ArgTs &&... Args) {
839 Block *B = reinterpret_cast<Block *>(Allocator.Allocate<Block>());
840 new (B) Block(std::forward<ArgTs>(Args)...);
841 B->getSection().addBlock(*B);
842 return *B;
843 }
844
destroyBlock(Block & B)845 void destroyBlock(Block &B) {
846 B.~Block();
847 Allocator.Deallocate(&B);
848 }
849
destroySymbol(Symbol & S)850 void destroySymbol(Symbol &S) {
851 S.~Symbol();
852 Allocator.Deallocate(&S);
853 }
854
getSectionBlocks(Section & S)855 static iterator_range<Section::block_iterator> getSectionBlocks(Section &S) {
856 return S.blocks();
857 }
858
859 static iterator_range<Section::const_block_iterator>
getSectionConstBlocks(Section & S)860 getSectionConstBlocks(Section &S) {
861 return S.blocks();
862 }
863
864 static iterator_range<Section::symbol_iterator>
getSectionSymbols(Section & S)865 getSectionSymbols(Section &S) {
866 return S.symbols();
867 }
868
869 static iterator_range<Section::const_symbol_iterator>
getSectionConstSymbols(Section & S)870 getSectionConstSymbols(Section &S) {
871 return S.symbols();
872 }
873
874 public:
875 using external_symbol_iterator = ExternalSymbolSet::iterator;
876
877 using section_iterator = pointee_iterator<SectionList::iterator>;
878 using const_section_iterator = pointee_iterator<SectionList::const_iterator>;
879
880 template <typename OuterItrT, typename InnerItrT, typename T,
881 iterator_range<InnerItrT> getInnerRange(
882 typename OuterItrT::reference)>
883 class nested_collection_iterator
884 : public iterator_facade_base<
885 nested_collection_iterator<OuterItrT, InnerItrT, T, getInnerRange>,
886 std::forward_iterator_tag, T> {
887 public:
888 nested_collection_iterator() = default;
889
nested_collection_iterator(OuterItrT OuterI,OuterItrT OuterE)890 nested_collection_iterator(OuterItrT OuterI, OuterItrT OuterE)
891 : OuterI(OuterI), OuterE(OuterE),
892 InnerI(getInnerBegin(OuterI, OuterE)) {
893 moveToNonEmptyInnerOrEnd();
894 }
895
896 bool operator==(const nested_collection_iterator &RHS) const {
897 return (OuterI == RHS.OuterI) && (InnerI == RHS.InnerI);
898 }
899
900 T operator*() const {
901 assert(InnerI != getInnerRange(*OuterI).end() && "Dereferencing end?");
902 return *InnerI;
903 }
904
905 nested_collection_iterator operator++() {
906 ++InnerI;
907 moveToNonEmptyInnerOrEnd();
908 return *this;
909 }
910
911 private:
getInnerBegin(OuterItrT OuterI,OuterItrT OuterE)912 static InnerItrT getInnerBegin(OuterItrT OuterI, OuterItrT OuterE) {
913 return OuterI != OuterE ? getInnerRange(*OuterI).begin() : InnerItrT();
914 }
915
moveToNonEmptyInnerOrEnd()916 void moveToNonEmptyInnerOrEnd() {
917 while (OuterI != OuterE && InnerI == getInnerRange(*OuterI).end()) {
918 ++OuterI;
919 InnerI = getInnerBegin(OuterI, OuterE);
920 }
921 }
922
923 OuterItrT OuterI, OuterE;
924 InnerItrT InnerI;
925 };
926
927 using defined_symbol_iterator =
928 nested_collection_iterator<const_section_iterator,
929 Section::symbol_iterator, Symbol *,
930 getSectionSymbols>;
931
932 using const_defined_symbol_iterator =
933 nested_collection_iterator<const_section_iterator,
934 Section::const_symbol_iterator, const Symbol *,
935 getSectionConstSymbols>;
936
937 using block_iterator = nested_collection_iterator<const_section_iterator,
938 Section::block_iterator,
939 Block *, getSectionBlocks>;
940
941 using const_block_iterator =
942 nested_collection_iterator<const_section_iterator,
943 Section::const_block_iterator, const Block *,
944 getSectionConstBlocks>;
945
946 using GetEdgeKindNameFunction = const char *(*)(Edge::Kind);
947
LinkGraph(std::string Name,const Triple & TT,unsigned PointerSize,support::endianness Endianness,GetEdgeKindNameFunction GetEdgeKindName)948 LinkGraph(std::string Name, const Triple &TT, unsigned PointerSize,
949 support::endianness Endianness,
950 GetEdgeKindNameFunction GetEdgeKindName)
951 : Name(std::move(Name)), TT(TT), PointerSize(PointerSize),
952 Endianness(Endianness), GetEdgeKindName(std::move(GetEdgeKindName)) {}
953
954 LinkGraph(const LinkGraph &) = delete;
955 LinkGraph &operator=(const LinkGraph &) = delete;
956 LinkGraph(LinkGraph &&) = delete;
957 LinkGraph &operator=(LinkGraph &&) = delete;
958
959 /// Returns the name of this graph (usually the name of the original
960 /// underlying MemoryBuffer).
getName()961 const std::string &getName() const { return Name; }
962
963 /// Returns the target triple for this Graph.
getTargetTriple()964 const Triple &getTargetTriple() const { return TT; }
965
966 /// Returns the pointer size for use in this graph.
getPointerSize()967 unsigned getPointerSize() const { return PointerSize; }
968
969 /// Returns the endianness of content in this graph.
getEndianness()970 support::endianness getEndianness() const { return Endianness; }
971
getEdgeKindName(Edge::Kind K)972 const char *getEdgeKindName(Edge::Kind K) const { return GetEdgeKindName(K); }
973
974 /// Allocate a mutable buffer of the given size using the LinkGraph's
975 /// allocator.
allocateBuffer(size_t Size)976 MutableArrayRef<char> allocateBuffer(size_t Size) {
977 return {Allocator.Allocate<char>(Size), Size};
978 }
979
980 /// Allocate a copy of the given string using the LinkGraph's allocator.
981 /// This can be useful when renaming symbols or adding new content to the
982 /// graph.
allocateContent(ArrayRef<char> Source)983 MutableArrayRef<char> allocateContent(ArrayRef<char> Source) {
984 auto *AllocatedBuffer = Allocator.Allocate<char>(Source.size());
985 llvm::copy(Source, AllocatedBuffer);
986 return MutableArrayRef<char>(AllocatedBuffer, Source.size());
987 }
988
989 /// Allocate a copy of the given string using the LinkGraph's allocator.
990 /// This can be useful when renaming symbols or adding new content to the
991 /// graph.
992 ///
993 /// Note: This Twine-based overload requires an extra string copy and an
994 /// extra heap allocation for large strings. The ArrayRef<char> overload
995 /// should be preferred where possible.
allocateString(Twine Source)996 MutableArrayRef<char> allocateString(Twine Source) {
997 SmallString<256> TmpBuffer;
998 auto SourceStr = Source.toStringRef(TmpBuffer);
999 auto *AllocatedBuffer = Allocator.Allocate<char>(SourceStr.size());
1000 llvm::copy(SourceStr, AllocatedBuffer);
1001 return MutableArrayRef<char>(AllocatedBuffer, SourceStr.size());
1002 }
1003
1004 /// Create a section with the given name, protection flags, and alignment.
createSection(StringRef Name,MemProt Prot)1005 Section &createSection(StringRef Name, MemProt Prot) {
1006 assert(llvm::find_if(Sections,
1007 [&](std::unique_ptr<Section> &Sec) {
1008 return Sec->getName() == Name;
1009 }) == Sections.end() &&
1010 "Duplicate section name");
1011 std::unique_ptr<Section> Sec(new Section(Name, Prot, Sections.size()));
1012 Sections.push_back(std::move(Sec));
1013 return *Sections.back();
1014 }
1015
1016 /// Create a content block.
createContentBlock(Section & Parent,ArrayRef<char> Content,orc::ExecutorAddr Address,uint64_t Alignment,uint64_t AlignmentOffset)1017 Block &createContentBlock(Section &Parent, ArrayRef<char> Content,
1018 orc::ExecutorAddr Address, uint64_t Alignment,
1019 uint64_t AlignmentOffset) {
1020 return createBlock(Parent, Content, Address, Alignment, AlignmentOffset);
1021 }
1022
1023 /// Create a content block with initially mutable data.
createMutableContentBlock(Section & Parent,MutableArrayRef<char> MutableContent,orc::ExecutorAddr Address,uint64_t Alignment,uint64_t AlignmentOffset)1024 Block &createMutableContentBlock(Section &Parent,
1025 MutableArrayRef<char> MutableContent,
1026 orc::ExecutorAddr Address,
1027 uint64_t Alignment,
1028 uint64_t AlignmentOffset) {
1029 return createBlock(Parent, MutableContent, Address, Alignment,
1030 AlignmentOffset);
1031 }
1032
1033 /// Create a zero-fill block.
createZeroFillBlock(Section & Parent,orc::ExecutorAddrDiff Size,orc::ExecutorAddr Address,uint64_t Alignment,uint64_t AlignmentOffset)1034 Block &createZeroFillBlock(Section &Parent, orc::ExecutorAddrDiff Size,
1035 orc::ExecutorAddr Address, uint64_t Alignment,
1036 uint64_t AlignmentOffset) {
1037 return createBlock(Parent, Size, Address, Alignment, AlignmentOffset);
1038 }
1039
1040 /// Cache type for the splitBlock function.
1041 using SplitBlockCache = Optional<SmallVector<Symbol *, 8>>;
1042
1043 /// Splits block B at the given index which must be greater than zero.
1044 /// If SplitIndex == B.getSize() then this function is a no-op and returns B.
1045 /// If SplitIndex < B.getSize() then this function returns a new block
1046 /// covering the range [ 0, SplitIndex ), and B is modified to cover the range
1047 /// [ SplitIndex, B.size() ).
1048 ///
1049 /// The optional Cache parameter can be used to speed up repeated calls to
1050 /// splitBlock for a single block. If the value is None the cache will be
1051 /// treated as uninitialized and splitBlock will populate it. Otherwise it
1052 /// is assumed to contain the list of Symbols pointing at B, sorted in
1053 /// descending order of offset.
1054 ///
1055 /// Notes:
1056 ///
1057 /// 1. splitBlock must be used with care. Splitting a block may cause
1058 /// incoming edges to become invalid if the edge target subexpression
1059 /// points outside the bounds of the newly split target block (E.g. an
1060 /// edge 'S + 10 : Pointer64' where S points to a newly split block
1061 /// whose size is less than 10). No attempt is made to detect invalidation
1062 /// of incoming edges, as in general this requires context that the
1063 /// LinkGraph does not have. Clients are responsible for ensuring that
1064 /// splitBlock is not used in a way that invalidates edges.
1065 ///
1066 /// 2. The newly introduced block will have a new ordinal which will be
1067 /// higher than any other ordinals in the section. Clients are responsible
1068 /// for re-assigning block ordinals to restore a compatible order if
1069 /// needed.
1070 ///
1071 /// 3. The cache is not automatically updated if new symbols are introduced
1072 /// between calls to splitBlock. Any newly introduced symbols may be
1073 /// added to the cache manually (descending offset order must be
1074 /// preserved), or the cache can be set to None and rebuilt by
1075 /// splitBlock on the next call.
1076 Block &splitBlock(Block &B, size_t SplitIndex,
1077 SplitBlockCache *Cache = nullptr);
1078
1079 /// Add an external symbol.
1080 /// Some formats (e.g. ELF) allow Symbols to have sizes. For Symbols whose
1081 /// size is not known, you should substitute '0'.
1082 /// For external symbols Linkage determines whether the symbol must be
1083 /// present during lookup: Externals with strong linkage must be found or
1084 /// an error will be emitted. Externals with weak linkage are permitted to
1085 /// be undefined, in which case they are assigned a value of 0.
addExternalSymbol(StringRef Name,orc::ExecutorAddrDiff Size,Linkage L)1086 Symbol &addExternalSymbol(StringRef Name, orc::ExecutorAddrDiff Size,
1087 Linkage L) {
1088 assert(llvm::count_if(ExternalSymbols,
1089 [&](const Symbol *Sym) {
1090 return Sym->getName() == Name;
1091 }) == 0 &&
1092 "Duplicate external symbol");
1093 auto &Sym = Symbol::constructExternal(
1094 Allocator.Allocate<Symbol>(),
1095 createAddressable(orc::ExecutorAddr(), false), Name, Size, L);
1096 ExternalSymbols.insert(&Sym);
1097 return Sym;
1098 }
1099
1100 /// Add an absolute symbol.
addAbsoluteSymbol(StringRef Name,orc::ExecutorAddr Address,orc::ExecutorAddrDiff Size,Linkage L,Scope S,bool IsLive)1101 Symbol &addAbsoluteSymbol(StringRef Name, orc::ExecutorAddr Address,
1102 orc::ExecutorAddrDiff Size, Linkage L, Scope S,
1103 bool IsLive) {
1104 assert(llvm::count_if(AbsoluteSymbols,
1105 [&](const Symbol *Sym) {
1106 return Sym->getName() == Name;
1107 }) == 0 &&
1108 "Duplicate absolute symbol");
1109 auto &Sym = Symbol::constructAbsolute(Allocator.Allocate<Symbol>(),
1110 createAddressable(Address), Name,
1111 Size, L, S, IsLive);
1112 AbsoluteSymbols.insert(&Sym);
1113 return Sym;
1114 }
1115
1116 /// Convenience method for adding a weak zero-fill symbol.
addCommonSymbol(StringRef Name,Scope S,Section & Section,orc::ExecutorAddr Address,orc::ExecutorAddrDiff Size,uint64_t Alignment,bool IsLive)1117 Symbol &addCommonSymbol(StringRef Name, Scope S, Section &Section,
1118 orc::ExecutorAddr Address, orc::ExecutorAddrDiff Size,
1119 uint64_t Alignment, bool IsLive) {
1120 assert(llvm::count_if(defined_symbols(),
1121 [&](const Symbol *Sym) {
1122 return Sym->getName() == Name;
1123 }) == 0 &&
1124 "Duplicate defined symbol");
1125 auto &Sym = Symbol::constructCommon(
1126 Allocator.Allocate<Symbol>(),
1127 createBlock(Section, Size, Address, Alignment, 0), Name, Size, S,
1128 IsLive);
1129 Section.addSymbol(Sym);
1130 return Sym;
1131 }
1132
1133 /// Add an anonymous symbol.
addAnonymousSymbol(Block & Content,orc::ExecutorAddrDiff Offset,orc::ExecutorAddrDiff Size,bool IsCallable,bool IsLive)1134 Symbol &addAnonymousSymbol(Block &Content, orc::ExecutorAddrDiff Offset,
1135 orc::ExecutorAddrDiff Size, bool IsCallable,
1136 bool IsLive) {
1137 auto &Sym = Symbol::constructAnonDef(Allocator.Allocate<Symbol>(), Content,
1138 Offset, Size, IsCallable, IsLive);
1139 Content.getSection().addSymbol(Sym);
1140 return Sym;
1141 }
1142
1143 /// Add a named symbol.
addDefinedSymbol(Block & Content,orc::ExecutorAddrDiff Offset,StringRef Name,orc::ExecutorAddrDiff Size,Linkage L,Scope S,bool IsCallable,bool IsLive)1144 Symbol &addDefinedSymbol(Block &Content, orc::ExecutorAddrDiff Offset,
1145 StringRef Name, orc::ExecutorAddrDiff Size,
1146 Linkage L, Scope S, bool IsCallable, bool IsLive) {
1147 assert((S == Scope::Local || llvm::count_if(defined_symbols(),
1148 [&](const Symbol *Sym) {
1149 return Sym->getName() == Name;
1150 }) == 0) &&
1151 "Duplicate defined symbol");
1152 auto &Sym =
1153 Symbol::constructNamedDef(Allocator.Allocate<Symbol>(), Content, Offset,
1154 Name, Size, L, S, IsLive, IsCallable);
1155 Content.getSection().addSymbol(Sym);
1156 return Sym;
1157 }
1158
sections()1159 iterator_range<section_iterator> sections() {
1160 return make_range(section_iterator(Sections.begin()),
1161 section_iterator(Sections.end()));
1162 }
1163
sections_size()1164 SectionList::size_type sections_size() const { return Sections.size(); }
1165
1166 /// Returns the section with the given name if it exists, otherwise returns
1167 /// null.
findSectionByName(StringRef Name)1168 Section *findSectionByName(StringRef Name) {
1169 for (auto &S : sections())
1170 if (S.getName() == Name)
1171 return &S;
1172 return nullptr;
1173 }
1174
blocks()1175 iterator_range<block_iterator> blocks() {
1176 return make_range(block_iterator(Sections.begin(), Sections.end()),
1177 block_iterator(Sections.end(), Sections.end()));
1178 }
1179
blocks()1180 iterator_range<const_block_iterator> blocks() const {
1181 return make_range(const_block_iterator(Sections.begin(), Sections.end()),
1182 const_block_iterator(Sections.end(), Sections.end()));
1183 }
1184
external_symbols()1185 iterator_range<external_symbol_iterator> external_symbols() {
1186 return make_range(ExternalSymbols.begin(), ExternalSymbols.end());
1187 }
1188
absolute_symbols()1189 iterator_range<external_symbol_iterator> absolute_symbols() {
1190 return make_range(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
1191 }
1192
defined_symbols()1193 iterator_range<defined_symbol_iterator> defined_symbols() {
1194 return make_range(defined_symbol_iterator(Sections.begin(), Sections.end()),
1195 defined_symbol_iterator(Sections.end(), Sections.end()));
1196 }
1197
defined_symbols()1198 iterator_range<const_defined_symbol_iterator> defined_symbols() const {
1199 return make_range(
1200 const_defined_symbol_iterator(Sections.begin(), Sections.end()),
1201 const_defined_symbol_iterator(Sections.end(), Sections.end()));
1202 }
1203
1204 /// Make the given symbol external (must not already be external).
1205 ///
1206 /// Symbol size, linkage and callability will be left unchanged. Symbol scope
1207 /// will be set to Default, and offset will be reset to 0.
makeExternal(Symbol & Sym)1208 void makeExternal(Symbol &Sym) {
1209 assert(!Sym.isExternal() && "Symbol is already external");
1210 if (Sym.isAbsolute()) {
1211 assert(AbsoluteSymbols.count(&Sym) &&
1212 "Sym is not in the absolute symbols set");
1213 assert(Sym.getOffset() == 0 && "Absolute not at offset 0");
1214 AbsoluteSymbols.erase(&Sym);
1215 Sym.getAddressable().setAbsolute(false);
1216 } else {
1217 assert(Sym.isDefined() && "Sym is not a defined symbol");
1218 Section &Sec = Sym.getBlock().getSection();
1219 Sec.removeSymbol(Sym);
1220 Sym.makeExternal(createAddressable(orc::ExecutorAddr(), false));
1221 }
1222 ExternalSymbols.insert(&Sym);
1223 }
1224
1225 /// Make the given symbol an absolute with the given address (must not already
1226 /// be absolute).
1227 ///
1228 /// The symbol's size, linkage, and callability, and liveness will be left
1229 /// unchanged, and its offset will be reset to 0.
1230 ///
1231 /// If the symbol was external then its scope will be set to local, otherwise
1232 /// it will be left unchanged.
makeAbsolute(Symbol & Sym,orc::ExecutorAddr Address)1233 void makeAbsolute(Symbol &Sym, orc::ExecutorAddr Address) {
1234 assert(!Sym.isAbsolute() && "Symbol is already absolute");
1235 if (Sym.isExternal()) {
1236 assert(ExternalSymbols.count(&Sym) &&
1237 "Sym is not in the absolute symbols set");
1238 assert(Sym.getOffset() == 0 && "External is not at offset 0");
1239 ExternalSymbols.erase(&Sym);
1240 Sym.getAddressable().setAbsolute(true);
1241 Sym.setScope(Scope::Local);
1242 } else {
1243 assert(Sym.isDefined() && "Sym is not a defined symbol");
1244 Section &Sec = Sym.getBlock().getSection();
1245 Sec.removeSymbol(Sym);
1246 Sym.makeAbsolute(createAddressable(Address));
1247 }
1248 AbsoluteSymbols.insert(&Sym);
1249 }
1250
1251 /// Turn an absolute or external symbol into a defined one by attaching it to
1252 /// a block. Symbol must not already be defined.
makeDefined(Symbol & Sym,Block & Content,orc::ExecutorAddrDiff Offset,orc::ExecutorAddrDiff Size,Linkage L,Scope S,bool IsLive)1253 void makeDefined(Symbol &Sym, Block &Content, orc::ExecutorAddrDiff Offset,
1254 orc::ExecutorAddrDiff Size, Linkage L, Scope S,
1255 bool IsLive) {
1256 assert(!Sym.isDefined() && "Sym is already a defined symbol");
1257 if (Sym.isAbsolute()) {
1258 assert(AbsoluteSymbols.count(&Sym) &&
1259 "Symbol is not in the absolutes set");
1260 AbsoluteSymbols.erase(&Sym);
1261 } else {
1262 assert(ExternalSymbols.count(&Sym) &&
1263 "Symbol is not in the externals set");
1264 ExternalSymbols.erase(&Sym);
1265 }
1266 Addressable &OldBase = *Sym.Base;
1267 Sym.setBlock(Content);
1268 Sym.setOffset(Offset);
1269 Sym.setSize(Size);
1270 Sym.setLinkage(L);
1271 Sym.setScope(S);
1272 Sym.setLive(IsLive);
1273 Content.getSection().addSymbol(Sym);
1274 destroyAddressable(OldBase);
1275 }
1276
1277 /// Transfer a defined symbol from one block to another.
1278 ///
1279 /// The symbol's offset within DestBlock is set to NewOffset.
1280 ///
1281 /// If ExplicitNewSize is given as None then the size of the symbol will be
1282 /// checked and auto-truncated to at most the size of the remainder (from the
1283 /// given offset) of the size of the new block.
1284 ///
1285 /// All other symbol attributes are unchanged.
transferDefinedSymbol(Symbol & Sym,Block & DestBlock,orc::ExecutorAddrDiff NewOffset,Optional<orc::ExecutorAddrDiff> ExplicitNewSize)1286 void transferDefinedSymbol(Symbol &Sym, Block &DestBlock,
1287 orc::ExecutorAddrDiff NewOffset,
1288 Optional<orc::ExecutorAddrDiff> ExplicitNewSize) {
1289 auto &OldSection = Sym.getBlock().getSection();
1290 Sym.setBlock(DestBlock);
1291 Sym.setOffset(NewOffset);
1292 if (ExplicitNewSize)
1293 Sym.setSize(*ExplicitNewSize);
1294 else {
1295 auto RemainingBlockSize = DestBlock.getSize() - NewOffset;
1296 if (Sym.getSize() > RemainingBlockSize)
1297 Sym.setSize(RemainingBlockSize);
1298 }
1299 if (&DestBlock.getSection() != &OldSection) {
1300 OldSection.removeSymbol(Sym);
1301 DestBlock.getSection().addSymbol(Sym);
1302 }
1303 }
1304
1305 /// Transfers the given Block and all Symbols pointing to it to the given
1306 /// Section.
1307 ///
1308 /// No attempt is made to check compatibility of the source and destination
1309 /// sections. Blocks may be moved between sections with incompatible
1310 /// permissions (e.g. from data to text). The client is responsible for
1311 /// ensuring that this is safe.
transferBlock(Block & B,Section & NewSection)1312 void transferBlock(Block &B, Section &NewSection) {
1313 auto &OldSection = B.getSection();
1314 if (&OldSection == &NewSection)
1315 return;
1316 SmallVector<Symbol *> AttachedSymbols;
1317 for (auto *S : OldSection.symbols())
1318 if (&S->getBlock() == &B)
1319 AttachedSymbols.push_back(S);
1320 for (auto *S : AttachedSymbols) {
1321 OldSection.removeSymbol(*S);
1322 NewSection.addSymbol(*S);
1323 }
1324 OldSection.removeBlock(B);
1325 NewSection.addBlock(B);
1326 }
1327
1328 /// Move all blocks and symbols from the source section to the destination
1329 /// section.
1330 ///
1331 /// If PreserveSrcSection is true (or SrcSection and DstSection are the same)
1332 /// then SrcSection is preserved, otherwise it is removed (the default).
1333 void mergeSections(Section &DstSection, Section &SrcSection,
1334 bool PreserveSrcSection = false) {
1335 if (&DstSection == &SrcSection)
1336 return;
1337 for (auto *B : SrcSection.blocks())
1338 B->setSection(DstSection);
1339 SrcSection.transferContentTo(DstSection);
1340 if (!PreserveSrcSection)
1341 removeSection(SrcSection);
1342 }
1343
1344 /// Removes an external symbol. Also removes the underlying Addressable.
removeExternalSymbol(Symbol & Sym)1345 void removeExternalSymbol(Symbol &Sym) {
1346 assert(!Sym.isDefined() && !Sym.isAbsolute() &&
1347 "Sym is not an external symbol");
1348 assert(ExternalSymbols.count(&Sym) && "Symbol is not in the externals set");
1349 ExternalSymbols.erase(&Sym);
1350 Addressable &Base = *Sym.Base;
1351 assert(llvm::find_if(ExternalSymbols,
1352 [&](Symbol *AS) { return AS->Base == &Base; }) ==
1353 ExternalSymbols.end() &&
1354 "Base addressable still in use");
1355 destroySymbol(Sym);
1356 destroyAddressable(Base);
1357 }
1358
1359 /// Remove an absolute symbol. Also removes the underlying Addressable.
removeAbsoluteSymbol(Symbol & Sym)1360 void removeAbsoluteSymbol(Symbol &Sym) {
1361 assert(!Sym.isDefined() && Sym.isAbsolute() &&
1362 "Sym is not an absolute symbol");
1363 assert(AbsoluteSymbols.count(&Sym) &&
1364 "Symbol is not in the absolute symbols set");
1365 AbsoluteSymbols.erase(&Sym);
1366 Addressable &Base = *Sym.Base;
1367 assert(llvm::find_if(ExternalSymbols,
1368 [&](Symbol *AS) { return AS->Base == &Base; }) ==
1369 ExternalSymbols.end() &&
1370 "Base addressable still in use");
1371 destroySymbol(Sym);
1372 destroyAddressable(Base);
1373 }
1374
1375 /// Removes defined symbols. Does not remove the underlying block.
removeDefinedSymbol(Symbol & Sym)1376 void removeDefinedSymbol(Symbol &Sym) {
1377 assert(Sym.isDefined() && "Sym is not a defined symbol");
1378 Sym.getBlock().getSection().removeSymbol(Sym);
1379 destroySymbol(Sym);
1380 }
1381
1382 /// Remove a block. The block reference is defunct after calling this
1383 /// function and should no longer be used.
removeBlock(Block & B)1384 void removeBlock(Block &B) {
1385 assert(llvm::none_of(B.getSection().symbols(),
1386 [&](const Symbol *Sym) {
1387 return &Sym->getBlock() == &B;
1388 }) &&
1389 "Block still has symbols attached");
1390 B.getSection().removeBlock(B);
1391 destroyBlock(B);
1392 }
1393
1394 /// Remove a section. The section reference is defunct after calling this
1395 /// function and should no longer be used.
removeSection(Section & Sec)1396 void removeSection(Section &Sec) {
1397 auto I = llvm::find_if(Sections, [&Sec](const std::unique_ptr<Section> &S) {
1398 return S.get() == &Sec;
1399 });
1400 assert(I != Sections.end() && "Section does not appear in this graph");
1401 Sections.erase(I);
1402 }
1403
1404 /// Accessor for the AllocActions object for this graph. This can be used to
1405 /// register allocation action calls prior to finalization.
1406 ///
1407 /// Accessing this object after finalization will result in undefined
1408 /// behavior.
allocActions()1409 orc::shared::AllocActions &allocActions() { return AAs; }
1410
1411 /// Dump the graph.
1412 void dump(raw_ostream &OS);
1413
1414 private:
1415 // Put the BumpPtrAllocator first so that we don't free any of the underlying
1416 // memory until the Symbol/Addressable destructors have been run.
1417 BumpPtrAllocator Allocator;
1418
1419 std::string Name;
1420 Triple TT;
1421 unsigned PointerSize;
1422 support::endianness Endianness;
1423 GetEdgeKindNameFunction GetEdgeKindName = nullptr;
1424 SectionList Sections;
1425 ExternalSymbolSet ExternalSymbols;
1426 ExternalSymbolSet AbsoluteSymbols;
1427 orc::shared::AllocActions AAs;
1428 };
1429
getMutableContent(LinkGraph & G)1430 inline MutableArrayRef<char> Block::getMutableContent(LinkGraph &G) {
1431 if (!ContentMutable)
1432 setMutableContent(G.allocateContent({Data, Size}));
1433 return MutableArrayRef<char>(const_cast<char *>(Data), Size);
1434 }
1435
1436 /// Enables easy lookup of blocks by addresses.
1437 class BlockAddressMap {
1438 public:
1439 using AddrToBlockMap = std::map<orc::ExecutorAddr, Block *>;
1440 using const_iterator = AddrToBlockMap::const_iterator;
1441
1442 /// A block predicate that always adds all blocks.
includeAllBlocks(const Block & B)1443 static bool includeAllBlocks(const Block &B) { return true; }
1444
1445 /// A block predicate that always includes blocks with non-null addresses.
includeNonNull(const Block & B)1446 static bool includeNonNull(const Block &B) { return !!B.getAddress(); }
1447
1448 BlockAddressMap() = default;
1449
1450 /// Add a block to the map. Returns an error if the block overlaps with any
1451 /// existing block.
1452 template <typename PredFn = decltype(includeAllBlocks)>
1453 Error addBlock(Block &B, PredFn Pred = includeAllBlocks) {
1454 if (!Pred(B))
1455 return Error::success();
1456
1457 auto I = AddrToBlock.upper_bound(B.getAddress());
1458
1459 // If we're not at the end of the map, check for overlap with the next
1460 // element.
1461 if (I != AddrToBlock.end()) {
1462 if (B.getAddress() + B.getSize() > I->second->getAddress())
1463 return overlapError(B, *I->second);
1464 }
1465
1466 // If we're not at the start of the map, check for overlap with the previous
1467 // element.
1468 if (I != AddrToBlock.begin()) {
1469 auto &PrevBlock = *std::prev(I)->second;
1470 if (PrevBlock.getAddress() + PrevBlock.getSize() > B.getAddress())
1471 return overlapError(B, PrevBlock);
1472 }
1473
1474 AddrToBlock.insert(I, std::make_pair(B.getAddress(), &B));
1475 return Error::success();
1476 }
1477
1478 /// Add a block to the map without checking for overlap with existing blocks.
1479 /// The client is responsible for ensuring that the block added does not
1480 /// overlap with any existing block.
addBlockWithoutChecking(Block & B)1481 void addBlockWithoutChecking(Block &B) { AddrToBlock[B.getAddress()] = &B; }
1482
1483 /// Add a range of blocks to the map. Returns an error if any block in the
1484 /// range overlaps with any other block in the range, or with any existing
1485 /// block in the map.
1486 template <typename BlockPtrRange,
1487 typename PredFn = decltype(includeAllBlocks)>
1488 Error addBlocks(BlockPtrRange &&Blocks, PredFn Pred = includeAllBlocks) {
1489 for (auto *B : Blocks)
1490 if (auto Err = addBlock(*B, Pred))
1491 return Err;
1492 return Error::success();
1493 }
1494
1495 /// Add a range of blocks to the map without checking for overlap with
1496 /// existing blocks. The client is responsible for ensuring that the block
1497 /// added does not overlap with any existing block.
1498 template <typename BlockPtrRange>
addBlocksWithoutChecking(BlockPtrRange && Blocks)1499 void addBlocksWithoutChecking(BlockPtrRange &&Blocks) {
1500 for (auto *B : Blocks)
1501 addBlockWithoutChecking(*B);
1502 }
1503
1504 /// Iterates over (Address, Block*) pairs in ascending order of address.
begin()1505 const_iterator begin() const { return AddrToBlock.begin(); }
end()1506 const_iterator end() const { return AddrToBlock.end(); }
1507
1508 /// Returns the block starting at the given address, or nullptr if no such
1509 /// block exists.
getBlockAt(orc::ExecutorAddr Addr)1510 Block *getBlockAt(orc::ExecutorAddr Addr) const {
1511 auto I = AddrToBlock.find(Addr);
1512 if (I == AddrToBlock.end())
1513 return nullptr;
1514 return I->second;
1515 }
1516
1517 /// Returns the block covering the given address, or nullptr if no such block
1518 /// exists.
getBlockCovering(orc::ExecutorAddr Addr)1519 Block *getBlockCovering(orc::ExecutorAddr Addr) const {
1520 auto I = AddrToBlock.upper_bound(Addr);
1521 if (I == AddrToBlock.begin())
1522 return nullptr;
1523 auto *B = std::prev(I)->second;
1524 if (Addr < B->getAddress() + B->getSize())
1525 return B;
1526 return nullptr;
1527 }
1528
1529 private:
overlapError(Block & NewBlock,Block & ExistingBlock)1530 Error overlapError(Block &NewBlock, Block &ExistingBlock) {
1531 auto NewBlockEnd = NewBlock.getAddress() + NewBlock.getSize();
1532 auto ExistingBlockEnd =
1533 ExistingBlock.getAddress() + ExistingBlock.getSize();
1534 return make_error<JITLinkError>(
1535 "Block at " +
1536 formatv("{0:x16} -- {1:x16}", NewBlock.getAddress().getValue(),
1537 NewBlockEnd.getValue()) +
1538 " overlaps " +
1539 formatv("{0:x16} -- {1:x16}", ExistingBlock.getAddress().getValue(),
1540 ExistingBlockEnd.getValue()));
1541 }
1542
1543 AddrToBlockMap AddrToBlock;
1544 };
1545
1546 /// A map of addresses to Symbols.
1547 class SymbolAddressMap {
1548 public:
1549 using SymbolVector = SmallVector<Symbol *, 1>;
1550
1551 /// Add a symbol to the SymbolAddressMap.
addSymbol(Symbol & Sym)1552 void addSymbol(Symbol &Sym) {
1553 AddrToSymbols[Sym.getAddress()].push_back(&Sym);
1554 }
1555
1556 /// Add all symbols in a given range to the SymbolAddressMap.
1557 template <typename SymbolPtrCollection>
addSymbols(SymbolPtrCollection && Symbols)1558 void addSymbols(SymbolPtrCollection &&Symbols) {
1559 for (auto *Sym : Symbols)
1560 addSymbol(*Sym);
1561 }
1562
1563 /// Returns the list of symbols that start at the given address, or nullptr if
1564 /// no such symbols exist.
getSymbolsAt(orc::ExecutorAddr Addr)1565 const SymbolVector *getSymbolsAt(orc::ExecutorAddr Addr) const {
1566 auto I = AddrToSymbols.find(Addr);
1567 if (I == AddrToSymbols.end())
1568 return nullptr;
1569 return &I->second;
1570 }
1571
1572 private:
1573 std::map<orc::ExecutorAddr, SymbolVector> AddrToSymbols;
1574 };
1575
1576 /// A function for mutating LinkGraphs.
1577 using LinkGraphPassFunction = std::function<Error(LinkGraph &)>;
1578
1579 /// A list of LinkGraph passes.
1580 using LinkGraphPassList = std::vector<LinkGraphPassFunction>;
1581
1582 /// An LinkGraph pass configuration, consisting of a list of pre-prune,
1583 /// post-prune, and post-fixup passes.
1584 struct PassConfiguration {
1585
1586 /// Pre-prune passes.
1587 ///
1588 /// These passes are called on the graph after it is built, and before any
1589 /// symbols have been pruned. Graph nodes still have their original vmaddrs.
1590 ///
1591 /// Notable use cases: Marking symbols live or should-discard.
1592 LinkGraphPassList PrePrunePasses;
1593
1594 /// Post-prune passes.
1595 ///
1596 /// These passes are called on the graph after dead stripping, but before
1597 /// memory is allocated or nodes assigned their final addresses.
1598 ///
1599 /// Notable use cases: Building GOT, stub, and TLV symbols.
1600 LinkGraphPassList PostPrunePasses;
1601
1602 /// Post-allocation passes.
1603 ///
1604 /// These passes are called on the graph after memory has been allocated and
1605 /// defined nodes have been assigned their final addresses, but before the
1606 /// context has been notified of these addresses. At this point externals
1607 /// have not been resolved, and symbol content has not yet been copied into
1608 /// working memory.
1609 ///
1610 /// Notable use cases: Setting up data structures associated with addresses
1611 /// of defined symbols (e.g. a mapping of __dso_handle to JITDylib* for the
1612 /// JIT runtime) -- using a PostAllocationPass for this ensures that the
1613 /// data structures are in-place before any query for resolved symbols
1614 /// can complete.
1615 LinkGraphPassList PostAllocationPasses;
1616
1617 /// Pre-fixup passes.
1618 ///
1619 /// These passes are called on the graph after memory has been allocated,
1620 /// content copied into working memory, and all nodes (including externals)
1621 /// have been assigned their final addresses, but before any fixups have been
1622 /// applied.
1623 ///
1624 /// Notable use cases: Late link-time optimizations like GOT and stub
1625 /// elimination.
1626 LinkGraphPassList PreFixupPasses;
1627
1628 /// Post-fixup passes.
1629 ///
1630 /// These passes are called on the graph after block contents has been copied
1631 /// to working memory, and fixups applied. Blocks have been updated to point
1632 /// to their fixed up content.
1633 ///
1634 /// Notable use cases: Testing and validation.
1635 LinkGraphPassList PostFixupPasses;
1636 };
1637
1638 /// Flags for symbol lookup.
1639 ///
1640 /// FIXME: These basically duplicate orc::SymbolLookupFlags -- We should merge
1641 /// the two types once we have an OrcSupport library.
1642 enum class SymbolLookupFlags { RequiredSymbol, WeaklyReferencedSymbol };
1643
1644 raw_ostream &operator<<(raw_ostream &OS, const SymbolLookupFlags &LF);
1645
1646 /// A map of symbol names to resolved addresses.
1647 using AsyncLookupResult = DenseMap<StringRef, JITEvaluatedSymbol>;
1648
1649 /// A function object to call with a resolved symbol map (See AsyncLookupResult)
1650 /// or an error if resolution failed.
1651 class JITLinkAsyncLookupContinuation {
1652 public:
1653 virtual ~JITLinkAsyncLookupContinuation() = default;
1654 virtual void run(Expected<AsyncLookupResult> LR) = 0;
1655
1656 private:
1657 virtual void anchor();
1658 };
1659
1660 /// Create a lookup continuation from a function object.
1661 template <typename Continuation>
1662 std::unique_ptr<JITLinkAsyncLookupContinuation>
createLookupContinuation(Continuation Cont)1663 createLookupContinuation(Continuation Cont) {
1664
1665 class Impl final : public JITLinkAsyncLookupContinuation {
1666 public:
1667 Impl(Continuation C) : C(std::move(C)) {}
1668 void run(Expected<AsyncLookupResult> LR) override { C(std::move(LR)); }
1669
1670 private:
1671 Continuation C;
1672 };
1673
1674 return std::make_unique<Impl>(std::move(Cont));
1675 }
1676
1677 /// Holds context for a single jitLink invocation.
1678 class JITLinkContext {
1679 public:
1680 using LookupMap = DenseMap<StringRef, SymbolLookupFlags>;
1681
1682 /// Create a JITLinkContext.
JITLinkContext(const JITLinkDylib * JD)1683 JITLinkContext(const JITLinkDylib *JD) : JD(JD) {}
1684
1685 /// Destroy a JITLinkContext.
1686 virtual ~JITLinkContext();
1687
1688 /// Return the JITLinkDylib that this link is targeting, if any.
getJITLinkDylib()1689 const JITLinkDylib *getJITLinkDylib() const { return JD; }
1690
1691 /// Return the MemoryManager to be used for this link.
1692 virtual JITLinkMemoryManager &getMemoryManager() = 0;
1693
1694 /// Notify this context that linking failed.
1695 /// Called by JITLink if linking cannot be completed.
1696 virtual void notifyFailed(Error Err) = 0;
1697
1698 /// Called by JITLink to resolve external symbols. This method is passed a
1699 /// lookup continutation which it must call with a result to continue the
1700 /// linking process.
1701 virtual void lookup(const LookupMap &Symbols,
1702 std::unique_ptr<JITLinkAsyncLookupContinuation> LC) = 0;
1703
1704 /// Called by JITLink once all defined symbols in the graph have been assigned
1705 /// their final memory locations in the target process. At this point the
1706 /// LinkGraph can be inspected to build a symbol table, however the block
1707 /// content will not generally have been copied to the target location yet.
1708 ///
1709 /// If the client detects an error in the LinkGraph state (e.g. unexpected or
1710 /// missing symbols) they may return an error here. The error will be
1711 /// propagated to notifyFailed and the linker will bail out.
1712 virtual Error notifyResolved(LinkGraph &G) = 0;
1713
1714 /// Called by JITLink to notify the context that the object has been
1715 /// finalized (i.e. emitted to memory and memory permissions set). If all of
1716 /// this objects dependencies have also been finalized then the code is ready
1717 /// to run.
1718 virtual void notifyFinalized(JITLinkMemoryManager::FinalizedAlloc Alloc) = 0;
1719
1720 /// Called by JITLink prior to linking to determine whether default passes for
1721 /// the target should be added. The default implementation returns true.
1722 /// If subclasses override this method to return false for any target then
1723 /// they are required to fully configure the pass pipeline for that target.
1724 virtual bool shouldAddDefaultTargetPasses(const Triple &TT) const;
1725
1726 /// Returns the mark-live pass to be used for this link. If no pass is
1727 /// returned (the default) then the target-specific linker implementation will
1728 /// choose a conservative default (usually marking all symbols live).
1729 /// This function is only called if shouldAddDefaultTargetPasses returns true,
1730 /// otherwise the JITContext is responsible for adding a mark-live pass in
1731 /// modifyPassConfig.
1732 virtual LinkGraphPassFunction getMarkLivePass(const Triple &TT) const;
1733
1734 /// Called by JITLink to modify the pass pipeline prior to linking.
1735 /// The default version performs no modification.
1736 virtual Error modifyPassConfig(LinkGraph &G, PassConfiguration &Config);
1737
1738 private:
1739 const JITLinkDylib *JD = nullptr;
1740 };
1741
1742 /// Marks all symbols in a graph live. This can be used as a default,
1743 /// conservative mark-live implementation.
1744 Error markAllSymbolsLive(LinkGraph &G);
1745
1746 /// Create an out of range error for the given edge in the given block.
1747 Error makeTargetOutOfRangeError(const LinkGraph &G, const Block &B,
1748 const Edge &E);
1749
1750 Error makeAlignmentError(llvm::orc::ExecutorAddr Loc, uint64_t Value, int N,
1751 const Edge &E);
1752
1753 /// Base case for edge-visitors where the visitor-list is empty.
visitEdge(LinkGraph & G,Block * B,Edge & E)1754 inline void visitEdge(LinkGraph &G, Block *B, Edge &E) {}
1755
1756 /// Applies the first visitor in the list to the given edge. If the visitor's
1757 /// visitEdge method returns true then we return immediately, otherwise we
1758 /// apply the next visitor.
1759 template <typename VisitorT, typename... VisitorTs>
visitEdge(LinkGraph & G,Block * B,Edge & E,VisitorT && V,VisitorTs &&...Vs)1760 void visitEdge(LinkGraph &G, Block *B, Edge &E, VisitorT &&V,
1761 VisitorTs &&...Vs) {
1762 if (!V.visitEdge(G, B, E))
1763 visitEdge(G, B, E, std::forward<VisitorTs>(Vs)...);
1764 }
1765
1766 /// For each edge in the given graph, apply a list of visitors to the edge,
1767 /// stopping when the first visitor's visitEdge method returns true.
1768 ///
1769 /// Only visits edges that were in the graph at call time: if any visitor
1770 /// adds new edges those will not be visited. Visitors are not allowed to
1771 /// remove edges (though they can change their kind, target, and addend).
1772 template <typename... VisitorTs>
visitExistingEdges(LinkGraph & G,VisitorTs &&...Vs)1773 void visitExistingEdges(LinkGraph &G, VisitorTs &&...Vs) {
1774 // We may add new blocks during this process, but we don't want to iterate
1775 // over them, so build a worklist.
1776 std::vector<Block *> Worklist(G.blocks().begin(), G.blocks().end());
1777
1778 for (auto *B : Worklist)
1779 for (auto &E : B->edges())
1780 visitEdge(G, B, E, std::forward<VisitorTs>(Vs)...);
1781 }
1782
1783 /// Create a LinkGraph from the given object buffer.
1784 ///
1785 /// Note: The graph does not take ownership of the underlying buffer, nor copy
1786 /// its contents. The caller is responsible for ensuring that the object buffer
1787 /// outlives the graph.
1788 Expected<std::unique_ptr<LinkGraph>>
1789 createLinkGraphFromObject(MemoryBufferRef ObjectBuffer);
1790
1791 /// Link the given graph.
1792 void link(std::unique_ptr<LinkGraph> G, std::unique_ptr<JITLinkContext> Ctx);
1793
1794 } // end namespace jitlink
1795 } // end namespace llvm
1796
1797 #endif // LLVM_EXECUTIONENGINE_JITLINK_JITLINK_H
1798