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 "JITLinkMemoryManager.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/ExecutionEngine/JITSymbol.h"
22 #include "llvm/Support/Allocator.h"
23 #include "llvm/Support/Endian.h"
24 #include "llvm/Support/Error.h"
25 #include "llvm/Support/FormatVariadic.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/Memory.h"
28 #include "llvm/Support/MemoryBuffer.h"
29
30 #include <map>
31 #include <string>
32 #include <system_error>
33
34 namespace llvm {
35 namespace jitlink {
36
37 class Symbol;
38 class Section;
39
40 /// Base class for errors originating in JIT linker, e.g. missing relocation
41 /// support.
42 class JITLinkError : public ErrorInfo<JITLinkError> {
43 public:
44 static char ID;
45
JITLinkError(Twine ErrMsg)46 JITLinkError(Twine ErrMsg) : ErrMsg(ErrMsg.str()) {}
47
48 void log(raw_ostream &OS) const override;
getErrorMessage()49 const std::string &getErrorMessage() const { return ErrMsg; }
50 std::error_code convertToErrorCode() const override;
51
52 private:
53 std::string ErrMsg;
54 };
55
56 /// Represents fixups and constraints in the LinkGraph.
57 class Edge {
58 public:
59 using Kind = uint8_t;
60
61 enum GenericEdgeKind : Kind {
62 Invalid, // Invalid edge value.
63 FirstKeepAlive, // Keeps target alive. Offset/addend zero.
64 KeepAlive = FirstKeepAlive, // Tag first edge kind that preserves liveness.
65 FirstRelocation // First architecture specific relocation.
66 };
67
68 using OffsetT = uint32_t;
69 using AddendT = int64_t;
70
Edge(Kind K,OffsetT Offset,Symbol & Target,AddendT Addend)71 Edge(Kind K, OffsetT Offset, Symbol &Target, AddendT Addend)
72 : Target(&Target), Offset(Offset), Addend(Addend), K(K) {}
73
getOffset()74 OffsetT getOffset() const { return Offset; }
setOffset(OffsetT Offset)75 void setOffset(OffsetT Offset) { this->Offset = Offset; }
getKind()76 Kind getKind() const { return K; }
setKind(Kind K)77 void setKind(Kind K) { this->K = K; }
isRelocation()78 bool isRelocation() const { return K >= FirstRelocation; }
getRelocation()79 Kind getRelocation() const {
80 assert(isRelocation() && "Not a relocation edge");
81 return K - FirstRelocation;
82 }
isKeepAlive()83 bool isKeepAlive() const { return K >= FirstKeepAlive; }
getTarget()84 Symbol &getTarget() const { return *Target; }
setTarget(Symbol & Target)85 void setTarget(Symbol &Target) { this->Target = &Target; }
getAddend()86 AddendT getAddend() const { return Addend; }
setAddend(AddendT Addend)87 void setAddend(AddendT Addend) { this->Addend = Addend; }
88
89 private:
90 Symbol *Target = nullptr;
91 OffsetT Offset = 0;
92 AddendT Addend = 0;
93 Kind K = 0;
94 };
95
96 /// Returns the string name of the given generic edge kind, or "unknown"
97 /// otherwise. Useful for debugging.
98 const char *getGenericEdgeKindName(Edge::Kind K);
99
100 /// Base class for Addressable entities (externals, absolutes, blocks).
101 class Addressable {
102 friend class LinkGraph;
103
104 protected:
Addressable(JITTargetAddress Address,bool IsDefined)105 Addressable(JITTargetAddress Address, bool IsDefined)
106 : Address(Address), IsDefined(IsDefined), IsAbsolute(false) {}
107
Addressable(JITTargetAddress Address)108 Addressable(JITTargetAddress Address)
109 : Address(Address), IsDefined(false), IsAbsolute(true) {
110 assert(!(IsDefined && IsAbsolute) &&
111 "Block cannot be both defined and absolute");
112 }
113
114 public:
115 Addressable(const Addressable &) = delete;
116 Addressable &operator=(const Addressable &) = default;
117 Addressable(Addressable &&) = delete;
118 Addressable &operator=(Addressable &&) = default;
119
getAddress()120 JITTargetAddress getAddress() const { return Address; }
setAddress(JITTargetAddress Address)121 void setAddress(JITTargetAddress Address) { this->Address = Address; }
122
123 /// Returns true if this is a defined addressable, in which case you
124 /// can downcast this to a .
isDefined()125 bool isDefined() const { return static_cast<bool>(IsDefined); }
isAbsolute()126 bool isAbsolute() const { return static_cast<bool>(IsAbsolute); }
127
128 private:
129 JITTargetAddress Address = 0;
130 uint64_t IsDefined : 1;
131 uint64_t IsAbsolute : 1;
132 };
133
134 using SectionOrdinal = unsigned;
135
136 /// An Addressable with content and edges.
137 class Block : public Addressable {
138 friend class LinkGraph;
139
140 private:
141 /// Create a zero-fill defined addressable.
Block(Section & Parent,JITTargetAddress Size,JITTargetAddress Address,uint64_t Alignment,uint64_t AlignmentOffset)142 Block(Section &Parent, JITTargetAddress Size, JITTargetAddress Address,
143 uint64_t Alignment, uint64_t AlignmentOffset)
144 : Addressable(Address, true), Parent(Parent), Size(Size) {
145 assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
146 assert(AlignmentOffset < Alignment &&
147 "Alignment offset cannot exceed alignment");
148 assert(AlignmentOffset <= MaxAlignmentOffset &&
149 "Alignment offset exceeds maximum");
150 P2Align = Alignment ? countTrailingZeros(Alignment) : 0;
151 this->AlignmentOffset = AlignmentOffset;
152 }
153
154 /// Create a defined addressable for the given content.
Block(Section & Parent,StringRef Content,JITTargetAddress Address,uint64_t Alignment,uint64_t AlignmentOffset)155 Block(Section &Parent, StringRef Content, JITTargetAddress Address,
156 uint64_t Alignment, uint64_t AlignmentOffset)
157 : Addressable(Address, true), Parent(Parent), Data(Content.data()),
158 Size(Content.size()) {
159 assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
160 assert(AlignmentOffset < Alignment &&
161 "Alignment offset cannot exceed alignment");
162 assert(AlignmentOffset <= MaxAlignmentOffset &&
163 "Alignment offset exceeds maximum");
164 P2Align = Alignment ? countTrailingZeros(Alignment) : 0;
165 this->AlignmentOffset = AlignmentOffset;
166 }
167
168 public:
169 using EdgeVector = std::vector<Edge>;
170 using edge_iterator = EdgeVector::iterator;
171 using const_edge_iterator = EdgeVector::const_iterator;
172
173 Block(const Block &) = delete;
174 Block &operator=(const Block &) = delete;
175 Block(Block &&) = delete;
176 Block &operator=(Block &&) = delete;
177
178 /// Return the parent section for this block.
getSection()179 Section &getSection() const { return Parent; }
180
181 /// Returns true if this is a zero-fill block.
182 ///
183 /// If true, getSize is callable but getContent is not (the content is
184 /// defined to be a sequence of zero bytes of length Size).
isZeroFill()185 bool isZeroFill() const { return !Data; }
186
187 /// Returns the size of this defined addressable.
getSize()188 size_t getSize() const { return Size; }
189
190 /// Get the content for this block. Block must not be a zero-fill block.
getContent()191 StringRef getContent() const {
192 assert(Data && "Section does not contain content");
193 return StringRef(Data, Size);
194 }
195
196 /// Set the content for this block.
197 /// Caller is responsible for ensuring the underlying bytes are not
198 /// deallocated while pointed to by this block.
setContent(StringRef Content)199 void setContent(StringRef Content) {
200 Data = Content.data();
201 Size = Content.size();
202 }
203
204 /// Get the alignment for this content.
getAlignment()205 uint64_t getAlignment() const { return 1ull << P2Align; }
206
207 /// Set the alignment for this content.
setAlignment(uint64_t Alignment)208 void setAlignment(uint64_t Alignment) {
209 assert(isPowerOf2_64(Alignment) && "Alignment must be a power of two");
210 P2Align = Alignment ? countTrailingZeros(Alignment) : 0;
211 }
212
213 /// Get the alignment offset for this content.
getAlignmentOffset()214 uint64_t getAlignmentOffset() const { return AlignmentOffset; }
215
216 /// Set the alignment offset for this content.
setAlignmentOffset(uint64_t AlignmentOffset)217 void setAlignmentOffset(uint64_t AlignmentOffset) {
218 assert(AlignmentOffset < (1ull << P2Align) &&
219 "Alignment offset can't exceed alignment");
220 this->AlignmentOffset = AlignmentOffset;
221 }
222
223 /// Add an edge to this block.
addEdge(Edge::Kind K,Edge::OffsetT Offset,Symbol & Target,Edge::AddendT Addend)224 void addEdge(Edge::Kind K, Edge::OffsetT Offset, Symbol &Target,
225 Edge::AddendT Addend) {
226 Edges.push_back(Edge(K, Offset, Target, Addend));
227 }
228
229 /// Add an edge by copying an existing one. This is typically used when
230 /// moving edges between blocks.
addEdge(const Edge & E)231 void addEdge(const Edge &E) { Edges.push_back(E); }
232
233 /// Return the list of edges attached to this content.
edges()234 iterator_range<edge_iterator> edges() {
235 return make_range(Edges.begin(), Edges.end());
236 }
237
238 /// Returns the list of edges attached to this content.
edges()239 iterator_range<const_edge_iterator> edges() const {
240 return make_range(Edges.begin(), Edges.end());
241 }
242
243 /// Return the size of the edges list.
edges_size()244 size_t edges_size() const { return Edges.size(); }
245
246 /// Returns true if the list of edges is empty.
edges_empty()247 bool edges_empty() const { return Edges.empty(); }
248
249 /// Remove the edge pointed to by the given iterator.
250 /// Invalidates all iterators that point to or past the given one.
removeEdge(const_edge_iterator I)251 void removeEdge(const_edge_iterator I) { Edges.erase(I); }
252
253 private:
254 static constexpr uint64_t MaxAlignmentOffset = (1ULL << 57) - 1;
255
256 uint64_t P2Align : 5;
257 uint64_t AlignmentOffset : 57;
258 Section &Parent;
259 const char *Data = nullptr;
260 size_t Size = 0;
261 std::vector<Edge> Edges;
262 };
263
264 /// Describes symbol linkage. This can be used to make resolve definition
265 /// clashes.
266 enum class Linkage : uint8_t {
267 Strong,
268 Weak,
269 };
270
271 /// For errors and debugging output.
272 const char *getLinkageName(Linkage L);
273
274 /// Defines the scope in which this symbol should be visible:
275 /// Default -- Visible in the public interface of the linkage unit.
276 /// Hidden -- Visible within the linkage unit, but not exported from it.
277 /// Local -- Visible only within the LinkGraph.
278 enum class Scope : uint8_t { Default, Hidden, Local };
279
280 /// For debugging output.
281 const char *getScopeName(Scope S);
282
283 raw_ostream &operator<<(raw_ostream &OS, const Block &B);
284
285 /// Symbol representation.
286 ///
287 /// Symbols represent locations within Addressable objects.
288 /// They can be either Named or Anonymous.
289 /// Anonymous symbols have neither linkage nor visibility, and must point at
290 /// ContentBlocks.
291 /// Named symbols may be in one of four states:
292 /// - Null: Default initialized. Assignable, but otherwise unusable.
293 /// - Defined: Has both linkage and visibility and points to a ContentBlock
294 /// - Common: Has both linkage and visibility, points to a null Addressable.
295 /// - External: Has neither linkage nor visibility, points to an external
296 /// Addressable.
297 ///
298 class Symbol {
299 friend class LinkGraph;
300
301 private:
Symbol(Addressable & Base,JITTargetAddress Offset,StringRef Name,JITTargetAddress Size,Linkage L,Scope S,bool IsLive,bool IsCallable)302 Symbol(Addressable &Base, JITTargetAddress Offset, StringRef Name,
303 JITTargetAddress Size, Linkage L, Scope S, bool IsLive,
304 bool IsCallable)
305 : Name(Name), Base(&Base), Offset(Offset), Size(Size) {
306 assert(Offset <= MaxOffset && "Offset out of range");
307 setLinkage(L);
308 setScope(S);
309 setLive(IsLive);
310 setCallable(IsCallable);
311 }
312
constructCommon(void * SymStorage,Block & Base,StringRef Name,JITTargetAddress Size,Scope S,bool IsLive)313 static Symbol &constructCommon(void *SymStorage, Block &Base, StringRef Name,
314 JITTargetAddress Size, Scope S, bool IsLive) {
315 assert(SymStorage && "Storage cannot be null");
316 assert(!Name.empty() && "Common symbol name cannot be empty");
317 assert(Base.isDefined() &&
318 "Cannot create common symbol from undefined block");
319 assert(static_cast<Block &>(Base).getSize() == Size &&
320 "Common symbol size should match underlying block size");
321 auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
322 new (Sym) Symbol(Base, 0, Name, Size, Linkage::Weak, S, IsLive, false);
323 return *Sym;
324 }
325
constructExternal(void * SymStorage,Addressable & Base,StringRef Name,JITTargetAddress Size,Linkage L)326 static Symbol &constructExternal(void *SymStorage, Addressable &Base,
327 StringRef Name, JITTargetAddress Size,
328 Linkage L) {
329 assert(SymStorage && "Storage cannot be null");
330 assert(!Base.isDefined() &&
331 "Cannot create external symbol from defined block");
332 assert(!Name.empty() && "External symbol name cannot be empty");
333 auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
334 new (Sym) Symbol(Base, 0, Name, Size, L, Scope::Default, false, false);
335 return *Sym;
336 }
337
constructAbsolute(void * SymStorage,Addressable & Base,StringRef Name,JITTargetAddress Size,Linkage L,Scope S,bool IsLive)338 static Symbol &constructAbsolute(void *SymStorage, Addressable &Base,
339 StringRef Name, JITTargetAddress Size,
340 Linkage L, Scope S, bool IsLive) {
341 assert(SymStorage && "Storage cannot be null");
342 assert(!Base.isDefined() &&
343 "Cannot create absolute symbol from a defined block");
344 auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
345 new (Sym) Symbol(Base, 0, Name, Size, L, S, IsLive, false);
346 return *Sym;
347 }
348
constructAnonDef(void * SymStorage,Block & Base,JITTargetAddress Offset,JITTargetAddress Size,bool IsCallable,bool IsLive)349 static Symbol &constructAnonDef(void *SymStorage, Block &Base,
350 JITTargetAddress Offset,
351 JITTargetAddress Size, bool IsCallable,
352 bool IsLive) {
353 assert(SymStorage && "Storage cannot be null");
354 assert(Offset < Base.getSize() && "Symbol offset is outside block");
355 auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
356 new (Sym) Symbol(Base, Offset, StringRef(), Size, Linkage::Strong,
357 Scope::Local, IsLive, IsCallable);
358 return *Sym;
359 }
360
constructNamedDef(void * SymStorage,Block & Base,JITTargetAddress Offset,StringRef Name,JITTargetAddress Size,Linkage L,Scope S,bool IsLive,bool IsCallable)361 static Symbol &constructNamedDef(void *SymStorage, Block &Base,
362 JITTargetAddress Offset, StringRef Name,
363 JITTargetAddress Size, Linkage L, Scope S,
364 bool IsLive, bool IsCallable) {
365 assert(SymStorage && "Storage cannot be null");
366 assert(Offset < Base.getSize() && "Symbol offset is outside block");
367 assert(!Name.empty() && "Name cannot be empty");
368 auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
369 new (Sym) Symbol(Base, Offset, Name, Size, L, S, IsLive, IsCallable);
370 return *Sym;
371 }
372
373 public:
374 /// Create a null Symbol. This allows Symbols to be default initialized for
375 /// use in containers (e.g. as map values). Null symbols are only useful for
376 /// assigning to.
377 Symbol() = default;
378
379 // Symbols are not movable or copyable.
380 Symbol(const Symbol &) = delete;
381 Symbol &operator=(const Symbol &) = delete;
382 Symbol(Symbol &&) = delete;
383 Symbol &operator=(Symbol &&) = delete;
384
385 /// Returns true if this symbol has a name.
hasName()386 bool hasName() const { return !Name.empty(); }
387
388 /// Returns the name of this symbol (empty if the symbol is anonymous).
getName()389 StringRef getName() const {
390 assert((!Name.empty() || getScope() == Scope::Local) &&
391 "Anonymous symbol has non-local scope");
392 return Name;
393 }
394
395 /// Returns true if this Symbol has content (potentially) defined within this
396 /// object file (i.e. is anything but an external or absolute symbol).
isDefined()397 bool isDefined() const {
398 assert(Base && "Attempt to access null symbol");
399 return Base->isDefined();
400 }
401
402 /// Returns true if this symbol is live (i.e. should be treated as a root for
403 /// dead stripping).
isLive()404 bool isLive() const {
405 assert(Base && "Attempting to access null symbol");
406 return IsLive;
407 }
408
409 /// Set this symbol's live bit.
setLive(bool IsLive)410 void setLive(bool IsLive) { this->IsLive = IsLive; }
411
412 /// Returns true is this symbol is callable.
isCallable()413 bool isCallable() const { return IsCallable; }
414
415 /// Set this symbol's callable bit.
setCallable(bool IsCallable)416 void setCallable(bool IsCallable) { this->IsCallable = IsCallable; }
417
418 /// Returns true if the underlying addressable is an unresolved external.
isExternal()419 bool isExternal() const {
420 assert(Base && "Attempt to access null symbol");
421 return !Base->isDefined() && !Base->isAbsolute();
422 }
423
424 /// Returns true if the underlying addressable is an absolute symbol.
isAbsolute()425 bool isAbsolute() const {
426 assert(Base && "Attempt to access null symbol");
427 return !Base->isDefined() && Base->isAbsolute();
428 }
429
430 /// Return the addressable that this symbol points to.
getAddressable()431 Addressable &getAddressable() {
432 assert(Base && "Cannot get underlying addressable for null symbol");
433 return *Base;
434 }
435
436 /// Return the addressable that thsi symbol points to.
getAddressable()437 const Addressable &getAddressable() const {
438 assert(Base && "Cannot get underlying addressable for null symbol");
439 return *Base;
440 }
441
442 /// Return the Block for this Symbol (Symbol must be defined).
getBlock()443 Block &getBlock() {
444 assert(Base && "Cannot get block for null symbol");
445 assert(Base->isDefined() && "Not a defined symbol");
446 return static_cast<Block &>(*Base);
447 }
448
449 /// Return the Block for this Symbol (Symbol must be defined).
getBlock()450 const Block &getBlock() const {
451 assert(Base && "Cannot get block for null symbol");
452 assert(Base->isDefined() && "Not a defined symbol");
453 return static_cast<const Block &>(*Base);
454 }
455
456 /// Returns the offset for this symbol within the underlying addressable.
getOffset()457 JITTargetAddress getOffset() const { return Offset; }
458
459 /// Returns the address of this symbol.
getAddress()460 JITTargetAddress getAddress() const { return Base->getAddress() + Offset; }
461
462 /// Returns the size of this symbol.
getSize()463 JITTargetAddress getSize() const { return Size; }
464
465 /// Returns true if this symbol is backed by a zero-fill block.
466 /// This method may only be called on defined symbols.
isSymbolZeroFill()467 bool isSymbolZeroFill() const { return getBlock().isZeroFill(); }
468
469 /// Returns the content in the underlying block covered by this symbol.
470 /// This method may only be called on defined non-zero-fill symbols.
getSymbolContent()471 StringRef getSymbolContent() const {
472 return getBlock().getContent().substr(Offset, Size);
473 }
474
475 /// Get the linkage for this Symbol.
getLinkage()476 Linkage getLinkage() const { return static_cast<Linkage>(L); }
477
478 /// Set the linkage for this Symbol.
setLinkage(Linkage L)479 void setLinkage(Linkage L) {
480 assert((L == Linkage::Strong || (!Base->isAbsolute() && !Name.empty())) &&
481 "Linkage can only be applied to defined named symbols");
482 this->L = static_cast<uint8_t>(L);
483 }
484
485 /// Get the visibility for this Symbol.
getScope()486 Scope getScope() const { return static_cast<Scope>(S); }
487
488 /// Set the visibility for this Symbol.
setScope(Scope S)489 void setScope(Scope S) {
490 assert((S == Scope::Default || Base->isDefined() || Base->isAbsolute()) &&
491 "Invalid visibility for symbol type");
492 this->S = static_cast<uint8_t>(S);
493 }
494
495 private:
makeExternal(Addressable & A)496 void makeExternal(Addressable &A) {
497 assert(!A.isDefined() && "Attempting to make external with defined block");
498 Base = &A;
499 Offset = 0;
500 setLinkage(Linkage::Strong);
501 setScope(Scope::Default);
502 IsLive = 0;
503 // note: Size and IsCallable fields left unchanged.
504 }
505
setBlock(Block & B)506 void setBlock(Block &B) { Base = &B; }
507
setOffset(uint64_t NewOffset)508 void setOffset(uint64_t NewOffset) {
509 assert(NewOffset <= MaxOffset && "Offset out of range");
510 Offset = NewOffset;
511 }
512
513 static constexpr uint64_t MaxOffset = (1ULL << 59) - 1;
514
515 // FIXME: A char* or SymbolStringPtr may pack better.
516 StringRef Name;
517 Addressable *Base = nullptr;
518 uint64_t Offset : 59;
519 uint64_t L : 1;
520 uint64_t S : 2;
521 uint64_t IsLive : 1;
522 uint64_t IsCallable : 1;
523 JITTargetAddress Size = 0;
524 };
525
526 raw_ostream &operator<<(raw_ostream &OS, const Symbol &A);
527
528 void printEdge(raw_ostream &OS, const Block &B, const Edge &E,
529 StringRef EdgeKindName);
530
531 /// Represents an object file section.
532 class Section {
533 friend class LinkGraph;
534
535 private:
Section(StringRef Name,sys::Memory::ProtectionFlags Prot,SectionOrdinal SecOrdinal)536 Section(StringRef Name, sys::Memory::ProtectionFlags Prot,
537 SectionOrdinal SecOrdinal)
538 : Name(Name), Prot(Prot), SecOrdinal(SecOrdinal) {}
539
540 using SymbolSet = DenseSet<Symbol *>;
541 using BlockSet = DenseSet<Block *>;
542
543 public:
544 using symbol_iterator = SymbolSet::iterator;
545 using const_symbol_iterator = SymbolSet::const_iterator;
546
547 using block_iterator = BlockSet::iterator;
548 using const_block_iterator = BlockSet::const_iterator;
549
550 ~Section();
551
552 /// Returns the name of this section.
getName()553 StringRef getName() const { return Name; }
554
555 /// Returns the protection flags for this section.
getProtectionFlags()556 sys::Memory::ProtectionFlags getProtectionFlags() const { return Prot; }
557
558 /// Returns the ordinal for this section.
getOrdinal()559 SectionOrdinal getOrdinal() const { return SecOrdinal; }
560
561 /// Returns an iterator over the blocks defined in this section.
blocks()562 iterator_range<block_iterator> blocks() {
563 return make_range(Blocks.begin(), Blocks.end());
564 }
565
566 /// Returns an iterator over the blocks defined in this section.
blocks()567 iterator_range<const_block_iterator> blocks() const {
568 return make_range(Blocks.begin(), Blocks.end());
569 }
570
571 /// Returns an iterator over the symbols defined in this section.
symbols()572 iterator_range<symbol_iterator> symbols() {
573 return make_range(Symbols.begin(), Symbols.end());
574 }
575
576 /// Returns an iterator over the symbols defined in this section.
symbols()577 iterator_range<const_symbol_iterator> symbols() const {
578 return make_range(Symbols.begin(), Symbols.end());
579 }
580
581 /// Return the number of symbols in this section.
symbols_size()582 SymbolSet::size_type symbols_size() { return Symbols.size(); }
583
584 private:
addSymbol(Symbol & Sym)585 void addSymbol(Symbol &Sym) {
586 assert(!Symbols.count(&Sym) && "Symbol is already in this section");
587 Symbols.insert(&Sym);
588 }
589
removeSymbol(Symbol & Sym)590 void removeSymbol(Symbol &Sym) {
591 assert(Symbols.count(&Sym) && "symbol is not in this section");
592 Symbols.erase(&Sym);
593 }
594
addBlock(Block & B)595 void addBlock(Block &B) {
596 assert(!Blocks.count(&B) && "Block is already in this section");
597 Blocks.insert(&B);
598 }
599
removeBlock(Block & B)600 void removeBlock(Block &B) {
601 assert(Blocks.count(&B) && "Block is not in this section");
602 Blocks.erase(&B);
603 }
604
605 StringRef Name;
606 sys::Memory::ProtectionFlags Prot;
607 SectionOrdinal SecOrdinal = 0;
608 BlockSet Blocks;
609 SymbolSet Symbols;
610 };
611
612 /// Represents a section address range via a pair of Block pointers
613 /// to the first and last Blocks in the section.
614 class SectionRange {
615 public:
616 SectionRange() = default;
SectionRange(const Section & Sec)617 SectionRange(const Section &Sec) {
618 if (llvm::empty(Sec.blocks()))
619 return;
620 First = Last = *Sec.blocks().begin();
621 for (auto *B : Sec.blocks()) {
622 if (B->getAddress() < First->getAddress())
623 First = B;
624 if (B->getAddress() > Last->getAddress())
625 Last = B;
626 }
627 }
getFirstBlock()628 Block *getFirstBlock() const {
629 assert((!Last || First) && "First can not be null if end is non-null");
630 return First;
631 }
getLastBlock()632 Block *getLastBlock() const {
633 assert((First || !Last) && "Last can not be null if start is non-null");
634 return Last;
635 }
isEmpty()636 bool isEmpty() const {
637 assert((First || !Last) && "Last can not be null if start is non-null");
638 return !First;
639 }
getStart()640 JITTargetAddress getStart() const {
641 return First ? First->getAddress() : 0;
642 }
getEnd()643 JITTargetAddress getEnd() const {
644 return Last ? Last->getAddress() + Last->getSize() : 0;
645 }
getSize()646 uint64_t getSize() const { return getEnd() - getStart(); }
647
648 private:
649 Block *First = nullptr;
650 Block *Last = nullptr;
651 };
652
653 class LinkGraph {
654 private:
655 using SectionList = std::vector<std::unique_ptr<Section>>;
656 using ExternalSymbolSet = DenseSet<Symbol *>;
657 using BlockSet = DenseSet<Block *>;
658
659 template <typename... ArgTs>
createAddressable(ArgTs &&...Args)660 Addressable &createAddressable(ArgTs &&... Args) {
661 Addressable *A =
662 reinterpret_cast<Addressable *>(Allocator.Allocate<Addressable>());
663 new (A) Addressable(std::forward<ArgTs>(Args)...);
664 return *A;
665 }
666
destroyAddressable(Addressable & A)667 void destroyAddressable(Addressable &A) {
668 A.~Addressable();
669 Allocator.Deallocate(&A);
670 }
671
createBlock(ArgTs &&...Args)672 template <typename... ArgTs> Block &createBlock(ArgTs &&... Args) {
673 Block *B = reinterpret_cast<Block *>(Allocator.Allocate<Block>());
674 new (B) Block(std::forward<ArgTs>(Args)...);
675 B->getSection().addBlock(*B);
676 return *B;
677 }
678
destroyBlock(Block & B)679 void destroyBlock(Block &B) {
680 B.~Block();
681 Allocator.Deallocate(&B);
682 }
683
destroySymbol(Symbol & S)684 void destroySymbol(Symbol &S) {
685 S.~Symbol();
686 Allocator.Deallocate(&S);
687 }
688
getSectionBlocks(Section & S)689 static iterator_range<Section::block_iterator> getSectionBlocks(Section &S) {
690 return S.blocks();
691 }
692
693 static iterator_range<Section::const_block_iterator>
getSectionConstBlocks(Section & S)694 getSectionConstBlocks(Section &S) {
695 return S.blocks();
696 }
697
698 static iterator_range<Section::symbol_iterator>
getSectionSymbols(Section & S)699 getSectionSymbols(Section &S) {
700 return S.symbols();
701 }
702
703 static iterator_range<Section::const_symbol_iterator>
getSectionConstSymbols(Section & S)704 getSectionConstSymbols(Section &S) {
705 return S.symbols();
706 }
707
708 public:
709 using external_symbol_iterator = ExternalSymbolSet::iterator;
710
711 using section_iterator = pointee_iterator<SectionList::iterator>;
712 using const_section_iterator = pointee_iterator<SectionList::const_iterator>;
713
714 template <typename OuterItrT, typename InnerItrT, typename T,
715 iterator_range<InnerItrT> getInnerRange(
716 typename OuterItrT::reference)>
717 class nested_collection_iterator
718 : public iterator_facade_base<
719 nested_collection_iterator<OuterItrT, InnerItrT, T, getInnerRange>,
720 std::forward_iterator_tag, T> {
721 public:
722 nested_collection_iterator() = default;
723
nested_collection_iterator(OuterItrT OuterI,OuterItrT OuterE)724 nested_collection_iterator(OuterItrT OuterI, OuterItrT OuterE)
725 : OuterI(OuterI), OuterE(OuterE),
726 InnerI(getInnerBegin(OuterI, OuterE)) {
727 moveToNonEmptyInnerOrEnd();
728 }
729
730 bool operator==(const nested_collection_iterator &RHS) const {
731 return (OuterI == RHS.OuterI) && (InnerI == RHS.InnerI);
732 }
733
734 T operator*() const {
735 assert(InnerI != getInnerRange(*OuterI).end() && "Dereferencing end?");
736 return *InnerI;
737 }
738
739 nested_collection_iterator operator++() {
740 ++InnerI;
741 moveToNonEmptyInnerOrEnd();
742 return *this;
743 }
744
745 private:
getInnerBegin(OuterItrT OuterI,OuterItrT OuterE)746 static InnerItrT getInnerBegin(OuterItrT OuterI, OuterItrT OuterE) {
747 return OuterI != OuterE ? getInnerRange(*OuterI).begin() : InnerItrT();
748 }
749
moveToNonEmptyInnerOrEnd()750 void moveToNonEmptyInnerOrEnd() {
751 while (OuterI != OuterE && InnerI == getInnerRange(*OuterI).end()) {
752 ++OuterI;
753 InnerI = getInnerBegin(OuterI, OuterE);
754 }
755 }
756
757 OuterItrT OuterI, OuterE;
758 InnerItrT InnerI;
759 };
760
761 using defined_symbol_iterator =
762 nested_collection_iterator<const_section_iterator,
763 Section::symbol_iterator, Symbol *,
764 getSectionSymbols>;
765
766 using const_defined_symbol_iterator =
767 nested_collection_iterator<const_section_iterator,
768 Section::const_symbol_iterator, const Symbol *,
769 getSectionConstSymbols>;
770
771 using block_iterator = nested_collection_iterator<const_section_iterator,
772 Section::block_iterator,
773 Block *, getSectionBlocks>;
774
775 using const_block_iterator =
776 nested_collection_iterator<const_section_iterator,
777 Section::const_block_iterator, const Block *,
778 getSectionConstBlocks>;
779
LinkGraph(std::string Name,unsigned PointerSize,support::endianness Endianness)780 LinkGraph(std::string Name, unsigned PointerSize,
781 support::endianness Endianness)
782 : Name(std::move(Name)), PointerSize(PointerSize),
783 Endianness(Endianness) {}
784
785 /// Returns the name of this graph (usually the name of the original
786 /// underlying MemoryBuffer).
getName()787 const std::string &getName() { return Name; }
788
789 /// Returns the pointer size for use in this graph.
getPointerSize()790 unsigned getPointerSize() const { return PointerSize; }
791
792 /// Returns the endianness of content in this graph.
getEndianness()793 support::endianness getEndianness() const { return Endianness; }
794
795 /// Create a section with the given name, protection flags, and alignment.
createSection(StringRef Name,sys::Memory::ProtectionFlags Prot)796 Section &createSection(StringRef Name, sys::Memory::ProtectionFlags Prot) {
797 std::unique_ptr<Section> Sec(new Section(Name, Prot, Sections.size()));
798 Sections.push_back(std::move(Sec));
799 return *Sections.back();
800 }
801
802 /// Create a content block.
createContentBlock(Section & Parent,StringRef Content,uint64_t Address,uint64_t Alignment,uint64_t AlignmentOffset)803 Block &createContentBlock(Section &Parent, StringRef Content,
804 uint64_t Address, uint64_t Alignment,
805 uint64_t AlignmentOffset) {
806 return createBlock(Parent, Content, Address, Alignment, AlignmentOffset);
807 }
808
809 /// Create a zero-fill block.
createZeroFillBlock(Section & Parent,uint64_t Size,uint64_t Address,uint64_t Alignment,uint64_t AlignmentOffset)810 Block &createZeroFillBlock(Section &Parent, uint64_t Size, uint64_t Address,
811 uint64_t Alignment, uint64_t AlignmentOffset) {
812 return createBlock(Parent, Size, Address, Alignment, AlignmentOffset);
813 }
814
815 /// Cache type for the splitBlock function.
816 using SplitBlockCache = Optional<SmallVector<Symbol *, 8>>;
817
818 /// Splits block B at the given index which must be greater than zero.
819 /// If SplitIndex == B.getSize() then this function is a no-op and returns B.
820 /// If SplitIndex < B.getSize() then this function returns a new block
821 /// covering the range [ 0, SplitIndex ), and B is modified to cover the range
822 /// [ SplitIndex, B.size() ).
823 ///
824 /// The optional Cache parameter can be used to speed up repeated calls to
825 /// splitBlock for a single block. If the value is None the cache will be
826 /// treated as uninitialized and splitBlock will populate it. Otherwise it
827 /// is assumed to contain the list of Symbols pointing at B, sorted in
828 /// descending order of offset.
829 ///
830 /// Notes:
831 ///
832 /// 1. The newly introduced block will have a new ordinal which will be
833 /// higher than any other ordinals in the section. Clients are responsible
834 /// for re-assigning block ordinals to restore a compatible order if
835 /// needed.
836 ///
837 /// 2. The cache is not automatically updated if new symbols are introduced
838 /// between calls to splitBlock. Any newly introduced symbols may be
839 /// added to the cache manually (descending offset order must be
840 /// preserved), or the cache can be set to None and rebuilt by
841 /// splitBlock on the next call.
842 Block &splitBlock(Block &B, size_t SplitIndex,
843 SplitBlockCache *Cache = nullptr);
844
845 /// Add an external symbol.
846 /// Some formats (e.g. ELF) allow Symbols to have sizes. For Symbols whose
847 /// size is not known, you should substitute '0'.
848 /// For external symbols Linkage determines whether the symbol must be
849 /// present during lookup: Externals with strong linkage must be found or
850 /// an error will be emitted. Externals with weak linkage are permitted to
851 /// be undefined, in which case they are assigned a value of 0.
addExternalSymbol(StringRef Name,uint64_t Size,Linkage L)852 Symbol &addExternalSymbol(StringRef Name, uint64_t Size, Linkage L) {
853 auto &Sym =
854 Symbol::constructExternal(Allocator.Allocate<Symbol>(),
855 createAddressable(0, false), Name, Size, L);
856 ExternalSymbols.insert(&Sym);
857 return Sym;
858 }
859
860 /// Add an absolute symbol.
addAbsoluteSymbol(StringRef Name,JITTargetAddress Address,uint64_t Size,Linkage L,Scope S,bool IsLive)861 Symbol &addAbsoluteSymbol(StringRef Name, JITTargetAddress Address,
862 uint64_t Size, Linkage L, Scope S, bool IsLive) {
863 auto &Sym = Symbol::constructAbsolute(Allocator.Allocate<Symbol>(),
864 createAddressable(Address), Name,
865 Size, L, S, IsLive);
866 AbsoluteSymbols.insert(&Sym);
867 return Sym;
868 }
869
870 /// Convenience method for adding a weak zero-fill symbol.
addCommonSymbol(StringRef Name,Scope S,Section & Section,JITTargetAddress Address,uint64_t Size,uint64_t Alignment,bool IsLive)871 Symbol &addCommonSymbol(StringRef Name, Scope S, Section &Section,
872 JITTargetAddress Address, uint64_t Size,
873 uint64_t Alignment, bool IsLive) {
874 auto &Sym = Symbol::constructCommon(
875 Allocator.Allocate<Symbol>(),
876 createBlock(Section, Size, Address, Alignment, 0), Name, Size, S,
877 IsLive);
878 Section.addSymbol(Sym);
879 return Sym;
880 }
881
882 /// Add an anonymous symbol.
addAnonymousSymbol(Block & Content,JITTargetAddress Offset,JITTargetAddress Size,bool IsCallable,bool IsLive)883 Symbol &addAnonymousSymbol(Block &Content, JITTargetAddress Offset,
884 JITTargetAddress Size, bool IsCallable,
885 bool IsLive) {
886 auto &Sym = Symbol::constructAnonDef(Allocator.Allocate<Symbol>(), Content,
887 Offset, Size, IsCallable, IsLive);
888 Content.getSection().addSymbol(Sym);
889 return Sym;
890 }
891
892 /// Add a named symbol.
addDefinedSymbol(Block & Content,JITTargetAddress Offset,StringRef Name,JITTargetAddress Size,Linkage L,Scope S,bool IsCallable,bool IsLive)893 Symbol &addDefinedSymbol(Block &Content, JITTargetAddress Offset,
894 StringRef Name, JITTargetAddress Size, Linkage L,
895 Scope S, bool IsCallable, bool IsLive) {
896 auto &Sym =
897 Symbol::constructNamedDef(Allocator.Allocate<Symbol>(), Content, Offset,
898 Name, Size, L, S, IsLive, IsCallable);
899 Content.getSection().addSymbol(Sym);
900 return Sym;
901 }
902
sections()903 iterator_range<section_iterator> sections() {
904 return make_range(section_iterator(Sections.begin()),
905 section_iterator(Sections.end()));
906 }
907
908 /// Returns the section with the given name if it exists, otherwise returns
909 /// null.
findSectionByName(StringRef Name)910 Section *findSectionByName(StringRef Name) {
911 for (auto &S : sections())
912 if (S.getName() == Name)
913 return &S;
914 return nullptr;
915 }
916
blocks()917 iterator_range<block_iterator> blocks() {
918 return make_range(block_iterator(Sections.begin(), Sections.end()),
919 block_iterator(Sections.end(), Sections.end()));
920 }
921
blocks()922 iterator_range<const_block_iterator> blocks() const {
923 return make_range(const_block_iterator(Sections.begin(), Sections.end()),
924 const_block_iterator(Sections.end(), Sections.end()));
925 }
926
external_symbols()927 iterator_range<external_symbol_iterator> external_symbols() {
928 return make_range(ExternalSymbols.begin(), ExternalSymbols.end());
929 }
930
absolute_symbols()931 iterator_range<external_symbol_iterator> absolute_symbols() {
932 return make_range(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
933 }
934
defined_symbols()935 iterator_range<defined_symbol_iterator> defined_symbols() {
936 return make_range(defined_symbol_iterator(Sections.begin(), Sections.end()),
937 defined_symbol_iterator(Sections.end(), Sections.end()));
938 }
939
defined_symbols()940 iterator_range<const_defined_symbol_iterator> defined_symbols() const {
941 return make_range(
942 const_defined_symbol_iterator(Sections.begin(), Sections.end()),
943 const_defined_symbol_iterator(Sections.end(), Sections.end()));
944 }
945
946 /// Turn a defined symbol into an external one.
makeExternal(Symbol & Sym)947 void makeExternal(Symbol &Sym) {
948 if (Sym.getAddressable().isAbsolute()) {
949 assert(AbsoluteSymbols.count(&Sym) &&
950 "Sym is not in the absolute symbols set");
951 AbsoluteSymbols.erase(&Sym);
952 } else {
953 assert(Sym.isDefined() && "Sym is not a defined symbol");
954 Section &Sec = Sym.getBlock().getSection();
955 Sec.removeSymbol(Sym);
956 }
957 Sym.makeExternal(createAddressable(false));
958 ExternalSymbols.insert(&Sym);
959 }
960
961 /// Removes an external symbol. Also removes the underlying Addressable.
removeExternalSymbol(Symbol & Sym)962 void removeExternalSymbol(Symbol &Sym) {
963 assert(!Sym.isDefined() && !Sym.isAbsolute() &&
964 "Sym is not an external symbol");
965 assert(ExternalSymbols.count(&Sym) && "Symbol is not in the externals set");
966 ExternalSymbols.erase(&Sym);
967 Addressable &Base = *Sym.Base;
968 destroySymbol(Sym);
969 destroyAddressable(Base);
970 }
971
972 /// Remove an absolute symbol. Also removes the underlying Addressable.
removeAbsoluteSymbol(Symbol & Sym)973 void removeAbsoluteSymbol(Symbol &Sym) {
974 assert(!Sym.isDefined() && Sym.isAbsolute() &&
975 "Sym is not an absolute symbol");
976 assert(AbsoluteSymbols.count(&Sym) &&
977 "Symbol is not in the absolute symbols set");
978 AbsoluteSymbols.erase(&Sym);
979 Addressable &Base = *Sym.Base;
980 destroySymbol(Sym);
981 destroyAddressable(Base);
982 }
983
984 /// Removes defined symbols. Does not remove the underlying block.
removeDefinedSymbol(Symbol & Sym)985 void removeDefinedSymbol(Symbol &Sym) {
986 assert(Sym.isDefined() && "Sym is not a defined symbol");
987 Sym.getBlock().getSection().removeSymbol(Sym);
988 destroySymbol(Sym);
989 }
990
991 /// Remove a block.
removeBlock(Block & B)992 void removeBlock(Block &B) {
993 B.getSection().removeBlock(B);
994 destroyBlock(B);
995 }
996
997 /// Dump the graph.
998 ///
999 /// If supplied, the EdgeKindToName function will be used to name edge
1000 /// kinds in the debug output. Otherwise raw edge kind numbers will be
1001 /// displayed.
1002 void dump(raw_ostream &OS,
1003 std::function<StringRef(Edge::Kind)> EdegKindToName =
1004 std::function<StringRef(Edge::Kind)>());
1005
1006 private:
1007 // Put the BumpPtrAllocator first so that we don't free any of the underlying
1008 // memory until the Symbol/Addressable destructors have been run.
1009 BumpPtrAllocator Allocator;
1010
1011 std::string Name;
1012 unsigned PointerSize;
1013 support::endianness Endianness;
1014 SectionList Sections;
1015 ExternalSymbolSet ExternalSymbols;
1016 ExternalSymbolSet AbsoluteSymbols;
1017 };
1018
1019 /// Enables easy lookup of blocks by addresses.
1020 class BlockAddressMap {
1021 public:
1022 using AddrToBlockMap = std::map<JITTargetAddress, Block *>;
1023 using const_iterator = AddrToBlockMap::const_iterator;
1024
1025 /// A block predicate that always adds all blocks.
includeAllBlocks(const Block & B)1026 static bool includeAllBlocks(const Block &B) { return true; }
1027
1028 /// A block predicate that always includes blocks with non-null addresses.
includeNonNull(const Block & B)1029 static bool includeNonNull(const Block &B) { return B.getAddress(); }
1030
1031 BlockAddressMap() = default;
1032
1033 /// Add a block to the map. Returns an error if the block overlaps with any
1034 /// existing block.
1035 template <typename PredFn = decltype(includeAllBlocks)>
1036 Error addBlock(Block &B, PredFn Pred = includeAllBlocks) {
1037 if (!Pred(B))
1038 return Error::success();
1039
1040 auto I = AddrToBlock.upper_bound(B.getAddress());
1041
1042 // If we're not at the end of the map, check for overlap with the next
1043 // element.
1044 if (I != AddrToBlock.end()) {
1045 if (B.getAddress() + B.getSize() > I->second->getAddress())
1046 return overlapError(B, *I->second);
1047 }
1048
1049 // If we're not at the start of the map, check for overlap with the previous
1050 // element.
1051 if (I != AddrToBlock.begin()) {
1052 auto &PrevBlock = *std::prev(I)->second;
1053 if (PrevBlock.getAddress() + PrevBlock.getSize() > B.getAddress())
1054 return overlapError(B, PrevBlock);
1055 }
1056
1057 AddrToBlock.insert(I, std::make_pair(B.getAddress(), &B));
1058 return Error::success();
1059 }
1060
1061 /// Add a block to the map without checking for overlap with existing blocks.
1062 /// The client is responsible for ensuring that the block added does not
1063 /// overlap with any existing block.
addBlockWithoutChecking(Block & B)1064 void addBlockWithoutChecking(Block &B) { AddrToBlock[B.getAddress()] = &B; }
1065
1066 /// Add a range of blocks to the map. Returns an error if any block in the
1067 /// range overlaps with any other block in the range, or with any existing
1068 /// block in the map.
1069 template <typename BlockPtrRange,
1070 typename PredFn = decltype(includeAllBlocks)>
1071 Error addBlocks(BlockPtrRange &&Blocks, PredFn Pred = includeAllBlocks) {
1072 for (auto *B : Blocks)
1073 if (auto Err = addBlock(*B, Pred))
1074 return Err;
1075 return Error::success();
1076 }
1077
1078 /// Add a range of blocks to the map without checking for overlap with
1079 /// existing blocks. The client is responsible for ensuring that the block
1080 /// added does not overlap with any existing block.
1081 template <typename BlockPtrRange>
addBlocksWithoutChecking(BlockPtrRange && Blocks)1082 void addBlocksWithoutChecking(BlockPtrRange &&Blocks) {
1083 for (auto *B : Blocks)
1084 addBlockWithoutChecking(*B);
1085 }
1086
1087 /// Iterates over (Address, Block*) pairs in ascending order of address.
begin()1088 const_iterator begin() const { return AddrToBlock.begin(); }
end()1089 const_iterator end() const { return AddrToBlock.end(); }
1090
1091 /// Returns the block starting at the given address, or nullptr if no such
1092 /// block exists.
getBlockAt(JITTargetAddress Addr)1093 Block *getBlockAt(JITTargetAddress Addr) const {
1094 auto I = AddrToBlock.find(Addr);
1095 if (I == AddrToBlock.end())
1096 return nullptr;
1097 return I->second;
1098 }
1099
1100 /// Returns the block covering the given address, or nullptr if no such block
1101 /// exists.
getBlockCovering(JITTargetAddress Addr)1102 Block *getBlockCovering(JITTargetAddress Addr) const {
1103 auto I = AddrToBlock.upper_bound(Addr);
1104 if (I == AddrToBlock.begin())
1105 return nullptr;
1106 auto *B = std::prev(I)->second;
1107 if (Addr < B->getAddress() + B->getSize())
1108 return B;
1109 return nullptr;
1110 }
1111
1112 private:
overlapError(Block & NewBlock,Block & ExistingBlock)1113 Error overlapError(Block &NewBlock, Block &ExistingBlock) {
1114 auto NewBlockEnd = NewBlock.getAddress() + NewBlock.getSize();
1115 auto ExistingBlockEnd =
1116 ExistingBlock.getAddress() + ExistingBlock.getSize();
1117 return make_error<JITLinkError>(
1118 "Block at " +
1119 formatv("{0:x16} -- {1:x16}", NewBlock.getAddress(), NewBlockEnd) +
1120 " overlaps " +
1121 formatv("{0:x16} -- {1:x16}", ExistingBlock.getAddress(),
1122 ExistingBlockEnd));
1123 }
1124
1125 AddrToBlockMap AddrToBlock;
1126 };
1127
1128 /// A map of addresses to Symbols.
1129 class SymbolAddressMap {
1130 public:
1131 using SymbolVector = SmallVector<Symbol *, 1>;
1132
1133 /// Add a symbol to the SymbolAddressMap.
addSymbol(Symbol & Sym)1134 void addSymbol(Symbol &Sym) {
1135 AddrToSymbols[Sym.getAddress()].push_back(&Sym);
1136 }
1137
1138 /// Add all symbols in a given range to the SymbolAddressMap.
1139 template <typename SymbolPtrCollection>
addSymbols(SymbolPtrCollection && Symbols)1140 void addSymbols(SymbolPtrCollection &&Symbols) {
1141 for (auto *Sym : Symbols)
1142 addSymbol(*Sym);
1143 }
1144
1145 /// Returns the list of symbols that start at the given address, or nullptr if
1146 /// no such symbols exist.
getSymbolsAt(JITTargetAddress Addr)1147 const SymbolVector *getSymbolsAt(JITTargetAddress Addr) const {
1148 auto I = AddrToSymbols.find(Addr);
1149 if (I == AddrToSymbols.end())
1150 return nullptr;
1151 return &I->second;
1152 }
1153
1154 private:
1155 std::map<JITTargetAddress, SymbolVector> AddrToSymbols;
1156 };
1157
1158 /// A function for mutating LinkGraphs.
1159 using LinkGraphPassFunction = std::function<Error(LinkGraph &)>;
1160
1161 /// A list of LinkGraph passes.
1162 using LinkGraphPassList = std::vector<LinkGraphPassFunction>;
1163
1164 /// An LinkGraph pass configuration, consisting of a list of pre-prune,
1165 /// post-prune, and post-fixup passes.
1166 struct PassConfiguration {
1167
1168 /// Pre-prune passes.
1169 ///
1170 /// These passes are called on the graph after it is built, and before any
1171 /// symbols have been pruned.
1172 ///
1173 /// Notable use cases: Marking symbols live or should-discard.
1174 LinkGraphPassList PrePrunePasses;
1175
1176 /// Post-prune passes.
1177 ///
1178 /// These passes are called on the graph after dead stripping, but before
1179 /// fixups are applied.
1180 ///
1181 /// Notable use cases: Building GOT, stub, and TLV symbols.
1182 LinkGraphPassList PostPrunePasses;
1183
1184 /// Post-fixup passes.
1185 ///
1186 /// These passes are called on the graph after block contents has been copied
1187 /// to working memory, and fixups applied.
1188 ///
1189 /// Notable use cases: Testing and validation.
1190 LinkGraphPassList PostFixupPasses;
1191 };
1192
1193 /// Flags for symbol lookup.
1194 ///
1195 /// FIXME: These basically duplicate orc::SymbolLookupFlags -- We should merge
1196 /// the two types once we have an OrcSupport library.
1197 enum class SymbolLookupFlags { RequiredSymbol, WeaklyReferencedSymbol };
1198
1199 raw_ostream &operator<<(raw_ostream &OS, const SymbolLookupFlags &LF);
1200
1201 /// A map of symbol names to resolved addresses.
1202 using AsyncLookupResult = DenseMap<StringRef, JITEvaluatedSymbol>;
1203
1204 /// A function object to call with a resolved symbol map (See AsyncLookupResult)
1205 /// or an error if resolution failed.
1206 class JITLinkAsyncLookupContinuation {
1207 public:
~JITLinkAsyncLookupContinuation()1208 virtual ~JITLinkAsyncLookupContinuation() {}
1209 virtual void run(Expected<AsyncLookupResult> LR) = 0;
1210
1211 private:
1212 virtual void anchor();
1213 };
1214
1215 /// Create a lookup continuation from a function object.
1216 template <typename Continuation>
1217 std::unique_ptr<JITLinkAsyncLookupContinuation>
createLookupContinuation(Continuation Cont)1218 createLookupContinuation(Continuation Cont) {
1219
1220 class Impl final : public JITLinkAsyncLookupContinuation {
1221 public:
1222 Impl(Continuation C) : C(std::move(C)) {}
1223 void run(Expected<AsyncLookupResult> LR) override { C(std::move(LR)); }
1224
1225 private:
1226 Continuation C;
1227 };
1228
1229 return std::make_unique<Impl>(std::move(Cont));
1230 }
1231
1232 /// Holds context for a single jitLink invocation.
1233 class JITLinkContext {
1234 public:
1235 using LookupMap = DenseMap<StringRef, SymbolLookupFlags>;
1236
1237 /// Destroy a JITLinkContext.
1238 virtual ~JITLinkContext();
1239
1240 /// Return the MemoryManager to be used for this link.
1241 virtual JITLinkMemoryManager &getMemoryManager() = 0;
1242
1243 /// Returns a StringRef for the object buffer.
1244 /// This method can not be called once takeObjectBuffer has been called.
1245 virtual MemoryBufferRef getObjectBuffer() const = 0;
1246
1247 /// Notify this context that linking failed.
1248 /// Called by JITLink if linking cannot be completed.
1249 virtual void notifyFailed(Error Err) = 0;
1250
1251 /// Called by JITLink to resolve external symbols. This method is passed a
1252 /// lookup continutation which it must call with a result to continue the
1253 /// linking process.
1254 virtual void lookup(const LookupMap &Symbols,
1255 std::unique_ptr<JITLinkAsyncLookupContinuation> LC) = 0;
1256
1257 /// Called by JITLink once all defined symbols in the graph have been assigned
1258 /// their final memory locations in the target process. At this point the
1259 /// LinkGraph can be inspected to build a symbol table, however the block
1260 /// content will not generally have been copied to the target location yet.
1261 virtual void notifyResolved(LinkGraph &G) = 0;
1262
1263 /// Called by JITLink to notify the context that the object has been
1264 /// finalized (i.e. emitted to memory and memory permissions set). If all of
1265 /// this objects dependencies have also been finalized then the code is ready
1266 /// to run.
1267 virtual void
1268 notifyFinalized(std::unique_ptr<JITLinkMemoryManager::Allocation> A) = 0;
1269
1270 /// Called by JITLink prior to linking to determine whether default passes for
1271 /// the target should be added. The default implementation returns true.
1272 /// If subclasses override this method to return false for any target then
1273 /// they are required to fully configure the pass pipeline for that target.
1274 virtual bool shouldAddDefaultTargetPasses(const Triple &TT) const;
1275
1276 /// Returns the mark-live pass to be used for this link. If no pass is
1277 /// returned (the default) then the target-specific linker implementation will
1278 /// choose a conservative default (usually marking all symbols live).
1279 /// This function is only called if shouldAddDefaultTargetPasses returns true,
1280 /// otherwise the JITContext is responsible for adding a mark-live pass in
1281 /// modifyPassConfig.
1282 virtual LinkGraphPassFunction getMarkLivePass(const Triple &TT) const;
1283
1284 /// Called by JITLink to modify the pass pipeline prior to linking.
1285 /// The default version performs no modification.
1286 virtual Error modifyPassConfig(const Triple &TT, PassConfiguration &Config);
1287 };
1288
1289 /// Marks all symbols in a graph live. This can be used as a default,
1290 /// conservative mark-live implementation.
1291 Error markAllSymbolsLive(LinkGraph &G);
1292
1293 /// Basic JITLink implementation.
1294 ///
1295 /// This function will use sensible defaults for GOT and Stub handling.
1296 void jitLink(std::unique_ptr<JITLinkContext> Ctx);
1297
1298 } // end namespace jitlink
1299 } // end namespace llvm
1300
1301 #endif // LLVM_EXECUTIONENGINE_JITLINK_JITLINK_H
1302