JITLink.h 66 KB

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