xref: /freebsd/contrib/llvm-project/llvm/lib/ExecutionEngine/JITLink/ELF_riscv.cpp (revision e6bfd18d21b225af6a0ed67ceeaf1293b7b9eba5)
1 //===------- ELF_riscv.cpp -JIT linker implementation for ELF/riscv -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // ELF/riscv jit-link implementation.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ExecutionEngine/JITLink/ELF_riscv.h"
14 #include "ELFLinkGraphBuilder.h"
15 #include "JITLinkGeneric.h"
16 #include "PerGraphGOTAndPLTStubsBuilder.h"
17 #include "llvm/BinaryFormat/ELF.h"
18 #include "llvm/ExecutionEngine/JITLink/JITLink.h"
19 #include "llvm/ExecutionEngine/JITLink/riscv.h"
20 #include "llvm/Object/ELF.h"
21 #include "llvm/Object/ELFObjectFile.h"
22 #include "llvm/Support/Endian.h"
23 
24 #define DEBUG_TYPE "jitlink"
25 using namespace llvm;
26 using namespace llvm::jitlink;
27 using namespace llvm::jitlink::riscv;
28 
29 namespace {
30 
31 class PerGraphGOTAndPLTStubsBuilder_ELF_riscv
32     : public PerGraphGOTAndPLTStubsBuilder<
33           PerGraphGOTAndPLTStubsBuilder_ELF_riscv> {
34 public:
35   static constexpr size_t StubEntrySize = 16;
36   static const uint8_t NullGOTEntryContent[8];
37   static const uint8_t RV64StubContent[StubEntrySize];
38   static const uint8_t RV32StubContent[StubEntrySize];
39 
40   using PerGraphGOTAndPLTStubsBuilder<
41       PerGraphGOTAndPLTStubsBuilder_ELF_riscv>::PerGraphGOTAndPLTStubsBuilder;
42 
43   bool isRV64() const { return G.getPointerSize() == 8; }
44 
45   bool isGOTEdgeToFix(Edge &E) const { return E.getKind() == R_RISCV_GOT_HI20; }
46 
47   Symbol &createGOTEntry(Symbol &Target) {
48     Block &GOTBlock =
49         G.createContentBlock(getGOTSection(), getGOTEntryBlockContent(),
50                              orc::ExecutorAddr(), G.getPointerSize(), 0);
51     GOTBlock.addEdge(isRV64() ? R_RISCV_64 : R_RISCV_32, 0, Target, 0);
52     return G.addAnonymousSymbol(GOTBlock, 0, G.getPointerSize(), false, false);
53   }
54 
55   Symbol &createPLTStub(Symbol &Target) {
56     Block &StubContentBlock = G.createContentBlock(
57         getStubsSection(), getStubBlockContent(), orc::ExecutorAddr(), 4, 0);
58     auto &GOTEntrySymbol = getGOTEntry(Target);
59     StubContentBlock.addEdge(R_RISCV_CALL, 0, GOTEntrySymbol, 0);
60     return G.addAnonymousSymbol(StubContentBlock, 0, StubEntrySize, true,
61                                 false);
62   }
63 
64   void fixGOTEdge(Edge &E, Symbol &GOTEntry) {
65     // Replace the relocation pair (R_RISCV_GOT_HI20, R_RISCV_PCREL_LO12)
66     // with (R_RISCV_PCREL_HI20, R_RISCV_PCREL_LO12)
67     // Therefore, here just change the R_RISCV_GOT_HI20 to R_RISCV_PCREL_HI20
68     E.setKind(R_RISCV_PCREL_HI20);
69     E.setTarget(GOTEntry);
70   }
71 
72   void fixPLTEdge(Edge &E, Symbol &PLTStubs) {
73     assert(E.getKind() == R_RISCV_CALL_PLT && "Not a R_RISCV_CALL_PLT edge?");
74     E.setKind(R_RISCV_CALL);
75     E.setTarget(PLTStubs);
76   }
77 
78   bool isExternalBranchEdge(Edge &E) const {
79     return E.getKind() == R_RISCV_CALL_PLT;
80   }
81 
82 private:
83   Section &getGOTSection() const {
84     if (!GOTSection)
85       GOTSection = &G.createSection("$__GOT", MemProt::Read);
86     return *GOTSection;
87   }
88 
89   Section &getStubsSection() const {
90     if (!StubsSection)
91       StubsSection =
92           &G.createSection("$__STUBS", MemProt::Read | MemProt::Exec);
93     return *StubsSection;
94   }
95 
96   ArrayRef<char> getGOTEntryBlockContent() {
97     return {reinterpret_cast<const char *>(NullGOTEntryContent),
98             G.getPointerSize()};
99   }
100 
101   ArrayRef<char> getStubBlockContent() {
102     auto StubContent = isRV64() ? RV64StubContent : RV32StubContent;
103     return {reinterpret_cast<const char *>(StubContent), StubEntrySize};
104   }
105 
106   mutable Section *GOTSection = nullptr;
107   mutable Section *StubsSection = nullptr;
108 };
109 
110 const uint8_t PerGraphGOTAndPLTStubsBuilder_ELF_riscv::NullGOTEntryContent[8] =
111     {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
112 
113 const uint8_t
114     PerGraphGOTAndPLTStubsBuilder_ELF_riscv::RV64StubContent[StubEntrySize] = {
115         0x17, 0x0e, 0x00, 0x00,  // auipc t3, literal
116         0x03, 0x3e, 0x0e, 0x00,  // ld    t3, literal(t3)
117         0x67, 0x00, 0x0e, 0x00,  // jr    t3
118         0x13, 0x00, 0x00, 0x00}; // nop
119 
120 const uint8_t
121     PerGraphGOTAndPLTStubsBuilder_ELF_riscv::RV32StubContent[StubEntrySize] = {
122         0x17, 0x0e, 0x00, 0x00,  // auipc t3, literal
123         0x03, 0x2e, 0x0e, 0x00,  // lw    t3, literal(t3)
124         0x67, 0x00, 0x0e, 0x00,  // jr    t3
125         0x13, 0x00, 0x00, 0x00}; // nop
126 } // namespace
127 namespace llvm {
128 namespace jitlink {
129 
130 static Expected<const Edge &> getRISCVPCRelHi20(const Edge &E) {
131   using namespace riscv;
132   assert((E.getKind() == R_RISCV_PCREL_LO12_I ||
133           E.getKind() == R_RISCV_PCREL_LO12_S) &&
134          "Can only have high relocation for R_RISCV_PCREL_LO12_I or "
135          "R_RISCV_PCREL_LO12_S");
136 
137   const Symbol &Sym = E.getTarget();
138   const Block &B = Sym.getBlock();
139   orc::ExecutorAddrDiff Offset = Sym.getOffset();
140 
141   struct Comp {
142     bool operator()(const Edge &Lhs, orc::ExecutorAddrDiff Offset) {
143       return Lhs.getOffset() < Offset;
144     }
145     bool operator()(orc::ExecutorAddrDiff Offset, const Edge &Rhs) {
146       return Offset < Rhs.getOffset();
147     }
148   };
149 
150   auto Bound =
151       std::equal_range(B.edges().begin(), B.edges().end(), Offset, Comp{});
152 
153   for (auto It = Bound.first; It != Bound.second; ++It) {
154     if (It->getKind() == R_RISCV_PCREL_HI20)
155       return *It;
156   }
157 
158   return make_error<JITLinkError>(
159       "No HI20 PCREL relocation type be found for LO12 PCREL relocation type");
160 }
161 
162 static uint32_t extractBits(uint32_t Num, unsigned Low, unsigned Size) {
163   return (Num & (((1ULL << Size) - 1) << Low)) >> Low;
164 }
165 
166 static inline bool isAlignmentCorrect(uint64_t Value, int N) {
167   return (Value & (N - 1)) ? false : true;
168 }
169 
170 // Requires 0 < N <= 64.
171 static inline bool isInRangeForImm(int64_t Value, int N) {
172   return Value == llvm::SignExtend64(Value, N);
173 }
174 
175 class ELFJITLinker_riscv : public JITLinker<ELFJITLinker_riscv> {
176   friend class JITLinker<ELFJITLinker_riscv>;
177 
178 public:
179   ELFJITLinker_riscv(std::unique_ptr<JITLinkContext> Ctx,
180                      std::unique_ptr<LinkGraph> G, PassConfiguration PassConfig)
181       : JITLinker(std::move(Ctx), std::move(G), std::move(PassConfig)) {}
182 
183 private:
184   Error applyFixup(LinkGraph &G, Block &B, const Edge &E) const {
185     using namespace riscv;
186     using namespace llvm::support;
187 
188     char *BlockWorkingMem = B.getAlreadyMutableContent().data();
189     char *FixupPtr = BlockWorkingMem + E.getOffset();
190     orc::ExecutorAddr FixupAddress = B.getAddress() + E.getOffset();
191     switch (E.getKind()) {
192     case R_RISCV_32: {
193       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
194       *(little32_t *)FixupPtr = static_cast<uint32_t>(Value);
195       break;
196     }
197     case R_RISCV_64: {
198       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
199       *(little64_t *)FixupPtr = static_cast<uint64_t>(Value);
200       break;
201     }
202     case R_RISCV_BRANCH: {
203       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
204       if (LLVM_UNLIKELY(!isInRangeForImm(Value >> 1, 12)))
205         return makeTargetOutOfRangeError(G, B, E);
206       if (LLVM_UNLIKELY(!isAlignmentCorrect(Value, 2)))
207         return makeAlignmentError(FixupAddress, Value, 2, E);
208       uint32_t Imm31_25 =
209           extractBits(Value, 5, 6) << 25 | extractBits(Value, 12, 1) << 31;
210       uint32_t Imm11_7 =
211           extractBits(Value, 1, 4) << 8 | extractBits(Value, 11, 1) << 7;
212       uint32_t RawInstr = *(little32_t *)FixupPtr;
213       *(little32_t *)FixupPtr = (RawInstr & 0x1FFF07F) | Imm31_25 | Imm11_7;
214       break;
215     }
216     case R_RISCV_JAL: {
217       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
218       if (LLVM_UNLIKELY(!isInRangeForImm(Value >> 1, 20)))
219         return makeTargetOutOfRangeError(G, B, E);
220       if (LLVM_UNLIKELY(!isAlignmentCorrect(Value, 2)))
221         return makeAlignmentError(FixupAddress, Value, 2, E);
222       uint32_t Imm20 = extractBits(Value, 20, 1) << 31;
223       uint32_t Imm10_1 = extractBits(Value, 1, 10) << 21;
224       uint32_t Imm11 = extractBits(Value, 11, 1) << 20;
225       uint32_t Imm19_12 = extractBits(Value, 12, 8) << 12;
226       uint32_t RawInstr = *(little32_t *)FixupPtr;
227       *(little32_t *)FixupPtr = RawInstr | Imm20 | Imm10_1 | Imm11 | Imm19_12;
228       break;
229     }
230     case R_RISCV_HI20: {
231       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
232       int64_t Hi = Value + 0x800;
233       if (LLVM_UNLIKELY(!isInRangeForImm(Hi, 32)))
234         return makeTargetOutOfRangeError(G, B, E);
235       uint32_t RawInstr = *(little32_t *)FixupPtr;
236       *(little32_t *)FixupPtr =
237           (RawInstr & 0xFFF) | (static_cast<uint32_t>(Hi & 0xFFFFF000));
238       break;
239     }
240     case R_RISCV_LO12_I: {
241       // FIXME: We assume that R_RISCV_HI20 is present in object code and pairs
242       // with current relocation R_RISCV_LO12_I. So here may need a check.
243       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
244       int32_t Lo = Value & 0xFFF;
245       uint32_t RawInstr = *(little32_t *)FixupPtr;
246       *(little32_t *)FixupPtr =
247           (RawInstr & 0xFFFFF) | (static_cast<uint32_t>(Lo & 0xFFF) << 20);
248       break;
249     }
250     case R_RISCV_CALL: {
251       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
252       int64_t Hi = Value + 0x800;
253       if (LLVM_UNLIKELY(!isInRangeForImm(Hi, 32)))
254         return makeTargetOutOfRangeError(G, B, E);
255       int32_t Lo = Value & 0xFFF;
256       uint32_t RawInstrAuipc = *(little32_t *)FixupPtr;
257       uint32_t RawInstrJalr = *(little32_t *)(FixupPtr + 4);
258       *(little32_t *)FixupPtr =
259           RawInstrAuipc | (static_cast<uint32_t>(Hi & 0xFFFFF000));
260       *(little32_t *)(FixupPtr + 4) =
261           RawInstrJalr | (static_cast<uint32_t>(Lo) << 20);
262       break;
263     }
264     case R_RISCV_PCREL_HI20: {
265       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
266       int64_t Hi = Value + 0x800;
267       if (LLVM_UNLIKELY(!isInRangeForImm(Hi, 32)))
268         return makeTargetOutOfRangeError(G, B, E);
269       uint32_t RawInstr = *(little32_t *)FixupPtr;
270       *(little32_t *)FixupPtr =
271           (RawInstr & 0xFFF) | (static_cast<uint32_t>(Hi & 0xFFFFF000));
272       break;
273     }
274     case R_RISCV_PCREL_LO12_I: {
275       // FIXME: We assume that R_RISCV_PCREL_HI20 is present in object code and
276       // pairs with current relocation R_RISCV_PCREL_LO12_I. So here may need a
277       // check.
278       auto RelHI20 = getRISCVPCRelHi20(E);
279       if (!RelHI20)
280         return RelHI20.takeError();
281       int64_t Value = RelHI20->getTarget().getAddress() +
282                       RelHI20->getAddend() - E.getTarget().getAddress();
283       int64_t Lo = Value & 0xFFF;
284       uint32_t RawInstr = *(little32_t *)FixupPtr;
285       *(little32_t *)FixupPtr =
286           (RawInstr & 0xFFFFF) | (static_cast<uint32_t>(Lo & 0xFFF) << 20);
287       break;
288     }
289     case R_RISCV_PCREL_LO12_S: {
290       // FIXME: We assume that R_RISCV_PCREL_HI20 is present in object code and
291       // pairs with current relocation R_RISCV_PCREL_LO12_S. So here may need a
292       // check.
293       auto RelHI20 = getRISCVPCRelHi20(E);
294       int64_t Value = RelHI20->getTarget().getAddress() +
295                       RelHI20->getAddend() - E.getTarget().getAddress();
296       int64_t Lo = Value & 0xFFF;
297       uint32_t Imm31_25 = extractBits(Lo, 5, 7) << 25;
298       uint32_t Imm11_7 = extractBits(Lo, 0, 5) << 7;
299       uint32_t RawInstr = *(little32_t *)FixupPtr;
300 
301       *(little32_t *)FixupPtr = (RawInstr & 0x1FFF07F) | Imm31_25 | Imm11_7;
302       break;
303     }
304     case R_RISCV_ADD64: {
305       int64_t Value = (E.getTarget().getAddress() +
306                        support::endian::read64le(reinterpret_cast<const void *>(
307                            FixupAddress.getValue())) +
308                        E.getAddend())
309                           .getValue();
310       *(little64_t *)FixupPtr = static_cast<uint64_t>(Value);
311       break;
312     }
313     case R_RISCV_ADD32: {
314       int64_t Value = (E.getTarget().getAddress() +
315                        support::endian::read32le(reinterpret_cast<const void *>(
316                            FixupAddress.getValue())) +
317                        E.getAddend())
318                           .getValue();
319       *(little32_t *)FixupPtr = static_cast<uint32_t>(Value);
320       break;
321     }
322     case R_RISCV_ADD16: {
323       int64_t Value = (E.getTarget().getAddress() +
324                        support::endian::read16le(reinterpret_cast<const void *>(
325                            FixupAddress.getValue())) +
326                        E.getAddend())
327                           .getValue();
328       *(little16_t *)FixupPtr = static_cast<uint32_t>(Value);
329       break;
330     }
331     case R_RISCV_ADD8: {
332       int64_t Value =
333           (E.getTarget().getAddress() +
334            *(reinterpret_cast<const uint8_t *>(FixupAddress.getValue())) +
335            E.getAddend())
336               .getValue();
337       *FixupPtr = static_cast<uint8_t>(Value);
338       break;
339     }
340     case R_RISCV_SUB64: {
341       int64_t Value = support::endian::read64le(reinterpret_cast<const void *>(
342                           FixupAddress.getValue())) -
343                       E.getTarget().getAddress().getValue() - E.getAddend();
344       *(little64_t *)FixupPtr = static_cast<uint64_t>(Value);
345       break;
346     }
347     case R_RISCV_SUB32: {
348       int64_t Value = support::endian::read32le(reinterpret_cast<const void *>(
349                           FixupAddress.getValue())) -
350                       E.getTarget().getAddress().getValue() - E.getAddend();
351       *(little32_t *)FixupPtr = static_cast<uint32_t>(Value);
352       break;
353     }
354     case R_RISCV_SUB16: {
355       int64_t Value = support::endian::read16le(reinterpret_cast<const void *>(
356                           FixupAddress.getValue())) -
357                       E.getTarget().getAddress().getValue() - E.getAddend();
358       *(little16_t *)FixupPtr = static_cast<uint32_t>(Value);
359       break;
360     }
361     case R_RISCV_SUB8: {
362       int64_t Value =
363           *(reinterpret_cast<const uint8_t *>(FixupAddress.getValue())) -
364           E.getTarget().getAddress().getValue() - E.getAddend();
365       *FixupPtr = static_cast<uint8_t>(Value);
366       break;
367     }
368     case R_RISCV_SUB6: {
369       int64_t Value =
370           *(reinterpret_cast<const uint8_t *>(FixupAddress.getValue())) & 0x3f;
371       Value -= E.getTarget().getAddress().getValue() - E.getAddend();
372       *FixupPtr = (*FixupPtr & 0xc0) | (static_cast<uint8_t>(Value) & 0x3f);
373       break;
374     }
375     case R_RISCV_SET6: {
376       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
377       uint32_t RawData = *(little32_t *)FixupPtr;
378       int64_t Word6 = Value & 0x3f;
379       *(little32_t *)FixupPtr = (RawData & 0xffffffc0) | Word6;
380       break;
381     }
382     case R_RISCV_SET8: {
383       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
384       uint32_t RawData = *(little32_t *)FixupPtr;
385       int64_t Word8 = Value & 0xff;
386       *(little32_t *)FixupPtr = (RawData & 0xffffff00) | Word8;
387       break;
388     }
389     case R_RISCV_SET16: {
390       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
391       uint32_t RawData = *(little32_t *)FixupPtr;
392       int64_t Word16 = Value & 0xffff;
393       *(little32_t *)FixupPtr = (RawData & 0xffff0000) | Word16;
394       break;
395     }
396     case R_RISCV_SET32: {
397       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
398       int64_t Word32 = Value & 0xffffffff;
399       *(little32_t *)FixupPtr = Word32;
400       break;
401     }
402     case R_RISCV_32_PCREL: {
403       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
404       int64_t Word32 = Value & 0xffffffff;
405       *(little32_t *)FixupPtr = Word32;
406       break;
407     }
408     }
409     return Error::success();
410   }
411 };
412 
413 template <typename ELFT>
414 class ELFLinkGraphBuilder_riscv : public ELFLinkGraphBuilder<ELFT> {
415 private:
416   static Expected<riscv::EdgeKind_riscv>
417   getRelocationKind(const uint32_t Type) {
418     using namespace riscv;
419     switch (Type) {
420     case ELF::R_RISCV_32:
421       return EdgeKind_riscv::R_RISCV_32;
422     case ELF::R_RISCV_64:
423       return EdgeKind_riscv::R_RISCV_64;
424     case ELF::R_RISCV_BRANCH:
425       return EdgeKind_riscv::R_RISCV_BRANCH;
426     case ELF::R_RISCV_JAL:
427       return EdgeKind_riscv::R_RISCV_JAL;
428     case ELF::R_RISCV_HI20:
429       return EdgeKind_riscv::R_RISCV_HI20;
430     case ELF::R_RISCV_LO12_I:
431       return EdgeKind_riscv::R_RISCV_LO12_I;
432     case ELF::R_RISCV_CALL:
433       return EdgeKind_riscv::R_RISCV_CALL;
434     case ELF::R_RISCV_PCREL_HI20:
435       return EdgeKind_riscv::R_RISCV_PCREL_HI20;
436     case ELF::R_RISCV_PCREL_LO12_I:
437       return EdgeKind_riscv::R_RISCV_PCREL_LO12_I;
438     case ELF::R_RISCV_PCREL_LO12_S:
439       return EdgeKind_riscv::R_RISCV_PCREL_LO12_S;
440     case ELF::R_RISCV_GOT_HI20:
441       return EdgeKind_riscv::R_RISCV_GOT_HI20;
442     case ELF::R_RISCV_CALL_PLT:
443       return EdgeKind_riscv::R_RISCV_CALL_PLT;
444     case ELF::R_RISCV_ADD64:
445       return EdgeKind_riscv::R_RISCV_ADD64;
446     case ELF::R_RISCV_ADD32:
447       return EdgeKind_riscv::R_RISCV_ADD32;
448     case ELF::R_RISCV_ADD16:
449       return EdgeKind_riscv::R_RISCV_ADD16;
450     case ELF::R_RISCV_ADD8:
451       return EdgeKind_riscv::R_RISCV_ADD8;
452     case ELF::R_RISCV_SUB64:
453       return EdgeKind_riscv::R_RISCV_SUB64;
454     case ELF::R_RISCV_SUB32:
455       return EdgeKind_riscv::R_RISCV_SUB32;
456     case ELF::R_RISCV_SUB16:
457       return EdgeKind_riscv::R_RISCV_SUB16;
458     case ELF::R_RISCV_SUB8:
459       return EdgeKind_riscv::R_RISCV_SUB8;
460     case ELF::R_RISCV_SUB6:
461       return EdgeKind_riscv::R_RISCV_SUB6;
462     case ELF::R_RISCV_SET6:
463       return EdgeKind_riscv::R_RISCV_SET6;
464     case ELF::R_RISCV_SET8:
465       return EdgeKind_riscv::R_RISCV_SET8;
466     case ELF::R_RISCV_SET16:
467       return EdgeKind_riscv::R_RISCV_SET16;
468     case ELF::R_RISCV_SET32:
469       return EdgeKind_riscv::R_RISCV_SET32;
470     case ELF::R_RISCV_32_PCREL:
471       return EdgeKind_riscv::R_RISCV_32_PCREL;
472     }
473 
474     return make_error<JITLinkError>(
475         "Unsupported riscv relocation:" + formatv("{0:d}: ", Type) +
476         object::getELFRelocationTypeName(ELF::EM_RISCV, Type));
477   }
478 
479   Error addRelocations() override {
480     LLVM_DEBUG(dbgs() << "Processing relocations:\n");
481 
482     using Base = ELFLinkGraphBuilder<ELFT>;
483     using Self = ELFLinkGraphBuilder_riscv<ELFT>;
484     for (const auto &RelSect : Base::Sections)
485       if (Error Err = Base::forEachRelocation(RelSect, this,
486                                               &Self::addSingleRelocation))
487         return Err;
488 
489     return Error::success();
490   }
491 
492   Error addSingleRelocation(const typename ELFT::Rela &Rel,
493                             const typename ELFT::Shdr &FixupSect,
494                             Block &BlockToFix) {
495     using Base = ELFLinkGraphBuilder<ELFT>;
496 
497     uint32_t Type = Rel.getType(false);
498     // We do not implement linker relaxation, except what is required for
499     // alignment (see below).
500     if (Type == llvm::ELF::R_RISCV_RELAX)
501       return Error::success();
502 
503     int64_t Addend = Rel.r_addend;
504     if (Type == llvm::ELF::R_RISCV_ALIGN) {
505       uint64_t Alignment = PowerOf2Ceil(Addend);
506       // FIXME: Implement support for ensuring alignment together with linker
507       // relaxation; 2 bytes are guaranteed by the length of compressed
508       // instructions, so this does not need any action from our side.
509       if (Alignment > 2)
510         return make_error<JITLinkError>(
511             formatv("Unsupported relocation R_RISCV_ALIGN with alignment {0} "
512                     "larger than 2 (addend: {1})",
513                     Alignment, Addend));
514       return Error::success();
515     }
516 
517     Expected<riscv::EdgeKind_riscv> Kind = getRelocationKind(Type);
518     if (!Kind)
519       return Kind.takeError();
520 
521     uint32_t SymbolIndex = Rel.getSymbol(false);
522     auto ObjSymbol = Base::Obj.getRelocationSymbol(Rel, Base::SymTabSec);
523     if (!ObjSymbol)
524       return ObjSymbol.takeError();
525 
526     Symbol *GraphSymbol = Base::getGraphSymbol(SymbolIndex);
527     if (!GraphSymbol)
528       return make_error<StringError>(
529           formatv("Could not find symbol at given index, did you add it to "
530                   "JITSymbolTable? index: {0}, shndx: {1} Size of table: {2}",
531                   SymbolIndex, (*ObjSymbol)->st_shndx,
532                   Base::GraphSymbols.size()),
533           inconvertibleErrorCode());
534 
535     auto FixupAddress = orc::ExecutorAddr(FixupSect.sh_addr) + Rel.r_offset;
536     Edge::OffsetT Offset = FixupAddress - BlockToFix.getAddress();
537     Edge GE(*Kind, Offset, *GraphSymbol, Addend);
538     LLVM_DEBUG({
539       dbgs() << "    ";
540       printEdge(dbgs(), BlockToFix, GE, riscv::getEdgeKindName(*Kind));
541       dbgs() << "\n";
542     });
543 
544     BlockToFix.addEdge(std::move(GE));
545     return Error::success();
546   }
547 
548 public:
549   ELFLinkGraphBuilder_riscv(StringRef FileName,
550                             const object::ELFFile<ELFT> &Obj, const Triple T)
551       : ELFLinkGraphBuilder<ELFT>(Obj, std::move(T), FileName,
552                                   riscv::getEdgeKindName) {}
553 };
554 
555 Expected<std::unique_ptr<LinkGraph>>
556 createLinkGraphFromELFObject_riscv(MemoryBufferRef ObjectBuffer) {
557   LLVM_DEBUG({
558     dbgs() << "Building jitlink graph for new input "
559            << ObjectBuffer.getBufferIdentifier() << "...\n";
560   });
561 
562   auto ELFObj = object::ObjectFile::createELFObjectFile(ObjectBuffer);
563   if (!ELFObj)
564     return ELFObj.takeError();
565 
566   if ((*ELFObj)->getArch() == Triple::riscv64) {
567     auto &ELFObjFile = cast<object::ELFObjectFile<object::ELF64LE>>(**ELFObj);
568     return ELFLinkGraphBuilder_riscv<object::ELF64LE>(
569                (*ELFObj)->getFileName(), ELFObjFile.getELFFile(),
570                (*ELFObj)->makeTriple())
571         .buildGraph();
572   } else {
573     assert((*ELFObj)->getArch() == Triple::riscv32 &&
574            "Invalid triple for RISCV ELF object file");
575     auto &ELFObjFile = cast<object::ELFObjectFile<object::ELF32LE>>(**ELFObj);
576     return ELFLinkGraphBuilder_riscv<object::ELF32LE>(
577                (*ELFObj)->getFileName(), ELFObjFile.getELFFile(),
578                (*ELFObj)->makeTriple())
579         .buildGraph();
580   }
581 }
582 
583 void link_ELF_riscv(std::unique_ptr<LinkGraph> G,
584                     std::unique_ptr<JITLinkContext> Ctx) {
585   PassConfiguration Config;
586   const Triple &TT = G->getTargetTriple();
587   if (Ctx->shouldAddDefaultTargetPasses(TT)) {
588     if (auto MarkLive = Ctx->getMarkLivePass(TT))
589       Config.PrePrunePasses.push_back(std::move(MarkLive));
590     else
591       Config.PrePrunePasses.push_back(markAllSymbolsLive);
592     Config.PostPrunePasses.push_back(
593         PerGraphGOTAndPLTStubsBuilder_ELF_riscv::asPass);
594   }
595   if (auto Err = Ctx->modifyPassConfig(*G, Config))
596     return Ctx->notifyFailed(std::move(Err));
597 
598   ELFJITLinker_riscv::link(std::move(Ctx), std::move(G), std::move(Config));
599 }
600 
601 } // namespace jitlink
602 } // namespace llvm
603