LLVM 20.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"
19#include "llvm/ADT/STLExtras.h"
30#include "llvm/Support/Endian.h"
31#include "llvm/Support/Error.h"
37#include <optional>
38
39#include <map>
40#include <string>
41#include <system_error>
42
43namespace llvm {
44namespace jitlink {
45
46class LinkGraph;
47class Symbol;
48class Section;
49
50/// Base class for errors originating in JIT linker, e.g. missing relocation
51/// support.
52class JITLinkError : public ErrorInfo<JITLinkError> {
53public:
54 static char ID;
55
56 JITLinkError(Twine ErrMsg) : ErrMsg(ErrMsg.str()) {}
57
58 void log(raw_ostream &OS) const override;
59 const std::string &getErrorMessage() const { return ErrMsg; }
60 std::error_code convertToErrorCode() const override;
61
62private:
63 std::string ErrMsg;
64};
65
66/// Represents fixups and constraints in the LinkGraph.
67class Edge {
68public:
69 using Kind = uint8_t;
70
72 Invalid, // Invalid edge value.
73 FirstKeepAlive, // Keeps target alive. Offset/addend zero.
74 KeepAlive = FirstKeepAlive, // Tag first edge kind that preserves liveness.
75 FirstRelocation // First architecture specific relocation.
76 };
77
79 using AddendT = int64_t;
80
81 Edge(Kind K, OffsetT Offset, Symbol &Target, AddendT Addend)
82 : Target(&Target), Offset(Offset), Addend(Addend), K(K) {}
83
84 OffsetT getOffset() const { return Offset; }
85 void setOffset(OffsetT Offset) { this->Offset = Offset; }
86 Kind getKind() const { return K; }
87 void setKind(Kind K) { this->K = K; }
88 bool isRelocation() const { return K >= FirstRelocation; }
90 assert(isRelocation() && "Not a relocation edge");
91 return K - FirstRelocation;
92 }
93 bool isKeepAlive() const { return K >= FirstKeepAlive; }
94 Symbol &getTarget() const { return *Target; }
95 void setTarget(Symbol &Target) { this->Target = &Target; }
96 AddendT getAddend() const { return Addend; }
97 void setAddend(AddendT Addend) { this->Addend = Addend; }
98
99private:
100 Symbol *Target = nullptr;
101 OffsetT Offset = 0;
102 AddendT Addend = 0;
103 Kind K = 0;
104};
105
106/// Returns the string name of the given generic edge kind, or "unknown"
107/// otherwise. Useful for debugging.
109
110/// Base class for Addressable entities (externals, absolutes, blocks).
112 friend class LinkGraph;
113
114protected:
115 Addressable(orc::ExecutorAddr Address, bool IsDefined)
116 : Address(Address), IsDefined(IsDefined), IsAbsolute(false) {}
117
119 : Address(Address), IsDefined(false), IsAbsolute(true) {
120 assert(!(IsDefined && IsAbsolute) &&
121 "Block cannot be both defined and absolute");
122 }
123
124public:
125 Addressable(const Addressable &) = delete;
126 Addressable &operator=(const Addressable &) = default;
129
130 orc::ExecutorAddr getAddress() const { return Address; }
131 void setAddress(orc::ExecutorAddr Address) { this->Address = Address; }
132
133 /// Returns true if this is a defined addressable, in which case you
134 /// can downcast this to a Block.
135 bool isDefined() const { return static_cast<bool>(IsDefined); }
136 bool isAbsolute() const { return static_cast<bool>(IsAbsolute); }
137
138private:
139 void setAbsolute(bool IsAbsolute) {
140 assert(!IsDefined && "Cannot change the Absolute flag on a defined block");
141 this->IsAbsolute = IsAbsolute;
142 }
143
144 orc::ExecutorAddr Address;
145 uint64_t IsDefined : 1;
146 uint64_t IsAbsolute : 1;
147
148protected:
149 // bitfields for Block, allocated here to improve packing.
153};
154
156
157/// An Addressable with content and edges.
158class Block : public Addressable {
159 friend class LinkGraph;
160
161private:
162 /// Create a zero-fill defined addressable.
165 : Addressable(Address, true), Parent(&Parent), Size(Size) {
166 assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
167 assert(AlignmentOffset < Alignment &&
168 "Alignment offset cannot exceed alignment");
169 assert(AlignmentOffset <= MaxAlignmentOffset &&
170 "Alignment offset exceeds maximum");
171 ContentMutable = false;
172 P2Align = Alignment ? llvm::countr_zero(Alignment) : 0;
173 this->AlignmentOffset = AlignmentOffset;
174 }
175
176 /// Create a defined addressable for the given content.
177 /// The Content is assumed to be non-writable, and will be copied when
178 /// mutations are required.
181 : Addressable(Address, true), Parent(&Parent), Data(Content.data()),
182 Size(Content.size()) {
183 assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
184 assert(AlignmentOffset < Alignment &&
185 "Alignment offset cannot exceed alignment");
186 assert(AlignmentOffset <= MaxAlignmentOffset &&
187 "Alignment offset exceeds maximum");
188 ContentMutable = false;
189 P2Align = Alignment ? llvm::countr_zero(Alignment) : 0;
190 this->AlignmentOffset = AlignmentOffset;
191 }
192
193 /// Create a defined addressable for the given content.
194 /// The content is assumed to be writable, and the caller is responsible
195 /// for ensuring that it lives for the duration of the Block's lifetime.
196 /// The standard way to achieve this is to allocate it on the Graph's
197 /// allocator.
198 Block(Section &Parent, MutableArrayRef<char> Content,
200 : Addressable(Address, true), Parent(&Parent), Data(Content.data()),
201 Size(Content.size()) {
202 assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
203 assert(AlignmentOffset < Alignment &&
204 "Alignment offset cannot exceed alignment");
205 assert(AlignmentOffset <= MaxAlignmentOffset &&
206 "Alignment offset exceeds maximum");
207 ContentMutable = true;
208 P2Align = Alignment ? llvm::countr_zero(Alignment) : 0;
209 this->AlignmentOffset = AlignmentOffset;
210 }
211
212public:
213 using EdgeVector = std::vector<Edge>;
214 using edge_iterator = EdgeVector::iterator;
215 using const_edge_iterator = EdgeVector::const_iterator;
216
217 Block(const Block &) = delete;
218 Block &operator=(const Block &) = delete;
219 Block(Block &&) = delete;
220 Block &operator=(Block &&) = delete;
221
222 /// Return the parent section for this block.
223 Section &getSection() const { return *Parent; }
224
225 /// Returns true if this is a zero-fill block.
226 ///
227 /// If true, getSize is callable but getContent is not (the content is
228 /// defined to be a sequence of zero bytes of length Size).
229 bool isZeroFill() const { return !Data; }
230
231 /// Returns the size of this defined addressable.
232 size_t getSize() const { return Size; }
233
234 /// Turns this block into a zero-fill block of the given size.
235 void setZeroFillSize(size_t Size) {
236 Data = nullptr;
237 this->Size = Size;
238 }
239
240 /// Returns the address range of this defined addressable.
243 }
244
245 /// Get the content for this block. Block must not be a zero-fill block.
247 assert(Data && "Block does not contain content");
248 return ArrayRef<char>(Data, Size);
249 }
250
251 /// Set the content for this block.
252 /// Caller is responsible for ensuring the underlying bytes are not
253 /// deallocated while pointed to by this block.
255 assert(Content.data() && "Setting null content");
256 Data = Content.data();
257 Size = Content.size();
258 ContentMutable = false;
259 }
260
261 /// Get mutable content for this block.
262 ///
263 /// If this Block's content is not already mutable this will trigger a copy
264 /// of the existing immutable content to a new, mutable buffer allocated using
265 /// LinkGraph::allocateContent.
267
268 /// Get mutable content for this block.
269 ///
270 /// This block's content must already be mutable. It is a programmatic error
271 /// to call this on a block with immutable content -- consider using
272 /// getMutableContent instead.
274 assert(Data && "Block does not contain content");
275 assert(ContentMutable && "Content is not mutable");
276 return MutableArrayRef<char>(const_cast<char *>(Data), Size);
277 }
278
279 /// Set mutable content for this block.
280 ///
281 /// The caller is responsible for ensuring that the memory pointed to by
282 /// MutableContent is not deallocated while pointed to by this block.
284 assert(MutableContent.data() && "Setting null content");
285 Data = MutableContent.data();
286 Size = MutableContent.size();
287 ContentMutable = true;
288 }
289
290 /// Returns true if this block's content is mutable.
291 ///
292 /// This is primarily useful for asserting that a block is already in a
293 /// mutable state prior to modifying the content. E.g. when applying
294 /// fixups we expect the block to already be mutable as it should have been
295 /// copied to working memory.
296 bool isContentMutable() const { return ContentMutable; }
297
298 /// Get the alignment for this content.
299 uint64_t getAlignment() const { return 1ull << P2Align; }
300
301 /// Set the alignment for this content.
302 void setAlignment(uint64_t Alignment) {
303 assert(isPowerOf2_64(Alignment) && "Alignment must be a power of two");
304 P2Align = Alignment ? llvm::countr_zero(Alignment) : 0;
305 }
306
307 /// Get the alignment offset for this content.
309
310 /// Set the alignment offset for this content.
312 assert(AlignmentOffset < (1ull << P2Align) &&
313 "Alignment offset can't exceed alignment");
314 this->AlignmentOffset = AlignmentOffset;
315 }
316
317 /// Add an edge to this block.
319 Edge::AddendT Addend) {
320 assert((K == Edge::KeepAlive || !isZeroFill()) &&
321 "Adding edge to zero-fill block?");
322 Edges.push_back(Edge(K, Offset, Target, Addend));
323 }
324
325 /// Add an edge by copying an existing one. This is typically used when
326 /// moving edges between blocks.
327 void addEdge(const Edge &E) { Edges.push_back(E); }
328
329 /// Return the list of edges attached to this content.
331 return make_range(Edges.begin(), Edges.end());
332 }
333
334 /// Returns the list of edges attached to this content.
336 return make_range(Edges.begin(), Edges.end());
337 }
338
339 /// Returns an iterator over all edges at the given offset within the block.
341 return make_filter_range(edges(),
342 [O](const Edge &E) { return E.getOffset() == O; });
343 }
344
345 /// Returns an iterator over all edges at the given offset within the block.
346 auto edges_at(Edge::OffsetT O) const {
347 return make_filter_range(edges(),
348 [O](const Edge &E) { return E.getOffset() == O; });
349 }
350
351 /// Return the size of the edges list.
352 size_t edges_size() const { return Edges.size(); }
353
354 /// Returns true if the list of edges is empty.
355 bool edges_empty() const { return Edges.empty(); }
356
357 /// Remove the edge pointed to by the given iterator.
358 /// Returns an iterator to the new next element.
359 edge_iterator removeEdge(edge_iterator I) { return Edges.erase(I); }
360
361 /// Returns the address of the fixup for the given edge, which is equal to
362 /// this block's address plus the edge's offset.
364 return getAddress() + E.getOffset();
365 }
366
367private:
368 static constexpr uint64_t MaxAlignmentOffset = (1ULL << 56) - 1;
369
370 void setSection(Section &Parent) { this->Parent = &Parent; }
371
372 Section *Parent;
373 const char *Data = nullptr;
374 size_t Size = 0;
375 std::vector<Edge> Edges;
376};
377
378// Align an address to conform with block alignment requirements.
380 uint64_t Delta = (B.getAlignmentOffset() - Addr) % B.getAlignment();
381 return Addr + Delta;
382}
383
384// Align a orc::ExecutorAddr to conform with block alignment requirements.
386 return orc::ExecutorAddr(alignToBlock(Addr.getValue(), B));
387}
388
389// Returns true if the given blocks contains exactly one valid c-string.
390// Zero-fill blocks of size 1 count as valid empty strings. Content blocks
391// must end with a zero, and contain no zeros before the end.
392bool isCStringBlock(Block &B);
393
394/// Describes symbol linkage. This can be used to resolve definition clashes.
395enum class Linkage : uint8_t {
396 Strong,
397 Weak,
398};
399
400/// Holds target-specific properties for a symbol.
402
403/// For errors and debugging output.
404const char *getLinkageName(Linkage L);
405
406/// Defines the scope in which this symbol should be visible:
407/// Default -- Visible in the public interface of the linkage unit.
408/// Hidden -- Visible within the linkage unit, but not exported from it.
409/// SideEffectsOnly -- Like hidden, but symbol can only be looked up once
410/// to trigger materialization of the containing graph.
411/// Local -- Visible only within the LinkGraph.
413
414/// For debugging output.
415const char *getScopeName(Scope S);
416
417raw_ostream &operator<<(raw_ostream &OS, const Block &B);
418
419/// Symbol representation.
420///
421/// Symbols represent locations within Addressable objects.
422/// They can be either Named or Anonymous.
423/// Anonymous symbols have neither linkage nor visibility, and must point at
424/// ContentBlocks.
425/// Named symbols may be in one of four states:
426/// - Null: Default initialized. Assignable, but otherwise unusable.
427/// - Defined: Has both linkage and visibility and points to a ContentBlock
428/// - Common: Has both linkage and visibility, points to a null Addressable.
429/// - External: Has neither linkage nor visibility, points to an external
430/// Addressable.
431///
432class Symbol {
433 friend class LinkGraph;
434
435private:
438 Scope S, bool IsLive, bool IsCallable)
439 : Name(std::move(Name)), Base(&Base), Offset(Offset), WeakRef(0),
440 Size(Size) {
441 assert(Offset <= MaxOffset && "Offset out of range");
442 setLinkage(L);
443 setScope(S);
444 setLive(IsLive);
445 setCallable(IsCallable);
447 }
448
449 static Symbol &constructExternal(BumpPtrAllocator &Allocator,
450 Addressable &Base,
453 bool WeaklyReferenced) {
454 assert(!Base.isDefined() &&
455 "Cannot create external symbol from defined block");
456 assert(Name && "External symbol name cannot be empty");
457 auto *Sym = Allocator.Allocate<Symbol>();
458 new (Sym)
459 Symbol(Base, 0, std::move(Name), Size, L, Scope::Default, false, false);
460 Sym->setWeaklyReferenced(WeaklyReferenced);
461 return *Sym;
462 }
463
464 static Symbol &constructAbsolute(BumpPtrAllocator &Allocator,
465 Addressable &Base,
466 orc::SymbolStringPtr &&Name,
468 Scope S, bool IsLive) {
469 assert(!Base.isDefined() &&
470 "Cannot create absolute symbol from a defined block");
471 auto *Sym = Allocator.Allocate<Symbol>();
472 new (Sym) Symbol(Base, 0, std::move(Name), Size, L, S, IsLive, false);
473 return *Sym;
474 }
475
476 static Symbol &constructAnonDef(BumpPtrAllocator &Allocator, Block &Base,
478 orc::ExecutorAddrDiff Size, bool IsCallable,
479 bool IsLive) {
480 assert((Offset + Size) <= Base.getSize() &&
481 "Symbol extends past end of block");
482 auto *Sym = Allocator.Allocate<Symbol>();
483 new (Sym) Symbol(Base, Offset, nullptr, Size, Linkage::Strong, Scope::Local,
484 IsLive, IsCallable);
485 return *Sym;
486 }
487
488 static Symbol &constructNamedDef(BumpPtrAllocator &Allocator, Block &Base,
490 orc::SymbolStringPtr Name,
492 Scope S, bool IsLive, bool IsCallable) {
493 assert((Offset + Size) <= Base.getSize() &&
494 "Symbol extends past end of block");
495 assert(Name && "Name cannot be empty");
496 auto *Sym = Allocator.Allocate<Symbol>();
497 new (Sym)
498 Symbol(Base, Offset, std::move(Name), Size, L, S, IsLive, IsCallable);
499 return *Sym;
500 }
501
502public:
503 /// Create a null Symbol. This allows Symbols to be default initialized for
504 /// use in containers (e.g. as map values). Null symbols are only useful for
505 /// assigning to.
506 Symbol() = default;
507
508 // Symbols are not movable or copyable.
509 Symbol(const Symbol &) = delete;
510 Symbol &operator=(const Symbol &) = delete;
511 Symbol(Symbol &&) = delete;
512 Symbol &operator=(Symbol &&) = delete;
513
514 /// Returns true if this symbol has a name.
515 bool hasName() const { return Name != nullptr; }
516
517 /// Returns the name of this symbol (empty if the symbol is anonymous).
519 assert((hasName() || getScope() == Scope::Local) &&
520 "Anonymous symbol has non-local scope");
521
522 return Name;
523 }
524
525 /// Rename this symbol. The client is responsible for updating scope and
526 /// linkage if this name-change requires it.
527 void setName(const orc::SymbolStringPtr Name) { this->Name = Name; }
528
529 /// Returns true if this Symbol has content (potentially) defined within this
530 /// object file (i.e. is anything but an external or absolute symbol).
531 bool isDefined() const {
532 assert(Base && "Attempt to access null symbol");
533 return Base->isDefined();
534 }
535
536 /// Returns true if this symbol is live (i.e. should be treated as a root for
537 /// dead stripping).
538 bool isLive() const {
539 assert(Base && "Attempting to access null symbol");
540 return IsLive;
541 }
542
543 /// Set this symbol's live bit.
544 void setLive(bool IsLive) { this->IsLive = IsLive; }
545
546 /// Returns true is this symbol is callable.
547 bool isCallable() const { return IsCallable; }
548
549 /// Set this symbol's callable bit.
550 void setCallable(bool IsCallable) { this->IsCallable = IsCallable; }
551
552 /// Returns true if the underlying addressable is an unresolved external.
553 bool isExternal() const {
554 assert(Base && "Attempt to access null symbol");
555 return !Base->isDefined() && !Base->isAbsolute();
556 }
557
558 /// Returns true if the underlying addressable is an absolute symbol.
559 bool isAbsolute() const {
560 assert(Base && "Attempt to access null symbol");
561 return Base->isAbsolute();
562 }
563
564 /// Return the addressable that this symbol points to.
566 assert(Base && "Cannot get underlying addressable for null symbol");
567 return *Base;
568 }
569
570 /// Return the addressable that this symbol points to.
572 assert(Base && "Cannot get underlying addressable for null symbol");
573 return *Base;
574 }
575
576 /// Return the Block for this Symbol (Symbol must be defined).
578 assert(Base && "Cannot get block for null symbol");
579 assert(Base->isDefined() && "Not a defined symbol");
580 return static_cast<Block &>(*Base);
581 }
582
583 /// Return the Block for this Symbol (Symbol must be defined).
584 const Block &getBlock() const {
585 assert(Base && "Cannot get block for null symbol");
586 assert(Base->isDefined() && "Not a defined symbol");
587 return static_cast<const Block &>(*Base);
588 }
589
590 /// Returns the offset for this symbol within the underlying addressable.
592
594 assert(NewOffset <= getBlock().getSize() && "Offset out of range");
595 Offset = NewOffset;
596 }
597
598 /// Returns the address of this symbol.
599 orc::ExecutorAddr getAddress() const { return Base->getAddress() + Offset; }
600
601 /// Returns the size of this symbol.
603
604 /// Set the size of this symbol.
606 assert(Base && "Cannot set size for null Symbol");
607 assert((Size == 0 || Base->isDefined()) &&
608 "Non-zero size can only be set for defined symbols");
609 assert((Offset + Size <= static_cast<const Block &>(*Base).getSize()) &&
610 "Symbol size cannot extend past the end of its containing block");
611 this->Size = Size;
612 }
613
614 /// Returns the address range of this symbol.
617 }
618
619 /// Returns true if this symbol is backed by a zero-fill block.
620 /// This method may only be called on defined symbols.
621 bool isSymbolZeroFill() const { return getBlock().isZeroFill(); }
622
623 /// Returns the content in the underlying block covered by this symbol.
624 /// This method may only be called on defined non-zero-fill symbols.
626 return getBlock().getContent().slice(Offset, Size);
627 }
628
629 /// Get the linkage for this Symbol.
630 Linkage getLinkage() const { return static_cast<Linkage>(L); }
631
632 /// Set the linkage for this Symbol.
634 assert((L == Linkage::Strong || (!Base->isAbsolute() && Name)) &&
635 "Linkage can only be applied to defined named symbols");
636 this->L = static_cast<uint8_t>(L);
637 }
638
639 /// Get the visibility for this Symbol.
640 Scope getScope() const { return static_cast<Scope>(S); }
641
642 /// Set the visibility for this Symbol.
643 void setScope(Scope S) {
644 assert((hasName() || S == Scope::Local) &&
645 "Can not set anonymous symbol to non-local scope");
646 assert((S != Scope::Local || Base->isDefined() || Base->isAbsolute()) &&
647 "Invalid visibility for symbol type");
648 this->S = static_cast<uint8_t>(S);
649 }
650
651 /// Get the target flags of this Symbol.
652 TargetFlagsType getTargetFlags() const { return TargetFlags; }
653
654 /// Set the target flags for this Symbol.
656 assert(Flags <= 1 && "Add more bits to store more than single flag");
657 TargetFlags = Flags;
658 }
659
660 /// Returns true if this is a weakly referenced external symbol.
661 /// This method may only be called on external symbols.
662 bool isWeaklyReferenced() const {
663 assert(isExternal() && "isWeaklyReferenced called on non-external");
664 return WeakRef;
665 }
666
667 /// Set the WeaklyReferenced value for this symbol.
668 /// This method may only be called on external symbols.
669 void setWeaklyReferenced(bool WeakRef) {
670 assert(isExternal() && "setWeaklyReferenced called on non-external");
671 this->WeakRef = WeakRef;
672 }
673
674private:
675 void makeExternal(Addressable &A) {
676 assert(!A.isDefined() && !A.isAbsolute() &&
677 "Attempting to make external with defined or absolute block");
678 Base = &A;
679 Offset = 0;
681 IsLive = 0;
682 // note: Size, Linkage and IsCallable fields left unchanged.
683 }
684
685 void makeAbsolute(Addressable &A) {
686 assert(!A.isDefined() && A.isAbsolute() &&
687 "Attempting to make absolute with defined or external block");
688 Base = &A;
689 Offset = 0;
690 }
691
692 void setBlock(Block &B) { Base = &B; }
693
694 static constexpr uint64_t MaxOffset = (1ULL << 59) - 1;
695
696 orc::SymbolStringPtr Name = nullptr;
697 Addressable *Base = nullptr;
698 uint64_t Offset : 57;
699 uint64_t L : 1;
700 uint64_t S : 2;
701 uint64_t IsLive : 1;
702 uint64_t IsCallable : 1;
703 uint64_t WeakRef : 1;
704 uint64_t TargetFlags : 1;
705 size_t Size = 0;
706};
707
708raw_ostream &operator<<(raw_ostream &OS, const Symbol &A);
709
710void printEdge(raw_ostream &OS, const Block &B, const Edge &E,
711 StringRef EdgeKindName);
712
713/// Represents an object file section.
714class Section {
715 friend class LinkGraph;
716
717private:
719 : Name(Name), Prot(Prot), SecOrdinal(SecOrdinal) {}
720
721 using SymbolSet = DenseSet<Symbol *>;
722 using BlockSet = DenseSet<Block *>;
723
724public:
727
730
731 ~Section();
732
733 // Sections are not movable or copyable.
734 Section(const Section &) = delete;
735 Section &operator=(const Section &) = delete;
736 Section(Section &&) = delete;
737 Section &operator=(Section &&) = delete;
738
739 /// Returns the name of this section.
740 StringRef getName() const { return Name; }
741
742 /// Returns the protection flags for this section.
743 orc::MemProt getMemProt() const { return Prot; }
744
745 /// Set the protection flags for this section.
746 void setMemProt(orc::MemProt Prot) { this->Prot = Prot; }
747
748 /// Get the memory lifetime policy for this section.
750
751 /// Set the memory lifetime policy for this section.
752 void setMemLifetime(orc::MemLifetime ML) { this->ML = ML; }
753
754 /// Returns the ordinal for this section.
755 SectionOrdinal getOrdinal() const { return SecOrdinal; }
756
757 /// Returns true if this section is empty (contains no blocks or symbols).
758 bool empty() const { return Blocks.empty(); }
759
760 /// Returns an iterator over the blocks defined in this section.
762 return make_range(Blocks.begin(), Blocks.end());
763 }
764
765 /// Returns an iterator over the blocks defined in this section.
767 return make_range(Blocks.begin(), Blocks.end());
768 }
769
770 /// Returns the number of blocks in this section.
771 BlockSet::size_type blocks_size() const { return Blocks.size(); }
772
773 /// Returns an iterator over the symbols defined in this section.
775 return make_range(Symbols.begin(), Symbols.end());
776 }
777
778 /// Returns an iterator over the symbols defined in this section.
780 return make_range(Symbols.begin(), Symbols.end());
781 }
782
783 /// Return the number of symbols in this section.
784 SymbolSet::size_type symbols_size() const { return Symbols.size(); }
785
786private:
787 void addSymbol(Symbol &Sym) {
788 assert(!Symbols.count(&Sym) && "Symbol is already in this section");
789 Symbols.insert(&Sym);
790 }
791
792 void removeSymbol(Symbol &Sym) {
793 assert(Symbols.count(&Sym) && "symbol is not in this section");
794 Symbols.erase(&Sym);
795 }
796
797 void addBlock(Block &B) {
798 assert(!Blocks.count(&B) && "Block is already in this section");
799 Blocks.insert(&B);
800 }
801
802 void removeBlock(Block &B) {
803 assert(Blocks.count(&B) && "Block is not in this section");
804 Blocks.erase(&B);
805 }
806
807 void transferContentTo(Section &DstSection) {
808 if (&DstSection == this)
809 return;
810 for (auto *S : Symbols)
811 DstSection.addSymbol(*S);
812 for (auto *B : Blocks)
813 DstSection.addBlock(*B);
814 Symbols.clear();
815 Blocks.clear();
816 }
817
818 StringRef Name;
819 orc::MemProt Prot;
821 SectionOrdinal SecOrdinal = 0;
822 BlockSet Blocks;
823 SymbolSet Symbols;
824};
825
826/// Represents a section address range via a pair of Block pointers
827/// to the first and last Blocks in the section.
829public:
830 SectionRange() = default;
831 SectionRange(const Section &Sec) {
832 if (Sec.blocks().empty())
833 return;
834 First = Last = *Sec.blocks().begin();
835 for (auto *B : Sec.blocks()) {
836 if (B->getAddress() < First->getAddress())
837 First = B;
838 if (B->getAddress() > Last->getAddress())
839 Last = B;
840 }
841 }
843 assert((!Last || First) && "First can not be null if end is non-null");
844 return First;
845 }
847 assert((First || !Last) && "Last can not be null if start is non-null");
848 return Last;
849 }
850 bool empty() const {
851 assert((First || !Last) && "Last can not be null if start is non-null");
852 return !First;
853 }
855 return First ? First->getAddress() : orc::ExecutorAddr();
856 }
858 return Last ? Last->getAddress() + Last->getSize() : orc::ExecutorAddr();
859 }
861
864 }
865
866private:
867 Block *First = nullptr;
868 Block *Last = nullptr;
869};
870
872private:
877
878 template <typename... ArgTs>
879 Addressable &createAddressable(ArgTs &&... Args) {
880 Addressable *A =
881 reinterpret_cast<Addressable *>(Allocator.Allocate<Addressable>());
882 new (A) Addressable(std::forward<ArgTs>(Args)...);
883 return *A;
884 }
885
886 void destroyAddressable(Addressable &A) {
887 A.~Addressable();
888 Allocator.Deallocate(&A);
889 }
890
891 template <typename... ArgTs> Block &createBlock(ArgTs &&... Args) {
892 Block *B = reinterpret_cast<Block *>(Allocator.Allocate<Block>());
893 new (B) Block(std::forward<ArgTs>(Args)...);
894 B->getSection().addBlock(*B);
895 return *B;
896 }
897
898 void destroyBlock(Block &B) {
899 B.~Block();
900 Allocator.Deallocate(&B);
901 }
902
903 void destroySymbol(Symbol &S) {
904 S.~Symbol();
905 Allocator.Deallocate(&S);
906 }
907
908 static iterator_range<Section::block_iterator> getSectionBlocks(Section &S) {
909 return S.blocks();
910 }
911
913 getSectionConstBlocks(const Section &S) {
914 return S.blocks();
915 }
916
918 getSectionSymbols(Section &S) {
919 return S.symbols();
920 }
921
923 getSectionConstSymbols(const Section &S) {
924 return S.symbols();
925 }
926
927 struct GetExternalSymbolMapEntryValue {
928 Symbol *operator()(ExternalSymbolMap::value_type &KV) const {
929 return KV.second;
930 }
931 };
932
933 struct GetSectionMapEntryValue {
934 Section &operator()(SectionMap::value_type &KV) const { return *KV.second; }
935 };
936
937 struct GetSectionMapEntryConstValue {
938 const Section &operator()(const SectionMap::value_type &KV) const {
939 return *KV.second;
940 }
941 };
942
943public:
946 GetExternalSymbolMapEntryValue>;
948
953
954 template <typename OuterItrT, typename InnerItrT, typename T,
955 iterator_range<InnerItrT> getInnerRange(
956 typename OuterItrT::reference)>
958 : public iterator_facade_base<
959 nested_collection_iterator<OuterItrT, InnerItrT, T, getInnerRange>,
960 std::forward_iterator_tag, T> {
961 public:
963
964 nested_collection_iterator(OuterItrT OuterI, OuterItrT OuterE)
965 : OuterI(OuterI), OuterE(OuterE),
966 InnerI(getInnerBegin(OuterI, OuterE)) {
967 moveToNonEmptyInnerOrEnd();
968 }
969
971 return (OuterI == RHS.OuterI) && (InnerI == RHS.InnerI);
972 }
973
974 T operator*() const {
975 assert(InnerI != getInnerRange(*OuterI).end() && "Dereferencing end?");
976 return *InnerI;
977 }
978
980 ++InnerI;
981 moveToNonEmptyInnerOrEnd();
982 return *this;
983 }
984
985 private:
986 static InnerItrT getInnerBegin(OuterItrT OuterI, OuterItrT OuterE) {
987 return OuterI != OuterE ? getInnerRange(*OuterI).begin() : InnerItrT();
988 }
989
990 void moveToNonEmptyInnerOrEnd() {
991 while (OuterI != OuterE && InnerI == getInnerRange(*OuterI).end()) {
992 ++OuterI;
993 InnerI = getInnerBegin(OuterI, OuterE);
994 }
995 }
996
997 OuterItrT OuterI, OuterE;
998 InnerItrT InnerI;
999 };
1000
1003 Symbol *, getSectionSymbols>;
1004
1008 getSectionConstSymbols>;
1009
1012 Block *, getSectionBlocks>;
1013
1017 getSectionConstBlocks>;
1018
1019 using GetEdgeKindNameFunction = const char *(*)(Edge::Kind);
1020
1021 LinkGraph(std::string Name, std::shared_ptr<orc::SymbolStringPool> SSP,
1022 Triple TT, SubtargetFeatures Features,
1023 GetEdgeKindNameFunction GetEdgeKindName)
1024 : Name(std::move(Name)), SSP(std::move(SSP)), TT(std::move(TT)),
1025 Features(std::move(Features)),
1026 GetEdgeKindName(std::move(GetEdgeKindName)) {
1027 assert(!(Triple::getArchPointerBitWidth(this->TT.getArch()) % 8) &&
1028 "Arch bitwidth is not a multiple of 8");
1029 }
1030
1031 LinkGraph(const LinkGraph &) = delete;
1032 LinkGraph &operator=(const LinkGraph &) = delete;
1033 LinkGraph(LinkGraph &&) = delete;
1035 ~LinkGraph();
1036
1037 /// Returns the name of this graph (usually the name of the original
1038 /// underlying MemoryBuffer).
1039 const std::string &getName() const { return Name; }
1040
1041 /// Returns the target triple for this Graph.
1042 const Triple &getTargetTriple() const { return TT; }
1043
1044 /// Return the subtarget features for this Graph.
1045 const SubtargetFeatures &getFeatures() const { return Features; }
1046
1047 /// Returns the pointer size for use in this graph.
1048 unsigned getPointerSize() const { return TT.getArchPointerBitWidth() / 8; }
1049
1050 /// Returns the endianness of content in this graph.
1053 }
1054
1055 const char *getEdgeKindName(Edge::Kind K) const { return GetEdgeKindName(K); }
1056
1057 std::shared_ptr<orc::SymbolStringPool> getSymbolStringPool() { return SSP; }
1058
1059 /// Allocate a mutable buffer of the given size using the LinkGraph's
1060 /// allocator.
1062 return {Allocator.Allocate<char>(Size), Size};
1063 }
1064
1065 /// Allocate a copy of the given string using the LinkGraph's allocator.
1066 /// This can be useful when renaming symbols or adding new content to the
1067 /// graph.
1069 auto *AllocatedBuffer = Allocator.Allocate<char>(Source.size());
1070 llvm::copy(Source, AllocatedBuffer);
1071 return MutableArrayRef<char>(AllocatedBuffer, Source.size());
1072 }
1073
1074 /// Allocate a copy of the given string using the LinkGraph's allocator.
1075 /// This can be useful when renaming symbols or adding new content to the
1076 /// graph.
1077 ///
1078 /// Note: This Twine-based overload requires an extra string copy and an
1079 /// extra heap allocation for large strings. The ArrayRef<char> overload
1080 /// should be preferred where possible.
1082 SmallString<256> TmpBuffer;
1083 auto SourceStr = Source.toStringRef(TmpBuffer);
1084 auto *AllocatedBuffer = Allocator.Allocate<char>(SourceStr.size());
1085 llvm::copy(SourceStr, AllocatedBuffer);
1086 return MutableArrayRef<char>(AllocatedBuffer, SourceStr.size());
1087 }
1088
1089 /// Allocate a copy of the given string using the LinkGraph's allocator
1090 /// and return it as a StringRef.
1091 ///
1092 /// This is a convenience wrapper around allocateContent(Twine) that is
1093 /// handy when creating new symbol names within the graph.
1095 auto Buf = allocateContent(Source);
1096 return {Buf.data(), Buf.size()};
1097 }
1098
1099 /// Allocate a copy of the given string using the LinkGraph's allocator.
1100 ///
1101 /// The allocated string will be terminated with a null character, and the
1102 /// returned MutableArrayRef will include this null character in the last
1103 /// position.
1105 char *AllocatedBuffer = Allocator.Allocate<char>(Source.size() + 1);
1106 llvm::copy(Source, AllocatedBuffer);
1107 AllocatedBuffer[Source.size()] = '\0';
1108 return MutableArrayRef<char>(AllocatedBuffer, Source.size() + 1);
1109 }
1110
1111 /// Allocate a copy of the given string using the LinkGraph's allocator.
1112 ///
1113 /// The allocated string will be terminated with a null character, and the
1114 /// returned MutableArrayRef will include this null character in the last
1115 /// position.
1116 ///
1117 /// Note: This Twine-based overload requires an extra string copy and an
1118 /// extra heap allocation for large strings. The ArrayRef<char> overload
1119 /// should be preferred where possible.
1121 SmallString<256> TmpBuffer;
1122 auto SourceStr = Source.toStringRef(TmpBuffer);
1123 auto *AllocatedBuffer = Allocator.Allocate<char>(SourceStr.size() + 1);
1124 llvm::copy(SourceStr, AllocatedBuffer);
1125 AllocatedBuffer[SourceStr.size()] = '\0';
1126 return MutableArrayRef<char>(AllocatedBuffer, SourceStr.size() + 1);
1127 }
1128
1129 /// Create a section with the given name, protection flags, and alignment.
1131 assert(!Sections.count(Name) && "Duplicate section name");
1132 std::unique_ptr<Section> Sec(new Section(Name, Prot, Sections.size()));
1133 return *Sections.insert(std::make_pair(Name, std::move(Sec))).first->second;
1134 }
1135
1136 /// Create a content block.
1139 uint64_t AlignmentOffset) {
1140 return createBlock(Parent, Content, Address, Alignment, AlignmentOffset);
1141 }
1142
1143 /// Create a content block with initially mutable data.
1145 MutableArrayRef<char> MutableContent,
1147 uint64_t Alignment,
1148 uint64_t AlignmentOffset) {
1149 return createBlock(Parent, MutableContent, Address, Alignment,
1150 AlignmentOffset);
1151 }
1152
1153 /// Create a content block with initially mutable data of the given size.
1154 /// Content will be allocated via the LinkGraph's allocateBuffer method.
1155 /// By default the memory will be zero-initialized. Passing false for
1156 /// ZeroInitialize will prevent this.
1157 Block &createMutableContentBlock(Section &Parent, size_t ContentSize,
1159 uint64_t Alignment, uint64_t AlignmentOffset,
1160 bool ZeroInitialize = true) {
1161 auto Content = allocateBuffer(ContentSize);
1162 if (ZeroInitialize)
1163 memset(Content.data(), 0, Content.size());
1164 return createBlock(Parent, Content, Address, Alignment, AlignmentOffset);
1165 }
1166
1167 /// Create a zero-fill block.
1170 uint64_t AlignmentOffset) {
1171 return createBlock(Parent, Size, Address, Alignment, AlignmentOffset);
1172 }
1173
1174 /// Returns a BinaryStreamReader for the given block.
1177 reinterpret_cast<const uint8_t *>(B.getContent().data()), B.getSize());
1179 }
1180
1181 /// Returns a BinaryStreamWriter for the given block.
1182 /// This will call getMutableContent to obtain mutable content for the block.
1185 reinterpret_cast<uint8_t *>(B.getMutableContent(*this).data()),
1186 B.getSize());
1188 }
1189
1190 /// Cache type for the splitBlock function.
1191 using SplitBlockCache = std::optional<SmallVector<Symbol *, 8>>;
1192
1193 /// Splits block B into a sequence of smaller blocks.
1194 ///
1195 /// SplitOffsets should be a sequence of ascending offsets in B. The starting
1196 /// offset should be greater than zero, and the final offset less than
1197 /// B.getSize() - 1.
1198 ///
1199 /// The resulting seqeunce of blocks will start with the original block B
1200 /// (truncated to end at the first split offset) followed by newly introduced
1201 /// blocks starting at the subsequent split points.
1202 ///
1203 /// The optional Cache parameter can be used to speed up repeated calls to
1204 /// splitBlock for blocks within a single Section. If the value is None then
1205 /// the cache will be treated as uninitialized and splitBlock will populate
1206 /// it. Otherwise it is assumed to contain the list of Symbols pointing at B,
1207 /// sorted in descending order of offset.
1208 ///
1209 ///
1210 /// Notes:
1211 ///
1212 /// 1. splitBlock must be used with care. Splitting a block may cause
1213 /// incoming edges to become invalid if the edge target subexpression
1214 /// points outside the bounds of the newly split target block (E.g. an
1215 /// edge 'S + 10 : Pointer64' where S points to a newly split block
1216 /// whose size is less than 10). No attempt is made to detect invalidation
1217 /// of incoming edges, as in general this requires context that the
1218 /// LinkGraph does not have. Clients are responsible for ensuring that
1219 /// splitBlock is not used in a way that invalidates edges.
1220 ///
1221 /// 2. The newly introduced blocks will have new ordinals that will be higher
1222 /// than any other ordinals in the section. Clients are responsible for
1223 /// re-assigning block ordinals to restore a compatible order if needed.
1224 ///
1225 /// 3. The cache is not automatically updated if new symbols are introduced
1226 /// between calls to splitBlock. Any newly introduced symbols may be
1227 /// added to the cache manually (descending offset order must be
1228 /// preserved), or the cache can be set to None and rebuilt by
1229 /// splitBlock on the next call.
1230 template <typename SplitOffsetRange>
1231 std::vector<Block *> splitBlock(Block &B, SplitOffsetRange &&SplitOffsets,
1232 LinkGraph::SplitBlockCache *Cache = nullptr) {
1233 std::vector<Block *> Blocks;
1234 Blocks.push_back(&B);
1235
1236 if (std::empty(SplitOffsets))
1237 return Blocks;
1238
1239 // Special case zero-fill:
1240 if (B.isZeroFill()) {
1241 size_t OrigSize = B.getSize();
1242 for (Edge::OffsetT Offset : SplitOffsets) {
1243 assert(Offset > 0 && Offset < B.getSize() &&
1244 "Split offset must be inside block content");
1245 Blocks.back()->setZeroFillSize(
1246 Offset - (Blocks.back()->getAddress() - B.getAddress()));
1247 Blocks.push_back(&createZeroFillBlock(
1248 B.getSection(), B.getSize(), B.getAddress() + Offset,
1249 B.getAlignment(),
1250 (B.getAlignmentOffset() + Offset) % B.getAlignment()));
1251 }
1252 Blocks.back()->setZeroFillSize(
1253 OrigSize - (Blocks.back()->getAddress() - B.getAddress()));
1254 return Blocks;
1255 }
1256
1257 // Handle content blocks. We'll just create the blocks with their starting
1258 // address and no content here. The bulk of the work is deferred to
1259 // splitBlockImpl.
1260 for (Edge::OffsetT Offset : SplitOffsets) {
1261 assert(Offset > 0 && Offset < B.getSize() &&
1262 "Split offset must be inside block content");
1263 Blocks.push_back(&createContentBlock(
1264 B.getSection(), ArrayRef<char>(), B.getAddress() + Offset,
1265 B.getAlignment(),
1266 (B.getAlignmentOffset() + Offset) % B.getAlignment()));
1267 }
1268
1269 return splitBlockImpl(std::move(Blocks), Cache);
1270 }
1271
1272 /// Intern the given string in the LinkGraph's SymbolStringPool.
1274 return SSP->intern(SymbolName);
1275 }
1276
1277 /// Add an external symbol.
1278 /// Some formats (e.g. ELF) allow Symbols to have sizes. For Symbols whose
1279 /// size is not known, you should substitute '0'.
1280 /// The IsWeaklyReferenced argument determines whether the symbol must be
1281 /// present during lookup: Externals that are strongly referenced must be
1282 /// found or an error will be emitted. Externals that are weakly referenced
1283 /// are permitted to be undefined, in which case they are assigned an address
1284 /// of 0.
1287 bool IsWeaklyReferenced) {
1288 assert(!ExternalSymbols.contains(*Name) && "Duplicate external symbol");
1289 auto &Sym = Symbol::constructExternal(
1290 Allocator, createAddressable(orc::ExecutorAddr(), false),
1291 std::move(Name), Size, Linkage::Strong, IsWeaklyReferenced);
1292 ExternalSymbols.insert({*Sym.getName(), &Sym});
1293 return Sym;
1294 }
1295
1297 bool IsWeaklyReferenced) {
1298 return addExternalSymbol(SSP->intern(Name), Size, IsWeaklyReferenced);
1299 }
1300
1301 /// Add an absolute symbol.
1305 bool IsLive) {
1306 assert((S == Scope::Local || llvm::count_if(AbsoluteSymbols,
1307 [&](const Symbol *Sym) {
1308 return Sym->getName() == Name;
1309 }) == 0) &&
1310 "Duplicate absolute symbol");
1311 auto &Sym = Symbol::constructAbsolute(Allocator, createAddressable(Address),
1312 std::move(Name), Size, L, S, IsLive);
1313 AbsoluteSymbols.insert(&Sym);
1314 return Sym;
1315 }
1316
1319 bool IsLive) {
1320
1321 return addAbsoluteSymbol(SSP->intern(Name), Address, Size, L, S, IsLive);
1322 }
1323
1324 /// Add an anonymous symbol.
1326 orc::ExecutorAddrDiff Size, bool IsCallable,
1327 bool IsLive) {
1328 auto &Sym = Symbol::constructAnonDef(Allocator, Content, Offset, Size,
1329 IsCallable, IsLive);
1330 Content.getSection().addSymbol(Sym);
1331 return Sym;
1332 }
1333
1334 /// Add a named symbol.
1337 Linkage L, Scope S, bool IsCallable, bool IsLive) {
1338 return addDefinedSymbol(Content, Offset, SSP->intern(Name), Size, L, S,
1339 IsCallable, IsLive);
1340 }
1341
1345 bool IsCallable, bool IsLive) {
1347 [&](const Symbol *Sym) {
1348 return Sym->getName() == Name;
1349 }) == 0) &&
1350 "Duplicate defined symbol");
1351 auto &Sym =
1352 Symbol::constructNamedDef(Allocator, Content, Offset, std::move(Name),
1353 Size, L, S, IsLive, IsCallable);
1354 Content.getSection().addSymbol(Sym);
1355 return Sym;
1356 }
1357
1359 return make_range(
1360 section_iterator(Sections.begin(), GetSectionMapEntryValue()),
1361 section_iterator(Sections.end(), GetSectionMapEntryValue()));
1362 }
1363
1365 return make_range(
1366 const_section_iterator(Sections.begin(),
1367 GetSectionMapEntryConstValue()),
1368 const_section_iterator(Sections.end(), GetSectionMapEntryConstValue()));
1369 }
1370
1371 size_t sections_size() const { return Sections.size(); }
1372
1373 /// Returns the section with the given name if it exists, otherwise returns
1374 /// null.
1376 auto I = Sections.find(Name);
1377 if (I == Sections.end())
1378 return nullptr;
1379 return I->second.get();
1380 }
1381
1383 auto Secs = sections();
1384 return make_range(block_iterator(Secs.begin(), Secs.end()),
1385 block_iterator(Secs.end(), Secs.end()));
1386 }
1387
1389 auto Secs = sections();
1390 return make_range(const_block_iterator(Secs.begin(), Secs.end()),
1391 const_block_iterator(Secs.end(), Secs.end()));
1392 }
1393
1395 return make_range(
1396 external_symbol_iterator(ExternalSymbols.begin(),
1397 GetExternalSymbolMapEntryValue()),
1398 external_symbol_iterator(ExternalSymbols.end(),
1399 GetExternalSymbolMapEntryValue()));
1400 }
1401
1402 /// Returns the external symbol with the given name if one exists, otherwise
1403 /// returns nullptr.
1405 for (auto *Sym : external_symbols())
1406 if (Sym->getName() == Name)
1407 return Sym;
1408 return nullptr;
1409 }
1410
1412 return make_range(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
1413 }
1414
1416 for (auto *Sym : absolute_symbols())
1417 if (Sym->getName() == Name)
1418 return Sym;
1419 return nullptr;
1420 }
1421
1423 auto Secs = sections();
1424 return make_range(defined_symbol_iterator(Secs.begin(), Secs.end()),
1425 defined_symbol_iterator(Secs.end(), Secs.end()));
1426 }
1427
1429 auto Secs = sections();
1430 return make_range(const_defined_symbol_iterator(Secs.begin(), Secs.end()),
1431 const_defined_symbol_iterator(Secs.end(), Secs.end()));
1432 }
1433
1434 /// Returns the defined symbol with the given name if one exists, otherwise
1435 /// returns nullptr.
1437 for (auto *Sym : defined_symbols())
1438 if (Sym->hasName() && Sym->getName() == Name)
1439 return Sym;
1440 return nullptr;
1441 }
1442
1443 /// Make the given symbol external (must not already be external).
1444 ///
1445 /// Symbol size, linkage and callability will be left unchanged. Symbol scope
1446 /// will be set to Default, and offset will be reset to 0.
1448 assert(!Sym.isExternal() && "Symbol is already external");
1449 if (Sym.isAbsolute()) {
1450 assert(AbsoluteSymbols.count(&Sym) &&
1451 "Sym is not in the absolute symbols set");
1452 assert(Sym.getOffset() == 0 && "Absolute not at offset 0");
1453 AbsoluteSymbols.erase(&Sym);
1454 auto &A = Sym.getAddressable();
1455 A.setAbsolute(false);
1456 A.setAddress(orc::ExecutorAddr());
1457 } else {
1458 assert(Sym.isDefined() && "Sym is not a defined symbol");
1459 Section &Sec = Sym.getBlock().getSection();
1460 Sec.removeSymbol(Sym);
1461 Sym.makeExternal(createAddressable(orc::ExecutorAddr(), false));
1462 }
1463 ExternalSymbols.insert({*Sym.getName(), &Sym});
1464 }
1465
1466 /// Make the given symbol an absolute with the given address (must not already
1467 /// be absolute).
1468 ///
1469 /// The symbol's size, linkage, and callability, and liveness will be left
1470 /// unchanged, and its offset will be reset to 0.
1471 ///
1472 /// If the symbol was external then its scope will be set to local, otherwise
1473 /// it will be left unchanged.
1475 assert(!Sym.isAbsolute() && "Symbol is already absolute");
1476 if (Sym.isExternal()) {
1477 assert(ExternalSymbols.contains(*Sym.getName()) &&
1478 "Sym is not in the absolute symbols set");
1479 assert(Sym.getOffset() == 0 && "External is not at offset 0");
1480 ExternalSymbols.erase(*Sym.getName());
1481 auto &A = Sym.getAddressable();
1482 A.setAbsolute(true);
1483 A.setAddress(Address);
1484 Sym.setScope(Scope::Local);
1485 } else {
1486 assert(Sym.isDefined() && "Sym is not a defined symbol");
1487 Section &Sec = Sym.getBlock().getSection();
1488 Sec.removeSymbol(Sym);
1489 Sym.makeAbsolute(createAddressable(Address));
1490 }
1491 AbsoluteSymbols.insert(&Sym);
1492 }
1493
1494 /// Turn an absolute or external symbol into a defined one by attaching it to
1495 /// a block. Symbol must not already be defined.
1498 bool IsLive) {
1499 assert(!Sym.isDefined() && "Sym is already a defined symbol");
1500 if (Sym.isAbsolute()) {
1501 assert(AbsoluteSymbols.count(&Sym) &&
1502 "Symbol is not in the absolutes set");
1503 AbsoluteSymbols.erase(&Sym);
1504 } else {
1505 assert(ExternalSymbols.contains(*Sym.getName()) &&
1506 "Symbol is not in the externals set");
1507 ExternalSymbols.erase(*Sym.getName());
1508 }
1509 Addressable &OldBase = *Sym.Base;
1510 Sym.setBlock(Content);
1511 Sym.setOffset(Offset);
1512 Sym.setSize(Size);
1513 Sym.setLinkage(L);
1514 Sym.setScope(S);
1515 Sym.setLive(IsLive);
1516 Content.getSection().addSymbol(Sym);
1517 destroyAddressable(OldBase);
1518 }
1519
1520 /// Transfer a defined symbol from one block to another.
1521 ///
1522 /// The symbol's offset within DestBlock is set to NewOffset.
1523 ///
1524 /// If ExplicitNewSize is given as None then the size of the symbol will be
1525 /// checked and auto-truncated to at most the size of the remainder (from the
1526 /// given offset) of the size of the new block.
1527 ///
1528 /// All other symbol attributes are unchanged.
1529 void
1531 orc::ExecutorAddrDiff NewOffset,
1532 std::optional<orc::ExecutorAddrDiff> ExplicitNewSize) {
1533 auto &OldSection = Sym.getBlock().getSection();
1534 Sym.setBlock(DestBlock);
1535 Sym.setOffset(NewOffset);
1536 if (ExplicitNewSize)
1537 Sym.setSize(*ExplicitNewSize);
1538 else {
1539 auto RemainingBlockSize = DestBlock.getSize() - NewOffset;
1540 if (Sym.getSize() > RemainingBlockSize)
1541 Sym.setSize(RemainingBlockSize);
1542 }
1543 if (&DestBlock.getSection() != &OldSection) {
1544 OldSection.removeSymbol(Sym);
1545 DestBlock.getSection().addSymbol(Sym);
1546 }
1547 }
1548
1549 /// Transfers the given Block and all Symbols pointing to it to the given
1550 /// Section.
1551 ///
1552 /// No attempt is made to check compatibility of the source and destination
1553 /// sections. Blocks may be moved between sections with incompatible
1554 /// permissions (e.g. from data to text). The client is responsible for
1555 /// ensuring that this is safe.
1556 void transferBlock(Block &B, Section &NewSection) {
1557 auto &OldSection = B.getSection();
1558 if (&OldSection == &NewSection)
1559 return;
1560 SmallVector<Symbol *> AttachedSymbols;
1561 for (auto *S : OldSection.symbols())
1562 if (&S->getBlock() == &B)
1563 AttachedSymbols.push_back(S);
1564 for (auto *S : AttachedSymbols) {
1565 OldSection.removeSymbol(*S);
1566 NewSection.addSymbol(*S);
1567 }
1568 OldSection.removeBlock(B);
1569 NewSection.addBlock(B);
1570 }
1571
1572 /// Move all blocks and symbols from the source section to the destination
1573 /// section.
1574 ///
1575 /// If PreserveSrcSection is true (or SrcSection and DstSection are the same)
1576 /// then SrcSection is preserved, otherwise it is removed (the default).
1577 void mergeSections(Section &DstSection, Section &SrcSection,
1578 bool PreserveSrcSection = false) {
1579 if (&DstSection == &SrcSection)
1580 return;
1581 for (auto *B : SrcSection.blocks())
1582 B->setSection(DstSection);
1583 SrcSection.transferContentTo(DstSection);
1584 if (!PreserveSrcSection)
1585 removeSection(SrcSection);
1586 }
1587
1588 /// Removes an external symbol. Also removes the underlying Addressable.
1590 assert(!Sym.isDefined() && !Sym.isAbsolute() &&
1591 "Sym is not an external symbol");
1592 assert(ExternalSymbols.contains(*Sym.getName()) &&
1593 "Symbol is not in the externals set");
1594 ExternalSymbols.erase(*Sym.getName());
1595 Addressable &Base = *Sym.Base;
1597 [&](Symbol *AS) { return AS->Base == &Base; }) &&
1598 "Base addressable still in use");
1599 destroySymbol(Sym);
1600 destroyAddressable(Base);
1601 }
1602
1603 /// Remove an absolute symbol. Also removes the underlying Addressable.
1605 assert(!Sym.isDefined() && Sym.isAbsolute() &&
1606 "Sym is not an absolute symbol");
1607 assert(AbsoluteSymbols.count(&Sym) &&
1608 "Symbol is not in the absolute symbols set");
1609 AbsoluteSymbols.erase(&Sym);
1610 Addressable &Base = *Sym.Base;
1612 [&](Symbol *AS) { return AS->Base == &Base; }) &&
1613 "Base addressable still in use");
1614 destroySymbol(Sym);
1615 destroyAddressable(Base);
1616 }
1617
1618 /// Removes defined symbols. Does not remove the underlying block.
1620 assert(Sym.isDefined() && "Sym is not a defined symbol");
1621 Sym.getBlock().getSection().removeSymbol(Sym);
1622 destroySymbol(Sym);
1623 }
1624
1625 /// Remove a block. The block reference is defunct after calling this
1626 /// function and should no longer be used.
1628 assert(llvm::none_of(B.getSection().symbols(),
1629 [&](const Symbol *Sym) {
1630 return &Sym->getBlock() == &B;
1631 }) &&
1632 "Block still has symbols attached");
1633 B.getSection().removeBlock(B);
1634 destroyBlock(B);
1635 }
1636
1637 /// Remove a section. The section reference is defunct after calling this
1638 /// function and should no longer be used.
1640 assert(Sections.count(Sec.getName()) && "Section not found");
1641 assert(Sections.find(Sec.getName())->second.get() == &Sec &&
1642 "Section map entry invalid");
1643 Sections.erase(Sec.getName());
1644 }
1645
1646 /// Accessor for the AllocActions object for this graph. This can be used to
1647 /// register allocation action calls prior to finalization.
1648 ///
1649 /// Accessing this object after finalization will result in undefined
1650 /// behavior.
1652
1653 /// Dump the graph.
1654 void dump(raw_ostream &OS);
1655
1656private:
1657 std::vector<Block *> splitBlockImpl(std::vector<Block *> Blocks,
1658 SplitBlockCache *Cache);
1659
1660 // Put the BumpPtrAllocator first so that we don't free any of the underlying
1661 // memory until the Symbol/Addressable destructors have been run.
1663
1664 std::string Name;
1665 std::shared_ptr<orc::SymbolStringPool> SSP;
1666 Triple TT;
1667 SubtargetFeatures Features;
1668 GetEdgeKindNameFunction GetEdgeKindName = nullptr;
1670 // FIXME(jared): these should become dense maps
1671 ExternalSymbolMap ExternalSymbols;
1672 AbsoluteSymbolSet AbsoluteSymbols;
1674};
1675
1677 if (!ContentMutable)
1678 setMutableContent(G.allocateContent({Data, Size}));
1679 return MutableArrayRef<char>(const_cast<char *>(Data), Size);
1680}
1681
1682/// Enables easy lookup of blocks by addresses.
1684public:
1685 using AddrToBlockMap = std::map<orc::ExecutorAddr, Block *>;
1686 using const_iterator = AddrToBlockMap::const_iterator;
1687
1688 /// A block predicate that always adds all blocks.
1689 static bool includeAllBlocks(const Block &B) { return true; }
1690
1691 /// A block predicate that always includes blocks with non-null addresses.
1692 static bool includeNonNull(const Block &B) { return !!B.getAddress(); }
1693
1694 BlockAddressMap() = default;
1695
1696 /// Add a block to the map. Returns an error if the block overlaps with any
1697 /// existing block.
1698 template <typename PredFn = decltype(includeAllBlocks)>
1700 if (!Pred(B))
1701 return Error::success();
1702
1703 auto I = AddrToBlock.upper_bound(B.getAddress());
1704
1705 // If we're not at the end of the map, check for overlap with the next
1706 // element.
1707 if (I != AddrToBlock.end()) {
1708 if (B.getAddress() + B.getSize() > I->second->getAddress())
1709 return overlapError(B, *I->second);
1710 }
1711
1712 // If we're not at the start of the map, check for overlap with the previous
1713 // element.
1714 if (I != AddrToBlock.begin()) {
1715 auto &PrevBlock = *std::prev(I)->second;
1716 if (PrevBlock.getAddress() + PrevBlock.getSize() > B.getAddress())
1717 return overlapError(B, PrevBlock);
1718 }
1719
1720 AddrToBlock.insert(I, std::make_pair(B.getAddress(), &B));
1721 return Error::success();
1722 }
1723
1724 /// Add a block to the map without checking for overlap with existing blocks.
1725 /// The client is responsible for ensuring that the block added does not
1726 /// overlap with any existing block.
1727 void addBlockWithoutChecking(Block &B) { AddrToBlock[B.getAddress()] = &B; }
1728
1729 /// Add a range of blocks to the map. Returns an error if any block in the
1730 /// range overlaps with any other block in the range, or with any existing
1731 /// block in the map.
1732 template <typename BlockPtrRange,
1733 typename PredFn = decltype(includeAllBlocks)>
1734 Error addBlocks(BlockPtrRange &&Blocks, PredFn Pred = includeAllBlocks) {
1735 for (auto *B : Blocks)
1736 if (auto Err = addBlock(*B, Pred))
1737 return Err;
1738 return Error::success();
1739 }
1740
1741 /// Add a range of blocks to the map without checking for overlap with
1742 /// existing blocks. The client is responsible for ensuring that the block
1743 /// added does not overlap with any existing block.
1744 template <typename BlockPtrRange>
1745 void addBlocksWithoutChecking(BlockPtrRange &&Blocks) {
1746 for (auto *B : Blocks)
1748 }
1749
1750 /// Iterates over (Address, Block*) pairs in ascending order of address.
1751 const_iterator begin() const { return AddrToBlock.begin(); }
1752 const_iterator end() const { return AddrToBlock.end(); }
1753
1754 /// Returns the block starting at the given address, or nullptr if no such
1755 /// block exists.
1757 auto I = AddrToBlock.find(Addr);
1758 if (I == AddrToBlock.end())
1759 return nullptr;
1760 return I->second;
1761 }
1762
1763 /// Returns the block covering the given address, or nullptr if no such block
1764 /// exists.
1766 auto I = AddrToBlock.upper_bound(Addr);
1767 if (I == AddrToBlock.begin())
1768 return nullptr;
1769 auto *B = std::prev(I)->second;
1770 if (Addr < B->getAddress() + B->getSize())
1771 return B;
1772 return nullptr;
1773 }
1774
1775private:
1776 Error overlapError(Block &NewBlock, Block &ExistingBlock) {
1777 auto NewBlockEnd = NewBlock.getAddress() + NewBlock.getSize();
1778 auto ExistingBlockEnd =
1779 ExistingBlock.getAddress() + ExistingBlock.getSize();
1780 return make_error<JITLinkError>(
1781 "Block at " +
1782 formatv("{0:x16} -- {1:x16}", NewBlock.getAddress().getValue(),
1783 NewBlockEnd.getValue()) +
1784 " overlaps " +
1785 formatv("{0:x16} -- {1:x16}", ExistingBlock.getAddress().getValue(),
1786 ExistingBlockEnd.getValue()));
1787 }
1788
1789 AddrToBlockMap AddrToBlock;
1790};
1791
1792/// A map of addresses to Symbols.
1794public:
1796
1797 /// Add a symbol to the SymbolAddressMap.
1799 AddrToSymbols[Sym.getAddress()].push_back(&Sym);
1800 }
1801
1802 /// Add all symbols in a given range to the SymbolAddressMap.
1803 template <typename SymbolPtrCollection>
1804 void addSymbols(SymbolPtrCollection &&Symbols) {
1805 for (auto *Sym : Symbols)
1806 addSymbol(*Sym);
1807 }
1808
1809 /// Returns the list of symbols that start at the given address, or nullptr if
1810 /// no such symbols exist.
1812 auto I = AddrToSymbols.find(Addr);
1813 if (I == AddrToSymbols.end())
1814 return nullptr;
1815 return &I->second;
1816 }
1817
1818private:
1819 std::map<orc::ExecutorAddr, SymbolVector> AddrToSymbols;
1820};
1821
1822/// A function for mutating LinkGraphs.
1824
1825/// A list of LinkGraph passes.
1826using LinkGraphPassList = std::vector<LinkGraphPassFunction>;
1827
1828/// An LinkGraph pass configuration, consisting of a list of pre-prune,
1829/// post-prune, and post-fixup passes.
1831
1832 /// Pre-prune passes.
1833 ///
1834 /// These passes are called on the graph after it is built, and before any
1835 /// symbols have been pruned. Graph nodes still have their original vmaddrs.
1836 ///
1837 /// Notable use cases: Marking symbols live or should-discard.
1839
1840 /// Post-prune passes.
1841 ///
1842 /// These passes are called on the graph after dead stripping, but before
1843 /// memory is allocated or nodes assigned their final addresses.
1844 ///
1845 /// Notable use cases: Building GOT, stub, and TLV symbols.
1847
1848 /// Post-allocation passes.
1849 ///
1850 /// These passes are called on the graph after memory has been allocated and
1851 /// defined nodes have been assigned their final addresses, but before the
1852 /// context has been notified of these addresses. At this point externals
1853 /// have not been resolved, and symbol content has not yet been copied into
1854 /// working memory.
1855 ///
1856 /// Notable use cases: Setting up data structures associated with addresses
1857 /// of defined symbols (e.g. a mapping of __dso_handle to JITDylib* for the
1858 /// JIT runtime) -- using a PostAllocationPass for this ensures that the
1859 /// data structures are in-place before any query for resolved symbols
1860 /// can complete.
1862
1863 /// Pre-fixup passes.
1864 ///
1865 /// These passes are called on the graph after memory has been allocated,
1866 /// content copied into working memory, and all nodes (including externals)
1867 /// have been assigned their final addresses, but before any fixups have been
1868 /// applied.
1869 ///
1870 /// Notable use cases: Late link-time optimizations like GOT and stub
1871 /// elimination.
1873
1874 /// Post-fixup passes.
1875 ///
1876 /// These passes are called on the graph after block contents has been copied
1877 /// to working memory, and fixups applied. Blocks have been updated to point
1878 /// to their fixed up content.
1879 ///
1880 /// Notable use cases: Testing and validation.
1882};
1883
1884/// Flags for symbol lookup.
1885///
1886/// FIXME: These basically duplicate orc::SymbolLookupFlags -- We should merge
1887/// the two types once we have an OrcSupport library.
1889
1891
1892/// A map of symbol names to resolved addresses.
1895
1896/// A function object to call with a resolved symbol map (See AsyncLookupResult)
1897/// or an error if resolution failed.
1899public:
1901 virtual void run(Expected<AsyncLookupResult> LR) = 0;
1902
1903private:
1904 virtual void anchor();
1905};
1906
1907/// Create a lookup continuation from a function object.
1908template <typename Continuation>
1909std::unique_ptr<JITLinkAsyncLookupContinuation>
1910createLookupContinuation(Continuation Cont) {
1911
1912 class Impl final : public JITLinkAsyncLookupContinuation {
1913 public:
1914 Impl(Continuation C) : C(std::move(C)) {}
1915 void run(Expected<AsyncLookupResult> LR) override { C(std::move(LR)); }
1916
1917 private:
1918 Continuation C;
1919 };
1920
1921 return std::make_unique<Impl>(std::move(Cont));
1922}
1923
1924/// Holds context for a single jitLink invocation.
1926public:
1928
1929 /// Create a JITLinkContext.
1930 JITLinkContext(const JITLinkDylib *JD) : JD(JD) {}
1931
1932 /// Destroy a JITLinkContext.
1934
1935 /// Return the JITLinkDylib that this link is targeting, if any.
1936 const JITLinkDylib *getJITLinkDylib() const { return JD; }
1937
1938 /// Return the MemoryManager to be used for this link.
1940
1941 /// Notify this context that linking failed.
1942 /// Called by JITLink if linking cannot be completed.
1943 virtual void notifyFailed(Error Err) = 0;
1944
1945 /// Called by JITLink to resolve external symbols. This method is passed a
1946 /// lookup continutation which it must call with a result to continue the
1947 /// linking process.
1948 virtual void lookup(const LookupMap &Symbols,
1949 std::unique_ptr<JITLinkAsyncLookupContinuation> LC) = 0;
1950
1951 /// Called by JITLink once all defined symbols in the graph have been assigned
1952 /// their final memory locations in the target process. At this point the
1953 /// LinkGraph can be inspected to build a symbol table, however the block
1954 /// content will not generally have been copied to the target location yet.
1955 ///
1956 /// If the client detects an error in the LinkGraph state (e.g. unexpected or
1957 /// missing symbols) they may return an error here. The error will be
1958 /// propagated to notifyFailed and the linker will bail out.
1960
1961 /// Called by JITLink to notify the context that the object has been
1962 /// finalized (i.e. emitted to memory and memory permissions set). If all of
1963 /// this objects dependencies have also been finalized then the code is ready
1964 /// to run.
1966
1967 /// Called by JITLink prior to linking to determine whether default passes for
1968 /// the target should be added. The default implementation returns true.
1969 /// If subclasses override this method to return false for any target then
1970 /// they are required to fully configure the pass pipeline for that target.
1971 virtual bool shouldAddDefaultTargetPasses(const Triple &TT) const;
1972
1973 /// Returns the mark-live pass to be used for this link. If no pass is
1974 /// returned (the default) then the target-specific linker implementation will
1975 /// choose a conservative default (usually marking all symbols live).
1976 /// This function is only called if shouldAddDefaultTargetPasses returns true,
1977 /// otherwise the JITContext is responsible for adding a mark-live pass in
1978 /// modifyPassConfig.
1979 virtual LinkGraphPassFunction getMarkLivePass(const Triple &TT) const;
1980
1981 /// Called by JITLink to modify the pass pipeline prior to linking.
1982 /// The default version performs no modification.
1984
1985private:
1986 const JITLinkDylib *JD = nullptr;
1987};
1988
1989/// Marks all symbols in a graph live. This can be used as a default,
1990/// conservative mark-live implementation.
1992
1993/// Create an out of range error for the given edge in the given block.
1995 const Edge &E);
1996
1998 const Edge &E);
1999
2000/// Creates a new pointer block in the given section and returns an
2001/// Anonymous symbol pointing to it.
2002///
2003/// The pointer block will have the following default values:
2004/// alignment: PointerSize
2005/// alignment-offset: 0
2006/// address: highest allowable
2008 unique_function<Symbol &(LinkGraph &G, Section &PointerSection,
2009 Symbol *InitialTarget, uint64_t InitialAddend)>;
2010
2011/// Get target-specific AnonymousPointerCreator
2013
2014/// Create a jump stub that jumps via the pointer at the given symbol and
2015/// an anonymous symbol pointing to it. Return the anonymous symbol.
2016///
2017/// The stub block will be created by createPointerJumpStubBlock.
2019 LinkGraph &G, Section &StubSection, Symbol &PointerSymbol)>;
2020
2021/// Get target-specific PointerJumpStubCreator
2023
2024/// Base case for edge-visitors where the visitor-list is empty.
2025inline void visitEdge(LinkGraph &G, Block *B, Edge &E) {}
2026
2027/// Applies the first visitor in the list to the given edge. If the visitor's
2028/// visitEdge method returns true then we return immediately, otherwise we
2029/// apply the next visitor.
2030template <typename VisitorT, typename... VisitorTs>
2031void visitEdge(LinkGraph &G, Block *B, Edge &E, VisitorT &&V,
2032 VisitorTs &&...Vs) {
2033 if (!V.visitEdge(G, B, E))
2034 visitEdge(G, B, E, std::forward<VisitorTs>(Vs)...);
2035}
2036
2037/// For each edge in the given graph, apply a list of visitors to the edge,
2038/// stopping when the first visitor's visitEdge method returns true.
2039///
2040/// Only visits edges that were in the graph at call time: if any visitor
2041/// adds new edges those will not be visited. Visitors are not allowed to
2042/// remove edges (though they can change their kind, target, and addend).
2043template <typename... VisitorTs>
2044void visitExistingEdges(LinkGraph &G, VisitorTs &&...Vs) {
2045 // We may add new blocks during this process, but we don't want to iterate
2046 // over them, so build a worklist.
2047 std::vector<Block *> Worklist(G.blocks().begin(), G.blocks().end());
2048
2049 for (auto *B : Worklist)
2050 for (auto &E : B->edges())
2051 visitEdge(G, B, E, std::forward<VisitorTs>(Vs)...);
2052}
2053
2054/// Create a LinkGraph from the given object buffer.
2055///
2056/// Note: The graph does not take ownership of the underlying buffer, nor copy
2057/// its contents. The caller is responsible for ensuring that the object buffer
2058/// outlives the graph.
2061 std::shared_ptr<orc::SymbolStringPool> SSP);
2062
2063/// Create a \c LinkGraph defining the given absolute symbols.
2064std::unique_ptr<LinkGraph>
2065absoluteSymbolsLinkGraph(Triple TT, std::shared_ptr<orc::SymbolStringPool> SSP,
2066 orc::SymbolMap Symbols);
2067
2068/// Link the given graph.
2069void link(std::unique_ptr<LinkGraph> G, std::unique_ptr<JITLinkContext> Ctx);
2070
2071} // end namespace jitlink
2072} // end namespace llvm
2073
2074#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.
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:559
RelaxConfig Config
Definition: ELF_riscv.cpp:506
DenseMap< Block *, BlockRelaxAux > Blocks
Definition: ELF_riscv.cpp:507
uint64_t Offset
Definition: ELF_riscv.cpp:478
Symbol * Sym
Definition: ELF_riscv.cpp:479
static void makeAbsolute(SmallVectorImpl< char > &Path)
Make Path absolute.
This file provides a collection of function (or more generally, callable) type erasure utilities supp...
#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())
const Value * getAddress(const DbgVariableIntrinsic *DVI)
Definition: SROA.cpp:5023
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
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:168
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:198
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:278
Base class for user error types.
Definition: Error.h:355
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:310
T * data() const
Definition: ArrayRef.h:357
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:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
iterator end()
Definition: StringMap.h:220
iterator begin()
Definition: StringMap.h:219
bool contains(StringRef Key) const
contains - Return true if the element is in the map, false otherwise.
Definition: StringMap.h:273
StringMapIterator< Symbol * > iterator
Definition: StringMap.h:217
void erase(iterator I)
Definition: StringMap.h:416
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition: StringMap.h:308
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
Manages the enabling and disabling of subtarget specific features.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
unsigned getArchPointerBitWidth() const
Returns the pointer width of this architecture.
Definition: Triple.h:497
bool isLittleEndian() const
Tests whether the target triple is little endian.
Definition: Triple.cpp:1987
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition: Triple.h:395
static unsigned getArchPointerBitWidth(llvm::Triple::ArchType Arch)
Returns the pointer width of this architecture.
Definition: Triple.cpp:1641
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:213
ConstIterator const_iterator
Definition: DenseSet.h:179
size_type size() const
Definition: DenseSet.h:81
bool erase(const ValueT &V)
Definition: DenseSet.h:97
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:95
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
Base class for both owning and non-owning symbol-string ptrs.
Pointer to a pooled string representing a symbol name.
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
MemLifetime
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:480
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:1697
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:298
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:215
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
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:1753
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition: STLExtras.h:573
BumpPtrAllocatorImpl BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition: Allocator.h:382
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:1841
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:1873
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:1945
endianness
Definition: bit.h:70
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
#define N
Represents an address range in the exceutor process.