#ifndef LLVM_EXECUTIONENGINE_JITLINK_JITLINK_H
#define LLVM_EXECUTIONENGINE_JITLINK_JITLINK_H
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h"
#include "llvm/ExecutionEngine/JITLink/MemoryFlags.h"
#include "llvm/ExecutionEngine/JITSymbol.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/MemoryBuffer.h"
#include <map>
#include <string>
#include <system_error>
namespace llvm {
namespace jitlink {
class LinkGraph;
class Symbol;
class Section;
class JITLinkError : public ErrorInfo<JITLinkError> {
public:
static char ID;
JITLinkError(Twine ErrMsg) : ErrMsg(ErrMsg.str()) {}
void log(raw_ostream &OS) const override;
const std::string &getErrorMessage() const { return ErrMsg; }
std::error_code convertToErrorCode() const override;
private:
std::string ErrMsg;
};
class Edge {
public:
using Kind = uint8_t;
enum GenericEdgeKind : Kind {
Invalid, FirstKeepAlive, KeepAlive = FirstKeepAlive, FirstRelocation };
using OffsetT = uint32_t;
using AddendT = int64_t;
Edge(Kind K, OffsetT Offset, Symbol &Target, AddendT Addend)
: Target(&Target), Offset(Offset), Addend(Addend), K(K) {}
OffsetT getOffset() const { return Offset; }
void setOffset(OffsetT Offset) { this->Offset = Offset; }
Kind getKind() const { return K; }
void setKind(Kind K) { this->K = K; }
bool isRelocation() const { return K >= FirstRelocation; }
Kind getRelocation() const {
assert(isRelocation() && "Not a relocation edge");
return K - FirstRelocation;
}
bool isKeepAlive() const { return K >= FirstKeepAlive; }
Symbol &getTarget() const { return *Target; }
void setTarget(Symbol &Target) { this->Target = &Target; }
AddendT getAddend() const { return Addend; }
void setAddend(AddendT Addend) { this->Addend = Addend; }
private:
Symbol *Target = nullptr;
OffsetT Offset = 0;
AddendT Addend = 0;
Kind K = 0;
};
const char *getGenericEdgeKindName(Edge::Kind K);
class Addressable {
friend class LinkGraph;
protected:
Addressable(orc::ExecutorAddr Address, bool IsDefined)
: Address(Address), IsDefined(IsDefined), IsAbsolute(false) {}
Addressable(orc::ExecutorAddr Address)
: Address(Address), IsDefined(false), IsAbsolute(true) {
assert(!(IsDefined && IsAbsolute) &&
"Block cannot be both defined and absolute");
}
public:
Addressable(const Addressable &) = delete;
Addressable &operator=(const Addressable &) = default;
Addressable(Addressable &&) = delete;
Addressable &operator=(Addressable &&) = default;
orc::ExecutorAddr getAddress() const { return Address; }
void setAddress(orc::ExecutorAddr Address) { this->Address = Address; }
bool isDefined() const { return static_cast<bool>(IsDefined); }
bool isAbsolute() const { return static_cast<bool>(IsAbsolute); }
private:
void setAbsolute(bool IsAbsolute) {
assert(!IsDefined && "Cannot change the Absolute flag on a defined block");
this->IsAbsolute = IsAbsolute;
}
orc::ExecutorAddr Address;
uint64_t IsDefined : 1;
uint64_t IsAbsolute : 1;
protected:
uint64_t ContentMutable : 1;
uint64_t P2Align : 5;
uint64_t AlignmentOffset : 56;
};
using SectionOrdinal = unsigned;
class Block : public Addressable {
friend class LinkGraph;
private:
Block(Section &Parent, orc::ExecutorAddrDiff Size, orc::ExecutorAddr Address,
uint64_t Alignment, uint64_t AlignmentOffset)
: Addressable(Address, true), Parent(&Parent), Size(Size) {
assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
assert(AlignmentOffset < Alignment &&
"Alignment offset cannot exceed alignment");
assert(AlignmentOffset <= MaxAlignmentOffset &&
"Alignment offset exceeds maximum");
ContentMutable = false;
P2Align = Alignment ? countTrailingZeros(Alignment) : 0;
this->AlignmentOffset = AlignmentOffset;
}
Block(Section &Parent, ArrayRef<char> Content, orc::ExecutorAddr Address,
uint64_t Alignment, uint64_t AlignmentOffset)
: Addressable(Address, true), Parent(&Parent), Data(Content.data()),
Size(Content.size()) {
assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
assert(AlignmentOffset < Alignment &&
"Alignment offset cannot exceed alignment");
assert(AlignmentOffset <= MaxAlignmentOffset &&
"Alignment offset exceeds maximum");
ContentMutable = false;
P2Align = Alignment ? countTrailingZeros(Alignment) : 0;
this->AlignmentOffset = AlignmentOffset;
}
Block(Section &Parent, MutableArrayRef<char> Content,
orc::ExecutorAddr Address, uint64_t Alignment, uint64_t AlignmentOffset)
: Addressable(Address, true), Parent(&Parent), Data(Content.data()),
Size(Content.size()) {
assert(isPowerOf2_64(Alignment) && "Alignment must be power of 2");
assert(AlignmentOffset < Alignment &&
"Alignment offset cannot exceed alignment");
assert(AlignmentOffset <= MaxAlignmentOffset &&
"Alignment offset exceeds maximum");
ContentMutable = true;
P2Align = Alignment ? countTrailingZeros(Alignment) : 0;
this->AlignmentOffset = AlignmentOffset;
}
public:
using EdgeVector = std::vector<Edge>;
using edge_iterator = EdgeVector::iterator;
using const_edge_iterator = EdgeVector::const_iterator;
Block(const Block &) = delete;
Block &operator=(const Block &) = delete;
Block(Block &&) = delete;
Block &operator=(Block &&) = delete;
Section &getSection() const { return *Parent; }
bool isZeroFill() const { return !Data; }
size_t getSize() const { return Size; }
orc::ExecutorAddrRange getRange() const {
return orc::ExecutorAddrRange(getAddress(), getSize());
}
ArrayRef<char> getContent() const {
assert(Data && "Block does not contain content");
return ArrayRef<char>(Data, Size);
}
void setContent(ArrayRef<char> Content) {
assert(Content.data() && "Setting null content");
Data = Content.data();
Size = Content.size();
ContentMutable = false;
}
MutableArrayRef<char> getMutableContent(LinkGraph &G);
MutableArrayRef<char> getAlreadyMutableContent() {
assert(Data && "Block does not contain content");
assert(ContentMutable && "Content is not mutable");
return MutableArrayRef<char>(const_cast<char *>(Data), Size);
}
void setMutableContent(MutableArrayRef<char> MutableContent) {
assert(MutableContent.data() && "Setting null content");
Data = MutableContent.data();
Size = MutableContent.size();
ContentMutable = true;
}
bool isContentMutable() const { return ContentMutable; }
uint64_t getAlignment() const { return 1ull << P2Align; }
void setAlignment(uint64_t Alignment) {
assert(isPowerOf2_64(Alignment) && "Alignment must be a power of two");
P2Align = Alignment ? countTrailingZeros(Alignment) : 0;
}
uint64_t getAlignmentOffset() const { return AlignmentOffset; }
void setAlignmentOffset(uint64_t AlignmentOffset) {
assert(AlignmentOffset < (1ull << P2Align) &&
"Alignment offset can't exceed alignment");
this->AlignmentOffset = AlignmentOffset;
}
void addEdge(Edge::Kind K, Edge::OffsetT Offset, Symbol &Target,
Edge::AddendT Addend) {
assert(!isZeroFill() && "Adding edge to zero-fill block?");
Edges.push_back(Edge(K, Offset, Target, Addend));
}
void addEdge(const Edge &E) { Edges.push_back(E); }
iterator_range<edge_iterator> edges() {
return make_range(Edges.begin(), Edges.end());
}
iterator_range<const_edge_iterator> edges() const {
return make_range(Edges.begin(), Edges.end());
}
size_t edges_size() const { return Edges.size(); }
bool edges_empty() const { return Edges.empty(); }
edge_iterator removeEdge(edge_iterator I) { return Edges.erase(I); }
orc::ExecutorAddr getFixupAddress(const Edge &E) const {
return getAddress() + E.getOffset();
}
private:
static constexpr uint64_t MaxAlignmentOffset = (1ULL << 56) - 1;
void setSection(Section &Parent) { this->Parent = &Parent; }
Section *Parent;
const char *Data = nullptr;
size_t Size = 0;
std::vector<Edge> Edges;
};
inline uint64_t alignToBlock(uint64_t Addr, Block &B) {
uint64_t Delta = (B.getAlignmentOffset() - Addr) % B.getAlignment();
return Addr + Delta;
}
inline orc::ExecutorAddr alignToBlock(orc::ExecutorAddr Addr, Block &B) {
return orc::ExecutorAddr(alignToBlock(Addr.getValue(), B));
}
enum class Linkage : uint8_t {
Strong,
Weak,
};
const char *getLinkageName(Linkage L);
enum class Scope : uint8_t {
Default,
Hidden,
Local
};
const char *getScopeName(Scope S);
raw_ostream &operator<<(raw_ostream &OS, const Block &B);
class Symbol {
friend class LinkGraph;
private:
Symbol(Addressable &Base, orc::ExecutorAddrDiff Offset, StringRef Name,
orc::ExecutorAddrDiff Size, Linkage L, Scope S, bool IsLive,
bool IsCallable)
: Name(Name), Base(&Base), Offset(Offset), Size(Size) {
assert(Offset <= MaxOffset && "Offset out of range");
setLinkage(L);
setScope(S);
setLive(IsLive);
setCallable(IsCallable);
}
static Symbol &constructCommon(void *SymStorage, Block &Base, StringRef Name,
orc::ExecutorAddrDiff Size, Scope S,
bool IsLive) {
assert(SymStorage && "Storage cannot be null");
assert(!Name.empty() && "Common symbol name cannot be empty");
assert(Base.isDefined() &&
"Cannot create common symbol from undefined block");
assert(static_cast<Block &>(Base).getSize() == Size &&
"Common symbol size should match underlying block size");
auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
new (Sym) Symbol(Base, 0, Name, Size, Linkage::Weak, S, IsLive, false);
return *Sym;
}
static Symbol &constructExternal(void *SymStorage, Addressable &Base,
StringRef Name, orc::ExecutorAddrDiff Size,
Linkage L) {
assert(SymStorage && "Storage cannot be null");
assert(!Base.isDefined() &&
"Cannot create external symbol from defined block");
assert(!Name.empty() && "External symbol name cannot be empty");
auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
new (Sym) Symbol(Base, 0, Name, Size, L, Scope::Default, false, false);
return *Sym;
}
static Symbol &constructAbsolute(void *SymStorage, Addressable &Base,
StringRef Name, orc::ExecutorAddrDiff Size,
Linkage L, Scope S, bool IsLive) {
assert(SymStorage && "Storage cannot be null");
assert(!Base.isDefined() &&
"Cannot create absolute symbol from a defined block");
auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
new (Sym) Symbol(Base, 0, Name, Size, L, S, IsLive, false);
return *Sym;
}
static Symbol &constructAnonDef(void *SymStorage, Block &Base,
orc::ExecutorAddrDiff Offset,
orc::ExecutorAddrDiff Size, bool IsCallable,
bool IsLive) {
assert(SymStorage && "Storage cannot be null");
assert((Offset + Size) <= Base.getSize() &&
"Symbol extends past end of block");
auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
new (Sym) Symbol(Base, Offset, StringRef(), Size, Linkage::Strong,
Scope::Local, IsLive, IsCallable);
return *Sym;
}
static Symbol &constructNamedDef(void *SymStorage, Block &Base,
orc::ExecutorAddrDiff Offset, StringRef Name,
orc::ExecutorAddrDiff Size, Linkage L,
Scope S, bool IsLive, bool IsCallable) {
assert(SymStorage && "Storage cannot be null");
assert((Offset + Size) <= Base.getSize() &&
"Symbol extends past end of block");
assert(!Name.empty() && "Name cannot be empty");
auto *Sym = reinterpret_cast<Symbol *>(SymStorage);
new (Sym) Symbol(Base, Offset, Name, Size, L, S, IsLive, IsCallable);
return *Sym;
}
public:
Symbol() = default;
Symbol(const Symbol &) = delete;
Symbol &operator=(const Symbol &) = delete;
Symbol(Symbol &&) = delete;
Symbol &operator=(Symbol &&) = delete;
bool hasName() const { return !Name.empty(); }
StringRef getName() const {
assert((!Name.empty() || getScope() == Scope::Local) &&
"Anonymous symbol has non-local scope");
return Name;
}
void setName(StringRef Name) { this->Name = Name; }
bool isDefined() const {
assert(Base && "Attempt to access null symbol");
return Base->isDefined();
}
bool isLive() const {
assert(Base && "Attempting to access null symbol");
return IsLive;
}
void setLive(bool IsLive) { this->IsLive = IsLive; }
bool isCallable() const { return IsCallable; }
void setCallable(bool IsCallable) { this->IsCallable = IsCallable; }
bool isExternal() const {
assert(Base && "Attempt to access null symbol");
return !Base->isDefined() && !Base->isAbsolute();
}
bool isAbsolute() const {
assert(Base && "Attempt to access null symbol");
return Base->isAbsolute();
}
Addressable &getAddressable() {
assert(Base && "Cannot get underlying addressable for null symbol");
return *Base;
}
const Addressable &getAddressable() const {
assert(Base && "Cannot get underlying addressable for null symbol");
return *Base;
}
Block &getBlock() {
assert(Base && "Cannot get block for null symbol");
assert(Base->isDefined() && "Not a defined symbol");
return static_cast<Block &>(*Base);
}
const Block &getBlock() const {
assert(Base && "Cannot get block for null symbol");
assert(Base->isDefined() && "Not a defined symbol");
return static_cast<const Block &>(*Base);
}
orc::ExecutorAddrDiff getOffset() const { return Offset; }
orc::ExecutorAddr getAddress() const { return Base->getAddress() + Offset; }
orc::ExecutorAddrDiff getSize() const { return Size; }
void setSize(orc::ExecutorAddrDiff Size) {
assert(Base && "Cannot set size for null Symbol");
assert((Size == 0 || Base->isDefined()) &&
"Non-zero size can only be set for defined symbols");
assert((Offset + Size <= static_cast<const Block &>(*Base).getSize()) &&
"Symbol size cannot extend past the end of its containing block");
this->Size = Size;
}
orc::ExecutorAddrRange getRange() const {
return orc::ExecutorAddrRange(getAddress(), getSize());
}
bool isSymbolZeroFill() const { return getBlock().isZeroFill(); }
ArrayRef<char> getSymbolContent() const {
return getBlock().getContent().slice(Offset, Size);
}
Linkage getLinkage() const { return static_cast<Linkage>(L); }
void setLinkage(Linkage L) {
assert((L == Linkage::Strong || (!Base->isAbsolute() && !Name.empty())) &&
"Linkage can only be applied to defined named symbols");
this->L = static_cast<uint8_t>(L);
}
Scope getScope() const { return static_cast<Scope>(S); }
void setScope(Scope S) {
assert((!Name.empty() || S == Scope::Local) &&
"Can not set anonymous symbol to non-local scope");
assert((S == Scope::Default || Base->isDefined() || Base->isAbsolute()) &&
"Invalid visibility for symbol type");
this->S = static_cast<uint8_t>(S);
}
private:
void makeExternal(Addressable &A) {
assert(!A.isDefined() && !A.isAbsolute() &&
"Attempting to make external with defined or absolute block");
Base = &A;
Offset = 0;
setScope(Scope::Default);
IsLive = 0;
}
void makeAbsolute(Addressable &A) {
assert(!A.isDefined() && A.isAbsolute() &&
"Attempting to make absolute with defined or external block");
Base = &A;
Offset = 0;
}
void setBlock(Block &B) { Base = &B; }
void setOffset(orc::ExecutorAddrDiff NewOffset) {
assert(NewOffset <= MaxOffset && "Offset out of range");
Offset = NewOffset;
}
static constexpr uint64_t MaxOffset = (1ULL << 59) - 1;
StringRef Name;
Addressable *Base = nullptr;
uint64_t Offset : 59;
uint64_t L : 1;
uint64_t S : 2;
uint64_t IsLive : 1;
uint64_t IsCallable : 1;
orc::ExecutorAddrDiff Size = 0;
};
raw_ostream &operator<<(raw_ostream &OS, const Symbol &A);
void printEdge(raw_ostream &OS, const Block &B, const Edge &E,
StringRef EdgeKindName);
class Section {
friend class LinkGraph;
private:
Section(StringRef Name, MemProt Prot, SectionOrdinal SecOrdinal)
: Name(Name), Prot(Prot), SecOrdinal(SecOrdinal) {}
using SymbolSet = DenseSet<Symbol *>;
using BlockSet = DenseSet<Block *>;
public:
using symbol_iterator = SymbolSet::iterator;
using const_symbol_iterator = SymbolSet::const_iterator;
using block_iterator = BlockSet::iterator;
using const_block_iterator = BlockSet::const_iterator;
~Section();
Section(const Section &) = delete;
Section &operator=(const Section &) = delete;
Section(Section &&) = delete;
Section &operator=(Section &&) = delete;
StringRef getName() const { return Name; }
MemProt getMemProt() const { return Prot; }
void setMemProt(MemProt Prot) { this->Prot = Prot; }
MemDeallocPolicy getMemDeallocPolicy() const { return MDP; }
void setMemDeallocPolicy(MemDeallocPolicy MDP) { this->MDP = MDP; }
SectionOrdinal getOrdinal() const { return SecOrdinal; }
iterator_range<block_iterator> blocks() {
return make_range(Blocks.begin(), Blocks.end());
}
iterator_range<const_block_iterator> blocks() const {
return make_range(Blocks.begin(), Blocks.end());
}
BlockSet::size_type blocks_size() const { return Blocks.size(); }
iterator_range<symbol_iterator> symbols() {
return make_range(Symbols.begin(), Symbols.end());
}
iterator_range<const_symbol_iterator> symbols() const {
return make_range(Symbols.begin(), Symbols.end());
}
SymbolSet::size_type symbols_size() const { return Symbols.size(); }
private:
void addSymbol(Symbol &Sym) {
assert(!Symbols.count(&Sym) && "Symbol is already in this section");
Symbols.insert(&Sym);
}
void removeSymbol(Symbol &Sym) {
assert(Symbols.count(&Sym) && "symbol is not in this section");
Symbols.erase(&Sym);
}
void addBlock(Block &B) {
assert(!Blocks.count(&B) && "Block is already in this section");
Blocks.insert(&B);
}
void removeBlock(Block &B) {
assert(Blocks.count(&B) && "Block is not in this section");
Blocks.erase(&B);
}
void transferContentTo(Section &DstSection) {
if (&DstSection == this)
return;
for (auto *S : Symbols)
DstSection.addSymbol(*S);
for (auto *B : Blocks)
DstSection.addBlock(*B);
Symbols.clear();
Blocks.clear();
}
StringRef Name;
MemProt Prot;
MemDeallocPolicy MDP = MemDeallocPolicy::Standard;
SectionOrdinal SecOrdinal = 0;
BlockSet Blocks;
SymbolSet Symbols;
};
class SectionRange {
public:
SectionRange() = default;
SectionRange(const Section &Sec) {
if (llvm::empty(Sec.blocks()))
return;
First = Last = *Sec.blocks().begin();
for (auto *B : Sec.blocks()) {
if (B->getAddress() < First->getAddress())
First = B;
if (B->getAddress() > Last->getAddress())
Last = B;
}
}
Block *getFirstBlock() const {
assert((!Last || First) && "First can not be null if end is non-null");
return First;
}
Block *getLastBlock() const {
assert((First || !Last) && "Last can not be null if start is non-null");
return Last;
}
bool empty() const {
assert((First || !Last) && "Last can not be null if start is non-null");
return !First;
}
orc::ExecutorAddr getStart() const {
return First ? First->getAddress() : orc::ExecutorAddr();
}
orc::ExecutorAddr getEnd() const {
return Last ? Last->getAddress() + Last->getSize() : orc::ExecutorAddr();
}
orc::ExecutorAddrDiff getSize() const { return getEnd() - getStart(); }
orc::ExecutorAddrRange getRange() const {
return orc::ExecutorAddrRange(getStart(), getEnd());
}
private:
Block *First = nullptr;
Block *Last = nullptr;
};
class LinkGraph {
private:
using SectionList = std::vector<std::unique_ptr<Section>>;
using ExternalSymbolSet = DenseSet<Symbol *>;
using BlockSet = DenseSet<Block *>;
template <typename... ArgTs>
Addressable &createAddressable(ArgTs &&... Args) {
Addressable *A =
reinterpret_cast<Addressable *>(Allocator.Allocate<Addressable>());
new (A) Addressable(std::forward<ArgTs>(Args)...);
return *A;
}
void destroyAddressable(Addressable &A) {
A.~Addressable();
Allocator.Deallocate(&A);
}
template <typename... ArgTs> Block &createBlock(ArgTs &&... Args) {
Block *B = reinterpret_cast<Block *>(Allocator.Allocate<Block>());
new (B) Block(std::forward<ArgTs>(Args)...);
B->getSection().addBlock(*B);
return *B;
}
void destroyBlock(Block &B) {
B.~Block();
Allocator.Deallocate(&B);
}
void destroySymbol(Symbol &S) {
S.~Symbol();
Allocator.Deallocate(&S);
}
static iterator_range<Section::block_iterator> getSectionBlocks(Section &S) {
return S.blocks();
}
static iterator_range<Section::const_block_iterator>
getSectionConstBlocks(Section &S) {
return S.blocks();
}
static iterator_range<Section::symbol_iterator>
getSectionSymbols(Section &S) {
return S.symbols();
}
static iterator_range<Section::const_symbol_iterator>
getSectionConstSymbols(Section &S) {
return S.symbols();
}
public:
using external_symbol_iterator = ExternalSymbolSet::iterator;
using section_iterator = pointee_iterator<SectionList::iterator>;
using const_section_iterator = pointee_iterator<SectionList::const_iterator>;
template <typename OuterItrT, typename InnerItrT, typename T,
iterator_range<InnerItrT> getInnerRange(
typename OuterItrT::reference)>
class nested_collection_iterator
: public iterator_facade_base<
nested_collection_iterator<OuterItrT, InnerItrT, T, getInnerRange>,
std::forward_iterator_tag, T> {
public:
nested_collection_iterator() = default;
nested_collection_iterator(OuterItrT OuterI, OuterItrT OuterE)
: OuterI(OuterI), OuterE(OuterE),
InnerI(getInnerBegin(OuterI, OuterE)) {
moveToNonEmptyInnerOrEnd();
}
bool operator==(const nested_collection_iterator &RHS) const {
return (OuterI == RHS.OuterI) && (InnerI == RHS.InnerI);
}
T operator*() const {
assert(InnerI != getInnerRange(*OuterI).end() && "Dereferencing end?");
return *InnerI;
}
nested_collection_iterator operator++() {
++InnerI;
moveToNonEmptyInnerOrEnd();
return *this;
}
private:
static InnerItrT getInnerBegin(OuterItrT OuterI, OuterItrT OuterE) {
return OuterI != OuterE ? getInnerRange(*OuterI).begin() : InnerItrT();
}
void moveToNonEmptyInnerOrEnd() {
while (OuterI != OuterE && InnerI == getInnerRange(*OuterI).end()) {
++OuterI;
InnerI = getInnerBegin(OuterI, OuterE);
}
}
OuterItrT OuterI, OuterE;
InnerItrT InnerI;
};
using defined_symbol_iterator =
nested_collection_iterator<const_section_iterator,
Section::symbol_iterator, Symbol *,
getSectionSymbols>;
using const_defined_symbol_iterator =
nested_collection_iterator<const_section_iterator,
Section::const_symbol_iterator, const Symbol *,
getSectionConstSymbols>;
using block_iterator = nested_collection_iterator<const_section_iterator,
Section::block_iterator,
Block *, getSectionBlocks>;
using const_block_iterator =
nested_collection_iterator<const_section_iterator,
Section::const_block_iterator, const Block *,
getSectionConstBlocks>;
using GetEdgeKindNameFunction = const char *(*)(Edge::Kind);
LinkGraph(std::string Name, const Triple &TT, unsigned PointerSize,
support::endianness Endianness,
GetEdgeKindNameFunction GetEdgeKindName)
: Name(std::move(Name)), TT(TT), PointerSize(PointerSize),
Endianness(Endianness), GetEdgeKindName(std::move(GetEdgeKindName)) {}
LinkGraph(const LinkGraph &) = delete;
LinkGraph &operator=(const LinkGraph &) = delete;
LinkGraph(LinkGraph &&) = delete;
LinkGraph &operator=(LinkGraph &&) = delete;
const std::string &getName() const { return Name; }
const Triple &getTargetTriple() const { return TT; }
unsigned getPointerSize() const { return PointerSize; }
support::endianness getEndianness() const { return Endianness; }
const char *getEdgeKindName(Edge::Kind K) const { return GetEdgeKindName(K); }
MutableArrayRef<char> allocateBuffer(size_t Size) {
return {Allocator.Allocate<char>(Size), Size};
}
MutableArrayRef<char> allocateContent(ArrayRef<char> Source) {
auto *AllocatedBuffer = Allocator.Allocate<char>(Source.size());
llvm::copy(Source, AllocatedBuffer);
return MutableArrayRef<char>(AllocatedBuffer, Source.size());
}
MutableArrayRef<char> allocateString(Twine Source) {
SmallString<256> TmpBuffer;
auto SourceStr = Source.toStringRef(TmpBuffer);
auto *AllocatedBuffer = Allocator.Allocate<char>(SourceStr.size());
llvm::copy(SourceStr, AllocatedBuffer);
return MutableArrayRef<char>(AllocatedBuffer, SourceStr.size());
}
Section &createSection(StringRef Name, MemProt Prot) {
assert(llvm::find_if(Sections,
[&](std::unique_ptr<Section> &Sec) {
return Sec->getName() == Name;
}) == Sections.end() &&
"Duplicate section name");
std::unique_ptr<Section> Sec(new Section(Name, Prot, Sections.size()));
Sections.push_back(std::move(Sec));
return *Sections.back();
}
Block &createContentBlock(Section &Parent, ArrayRef<char> Content,
orc::ExecutorAddr Address, uint64_t Alignment,
uint64_t AlignmentOffset) {
return createBlock(Parent, Content, Address, Alignment, AlignmentOffset);
}
Block &createMutableContentBlock(Section &Parent,
MutableArrayRef<char> MutableContent,
orc::ExecutorAddr Address,
uint64_t Alignment,
uint64_t AlignmentOffset) {
return createBlock(Parent, MutableContent, Address, Alignment,
AlignmentOffset);
}
Block &createZeroFillBlock(Section &Parent, orc::ExecutorAddrDiff Size,
orc::ExecutorAddr Address, uint64_t Alignment,
uint64_t AlignmentOffset) {
return createBlock(Parent, Size, Address, Alignment, AlignmentOffset);
}
using SplitBlockCache = Optional<SmallVector<Symbol *, 8>>;
Block &splitBlock(Block &B, size_t SplitIndex,
SplitBlockCache *Cache = nullptr);
Symbol &addExternalSymbol(StringRef Name, orc::ExecutorAddrDiff Size,
Linkage L) {
assert(llvm::count_if(ExternalSymbols,
[&](const Symbol *Sym) {
return Sym->getName() == Name;
}) == 0 &&
"Duplicate external symbol");
auto &Sym = Symbol::constructExternal(
Allocator.Allocate<Symbol>(),
createAddressable(orc::ExecutorAddr(), false), Name, Size, L);
ExternalSymbols.insert(&Sym);
return Sym;
}
Symbol &addAbsoluteSymbol(StringRef Name, orc::ExecutorAddr Address,
orc::ExecutorAddrDiff Size, Linkage L, Scope S,
bool IsLive) {
assert(llvm::count_if(AbsoluteSymbols,
[&](const Symbol *Sym) {
return Sym->getName() == Name;
}) == 0 &&
"Duplicate absolute symbol");
auto &Sym = Symbol::constructAbsolute(Allocator.Allocate<Symbol>(),
createAddressable(Address), Name,
Size, L, S, IsLive);
AbsoluteSymbols.insert(&Sym);
return Sym;
}
Symbol &addCommonSymbol(StringRef Name, Scope S, Section &Section,
orc::ExecutorAddr Address, orc::ExecutorAddrDiff Size,
uint64_t Alignment, bool IsLive) {
assert(llvm::count_if(defined_symbols(),
[&](const Symbol *Sym) {
return Sym->getName() == Name;
}) == 0 &&
"Duplicate defined symbol");
auto &Sym = Symbol::constructCommon(
Allocator.Allocate<Symbol>(),
createBlock(Section, Size, Address, Alignment, 0), Name, Size, S,
IsLive);
Section.addSymbol(Sym);
return Sym;
}
Symbol &addAnonymousSymbol(Block &Content, orc::ExecutorAddrDiff Offset,
orc::ExecutorAddrDiff Size, bool IsCallable,
bool IsLive) {
auto &Sym = Symbol::constructAnonDef(Allocator.Allocate<Symbol>(), Content,
Offset, Size, IsCallable, IsLive);
Content.getSection().addSymbol(Sym);
return Sym;
}
Symbol &addDefinedSymbol(Block &Content, orc::ExecutorAddrDiff Offset,
StringRef Name, orc::ExecutorAddrDiff Size,
Linkage L, Scope S, bool IsCallable, bool IsLive) {
assert((S == Scope::Local || llvm::count_if(defined_symbols(),
[&](const Symbol *Sym) {
return Sym->getName() == Name;
}) == 0) &&
"Duplicate defined symbol");
auto &Sym =
Symbol::constructNamedDef(Allocator.Allocate<Symbol>(), Content, Offset,
Name, Size, L, S, IsLive, IsCallable);
Content.getSection().addSymbol(Sym);
return Sym;
}
iterator_range<section_iterator> sections() {
return make_range(section_iterator(Sections.begin()),
section_iterator(Sections.end()));
}
SectionList::size_type sections_size() const { return Sections.size(); }
Section *findSectionByName(StringRef Name) {
for (auto &S : sections())
if (S.getName() == Name)
return &S;
return nullptr;
}
iterator_range<block_iterator> blocks() {
return make_range(block_iterator(Sections.begin(), Sections.end()),
block_iterator(Sections.end(), Sections.end()));
}
iterator_range<const_block_iterator> blocks() const {
return make_range(const_block_iterator(Sections.begin(), Sections.end()),
const_block_iterator(Sections.end(), Sections.end()));
}
iterator_range<external_symbol_iterator> external_symbols() {
return make_range(ExternalSymbols.begin(), ExternalSymbols.end());
}
iterator_range<external_symbol_iterator> absolute_symbols() {
return make_range(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
}
iterator_range<defined_symbol_iterator> defined_symbols() {
return make_range(defined_symbol_iterator(Sections.begin(), Sections.end()),
defined_symbol_iterator(Sections.end(), Sections.end()));
}
iterator_range<const_defined_symbol_iterator> defined_symbols() const {
return make_range(
const_defined_symbol_iterator(Sections.begin(), Sections.end()),
const_defined_symbol_iterator(Sections.end(), Sections.end()));
}
void makeExternal(Symbol &Sym) {
assert(!Sym.isExternal() && "Symbol is already external");
if (Sym.isAbsolute()) {
assert(AbsoluteSymbols.count(&Sym) &&
"Sym is not in the absolute symbols set");
assert(Sym.getOffset() == 0 && "Absolute not at offset 0");
AbsoluteSymbols.erase(&Sym);
Sym.getAddressable().setAbsolute(false);
} else {
assert(Sym.isDefined() && "Sym is not a defined symbol");
Section &Sec = Sym.getBlock().getSection();
Sec.removeSymbol(Sym);
Sym.makeExternal(createAddressable(orc::ExecutorAddr(), false));
}
ExternalSymbols.insert(&Sym);
}
void makeAbsolute(Symbol &Sym, orc::ExecutorAddr Address) {
assert(!Sym.isAbsolute() && "Symbol is already absolute");
if (Sym.isExternal()) {
assert(ExternalSymbols.count(&Sym) &&
"Sym is not in the absolute symbols set");
assert(Sym.getOffset() == 0 && "External is not at offset 0");
ExternalSymbols.erase(&Sym);
Sym.getAddressable().setAbsolute(true);
Sym.setScope(Scope::Local);
} else {
assert(Sym.isDefined() && "Sym is not a defined symbol");
Section &Sec = Sym.getBlock().getSection();
Sec.removeSymbol(Sym);
Sym.makeAbsolute(createAddressable(Address));
}
AbsoluteSymbols.insert(&Sym);
}
void makeDefined(Symbol &Sym, Block &Content, orc::ExecutorAddrDiff Offset,
orc::ExecutorAddrDiff Size, Linkage L, Scope S,
bool IsLive) {
assert(!Sym.isDefined() && "Sym is already a defined symbol");
if (Sym.isAbsolute()) {
assert(AbsoluteSymbols.count(&Sym) &&
"Symbol is not in the absolutes set");
AbsoluteSymbols.erase(&Sym);
} else {
assert(ExternalSymbols.count(&Sym) &&
"Symbol is not in the externals set");
ExternalSymbols.erase(&Sym);
}
Addressable &OldBase = *Sym.Base;
Sym.setBlock(Content);
Sym.setOffset(Offset);
Sym.setSize(Size);
Sym.setLinkage(L);
Sym.setScope(S);
Sym.setLive(IsLive);
Content.getSection().addSymbol(Sym);
destroyAddressable(OldBase);
}
void transferDefinedSymbol(Symbol &Sym, Block &DestBlock,
orc::ExecutorAddrDiff NewOffset,
Optional<orc::ExecutorAddrDiff> ExplicitNewSize) {
auto &OldSection = Sym.getBlock().getSection();
Sym.setBlock(DestBlock);
Sym.setOffset(NewOffset);
if (ExplicitNewSize)
Sym.setSize(*ExplicitNewSize);
else {
auto RemainingBlockSize = DestBlock.getSize() - NewOffset;
if (Sym.getSize() > RemainingBlockSize)
Sym.setSize(RemainingBlockSize);
}
if (&DestBlock.getSection() != &OldSection) {
OldSection.removeSymbol(Sym);
DestBlock.getSection().addSymbol(Sym);
}
}
void transferBlock(Block &B, Section &NewSection) {
auto &OldSection = B.getSection();
if (&OldSection == &NewSection)
return;
SmallVector<Symbol *> AttachedSymbols;
for (auto *S : OldSection.symbols())
if (&S->getBlock() == &B)
AttachedSymbols.push_back(S);
for (auto *S : AttachedSymbols) {
OldSection.removeSymbol(*S);
NewSection.addSymbol(*S);
}
OldSection.removeBlock(B);
NewSection.addBlock(B);
}
void mergeSections(Section &DstSection, Section &SrcSection,
bool PreserveSrcSection = false) {
if (&DstSection == &SrcSection)
return;
for (auto *B : SrcSection.blocks())
B->setSection(DstSection);
SrcSection.transferContentTo(DstSection);
if (!PreserveSrcSection)
removeSection(SrcSection);
}
void removeExternalSymbol(Symbol &Sym) {
assert(!Sym.isDefined() && !Sym.isAbsolute() &&
"Sym is not an external symbol");
assert(ExternalSymbols.count(&Sym) && "Symbol is not in the externals set");
ExternalSymbols.erase(&Sym);
Addressable &Base = *Sym.Base;
assert(llvm::find_if(ExternalSymbols,
[&](Symbol *AS) { return AS->Base == &Base; }) ==
ExternalSymbols.end() &&
"Base addressable still in use");
destroySymbol(Sym);
destroyAddressable(Base);
}
void removeAbsoluteSymbol(Symbol &Sym) {
assert(!Sym.isDefined() && Sym.isAbsolute() &&
"Sym is not an absolute symbol");
assert(AbsoluteSymbols.count(&Sym) &&
"Symbol is not in the absolute symbols set");
AbsoluteSymbols.erase(&Sym);
Addressable &Base = *Sym.Base;
assert(llvm::find_if(ExternalSymbols,
[&](Symbol *AS) { return AS->Base == &Base; }) ==
ExternalSymbols.end() &&
"Base addressable still in use");
destroySymbol(Sym);
destroyAddressable(Base);
}
void removeDefinedSymbol(Symbol &Sym) {
assert(Sym.isDefined() && "Sym is not a defined symbol");
Sym.getBlock().getSection().removeSymbol(Sym);
destroySymbol(Sym);
}
void removeBlock(Block &B) {
assert(llvm::none_of(B.getSection().symbols(),
[&](const Symbol *Sym) {
return &Sym->getBlock() == &B;
}) &&
"Block still has symbols attached");
B.getSection().removeBlock(B);
destroyBlock(B);
}
void removeSection(Section &Sec) {
auto I = llvm::find_if(Sections, [&Sec](const std::unique_ptr<Section> &S) {
return S.get() == &Sec;
});
assert(I != Sections.end() && "Section does not appear in this graph");
Sections.erase(I);
}
orc::shared::AllocActions &allocActions() { return AAs; }
void dump(raw_ostream &OS);
private:
BumpPtrAllocator Allocator;
std::string Name;
Triple TT;
unsigned PointerSize;
support::endianness Endianness;
GetEdgeKindNameFunction GetEdgeKindName = nullptr;
SectionList Sections;
ExternalSymbolSet ExternalSymbols;
ExternalSymbolSet AbsoluteSymbols;
orc::shared::AllocActions AAs;
};
inline MutableArrayRef<char> Block::getMutableContent(LinkGraph &G) {
if (!ContentMutable)
setMutableContent(G.allocateContent({Data, Size}));
return MutableArrayRef<char>(const_cast<char *>(Data), Size);
}
class BlockAddressMap {
public:
using AddrToBlockMap = std::map<orc::ExecutorAddr, Block *>;
using const_iterator = AddrToBlockMap::const_iterator;
static bool includeAllBlocks(const Block &B) { return true; }
static bool includeNonNull(const Block &B) { return !!B.getAddress(); }
BlockAddressMap() = default;
template <typename PredFn = decltype(includeAllBlocks)>
Error addBlock(Block &B, PredFn Pred = includeAllBlocks) {
if (!Pred(B))
return Error::success();
auto I = AddrToBlock.upper_bound(B.getAddress());
if (I != AddrToBlock.end()) {
if (B.getAddress() + B.getSize() > I->second->getAddress())
return overlapError(B, *I->second);
}
if (I != AddrToBlock.begin()) {
auto &PrevBlock = *std::prev(I)->second;
if (PrevBlock.getAddress() + PrevBlock.getSize() > B.getAddress())
return overlapError(B, PrevBlock);
}
AddrToBlock.insert(I, std::make_pair(B.getAddress(), &B));
return Error::success();
}
void addBlockWithoutChecking(Block &B) { AddrToBlock[B.getAddress()] = &B; }
template <typename BlockPtrRange,
typename PredFn = decltype(includeAllBlocks)>
Error addBlocks(BlockPtrRange &&Blocks, PredFn Pred = includeAllBlocks) {
for (auto *B : Blocks)
if (auto Err = addBlock(*B, Pred))
return Err;
return Error::success();
}
template <typename BlockPtrRange>
void addBlocksWithoutChecking(BlockPtrRange &&Blocks) {
for (auto *B : Blocks)
addBlockWithoutChecking(*B);
}
const_iterator begin() const { return AddrToBlock.begin(); }
const_iterator end() const { return AddrToBlock.end(); }
Block *getBlockAt(orc::ExecutorAddr Addr) const {
auto I = AddrToBlock.find(Addr);
if (I == AddrToBlock.end())
return nullptr;
return I->second;
}
Block *getBlockCovering(orc::ExecutorAddr Addr) const {
auto I = AddrToBlock.upper_bound(Addr);
if (I == AddrToBlock.begin())
return nullptr;
auto *B = std::prev(I)->second;
if (Addr < B->getAddress() + B->getSize())
return B;
return nullptr;
}
private:
Error overlapError(Block &NewBlock, Block &ExistingBlock) {
auto NewBlockEnd = NewBlock.getAddress() + NewBlock.getSize();
auto ExistingBlockEnd =
ExistingBlock.getAddress() + ExistingBlock.getSize();
return make_error<JITLinkError>(
"Block at " +
formatv("{0:x16} -- {1:x16}", NewBlock.getAddress().getValue(),
NewBlockEnd.getValue()) +
" overlaps " +
formatv("{0:x16} -- {1:x16}", ExistingBlock.getAddress().getValue(),
ExistingBlockEnd.getValue()));
}
AddrToBlockMap AddrToBlock;
};
class SymbolAddressMap {
public:
using SymbolVector = SmallVector<Symbol *, 1>;
void addSymbol(Symbol &Sym) {
AddrToSymbols[Sym.getAddress()].push_back(&Sym);
}
template <typename SymbolPtrCollection>
void addSymbols(SymbolPtrCollection &&Symbols) {
for (auto *Sym : Symbols)
addSymbol(*Sym);
}
const SymbolVector *getSymbolsAt(orc::ExecutorAddr Addr) const {
auto I = AddrToSymbols.find(Addr);
if (I == AddrToSymbols.end())
return nullptr;
return &I->second;
}
private:
std::map<orc::ExecutorAddr, SymbolVector> AddrToSymbols;
};
using LinkGraphPassFunction = std::function<Error(LinkGraph &)>;
using LinkGraphPassList = std::vector<LinkGraphPassFunction>;
struct PassConfiguration {
LinkGraphPassList PrePrunePasses;
LinkGraphPassList PostPrunePasses;
LinkGraphPassList PostAllocationPasses;
LinkGraphPassList PreFixupPasses;
LinkGraphPassList PostFixupPasses;
};
enum class SymbolLookupFlags { RequiredSymbol, WeaklyReferencedSymbol };
raw_ostream &operator<<(raw_ostream &OS, const SymbolLookupFlags &LF);
using AsyncLookupResult = DenseMap<StringRef, JITEvaluatedSymbol>;
class JITLinkAsyncLookupContinuation {
public:
virtual ~JITLinkAsyncLookupContinuation() = default;
virtual void run(Expected<AsyncLookupResult> LR) = 0;
private:
virtual void anchor();
};
template <typename Continuation>
std::unique_ptr<JITLinkAsyncLookupContinuation>
createLookupContinuation(Continuation Cont) {
class Impl final : public JITLinkAsyncLookupContinuation {
public:
Impl(Continuation C) : C(std::move(C)) {}
void run(Expected<AsyncLookupResult> LR) override { C(std::move(LR)); }
private:
Continuation C;
};
return std::make_unique<Impl>(std::move(Cont));
}
class JITLinkContext {
public:
using LookupMap = DenseMap<StringRef, SymbolLookupFlags>;
JITLinkContext(const JITLinkDylib *JD) : JD(JD) {}
virtual ~JITLinkContext();
const JITLinkDylib *getJITLinkDylib() const { return JD; }
virtual JITLinkMemoryManager &getMemoryManager() = 0;
virtual void notifyFailed(Error Err) = 0;
virtual void lookup(const LookupMap &Symbols,
std::unique_ptr<JITLinkAsyncLookupContinuation> LC) = 0;
virtual Error notifyResolved(LinkGraph &G) = 0;
virtual void notifyFinalized(JITLinkMemoryManager::FinalizedAlloc Alloc) = 0;
virtual bool shouldAddDefaultTargetPasses(const Triple &TT) const;
virtual LinkGraphPassFunction getMarkLivePass(const Triple &TT) const;
virtual Error modifyPassConfig(LinkGraph &G, PassConfiguration &Config);
private:
const JITLinkDylib *JD = nullptr;
};
Error markAllSymbolsLive(LinkGraph &G);
Error makeTargetOutOfRangeError(const LinkGraph &G, const Block &B,
const Edge &E);
Error makeAlignmentError(llvm::orc::ExecutorAddr Loc, uint64_t Value, int N,
const Edge &E);
inline void visitEdge(LinkGraph &G, Block *B, Edge &E) {}
template <typename VisitorT, typename... VisitorTs>
void visitEdge(LinkGraph &G, Block *B, Edge &E, VisitorT &&V,
VisitorTs &&...Vs) {
if (!V.visitEdge(G, B, E))
visitEdge(G, B, E, std::forward<VisitorTs>(Vs)...);
}
template <typename... VisitorTs>
void visitExistingEdges(LinkGraph &G, VisitorTs &&...Vs) {
std::vector<Block *> Worklist(G.blocks().begin(), G.blocks().end());
for (auto *B : Worklist)
for (auto &E : B->edges())
visitEdge(G, B, E, std::forward<VisitorTs>(Vs)...);
}
Expected<std::unique_ptr<LinkGraph>>
createLinkGraphFromObject(MemoryBufferRef ObjectBuffer);
void link(std::unique_ptr<LinkGraph> G, std::unique_ptr<JITLinkContext> Ctx);
} }
#endif