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