1fe6060f1SDimitry Andric //===------- ELF_riscv.cpp -JIT linker implementation for ELF/riscv -------===//
2fe6060f1SDimitry Andric //
3fe6060f1SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4fe6060f1SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5fe6060f1SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6fe6060f1SDimitry Andric //
7fe6060f1SDimitry Andric //===----------------------------------------------------------------------===//
8fe6060f1SDimitry Andric //
9fe6060f1SDimitry Andric // ELF/riscv jit-link implementation.
10fe6060f1SDimitry Andric //
11fe6060f1SDimitry Andric //===----------------------------------------------------------------------===//
12fe6060f1SDimitry Andric 
13fe6060f1SDimitry Andric #include "llvm/ExecutionEngine/JITLink/ELF_riscv.h"
14*5f757f3fSDimitry Andric #include "EHFrameSupportImpl.h"
15349cc55cSDimitry Andric #include "ELFLinkGraphBuilder.h"
16349cc55cSDimitry Andric #include "JITLinkGeneric.h"
17349cc55cSDimitry Andric #include "PerGraphGOTAndPLTStubsBuilder.h"
18349cc55cSDimitry Andric #include "llvm/BinaryFormat/ELF.h"
19*5f757f3fSDimitry Andric #include "llvm/ExecutionEngine/JITLink/DWARFRecordSectionSplitter.h"
20fe6060f1SDimitry Andric #include "llvm/ExecutionEngine/JITLink/JITLink.h"
21fe6060f1SDimitry Andric #include "llvm/ExecutionEngine/JITLink/riscv.h"
22fe6060f1SDimitry Andric #include "llvm/Object/ELF.h"
23fe6060f1SDimitry Andric #include "llvm/Object/ELFObjectFile.h"
2404eeddc0SDimitry Andric #include "llvm/Support/Endian.h"
25fe6060f1SDimitry Andric 
26fe6060f1SDimitry Andric #define DEBUG_TYPE "jitlink"
27fe6060f1SDimitry Andric using namespace llvm;
28349cc55cSDimitry Andric using namespace llvm::jitlink;
29349cc55cSDimitry Andric using namespace llvm::jitlink::riscv;
30fe6060f1SDimitry Andric 
31349cc55cSDimitry Andric namespace {
32349cc55cSDimitry Andric 
33349cc55cSDimitry Andric class PerGraphGOTAndPLTStubsBuilder_ELF_riscv
34349cc55cSDimitry Andric     : public PerGraphGOTAndPLTStubsBuilder<
35349cc55cSDimitry Andric           PerGraphGOTAndPLTStubsBuilder_ELF_riscv> {
36349cc55cSDimitry Andric public:
37349cc55cSDimitry Andric   static constexpr size_t StubEntrySize = 16;
38349cc55cSDimitry Andric   static const uint8_t NullGOTEntryContent[8];
39349cc55cSDimitry Andric   static const uint8_t RV64StubContent[StubEntrySize];
40349cc55cSDimitry Andric   static const uint8_t RV32StubContent[StubEntrySize];
41349cc55cSDimitry Andric 
42349cc55cSDimitry Andric   using PerGraphGOTAndPLTStubsBuilder<
43349cc55cSDimitry Andric       PerGraphGOTAndPLTStubsBuilder_ELF_riscv>::PerGraphGOTAndPLTStubsBuilder;
44349cc55cSDimitry Andric 
isRV64() const45349cc55cSDimitry Andric   bool isRV64() const { return G.getPointerSize() == 8; }
46349cc55cSDimitry Andric 
isGOTEdgeToFix(Edge & E) const47349cc55cSDimitry Andric   bool isGOTEdgeToFix(Edge &E) const { return E.getKind() == R_RISCV_GOT_HI20; }
48349cc55cSDimitry Andric 
createGOTEntry(Symbol & Target)49349cc55cSDimitry Andric   Symbol &createGOTEntry(Symbol &Target) {
5004eeddc0SDimitry Andric     Block &GOTBlock =
5104eeddc0SDimitry Andric         G.createContentBlock(getGOTSection(), getGOTEntryBlockContent(),
5204eeddc0SDimitry Andric                              orc::ExecutorAddr(), G.getPointerSize(), 0);
53349cc55cSDimitry Andric     GOTBlock.addEdge(isRV64() ? R_RISCV_64 : R_RISCV_32, 0, Target, 0);
54349cc55cSDimitry Andric     return G.addAnonymousSymbol(GOTBlock, 0, G.getPointerSize(), false, false);
55349cc55cSDimitry Andric   }
56349cc55cSDimitry Andric 
createPLTStub(Symbol & Target)57349cc55cSDimitry Andric   Symbol &createPLTStub(Symbol &Target) {
5804eeddc0SDimitry Andric     Block &StubContentBlock = G.createContentBlock(
5904eeddc0SDimitry Andric         getStubsSection(), getStubBlockContent(), orc::ExecutorAddr(), 4, 0);
60349cc55cSDimitry Andric     auto &GOTEntrySymbol = getGOTEntry(Target);
61349cc55cSDimitry Andric     StubContentBlock.addEdge(R_RISCV_CALL, 0, GOTEntrySymbol, 0);
62349cc55cSDimitry Andric     return G.addAnonymousSymbol(StubContentBlock, 0, StubEntrySize, true,
63349cc55cSDimitry Andric                                 false);
64349cc55cSDimitry Andric   }
65349cc55cSDimitry Andric 
fixGOTEdge(Edge & E,Symbol & GOTEntry)66349cc55cSDimitry Andric   void fixGOTEdge(Edge &E, Symbol &GOTEntry) {
67349cc55cSDimitry Andric     // Replace the relocation pair (R_RISCV_GOT_HI20, R_RISCV_PCREL_LO12)
68349cc55cSDimitry Andric     // with (R_RISCV_PCREL_HI20, R_RISCV_PCREL_LO12)
69349cc55cSDimitry Andric     // Therefore, here just change the R_RISCV_GOT_HI20 to R_RISCV_PCREL_HI20
70349cc55cSDimitry Andric     E.setKind(R_RISCV_PCREL_HI20);
71349cc55cSDimitry Andric     E.setTarget(GOTEntry);
72349cc55cSDimitry Andric   }
73349cc55cSDimitry Andric 
fixPLTEdge(Edge & E,Symbol & PLTStubs)74349cc55cSDimitry Andric   void fixPLTEdge(Edge &E, Symbol &PLTStubs) {
7506c3fb27SDimitry Andric     assert((E.getKind() == R_RISCV_CALL || E.getKind() == R_RISCV_CALL_PLT ||
7606c3fb27SDimitry Andric             E.getKind() == CallRelaxable) &&
7706c3fb27SDimitry Andric            "Not a PLT edge?");
78349cc55cSDimitry Andric     E.setKind(R_RISCV_CALL);
79349cc55cSDimitry Andric     E.setTarget(PLTStubs);
80349cc55cSDimitry Andric   }
81349cc55cSDimitry Andric 
isExternalBranchEdge(Edge & E) const82349cc55cSDimitry Andric   bool isExternalBranchEdge(Edge &E) const {
8306c3fb27SDimitry Andric     return (E.getKind() == R_RISCV_CALL || E.getKind() == R_RISCV_CALL_PLT ||
8406c3fb27SDimitry Andric             E.getKind() == CallRelaxable) &&
8506c3fb27SDimitry Andric            !E.getTarget().isDefined();
86349cc55cSDimitry Andric   }
87349cc55cSDimitry Andric 
88349cc55cSDimitry Andric private:
getGOTSection() const89349cc55cSDimitry Andric   Section &getGOTSection() const {
90349cc55cSDimitry Andric     if (!GOTSection)
91bdd1243dSDimitry Andric       GOTSection = &G.createSection("$__GOT", orc::MemProt::Read);
92349cc55cSDimitry Andric     return *GOTSection;
93349cc55cSDimitry Andric   }
94349cc55cSDimitry Andric 
getStubsSection() const95349cc55cSDimitry Andric   Section &getStubsSection() const {
96349cc55cSDimitry Andric     if (!StubsSection)
97349cc55cSDimitry Andric       StubsSection =
98bdd1243dSDimitry Andric           &G.createSection("$__STUBS", orc::MemProt::Read | orc::MemProt::Exec);
99349cc55cSDimitry Andric     return *StubsSection;
100349cc55cSDimitry Andric   }
101349cc55cSDimitry Andric 
getGOTEntryBlockContent()102349cc55cSDimitry Andric   ArrayRef<char> getGOTEntryBlockContent() {
103349cc55cSDimitry Andric     return {reinterpret_cast<const char *>(NullGOTEntryContent),
104349cc55cSDimitry Andric             G.getPointerSize()};
105349cc55cSDimitry Andric   }
106349cc55cSDimitry Andric 
getStubBlockContent()107349cc55cSDimitry Andric   ArrayRef<char> getStubBlockContent() {
108349cc55cSDimitry Andric     auto StubContent = isRV64() ? RV64StubContent : RV32StubContent;
109349cc55cSDimitry Andric     return {reinterpret_cast<const char *>(StubContent), StubEntrySize};
110349cc55cSDimitry Andric   }
111349cc55cSDimitry Andric 
112349cc55cSDimitry Andric   mutable Section *GOTSection = nullptr;
113349cc55cSDimitry Andric   mutable Section *StubsSection = nullptr;
114349cc55cSDimitry Andric };
115349cc55cSDimitry Andric 
116349cc55cSDimitry Andric const uint8_t PerGraphGOTAndPLTStubsBuilder_ELF_riscv::NullGOTEntryContent[8] =
117349cc55cSDimitry Andric     {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
118349cc55cSDimitry Andric 
119349cc55cSDimitry Andric const uint8_t
120349cc55cSDimitry Andric     PerGraphGOTAndPLTStubsBuilder_ELF_riscv::RV64StubContent[StubEntrySize] = {
121349cc55cSDimitry Andric         0x17, 0x0e, 0x00, 0x00,  // auipc t3, literal
122349cc55cSDimitry Andric         0x03, 0x3e, 0x0e, 0x00,  // ld    t3, literal(t3)
123349cc55cSDimitry Andric         0x67, 0x00, 0x0e, 0x00,  // jr    t3
124349cc55cSDimitry Andric         0x13, 0x00, 0x00, 0x00}; // nop
125349cc55cSDimitry Andric 
126349cc55cSDimitry Andric const uint8_t
127349cc55cSDimitry Andric     PerGraphGOTAndPLTStubsBuilder_ELF_riscv::RV32StubContent[StubEntrySize] = {
128349cc55cSDimitry Andric         0x17, 0x0e, 0x00, 0x00,  // auipc t3, literal
129349cc55cSDimitry Andric         0x03, 0x2e, 0x0e, 0x00,  // lw    t3, literal(t3)
130349cc55cSDimitry Andric         0x67, 0x00, 0x0e, 0x00,  // jr    t3
131349cc55cSDimitry Andric         0x13, 0x00, 0x00, 0x00}; // nop
132349cc55cSDimitry Andric } // namespace
133fe6060f1SDimitry Andric namespace llvm {
134fe6060f1SDimitry Andric namespace jitlink {
135fe6060f1SDimitry Andric 
getRISCVPCRelHi20(const Edge & E)136fe6060f1SDimitry Andric static Expected<const Edge &> getRISCVPCRelHi20(const Edge &E) {
137fe6060f1SDimitry Andric   using namespace riscv;
138fe6060f1SDimitry Andric   assert((E.getKind() == R_RISCV_PCREL_LO12_I ||
139fe6060f1SDimitry Andric           E.getKind() == R_RISCV_PCREL_LO12_S) &&
140fe6060f1SDimitry Andric          "Can only have high relocation for R_RISCV_PCREL_LO12_I or "
141fe6060f1SDimitry Andric          "R_RISCV_PCREL_LO12_S");
142fe6060f1SDimitry Andric 
143fe6060f1SDimitry Andric   const Symbol &Sym = E.getTarget();
144fe6060f1SDimitry Andric   const Block &B = Sym.getBlock();
14504eeddc0SDimitry Andric   orc::ExecutorAddrDiff Offset = Sym.getOffset();
146fe6060f1SDimitry Andric 
147fe6060f1SDimitry Andric   struct Comp {
14804eeddc0SDimitry Andric     bool operator()(const Edge &Lhs, orc::ExecutorAddrDiff Offset) {
149fe6060f1SDimitry Andric       return Lhs.getOffset() < Offset;
150fe6060f1SDimitry Andric     }
15104eeddc0SDimitry Andric     bool operator()(orc::ExecutorAddrDiff Offset, const Edge &Rhs) {
152fe6060f1SDimitry Andric       return Offset < Rhs.getOffset();
153fe6060f1SDimitry Andric     }
154fe6060f1SDimitry Andric   };
155fe6060f1SDimitry Andric 
156fe6060f1SDimitry Andric   auto Bound =
157fe6060f1SDimitry Andric       std::equal_range(B.edges().begin(), B.edges().end(), Offset, Comp{});
158fe6060f1SDimitry Andric 
159fe6060f1SDimitry Andric   for (auto It = Bound.first; It != Bound.second; ++It) {
160fe6060f1SDimitry Andric     if (It->getKind() == R_RISCV_PCREL_HI20)
161fe6060f1SDimitry Andric       return *It;
162fe6060f1SDimitry Andric   }
163fe6060f1SDimitry Andric 
164fe6060f1SDimitry Andric   return make_error<JITLinkError>(
165fe6060f1SDimitry Andric       "No HI20 PCREL relocation type be found for LO12 PCREL relocation type");
166fe6060f1SDimitry Andric }
167fe6060f1SDimitry Andric 
extractBits(uint32_t Num,unsigned Low,unsigned Size)16804eeddc0SDimitry Andric static uint32_t extractBits(uint32_t Num, unsigned Low, unsigned Size) {
16981ad6265SDimitry Andric   return (Num & (((1ULL << Size) - 1) << Low)) >> Low;
17004eeddc0SDimitry Andric }
17104eeddc0SDimitry Andric 
isAlignmentCorrect(uint64_t Value,int N)17281ad6265SDimitry Andric static inline bool isAlignmentCorrect(uint64_t Value, int N) {
17381ad6265SDimitry Andric   return (Value & (N - 1)) ? false : true;
17404eeddc0SDimitry Andric }
17504eeddc0SDimitry Andric 
17681ad6265SDimitry Andric // Requires 0 < N <= 64.
isInRangeForImm(int64_t Value,int N)17781ad6265SDimitry Andric static inline bool isInRangeForImm(int64_t Value, int N) {
17881ad6265SDimitry Andric   return Value == llvm::SignExtend64(Value, N);
179fe6060f1SDimitry Andric }
180fe6060f1SDimitry Andric 
181fe6060f1SDimitry Andric class ELFJITLinker_riscv : public JITLinker<ELFJITLinker_riscv> {
182fe6060f1SDimitry Andric   friend class JITLinker<ELFJITLinker_riscv>;
183fe6060f1SDimitry Andric 
184fe6060f1SDimitry Andric public:
ELFJITLinker_riscv(std::unique_ptr<JITLinkContext> Ctx,std::unique_ptr<LinkGraph> G,PassConfiguration PassConfig)185fe6060f1SDimitry Andric   ELFJITLinker_riscv(std::unique_ptr<JITLinkContext> Ctx,
186fe6060f1SDimitry Andric                      std::unique_ptr<LinkGraph> G, PassConfiguration PassConfig)
187fe6060f1SDimitry Andric       : JITLinker(std::move(Ctx), std::move(G), std::move(PassConfig)) {}
188fe6060f1SDimitry Andric 
189fe6060f1SDimitry Andric private:
applyFixup(LinkGraph & G,Block & B,const Edge & E) const190fe6060f1SDimitry Andric   Error applyFixup(LinkGraph &G, Block &B, const Edge &E) const {
191fe6060f1SDimitry Andric     using namespace riscv;
192fe6060f1SDimitry Andric     using namespace llvm::support;
193fe6060f1SDimitry Andric 
194fe6060f1SDimitry Andric     char *BlockWorkingMem = B.getAlreadyMutableContent().data();
195fe6060f1SDimitry Andric     char *FixupPtr = BlockWorkingMem + E.getOffset();
19604eeddc0SDimitry Andric     orc::ExecutorAddr FixupAddress = B.getAddress() + E.getOffset();
197fe6060f1SDimitry Andric     switch (E.getKind()) {
198349cc55cSDimitry Andric     case R_RISCV_32: {
19904eeddc0SDimitry Andric       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
200349cc55cSDimitry Andric       *(little32_t *)FixupPtr = static_cast<uint32_t>(Value);
201349cc55cSDimitry Andric       break;
202349cc55cSDimitry Andric     }
203349cc55cSDimitry Andric     case R_RISCV_64: {
20404eeddc0SDimitry Andric       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
205349cc55cSDimitry Andric       *(little64_t *)FixupPtr = static_cast<uint64_t>(Value);
206349cc55cSDimitry Andric       break;
207349cc55cSDimitry Andric     }
20804eeddc0SDimitry Andric     case R_RISCV_BRANCH: {
20904eeddc0SDimitry Andric       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
21081ad6265SDimitry Andric       if (LLVM_UNLIKELY(!isInRangeForImm(Value >> 1, 12)))
21181ad6265SDimitry Andric         return makeTargetOutOfRangeError(G, B, E);
21281ad6265SDimitry Andric       if (LLVM_UNLIKELY(!isAlignmentCorrect(Value, 2)))
21381ad6265SDimitry Andric         return makeAlignmentError(FixupAddress, Value, 2, E);
214bdd1243dSDimitry Andric       uint32_t Imm12 = extractBits(Value, 12, 1) << 31;
215bdd1243dSDimitry Andric       uint32_t Imm10_5 = extractBits(Value, 5, 6) << 25;
216bdd1243dSDimitry Andric       uint32_t Imm4_1 = extractBits(Value, 1, 4) << 8;
217bdd1243dSDimitry Andric       uint32_t Imm11 = extractBits(Value, 11, 1) << 7;
218fe6060f1SDimitry Andric       uint32_t RawInstr = *(little32_t *)FixupPtr;
219bdd1243dSDimitry Andric       *(little32_t *)FixupPtr =
220bdd1243dSDimitry Andric           (RawInstr & 0x1FFF07F) | Imm12 | Imm10_5 | Imm4_1 | Imm11;
22104eeddc0SDimitry Andric       break;
22204eeddc0SDimitry Andric     }
22381ad6265SDimitry Andric     case R_RISCV_JAL: {
22481ad6265SDimitry Andric       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
22581ad6265SDimitry Andric       if (LLVM_UNLIKELY(!isInRangeForImm(Value >> 1, 20)))
22681ad6265SDimitry Andric         return makeTargetOutOfRangeError(G, B, E);
22781ad6265SDimitry Andric       if (LLVM_UNLIKELY(!isAlignmentCorrect(Value, 2)))
22881ad6265SDimitry Andric         return makeAlignmentError(FixupAddress, Value, 2, E);
22981ad6265SDimitry Andric       uint32_t Imm20 = extractBits(Value, 20, 1) << 31;
23081ad6265SDimitry Andric       uint32_t Imm10_1 = extractBits(Value, 1, 10) << 21;
23181ad6265SDimitry Andric       uint32_t Imm11 = extractBits(Value, 11, 1) << 20;
23281ad6265SDimitry Andric       uint32_t Imm19_12 = extractBits(Value, 12, 8) << 12;
23381ad6265SDimitry Andric       uint32_t RawInstr = *(little32_t *)FixupPtr;
23404eeddc0SDimitry Andric       *(little32_t *)FixupPtr =
235bdd1243dSDimitry Andric           (RawInstr & 0xFFF) | Imm20 | Imm10_1 | Imm11 | Imm19_12;
236fe6060f1SDimitry Andric       break;
237fe6060f1SDimitry Andric     }
23806c3fb27SDimitry Andric     case CallRelaxable:
23906c3fb27SDimitry Andric       // Treat as R_RISCV_CALL when the relaxation pass did not run
24006c3fb27SDimitry Andric     case R_RISCV_CALL_PLT:
241fe6060f1SDimitry Andric     case R_RISCV_CALL: {
242fe6060f1SDimitry Andric       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
24304eeddc0SDimitry Andric       int64_t Hi = Value + 0x800;
24481ad6265SDimitry Andric       if (LLVM_UNLIKELY(!isInRangeForImm(Hi, 32)))
24504eeddc0SDimitry Andric         return makeTargetOutOfRangeError(G, B, E);
246fe6060f1SDimitry Andric       int32_t Lo = Value & 0xFFF;
247fe6060f1SDimitry Andric       uint32_t RawInstrAuipc = *(little32_t *)FixupPtr;
248fe6060f1SDimitry Andric       uint32_t RawInstrJalr = *(little32_t *)(FixupPtr + 4);
24904eeddc0SDimitry Andric       *(little32_t *)FixupPtr =
25004eeddc0SDimitry Andric           RawInstrAuipc | (static_cast<uint32_t>(Hi & 0xFFFFF000));
251fe6060f1SDimitry Andric       *(little32_t *)(FixupPtr + 4) =
252fe6060f1SDimitry Andric           RawInstrJalr | (static_cast<uint32_t>(Lo) << 20);
253fe6060f1SDimitry Andric       break;
254fe6060f1SDimitry Andric     }
255bdd1243dSDimitry Andric     // The relocations R_RISCV_CALL_PLT and R_RISCV_GOT_HI20 are handled by
256bdd1243dSDimitry Andric     // PerGraphGOTAndPLTStubsBuilder_ELF_riscv and are transformed into
257bdd1243dSDimitry Andric     // R_RISCV_CALL and R_RISCV_PCREL_HI20.
258fe6060f1SDimitry Andric     case R_RISCV_PCREL_HI20: {
259fe6060f1SDimitry Andric       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
26004eeddc0SDimitry Andric       int64_t Hi = Value + 0x800;
26181ad6265SDimitry Andric       if (LLVM_UNLIKELY(!isInRangeForImm(Hi, 32)))
26204eeddc0SDimitry Andric         return makeTargetOutOfRangeError(G, B, E);
263fe6060f1SDimitry Andric       uint32_t RawInstr = *(little32_t *)FixupPtr;
26404eeddc0SDimitry Andric       *(little32_t *)FixupPtr =
26504eeddc0SDimitry Andric           (RawInstr & 0xFFF) | (static_cast<uint32_t>(Hi & 0xFFFFF000));
266fe6060f1SDimitry Andric       break;
267fe6060f1SDimitry Andric     }
268fe6060f1SDimitry Andric     case R_RISCV_PCREL_LO12_I: {
26904eeddc0SDimitry Andric       // FIXME: We assume that R_RISCV_PCREL_HI20 is present in object code and
27004eeddc0SDimitry Andric       // pairs with current relocation R_RISCV_PCREL_LO12_I. So here may need a
27104eeddc0SDimitry Andric       // check.
272fe6060f1SDimitry Andric       auto RelHI20 = getRISCVPCRelHi20(E);
273fe6060f1SDimitry Andric       if (!RelHI20)
274fe6060f1SDimitry Andric         return RelHI20.takeError();
275fe6060f1SDimitry Andric       int64_t Value = RelHI20->getTarget().getAddress() +
276fe6060f1SDimitry Andric                       RelHI20->getAddend() - E.getTarget().getAddress();
277fe6060f1SDimitry Andric       int64_t Lo = Value & 0xFFF;
278fe6060f1SDimitry Andric       uint32_t RawInstr = *(little32_t *)FixupPtr;
279fe6060f1SDimitry Andric       *(little32_t *)FixupPtr =
280fe6060f1SDimitry Andric           (RawInstr & 0xFFFFF) | (static_cast<uint32_t>(Lo & 0xFFF) << 20);
281fe6060f1SDimitry Andric       break;
282fe6060f1SDimitry Andric     }
283fe6060f1SDimitry Andric     case R_RISCV_PCREL_LO12_S: {
28404eeddc0SDimitry Andric       // FIXME: We assume that R_RISCV_PCREL_HI20 is present in object code and
28504eeddc0SDimitry Andric       // pairs with current relocation R_RISCV_PCREL_LO12_S. So here may need a
28604eeddc0SDimitry Andric       // check.
287fe6060f1SDimitry Andric       auto RelHI20 = getRISCVPCRelHi20(E);
288bdd1243dSDimitry Andric       if (!RelHI20)
289bdd1243dSDimitry Andric         return RelHI20.takeError();
290fe6060f1SDimitry Andric       int64_t Value = RelHI20->getTarget().getAddress() +
291fe6060f1SDimitry Andric                       RelHI20->getAddend() - E.getTarget().getAddress();
292fe6060f1SDimitry Andric       int64_t Lo = Value & 0xFFF;
293bdd1243dSDimitry Andric       uint32_t Imm11_5 = extractBits(Lo, 5, 7) << 25;
294bdd1243dSDimitry Andric       uint32_t Imm4_0 = extractBits(Lo, 0, 5) << 7;
295fe6060f1SDimitry Andric       uint32_t RawInstr = *(little32_t *)FixupPtr;
296fe6060f1SDimitry Andric 
297bdd1243dSDimitry Andric       *(little32_t *)FixupPtr = (RawInstr & 0x1FFF07F) | Imm11_5 | Imm4_0;
298fe6060f1SDimitry Andric       break;
299fe6060f1SDimitry Andric     }
300bdd1243dSDimitry Andric     case R_RISCV_HI20: {
301bdd1243dSDimitry Andric       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
302bdd1243dSDimitry Andric       int64_t Hi = Value + 0x800;
303bdd1243dSDimitry Andric       if (LLVM_UNLIKELY(!isInRangeForImm(Hi, 32)))
304bdd1243dSDimitry Andric         return makeTargetOutOfRangeError(G, B, E);
305bdd1243dSDimitry Andric       uint32_t RawInstr = *(little32_t *)FixupPtr;
306bdd1243dSDimitry Andric       *(little32_t *)FixupPtr =
307bdd1243dSDimitry Andric           (RawInstr & 0xFFF) | (static_cast<uint32_t>(Hi & 0xFFFFF000));
30804eeddc0SDimitry Andric       break;
30904eeddc0SDimitry Andric     }
310bdd1243dSDimitry Andric     case R_RISCV_LO12_I: {
311bdd1243dSDimitry Andric       // FIXME: We assume that R_RISCV_HI20 is present in object code and pairs
312bdd1243dSDimitry Andric       // with current relocation R_RISCV_LO12_I. So here may need a check.
313bdd1243dSDimitry Andric       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
314bdd1243dSDimitry Andric       int32_t Lo = Value & 0xFFF;
315bdd1243dSDimitry Andric       uint32_t RawInstr = *(little32_t *)FixupPtr;
316bdd1243dSDimitry Andric       *(little32_t *)FixupPtr =
317bdd1243dSDimitry Andric           (RawInstr & 0xFFFFF) | (static_cast<uint32_t>(Lo & 0xFFF) << 20);
31804eeddc0SDimitry Andric       break;
31904eeddc0SDimitry Andric     }
320bdd1243dSDimitry Andric     case R_RISCV_LO12_S: {
321bdd1243dSDimitry Andric       // FIXME: We assume that R_RISCV_HI20 is present in object code and pairs
322bdd1243dSDimitry Andric       // with current relocation R_RISCV_LO12_S. So here may need a check.
323bdd1243dSDimitry Andric       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
324bdd1243dSDimitry Andric       int64_t Lo = Value & 0xFFF;
325bdd1243dSDimitry Andric       uint32_t Imm11_5 = extractBits(Lo, 5, 7) << 25;
326bdd1243dSDimitry Andric       uint32_t Imm4_0 = extractBits(Lo, 0, 5) << 7;
327bdd1243dSDimitry Andric       uint32_t RawInstr = *(little32_t *)FixupPtr;
328bdd1243dSDimitry Andric       *(little32_t *)FixupPtr = (RawInstr & 0x1FFF07F) | Imm11_5 | Imm4_0;
32904eeddc0SDimitry Andric       break;
33004eeddc0SDimitry Andric     }
33104eeddc0SDimitry Andric     case R_RISCV_ADD8: {
33204eeddc0SDimitry Andric       int64_t Value =
33304eeddc0SDimitry Andric           (E.getTarget().getAddress() +
33406c3fb27SDimitry Andric            *(reinterpret_cast<const uint8_t *>(FixupPtr)) + E.getAddend())
33504eeddc0SDimitry Andric               .getValue();
33604eeddc0SDimitry Andric       *FixupPtr = static_cast<uint8_t>(Value);
33704eeddc0SDimitry Andric       break;
33804eeddc0SDimitry Andric     }
339bdd1243dSDimitry Andric     case R_RISCV_ADD16: {
340bdd1243dSDimitry Andric       int64_t Value = (E.getTarget().getAddress() +
34106c3fb27SDimitry Andric                        support::endian::read16le(FixupPtr) + E.getAddend())
342bdd1243dSDimitry Andric                           .getValue();
343bdd1243dSDimitry Andric       *(little16_t *)FixupPtr = static_cast<uint16_t>(Value);
344bdd1243dSDimitry Andric       break;
345bdd1243dSDimitry Andric     }
346bdd1243dSDimitry Andric     case R_RISCV_ADD32: {
347bdd1243dSDimitry Andric       int64_t Value = (E.getTarget().getAddress() +
34806c3fb27SDimitry Andric                        support::endian::read32le(FixupPtr) + E.getAddend())
349bdd1243dSDimitry Andric                           .getValue();
350bdd1243dSDimitry Andric       *(little32_t *)FixupPtr = static_cast<uint32_t>(Value);
351bdd1243dSDimitry Andric       break;
352bdd1243dSDimitry Andric     }
353bdd1243dSDimitry Andric     case R_RISCV_ADD64: {
354bdd1243dSDimitry Andric       int64_t Value = (E.getTarget().getAddress() +
35506c3fb27SDimitry Andric                        support::endian::read64le(FixupPtr) + E.getAddend())
356bdd1243dSDimitry Andric                           .getValue();
35704eeddc0SDimitry Andric       *(little64_t *)FixupPtr = static_cast<uint64_t>(Value);
35804eeddc0SDimitry Andric       break;
35904eeddc0SDimitry Andric     }
360bdd1243dSDimitry Andric     case R_RISCV_SUB8: {
36106c3fb27SDimitry Andric       int64_t Value = *(reinterpret_cast<const uint8_t *>(FixupPtr)) -
36204eeddc0SDimitry Andric                       E.getTarget().getAddress().getValue() - E.getAddend();
363bdd1243dSDimitry Andric       *FixupPtr = static_cast<uint8_t>(Value);
36404eeddc0SDimitry Andric       break;
36504eeddc0SDimitry Andric     }
36604eeddc0SDimitry Andric     case R_RISCV_SUB16: {
36706c3fb27SDimitry Andric       int64_t Value = support::endian::read16le(FixupPtr) -
36804eeddc0SDimitry Andric                       E.getTarget().getAddress().getValue() - E.getAddend();
36904eeddc0SDimitry Andric       *(little16_t *)FixupPtr = static_cast<uint32_t>(Value);
37004eeddc0SDimitry Andric       break;
37104eeddc0SDimitry Andric     }
372bdd1243dSDimitry Andric     case R_RISCV_SUB32: {
37306c3fb27SDimitry Andric       int64_t Value = support::endian::read32le(FixupPtr) -
37404eeddc0SDimitry Andric                       E.getTarget().getAddress().getValue() - E.getAddend();
375bdd1243dSDimitry Andric       *(little32_t *)FixupPtr = static_cast<uint32_t>(Value);
376bdd1243dSDimitry Andric       break;
377bdd1243dSDimitry Andric     }
378bdd1243dSDimitry Andric     case R_RISCV_SUB64: {
37906c3fb27SDimitry Andric       int64_t Value = support::endian::read64le(FixupPtr) -
380bdd1243dSDimitry Andric                       E.getTarget().getAddress().getValue() - E.getAddend();
381bdd1243dSDimitry Andric       *(little64_t *)FixupPtr = static_cast<uint64_t>(Value);
382bdd1243dSDimitry Andric       break;
383bdd1243dSDimitry Andric     }
384bdd1243dSDimitry Andric     case R_RISCV_RVC_BRANCH: {
385bdd1243dSDimitry Andric       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
386bdd1243dSDimitry Andric       if (LLVM_UNLIKELY(!isInRangeForImm(Value >> 1, 8)))
387bdd1243dSDimitry Andric         return makeTargetOutOfRangeError(G, B, E);
388bdd1243dSDimitry Andric       if (LLVM_UNLIKELY(!isAlignmentCorrect(Value, 2)))
389bdd1243dSDimitry Andric         return makeAlignmentError(FixupAddress, Value, 2, E);
390bdd1243dSDimitry Andric       uint16_t Imm8 = extractBits(Value, 8, 1) << 12;
391bdd1243dSDimitry Andric       uint16_t Imm4_3 = extractBits(Value, 3, 2) << 10;
392bdd1243dSDimitry Andric       uint16_t Imm7_6 = extractBits(Value, 6, 2) << 5;
393bdd1243dSDimitry Andric       uint16_t Imm2_1 = extractBits(Value, 1, 2) << 3;
394bdd1243dSDimitry Andric       uint16_t Imm5 = extractBits(Value, 5, 1) << 2;
395bdd1243dSDimitry Andric       uint16_t RawInstr = *(little16_t *)FixupPtr;
396bdd1243dSDimitry Andric       *(little16_t *)FixupPtr =
397bdd1243dSDimitry Andric           (RawInstr & 0xE383) | Imm8 | Imm4_3 | Imm7_6 | Imm2_1 | Imm5;
398bdd1243dSDimitry Andric       break;
399bdd1243dSDimitry Andric     }
400bdd1243dSDimitry Andric     case R_RISCV_RVC_JUMP: {
401bdd1243dSDimitry Andric       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
402bdd1243dSDimitry Andric       if (LLVM_UNLIKELY(!isInRangeForImm(Value >> 1, 11)))
403bdd1243dSDimitry Andric         return makeTargetOutOfRangeError(G, B, E);
404bdd1243dSDimitry Andric       if (LLVM_UNLIKELY(!isAlignmentCorrect(Value, 2)))
405bdd1243dSDimitry Andric         return makeAlignmentError(FixupAddress, Value, 2, E);
406bdd1243dSDimitry Andric       uint16_t Imm11 = extractBits(Value, 11, 1) << 12;
407bdd1243dSDimitry Andric       uint16_t Imm4 = extractBits(Value, 4, 1) << 11;
408bdd1243dSDimitry Andric       uint16_t Imm9_8 = extractBits(Value, 8, 2) << 9;
409bdd1243dSDimitry Andric       uint16_t Imm10 = extractBits(Value, 10, 1) << 8;
410bdd1243dSDimitry Andric       uint16_t Imm6 = extractBits(Value, 6, 1) << 7;
411bdd1243dSDimitry Andric       uint16_t Imm7 = extractBits(Value, 7, 1) << 6;
412bdd1243dSDimitry Andric       uint16_t Imm3_1 = extractBits(Value, 1, 3) << 3;
413bdd1243dSDimitry Andric       uint16_t Imm5 = extractBits(Value, 5, 1) << 2;
414bdd1243dSDimitry Andric       uint16_t RawInstr = *(little16_t *)FixupPtr;
415bdd1243dSDimitry Andric       *(little16_t *)FixupPtr = (RawInstr & 0xE003) | Imm11 | Imm4 | Imm9_8 |
416bdd1243dSDimitry Andric                                 Imm10 | Imm6 | Imm7 | Imm3_1 | Imm5;
41704eeddc0SDimitry Andric       break;
41804eeddc0SDimitry Andric     }
41981ad6265SDimitry Andric     case R_RISCV_SUB6: {
42006c3fb27SDimitry Andric       int64_t Value = *(reinterpret_cast<const uint8_t *>(FixupPtr)) & 0x3f;
42181ad6265SDimitry Andric       Value -= E.getTarget().getAddress().getValue() - E.getAddend();
42281ad6265SDimitry Andric       *FixupPtr = (*FixupPtr & 0xc0) | (static_cast<uint8_t>(Value) & 0x3f);
42381ad6265SDimitry Andric       break;
42481ad6265SDimitry Andric     }
42504eeddc0SDimitry Andric     case R_RISCV_SET6: {
42604eeddc0SDimitry Andric       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
42704eeddc0SDimitry Andric       uint32_t RawData = *(little32_t *)FixupPtr;
42804eeddc0SDimitry Andric       int64_t Word6 = Value & 0x3f;
42904eeddc0SDimitry Andric       *(little32_t *)FixupPtr = (RawData & 0xffffffc0) | Word6;
43004eeddc0SDimitry Andric       break;
43104eeddc0SDimitry Andric     }
43204eeddc0SDimitry Andric     case R_RISCV_SET8: {
43304eeddc0SDimitry Andric       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
43404eeddc0SDimitry Andric       uint32_t RawData = *(little32_t *)FixupPtr;
43504eeddc0SDimitry Andric       int64_t Word8 = Value & 0xff;
43604eeddc0SDimitry Andric       *(little32_t *)FixupPtr = (RawData & 0xffffff00) | Word8;
43704eeddc0SDimitry Andric       break;
43804eeddc0SDimitry Andric     }
43904eeddc0SDimitry Andric     case R_RISCV_SET16: {
44004eeddc0SDimitry Andric       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
44104eeddc0SDimitry Andric       uint32_t RawData = *(little32_t *)FixupPtr;
44204eeddc0SDimitry Andric       int64_t Word16 = Value & 0xffff;
44304eeddc0SDimitry Andric       *(little32_t *)FixupPtr = (RawData & 0xffff0000) | Word16;
44404eeddc0SDimitry Andric       break;
44504eeddc0SDimitry Andric     }
44604eeddc0SDimitry Andric     case R_RISCV_SET32: {
44704eeddc0SDimitry Andric       int64_t Value = (E.getTarget().getAddress() + E.getAddend()).getValue();
44804eeddc0SDimitry Andric       int64_t Word32 = Value & 0xffffffff;
44904eeddc0SDimitry Andric       *(little32_t *)FixupPtr = Word32;
45004eeddc0SDimitry Andric       break;
45104eeddc0SDimitry Andric     }
45204eeddc0SDimitry Andric     case R_RISCV_32_PCREL: {
45304eeddc0SDimitry Andric       int64_t Value = E.getTarget().getAddress() + E.getAddend() - FixupAddress;
45404eeddc0SDimitry Andric       int64_t Word32 = Value & 0xffffffff;
45504eeddc0SDimitry Andric       *(little32_t *)FixupPtr = Word32;
45604eeddc0SDimitry Andric       break;
45704eeddc0SDimitry Andric     }
45806c3fb27SDimitry Andric     case AlignRelaxable:
45906c3fb27SDimitry Andric       // Ignore when the relaxation pass did not run
46006c3fb27SDimitry Andric       break;
461*5f757f3fSDimitry Andric     case NegDelta32: {
462*5f757f3fSDimitry Andric       int64_t Value = FixupAddress - E.getTarget().getAddress() + E.getAddend();
463*5f757f3fSDimitry Andric       if (LLVM_UNLIKELY(!isInRangeForImm(Value, 32)))
464*5f757f3fSDimitry Andric         return makeTargetOutOfRangeError(G, B, E);
465*5f757f3fSDimitry Andric       *(little32_t *)FixupPtr = static_cast<uint32_t>(Value);
466*5f757f3fSDimitry Andric       break;
467*5f757f3fSDimitry Andric     }
468fe6060f1SDimitry Andric     }
469fe6060f1SDimitry Andric     return Error::success();
470fe6060f1SDimitry Andric   }
471fe6060f1SDimitry Andric };
472fe6060f1SDimitry Andric 
47306c3fb27SDimitry Andric namespace {
47406c3fb27SDimitry Andric 
47506c3fb27SDimitry Andric struct SymbolAnchor {
47606c3fb27SDimitry Andric   uint64_t Offset;
47706c3fb27SDimitry Andric   Symbol *Sym;
47806c3fb27SDimitry Andric   bool End; // true for the anchor of getOffset() + getSize()
47906c3fb27SDimitry Andric };
48006c3fb27SDimitry Andric 
48106c3fb27SDimitry Andric struct BlockRelaxAux {
48206c3fb27SDimitry Andric   // This records symbol start and end offsets which will be adjusted according
48306c3fb27SDimitry Andric   // to the nearest RelocDeltas element.
48406c3fb27SDimitry Andric   SmallVector<SymbolAnchor, 0> Anchors;
48506c3fb27SDimitry Andric   // All edges that either 1) are R_RISCV_ALIGN or 2) have a R_RISCV_RELAX edge
48606c3fb27SDimitry Andric   // at the same offset.
48706c3fb27SDimitry Andric   SmallVector<Edge *, 0> RelaxEdges;
48806c3fb27SDimitry Andric   // For RelaxEdges[I], the actual offset is RelaxEdges[I]->getOffset() - (I ?
48906c3fb27SDimitry Andric   // RelocDeltas[I - 1] : 0).
49006c3fb27SDimitry Andric   SmallVector<uint32_t, 0> RelocDeltas;
49106c3fb27SDimitry Andric   // For RelaxEdges[I], the actual type is EdgeKinds[I].
49206c3fb27SDimitry Andric   SmallVector<Edge::Kind, 0> EdgeKinds;
49306c3fb27SDimitry Andric   // List of rewritten instructions. Contains one raw encoded instruction per
49406c3fb27SDimitry Andric   // element in EdgeKinds that isn't Invalid or R_RISCV_ALIGN.
49506c3fb27SDimitry Andric   SmallVector<uint32_t, 0> Writes;
49606c3fb27SDimitry Andric };
49706c3fb27SDimitry Andric 
49806c3fb27SDimitry Andric struct RelaxConfig {
49906c3fb27SDimitry Andric   bool IsRV32;
50006c3fb27SDimitry Andric   bool HasRVC;
50106c3fb27SDimitry Andric };
50206c3fb27SDimitry Andric 
50306c3fb27SDimitry Andric struct RelaxAux {
50406c3fb27SDimitry Andric   RelaxConfig Config;
50506c3fb27SDimitry Andric   DenseMap<Block *, BlockRelaxAux> Blocks;
50606c3fb27SDimitry Andric };
50706c3fb27SDimitry Andric 
50806c3fb27SDimitry Andric } // namespace
50906c3fb27SDimitry Andric 
shouldRelax(const Section & S)51006c3fb27SDimitry Andric static bool shouldRelax(const Section &S) {
51106c3fb27SDimitry Andric   return (S.getMemProt() & orc::MemProt::Exec) != orc::MemProt::None;
51206c3fb27SDimitry Andric }
51306c3fb27SDimitry Andric 
isRelaxable(const Edge & E)51406c3fb27SDimitry Andric static bool isRelaxable(const Edge &E) {
51506c3fb27SDimitry Andric   switch (E.getKind()) {
51606c3fb27SDimitry Andric   default:
51706c3fb27SDimitry Andric     return false;
51806c3fb27SDimitry Andric   case CallRelaxable:
51906c3fb27SDimitry Andric   case AlignRelaxable:
52006c3fb27SDimitry Andric     return true;
52106c3fb27SDimitry Andric   }
52206c3fb27SDimitry Andric }
52306c3fb27SDimitry Andric 
initRelaxAux(LinkGraph & G)52406c3fb27SDimitry Andric static RelaxAux initRelaxAux(LinkGraph &G) {
52506c3fb27SDimitry Andric   RelaxAux Aux;
52606c3fb27SDimitry Andric   Aux.Config.IsRV32 = G.getTargetTriple().isRISCV32();
52706c3fb27SDimitry Andric   const auto &Features = G.getFeatures().getFeatures();
528*5f757f3fSDimitry Andric   Aux.Config.HasRVC = llvm::is_contained(Features, "+c");
52906c3fb27SDimitry Andric 
53006c3fb27SDimitry Andric   for (auto &S : G.sections()) {
53106c3fb27SDimitry Andric     if (!shouldRelax(S))
53206c3fb27SDimitry Andric       continue;
53306c3fb27SDimitry Andric     for (auto *B : S.blocks()) {
53406c3fb27SDimitry Andric       auto BlockEmplaceResult = Aux.Blocks.try_emplace(B);
53506c3fb27SDimitry Andric       assert(BlockEmplaceResult.second && "Block encountered twice");
53606c3fb27SDimitry Andric       auto &BlockAux = BlockEmplaceResult.first->second;
53706c3fb27SDimitry Andric 
53806c3fb27SDimitry Andric       for (auto &E : B->edges())
53906c3fb27SDimitry Andric         if (isRelaxable(E))
54006c3fb27SDimitry Andric           BlockAux.RelaxEdges.push_back(&E);
54106c3fb27SDimitry Andric 
54206c3fb27SDimitry Andric       if (BlockAux.RelaxEdges.empty()) {
54306c3fb27SDimitry Andric         Aux.Blocks.erase(BlockEmplaceResult.first);
54406c3fb27SDimitry Andric         continue;
54506c3fb27SDimitry Andric       }
54606c3fb27SDimitry Andric 
54706c3fb27SDimitry Andric       const auto NumEdges = BlockAux.RelaxEdges.size();
54806c3fb27SDimitry Andric       BlockAux.RelocDeltas.resize(NumEdges, 0);
54906c3fb27SDimitry Andric       BlockAux.EdgeKinds.resize_for_overwrite(NumEdges);
55006c3fb27SDimitry Andric 
55106c3fb27SDimitry Andric       // Store anchors (offset and offset+size) for symbols.
55206c3fb27SDimitry Andric       for (auto *Sym : S.symbols()) {
55306c3fb27SDimitry Andric         if (!Sym->isDefined() || &Sym->getBlock() != B)
55406c3fb27SDimitry Andric           continue;
55506c3fb27SDimitry Andric 
55606c3fb27SDimitry Andric         BlockAux.Anchors.push_back({Sym->getOffset(), Sym, false});
55706c3fb27SDimitry Andric         BlockAux.Anchors.push_back(
55806c3fb27SDimitry Andric             {Sym->getOffset() + Sym->getSize(), Sym, true});
55906c3fb27SDimitry Andric       }
56006c3fb27SDimitry Andric     }
56106c3fb27SDimitry Andric   }
56206c3fb27SDimitry Andric 
56306c3fb27SDimitry Andric   // Sort anchors by offset so that we can find the closest relocation
56406c3fb27SDimitry Andric   // efficiently. For a zero size symbol, ensure that its start anchor precedes
56506c3fb27SDimitry Andric   // its end anchor. For two symbols with anchors at the same offset, their
56606c3fb27SDimitry Andric   // order does not matter.
56706c3fb27SDimitry Andric   for (auto &BlockAuxIter : Aux.Blocks) {
56806c3fb27SDimitry Andric     llvm::sort(BlockAuxIter.second.Anchors, [](auto &A, auto &B) {
56906c3fb27SDimitry Andric       return std::make_pair(A.Offset, A.End) < std::make_pair(B.Offset, B.End);
57006c3fb27SDimitry Andric     });
57106c3fb27SDimitry Andric   }
57206c3fb27SDimitry Andric 
57306c3fb27SDimitry Andric   return Aux;
57406c3fb27SDimitry Andric }
57506c3fb27SDimitry Andric 
relaxAlign(orc::ExecutorAddr Loc,const Edge & E,uint32_t & Remove,Edge::Kind & NewEdgeKind)57606c3fb27SDimitry Andric static void relaxAlign(orc::ExecutorAddr Loc, const Edge &E, uint32_t &Remove,
57706c3fb27SDimitry Andric                        Edge::Kind &NewEdgeKind) {
57806c3fb27SDimitry Andric   // E points to the start of the padding bytes.
57906c3fb27SDimitry Andric   // E + Addend points to the instruction to be aligned by removing padding.
58006c3fb27SDimitry Andric   // Alignment is the smallest power of 2 strictly greater than Addend.
58106c3fb27SDimitry Andric   const auto Align = NextPowerOf2(E.getAddend());
58206c3fb27SDimitry Andric   const auto DestLoc = alignTo(Loc.getValue(), Align);
58306c3fb27SDimitry Andric   const auto SrcLoc = Loc.getValue() + E.getAddend();
58406c3fb27SDimitry Andric   Remove = SrcLoc - DestLoc;
58506c3fb27SDimitry Andric   assert(static_cast<int32_t>(Remove) >= 0 &&
58606c3fb27SDimitry Andric          "R_RISCV_ALIGN needs expanding the content");
58706c3fb27SDimitry Andric   NewEdgeKind = AlignRelaxable;
58806c3fb27SDimitry Andric }
58906c3fb27SDimitry Andric 
relaxCall(const Block & B,BlockRelaxAux & Aux,const RelaxConfig & Config,orc::ExecutorAddr Loc,const Edge & E,uint32_t & Remove,Edge::Kind & NewEdgeKind)59006c3fb27SDimitry Andric static void relaxCall(const Block &B, BlockRelaxAux &Aux,
59106c3fb27SDimitry Andric                       const RelaxConfig &Config, orc::ExecutorAddr Loc,
59206c3fb27SDimitry Andric                       const Edge &E, uint32_t &Remove,
59306c3fb27SDimitry Andric                       Edge::Kind &NewEdgeKind) {
59406c3fb27SDimitry Andric   const auto JALR =
59506c3fb27SDimitry Andric       support::endian::read32le(B.getContent().data() + E.getOffset() + 4);
59606c3fb27SDimitry Andric   const auto RD = extractBits(JALR, 7, 5);
59706c3fb27SDimitry Andric   const auto Dest = E.getTarget().getAddress() + E.getAddend();
59806c3fb27SDimitry Andric   const auto Displace = Dest - Loc;
59906c3fb27SDimitry Andric 
60006c3fb27SDimitry Andric   if (Config.HasRVC && isInt<12>(Displace) && RD == 0) {
60106c3fb27SDimitry Andric     NewEdgeKind = R_RISCV_RVC_JUMP;
60206c3fb27SDimitry Andric     Aux.Writes.push_back(0xa001); // c.j
60306c3fb27SDimitry Andric     Remove = 6;
60406c3fb27SDimitry Andric   } else if (Config.HasRVC && Config.IsRV32 && isInt<12>(Displace) && RD == 1) {
60506c3fb27SDimitry Andric     NewEdgeKind = R_RISCV_RVC_JUMP;
60606c3fb27SDimitry Andric     Aux.Writes.push_back(0x2001); // c.jal
60706c3fb27SDimitry Andric     Remove = 6;
60806c3fb27SDimitry Andric   } else if (isInt<21>(Displace)) {
60906c3fb27SDimitry Andric     NewEdgeKind = R_RISCV_JAL;
61006c3fb27SDimitry Andric     Aux.Writes.push_back(0x6f | RD << 7); // jal
61106c3fb27SDimitry Andric     Remove = 4;
61206c3fb27SDimitry Andric   } else {
61306c3fb27SDimitry Andric     // Not relaxable
61406c3fb27SDimitry Andric     NewEdgeKind = R_RISCV_CALL_PLT;
61506c3fb27SDimitry Andric     Remove = 0;
61606c3fb27SDimitry Andric   }
61706c3fb27SDimitry Andric }
61806c3fb27SDimitry Andric 
relaxBlock(LinkGraph & G,Block & Block,BlockRelaxAux & Aux,const RelaxConfig & Config)61906c3fb27SDimitry Andric static bool relaxBlock(LinkGraph &G, Block &Block, BlockRelaxAux &Aux,
62006c3fb27SDimitry Andric                        const RelaxConfig &Config) {
62106c3fb27SDimitry Andric   const auto BlockAddr = Block.getAddress();
62206c3fb27SDimitry Andric   bool Changed = false;
62306c3fb27SDimitry Andric   ArrayRef<SymbolAnchor> SA = ArrayRef(Aux.Anchors);
62406c3fb27SDimitry Andric   uint32_t Delta = 0;
62506c3fb27SDimitry Andric 
62606c3fb27SDimitry Andric   Aux.EdgeKinds.assign(Aux.EdgeKinds.size(), Edge::Invalid);
62706c3fb27SDimitry Andric   Aux.Writes.clear();
62806c3fb27SDimitry Andric 
62906c3fb27SDimitry Andric   for (auto [I, E] : llvm::enumerate(Aux.RelaxEdges)) {
63006c3fb27SDimitry Andric     const auto Loc = BlockAddr + E->getOffset() - Delta;
63106c3fb27SDimitry Andric     auto &Cur = Aux.RelocDeltas[I];
63206c3fb27SDimitry Andric     uint32_t Remove = 0;
63306c3fb27SDimitry Andric     switch (E->getKind()) {
63406c3fb27SDimitry Andric     case AlignRelaxable:
63506c3fb27SDimitry Andric       relaxAlign(Loc, *E, Remove, Aux.EdgeKinds[I]);
63606c3fb27SDimitry Andric       break;
63706c3fb27SDimitry Andric     case CallRelaxable:
63806c3fb27SDimitry Andric       relaxCall(Block, Aux, Config, Loc, *E, Remove, Aux.EdgeKinds[I]);
63906c3fb27SDimitry Andric       break;
64006c3fb27SDimitry Andric     default:
64106c3fb27SDimitry Andric       llvm_unreachable("Unexpected relaxable edge kind");
64206c3fb27SDimitry Andric     }
64306c3fb27SDimitry Andric 
64406c3fb27SDimitry Andric     // For all anchors whose offsets are <= E->getOffset(), they are preceded by
64506c3fb27SDimitry Andric     // the previous relocation whose RelocDeltas value equals Delta.
64606c3fb27SDimitry Andric     // Decrease their offset and update their size.
64706c3fb27SDimitry Andric     for (; SA.size() && SA[0].Offset <= E->getOffset(); SA = SA.slice(1)) {
64806c3fb27SDimitry Andric       if (SA[0].End)
64906c3fb27SDimitry Andric         SA[0].Sym->setSize(SA[0].Offset - Delta - SA[0].Sym->getOffset());
65006c3fb27SDimitry Andric       else
65106c3fb27SDimitry Andric         SA[0].Sym->setOffset(SA[0].Offset - Delta);
65206c3fb27SDimitry Andric     }
65306c3fb27SDimitry Andric 
65406c3fb27SDimitry Andric     Delta += Remove;
65506c3fb27SDimitry Andric     if (Delta != Cur) {
65606c3fb27SDimitry Andric       Cur = Delta;
65706c3fb27SDimitry Andric       Changed = true;
65806c3fb27SDimitry Andric     }
65906c3fb27SDimitry Andric   }
66006c3fb27SDimitry Andric 
66106c3fb27SDimitry Andric   for (const SymbolAnchor &A : SA) {
66206c3fb27SDimitry Andric     if (A.End)
66306c3fb27SDimitry Andric       A.Sym->setSize(A.Offset - Delta - A.Sym->getOffset());
66406c3fb27SDimitry Andric     else
66506c3fb27SDimitry Andric       A.Sym->setOffset(A.Offset - Delta);
66606c3fb27SDimitry Andric   }
66706c3fb27SDimitry Andric 
66806c3fb27SDimitry Andric   return Changed;
66906c3fb27SDimitry Andric }
67006c3fb27SDimitry Andric 
relaxOnce(LinkGraph & G,RelaxAux & Aux)67106c3fb27SDimitry Andric static bool relaxOnce(LinkGraph &G, RelaxAux &Aux) {
67206c3fb27SDimitry Andric   bool Changed = false;
67306c3fb27SDimitry Andric 
67406c3fb27SDimitry Andric   for (auto &[B, BlockAux] : Aux.Blocks)
67506c3fb27SDimitry Andric     Changed |= relaxBlock(G, *B, BlockAux, Aux.Config);
67606c3fb27SDimitry Andric 
67706c3fb27SDimitry Andric   return Changed;
67806c3fb27SDimitry Andric }
67906c3fb27SDimitry Andric 
finalizeBlockRelax(LinkGraph & G,Block & Block,BlockRelaxAux & Aux)68006c3fb27SDimitry Andric static void finalizeBlockRelax(LinkGraph &G, Block &Block, BlockRelaxAux &Aux) {
68106c3fb27SDimitry Andric   auto Contents = Block.getAlreadyMutableContent();
68206c3fb27SDimitry Andric   auto *Dest = Contents.data();
68306c3fb27SDimitry Andric   auto NextWrite = Aux.Writes.begin();
68406c3fb27SDimitry Andric   uint32_t Offset = 0;
68506c3fb27SDimitry Andric   uint32_t Delta = 0;
68606c3fb27SDimitry Andric 
68706c3fb27SDimitry Andric   // Update section content: remove NOPs for R_RISCV_ALIGN and rewrite
68806c3fb27SDimitry Andric   // instructions for relaxed relocations.
68906c3fb27SDimitry Andric   for (auto [I, E] : llvm::enumerate(Aux.RelaxEdges)) {
69006c3fb27SDimitry Andric     uint32_t Remove = Aux.RelocDeltas[I] - Delta;
69106c3fb27SDimitry Andric     Delta = Aux.RelocDeltas[I];
69206c3fb27SDimitry Andric     if (Remove == 0 && Aux.EdgeKinds[I] == Edge::Invalid)
69306c3fb27SDimitry Andric       continue;
69406c3fb27SDimitry Andric 
69506c3fb27SDimitry Andric     // Copy from last location to the current relocated location.
69606c3fb27SDimitry Andric     const auto Size = E->getOffset() - Offset;
69706c3fb27SDimitry Andric     std::memmove(Dest, Contents.data() + Offset, Size);
69806c3fb27SDimitry Andric     Dest += Size;
69906c3fb27SDimitry Andric 
70006c3fb27SDimitry Andric     uint32_t Skip = 0;
70106c3fb27SDimitry Andric     switch (Aux.EdgeKinds[I]) {
70206c3fb27SDimitry Andric     case Edge::Invalid:
70306c3fb27SDimitry Andric       break;
70406c3fb27SDimitry Andric     case AlignRelaxable:
70506c3fb27SDimitry Andric       // For R_RISCV_ALIGN, we will place Offset in a location (among NOPs) to
70606c3fb27SDimitry Andric       // satisfy the alignment requirement. If both Remove and E->getAddend()
70706c3fb27SDimitry Andric       // are multiples of 4, it is as if we have skipped some NOPs. Otherwise we
70806c3fb27SDimitry Andric       // are in the middle of a 4-byte NOP, and we need to rewrite the NOP
70906c3fb27SDimitry Andric       // sequence.
71006c3fb27SDimitry Andric       if (Remove % 4 || E->getAddend() % 4) {
71106c3fb27SDimitry Andric         Skip = E->getAddend() - Remove;
71206c3fb27SDimitry Andric         uint32_t J = 0;
71306c3fb27SDimitry Andric         for (; J + 4 <= Skip; J += 4)
71406c3fb27SDimitry Andric           support::endian::write32le(Dest + J, 0x00000013); // nop
71506c3fb27SDimitry Andric         if (J != Skip) {
71606c3fb27SDimitry Andric           assert(J + 2 == Skip);
71706c3fb27SDimitry Andric           support::endian::write16le(Dest + J, 0x0001); // c.nop
71806c3fb27SDimitry Andric         }
71906c3fb27SDimitry Andric       }
72006c3fb27SDimitry Andric       break;
72106c3fb27SDimitry Andric     case R_RISCV_RVC_JUMP:
72206c3fb27SDimitry Andric       Skip = 2;
72306c3fb27SDimitry Andric       support::endian::write16le(Dest, *NextWrite++);
72406c3fb27SDimitry Andric       break;
72506c3fb27SDimitry Andric     case R_RISCV_JAL:
72606c3fb27SDimitry Andric       Skip = 4;
72706c3fb27SDimitry Andric       support::endian::write32le(Dest, *NextWrite++);
72806c3fb27SDimitry Andric       break;
72906c3fb27SDimitry Andric     }
73006c3fb27SDimitry Andric 
73106c3fb27SDimitry Andric     Dest += Skip;
73206c3fb27SDimitry Andric     Offset = E->getOffset() + Skip + Remove;
73306c3fb27SDimitry Andric   }
73406c3fb27SDimitry Andric 
73506c3fb27SDimitry Andric   std::memmove(Dest, Contents.data() + Offset, Contents.size() - Offset);
73606c3fb27SDimitry Andric 
73706c3fb27SDimitry Andric   // Fixup edge offsets and kinds.
73806c3fb27SDimitry Andric   Delta = 0;
73906c3fb27SDimitry Andric   size_t I = 0;
74006c3fb27SDimitry Andric   for (auto &E : Block.edges()) {
74106c3fb27SDimitry Andric     E.setOffset(E.getOffset() - Delta);
74206c3fb27SDimitry Andric 
74306c3fb27SDimitry Andric     if (I < Aux.RelaxEdges.size() && Aux.RelaxEdges[I] == &E) {
74406c3fb27SDimitry Andric       if (Aux.EdgeKinds[I] != Edge::Invalid)
74506c3fb27SDimitry Andric         E.setKind(Aux.EdgeKinds[I]);
74606c3fb27SDimitry Andric 
74706c3fb27SDimitry Andric       Delta = Aux.RelocDeltas[I];
74806c3fb27SDimitry Andric       ++I;
74906c3fb27SDimitry Andric     }
75006c3fb27SDimitry Andric   }
75106c3fb27SDimitry Andric 
75206c3fb27SDimitry Andric   // Remove AlignRelaxable edges: all other relaxable edges got modified and
75306c3fb27SDimitry Andric   // will be used later while linking. Alignment is entirely handled here so we
75406c3fb27SDimitry Andric   // don't need these edges anymore.
75506c3fb27SDimitry Andric   for (auto IE = Block.edges().begin(); IE != Block.edges().end();) {
75606c3fb27SDimitry Andric     if (IE->getKind() == AlignRelaxable)
75706c3fb27SDimitry Andric       IE = Block.removeEdge(IE);
75806c3fb27SDimitry Andric     else
75906c3fb27SDimitry Andric       ++IE;
76006c3fb27SDimitry Andric   }
76106c3fb27SDimitry Andric }
76206c3fb27SDimitry Andric 
finalizeRelax(LinkGraph & G,RelaxAux & Aux)76306c3fb27SDimitry Andric static void finalizeRelax(LinkGraph &G, RelaxAux &Aux) {
76406c3fb27SDimitry Andric   for (auto &[B, BlockAux] : Aux.Blocks)
76506c3fb27SDimitry Andric     finalizeBlockRelax(G, *B, BlockAux);
76606c3fb27SDimitry Andric }
76706c3fb27SDimitry Andric 
relax(LinkGraph & G)76806c3fb27SDimitry Andric static Error relax(LinkGraph &G) {
76906c3fb27SDimitry Andric   auto Aux = initRelaxAux(G);
77006c3fb27SDimitry Andric   while (relaxOnce(G, Aux)) {
77106c3fb27SDimitry Andric   }
77206c3fb27SDimitry Andric   finalizeRelax(G, Aux);
77306c3fb27SDimitry Andric   return Error::success();
77406c3fb27SDimitry Andric }
77506c3fb27SDimitry Andric 
776fe6060f1SDimitry Andric template <typename ELFT>
777fe6060f1SDimitry Andric class ELFLinkGraphBuilder_riscv : public ELFLinkGraphBuilder<ELFT> {
778fe6060f1SDimitry Andric private:
779fe6060f1SDimitry Andric   static Expected<riscv::EdgeKind_riscv>
getRelocationKind(const uint32_t Type)780fe6060f1SDimitry Andric   getRelocationKind(const uint32_t Type) {
781fe6060f1SDimitry Andric     using namespace riscv;
782fe6060f1SDimitry Andric     switch (Type) {
783fe6060f1SDimitry Andric     case ELF::R_RISCV_32:
784fe6060f1SDimitry Andric       return EdgeKind_riscv::R_RISCV_32;
785fe6060f1SDimitry Andric     case ELF::R_RISCV_64:
786fe6060f1SDimitry Andric       return EdgeKind_riscv::R_RISCV_64;
78704eeddc0SDimitry Andric     case ELF::R_RISCV_BRANCH:
78804eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_BRANCH;
78981ad6265SDimitry Andric     case ELF::R_RISCV_JAL:
79081ad6265SDimitry Andric       return EdgeKind_riscv::R_RISCV_JAL;
791fe6060f1SDimitry Andric     case ELF::R_RISCV_CALL:
792fe6060f1SDimitry Andric       return EdgeKind_riscv::R_RISCV_CALL;
793bdd1243dSDimitry Andric     case ELF::R_RISCV_CALL_PLT:
794bdd1243dSDimitry Andric       return EdgeKind_riscv::R_RISCV_CALL_PLT;
795bdd1243dSDimitry Andric     case ELF::R_RISCV_GOT_HI20:
796bdd1243dSDimitry Andric       return EdgeKind_riscv::R_RISCV_GOT_HI20;
797fe6060f1SDimitry Andric     case ELF::R_RISCV_PCREL_HI20:
798fe6060f1SDimitry Andric       return EdgeKind_riscv::R_RISCV_PCREL_HI20;
799fe6060f1SDimitry Andric     case ELF::R_RISCV_PCREL_LO12_I:
800fe6060f1SDimitry Andric       return EdgeKind_riscv::R_RISCV_PCREL_LO12_I;
801fe6060f1SDimitry Andric     case ELF::R_RISCV_PCREL_LO12_S:
802fe6060f1SDimitry Andric       return EdgeKind_riscv::R_RISCV_PCREL_LO12_S;
803bdd1243dSDimitry Andric     case ELF::R_RISCV_HI20:
804bdd1243dSDimitry Andric       return EdgeKind_riscv::R_RISCV_HI20;
805bdd1243dSDimitry Andric     case ELF::R_RISCV_LO12_I:
806bdd1243dSDimitry Andric       return EdgeKind_riscv::R_RISCV_LO12_I;
807bdd1243dSDimitry Andric     case ELF::R_RISCV_LO12_S:
808bdd1243dSDimitry Andric       return EdgeKind_riscv::R_RISCV_LO12_S;
80904eeddc0SDimitry Andric     case ELF::R_RISCV_ADD8:
81004eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_ADD8;
811bdd1243dSDimitry Andric     case ELF::R_RISCV_ADD16:
812bdd1243dSDimitry Andric       return EdgeKind_riscv::R_RISCV_ADD16;
813bdd1243dSDimitry Andric     case ELF::R_RISCV_ADD32:
814bdd1243dSDimitry Andric       return EdgeKind_riscv::R_RISCV_ADD32;
815bdd1243dSDimitry Andric     case ELF::R_RISCV_ADD64:
816bdd1243dSDimitry Andric       return EdgeKind_riscv::R_RISCV_ADD64;
81704eeddc0SDimitry Andric     case ELF::R_RISCV_SUB8:
81804eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_SUB8;
819bdd1243dSDimitry Andric     case ELF::R_RISCV_SUB16:
820bdd1243dSDimitry Andric       return EdgeKind_riscv::R_RISCV_SUB16;
821bdd1243dSDimitry Andric     case ELF::R_RISCV_SUB32:
822bdd1243dSDimitry Andric       return EdgeKind_riscv::R_RISCV_SUB32;
823bdd1243dSDimitry Andric     case ELF::R_RISCV_SUB64:
824bdd1243dSDimitry Andric       return EdgeKind_riscv::R_RISCV_SUB64;
825bdd1243dSDimitry Andric     case ELF::R_RISCV_RVC_BRANCH:
826bdd1243dSDimitry Andric       return EdgeKind_riscv::R_RISCV_RVC_BRANCH;
827bdd1243dSDimitry Andric     case ELF::R_RISCV_RVC_JUMP:
828bdd1243dSDimitry Andric       return EdgeKind_riscv::R_RISCV_RVC_JUMP;
82981ad6265SDimitry Andric     case ELF::R_RISCV_SUB6:
83081ad6265SDimitry Andric       return EdgeKind_riscv::R_RISCV_SUB6;
83104eeddc0SDimitry Andric     case ELF::R_RISCV_SET6:
83204eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_SET6;
83304eeddc0SDimitry Andric     case ELF::R_RISCV_SET8:
83404eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_SET8;
83504eeddc0SDimitry Andric     case ELF::R_RISCV_SET16:
83604eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_SET16;
83704eeddc0SDimitry Andric     case ELF::R_RISCV_SET32:
83804eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_SET32;
83904eeddc0SDimitry Andric     case ELF::R_RISCV_32_PCREL:
84004eeddc0SDimitry Andric       return EdgeKind_riscv::R_RISCV_32_PCREL;
84106c3fb27SDimitry Andric     case ELF::R_RISCV_ALIGN:
84206c3fb27SDimitry Andric       return EdgeKind_riscv::AlignRelaxable;
843fe6060f1SDimitry Andric     }
844fe6060f1SDimitry Andric 
84581ad6265SDimitry Andric     return make_error<JITLinkError>(
84681ad6265SDimitry Andric         "Unsupported riscv relocation:" + formatv("{0:d}: ", Type) +
84781ad6265SDimitry Andric         object::getELFRelocationTypeName(ELF::EM_RISCV, Type));
848fe6060f1SDimitry Andric   }
849fe6060f1SDimitry Andric 
getRelaxableRelocationKind(EdgeKind_riscv Kind)85006c3fb27SDimitry Andric   EdgeKind_riscv getRelaxableRelocationKind(EdgeKind_riscv Kind) {
85106c3fb27SDimitry Andric     switch (Kind) {
85206c3fb27SDimitry Andric     default:
85306c3fb27SDimitry Andric       // Just ignore unsupported relaxations
85406c3fb27SDimitry Andric       return Kind;
85506c3fb27SDimitry Andric     case R_RISCV_CALL:
85606c3fb27SDimitry Andric     case R_RISCV_CALL_PLT:
85706c3fb27SDimitry Andric       return CallRelaxable;
85806c3fb27SDimitry Andric     }
85906c3fb27SDimitry Andric   }
86006c3fb27SDimitry Andric 
addRelocations()861fe6060f1SDimitry Andric   Error addRelocations() override {
862349cc55cSDimitry Andric     LLVM_DEBUG(dbgs() << "Processing relocations:\n");
863349cc55cSDimitry Andric 
864fe6060f1SDimitry Andric     using Base = ELFLinkGraphBuilder<ELFT>;
865349cc55cSDimitry Andric     using Self = ELFLinkGraphBuilder_riscv<ELFT>;
866349cc55cSDimitry Andric     for (const auto &RelSect : Base::Sections)
867bdd1243dSDimitry Andric       if (Error Err = Base::forEachRelaRelocation(RelSect, this,
868349cc55cSDimitry Andric                                                   &Self::addSingleRelocation))
869349cc55cSDimitry Andric         return Err;
870fe6060f1SDimitry Andric 
871349cc55cSDimitry Andric     return Error::success();
872fe6060f1SDimitry Andric   }
873fe6060f1SDimitry Andric 
addSingleRelocation(const typename ELFT::Rela & Rel,const typename ELFT::Shdr & FixupSect,Block & BlockToFix)874349cc55cSDimitry Andric   Error addSingleRelocation(const typename ELFT::Rela &Rel,
875349cc55cSDimitry Andric                             const typename ELFT::Shdr &FixupSect,
87604eeddc0SDimitry Andric                             Block &BlockToFix) {
877349cc55cSDimitry Andric     using Base = ELFLinkGraphBuilder<ELFT>;
878349cc55cSDimitry Andric 
879753f127fSDimitry Andric     uint32_t Type = Rel.getType(false);
880753f127fSDimitry Andric     int64_t Addend = Rel.r_addend;
88106c3fb27SDimitry Andric 
88206c3fb27SDimitry Andric     if (Type == ELF::R_RISCV_RELAX) {
88306c3fb27SDimitry Andric       if (BlockToFix.edges_empty())
88406c3fb27SDimitry Andric         return make_error<StringError>(
88506c3fb27SDimitry Andric             "R_RISCV_RELAX without preceding relocation",
88606c3fb27SDimitry Andric             inconvertibleErrorCode());
88706c3fb27SDimitry Andric 
88806c3fb27SDimitry Andric       auto &PrevEdge = *std::prev(BlockToFix.edges().end());
88906c3fb27SDimitry Andric       auto Kind = static_cast<EdgeKind_riscv>(PrevEdge.getKind());
89006c3fb27SDimitry Andric       PrevEdge.setKind(getRelaxableRelocationKind(Kind));
891753f127fSDimitry Andric       return Error::success();
892753f127fSDimitry Andric     }
893753f127fSDimitry Andric 
894753f127fSDimitry Andric     Expected<riscv::EdgeKind_riscv> Kind = getRelocationKind(Type);
895753f127fSDimitry Andric     if (!Kind)
896753f127fSDimitry Andric       return Kind.takeError();
897753f127fSDimitry Andric 
898349cc55cSDimitry Andric     uint32_t SymbolIndex = Rel.getSymbol(false);
899349cc55cSDimitry Andric     auto ObjSymbol = Base::Obj.getRelocationSymbol(Rel, Base::SymTabSec);
900349cc55cSDimitry Andric     if (!ObjSymbol)
901349cc55cSDimitry Andric       return ObjSymbol.takeError();
902349cc55cSDimitry Andric 
903349cc55cSDimitry Andric     Symbol *GraphSymbol = Base::getGraphSymbol(SymbolIndex);
904349cc55cSDimitry Andric     if (!GraphSymbol)
905349cc55cSDimitry Andric       return make_error<StringError>(
906349cc55cSDimitry Andric           formatv("Could not find symbol at given index, did you add it to "
907349cc55cSDimitry Andric                   "JITSymbolTable? index: {0}, shndx: {1} Size of table: {2}",
908349cc55cSDimitry Andric                   SymbolIndex, (*ObjSymbol)->st_shndx,
909349cc55cSDimitry Andric                   Base::GraphSymbols.size()),
910349cc55cSDimitry Andric           inconvertibleErrorCode());
911349cc55cSDimitry Andric 
91204eeddc0SDimitry Andric     auto FixupAddress = orc::ExecutorAddr(FixupSect.sh_addr) + Rel.r_offset;
91304eeddc0SDimitry Andric     Edge::OffsetT Offset = FixupAddress - BlockToFix.getAddress();
914349cc55cSDimitry Andric     Edge GE(*Kind, Offset, *GraphSymbol, Addend);
915349cc55cSDimitry Andric     LLVM_DEBUG({
916349cc55cSDimitry Andric       dbgs() << "    ";
91704eeddc0SDimitry Andric       printEdge(dbgs(), BlockToFix, GE, riscv::getEdgeKindName(*Kind));
918349cc55cSDimitry Andric       dbgs() << "\n";
919349cc55cSDimitry Andric     });
920349cc55cSDimitry Andric 
92104eeddc0SDimitry Andric     BlockToFix.addEdge(std::move(GE));
922fe6060f1SDimitry Andric     return Error::success();
923fe6060f1SDimitry Andric   }
924fe6060f1SDimitry Andric 
925fe6060f1SDimitry Andric public:
ELFLinkGraphBuilder_riscv(StringRef FileName,const object::ELFFile<ELFT> & Obj,Triple TT,SubtargetFeatures Features)926fe6060f1SDimitry Andric   ELFLinkGraphBuilder_riscv(StringRef FileName,
92706c3fb27SDimitry Andric                             const object::ELFFile<ELFT> &Obj, Triple TT,
92806c3fb27SDimitry Andric                             SubtargetFeatures Features)
92906c3fb27SDimitry Andric       : ELFLinkGraphBuilder<ELFT>(Obj, std::move(TT), std::move(Features),
93006c3fb27SDimitry Andric                                   FileName, riscv::getEdgeKindName) {}
931fe6060f1SDimitry Andric };
932fe6060f1SDimitry Andric 
933fe6060f1SDimitry Andric Expected<std::unique_ptr<LinkGraph>>
createLinkGraphFromELFObject_riscv(MemoryBufferRef ObjectBuffer)934fe6060f1SDimitry Andric createLinkGraphFromELFObject_riscv(MemoryBufferRef ObjectBuffer) {
935fe6060f1SDimitry Andric   LLVM_DEBUG({
936fe6060f1SDimitry Andric     dbgs() << "Building jitlink graph for new input "
937fe6060f1SDimitry Andric            << ObjectBuffer.getBufferIdentifier() << "...\n";
938fe6060f1SDimitry Andric   });
939fe6060f1SDimitry Andric 
940fe6060f1SDimitry Andric   auto ELFObj = object::ObjectFile::createELFObjectFile(ObjectBuffer);
941fe6060f1SDimitry Andric   if (!ELFObj)
942fe6060f1SDimitry Andric     return ELFObj.takeError();
943fe6060f1SDimitry Andric 
94406c3fb27SDimitry Andric   auto Features = (*ELFObj)->getFeatures();
94506c3fb27SDimitry Andric   if (!Features)
94606c3fb27SDimitry Andric     return Features.takeError();
94706c3fb27SDimitry Andric 
948fe6060f1SDimitry Andric   if ((*ELFObj)->getArch() == Triple::riscv64) {
949fe6060f1SDimitry Andric     auto &ELFObjFile = cast<object::ELFObjectFile<object::ELF64LE>>(**ELFObj);
950fe6060f1SDimitry Andric     return ELFLinkGraphBuilder_riscv<object::ELF64LE>(
951fe6060f1SDimitry Andric                (*ELFObj)->getFileName(), ELFObjFile.getELFFile(),
95206c3fb27SDimitry Andric                (*ELFObj)->makeTriple(), std::move(*Features))
953fe6060f1SDimitry Andric         .buildGraph();
954fe6060f1SDimitry Andric   } else {
955fe6060f1SDimitry Andric     assert((*ELFObj)->getArch() == Triple::riscv32 &&
956fe6060f1SDimitry Andric            "Invalid triple for RISCV ELF object file");
957fe6060f1SDimitry Andric     auto &ELFObjFile = cast<object::ELFObjectFile<object::ELF32LE>>(**ELFObj);
958fe6060f1SDimitry Andric     return ELFLinkGraphBuilder_riscv<object::ELF32LE>(
959fe6060f1SDimitry Andric                (*ELFObj)->getFileName(), ELFObjFile.getELFFile(),
96006c3fb27SDimitry Andric                (*ELFObj)->makeTriple(), std::move(*Features))
961fe6060f1SDimitry Andric         .buildGraph();
962fe6060f1SDimitry Andric   }
963fe6060f1SDimitry Andric }
964fe6060f1SDimitry Andric 
link_ELF_riscv(std::unique_ptr<LinkGraph> G,std::unique_ptr<JITLinkContext> Ctx)965fe6060f1SDimitry Andric void link_ELF_riscv(std::unique_ptr<LinkGraph> G,
966fe6060f1SDimitry Andric                     std::unique_ptr<JITLinkContext> Ctx) {
967fe6060f1SDimitry Andric   PassConfiguration Config;
968fe6060f1SDimitry Andric   const Triple &TT = G->getTargetTriple();
969fe6060f1SDimitry Andric   if (Ctx->shouldAddDefaultTargetPasses(TT)) {
970*5f757f3fSDimitry Andric 
971*5f757f3fSDimitry Andric     Config.PrePrunePasses.push_back(DWARFRecordSectionSplitter(".eh_frame"));
972*5f757f3fSDimitry Andric     Config.PrePrunePasses.push_back(EHFrameEdgeFixer(
973*5f757f3fSDimitry Andric         ".eh_frame", G->getPointerSize(), Edge::Invalid, Edge::Invalid,
974*5f757f3fSDimitry Andric         Edge::Invalid, Edge::Invalid, NegDelta32));
975*5f757f3fSDimitry Andric     Config.PrePrunePasses.push_back(EHFrameNullTerminator(".eh_frame"));
976*5f757f3fSDimitry Andric 
977fe6060f1SDimitry Andric     if (auto MarkLive = Ctx->getMarkLivePass(TT))
978fe6060f1SDimitry Andric       Config.PrePrunePasses.push_back(std::move(MarkLive));
979fe6060f1SDimitry Andric     else
980fe6060f1SDimitry Andric       Config.PrePrunePasses.push_back(markAllSymbolsLive);
981349cc55cSDimitry Andric     Config.PostPrunePasses.push_back(
982349cc55cSDimitry Andric         PerGraphGOTAndPLTStubsBuilder_ELF_riscv::asPass);
98306c3fb27SDimitry Andric     Config.PostAllocationPasses.push_back(relax);
984fe6060f1SDimitry Andric   }
985fe6060f1SDimitry Andric   if (auto Err = Ctx->modifyPassConfig(*G, Config))
986fe6060f1SDimitry Andric     return Ctx->notifyFailed(std::move(Err));
987fe6060f1SDimitry Andric 
988fe6060f1SDimitry Andric   ELFJITLinker_riscv::link(std::move(Ctx), std::move(G), std::move(Config));
989fe6060f1SDimitry Andric }
990fe6060f1SDimitry Andric 
createRelaxationPass_ELF_riscv()99106c3fb27SDimitry Andric LinkGraphPassFunction createRelaxationPass_ELF_riscv() { return relax; }
99206c3fb27SDimitry Andric 
993fe6060f1SDimitry Andric } // namespace jitlink
994fe6060f1SDimitry Andric } // namespace llvm
995