xref: /freebsd/contrib/llvm-project/lld/ELF/Arch/RISCV.cpp (revision 6246ae0b85d8159978c01ae916a9ad6cde9378b5)
10b57cec5SDimitry Andric //===- RISCV.cpp ----------------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "InputFiles.h"
10753f127fSDimitry Andric #include "OutputSections.h"
11480093f4SDimitry Andric #include "Symbols.h"
120b57cec5SDimitry Andric #include "SyntheticSections.h"
130b57cec5SDimitry Andric #include "Target.h"
14753f127fSDimitry Andric #include "llvm/Support/TimeProfiler.h"
150b57cec5SDimitry Andric 
160b57cec5SDimitry Andric using namespace llvm;
170b57cec5SDimitry Andric using namespace llvm::object;
180b57cec5SDimitry Andric using namespace llvm::support::endian;
190b57cec5SDimitry Andric using namespace llvm::ELF;
205ffd83dbSDimitry Andric using namespace lld;
215ffd83dbSDimitry Andric using namespace lld::elf;
220b57cec5SDimitry Andric 
230b57cec5SDimitry Andric namespace {
240b57cec5SDimitry Andric 
250b57cec5SDimitry Andric class RISCV final : public TargetInfo {
260b57cec5SDimitry Andric public:
270b57cec5SDimitry Andric   RISCV();
280b57cec5SDimitry Andric   uint32_t calcEFlags() const override;
29fe6060f1SDimitry Andric   int64_t getImplicitAddend(const uint8_t *buf, RelType type) const override;
300b57cec5SDimitry Andric   void writeGotHeader(uint8_t *buf) const override;
310b57cec5SDimitry Andric   void writeGotPlt(uint8_t *buf, const Symbol &s) const override;
32fe6060f1SDimitry Andric   void writeIgotPlt(uint8_t *buf, const Symbol &s) const override;
330b57cec5SDimitry Andric   void writePltHeader(uint8_t *buf) const override;
34480093f4SDimitry Andric   void writePlt(uint8_t *buf, const Symbol &sym,
35480093f4SDimitry Andric                 uint64_t pltEntryAddr) const override;
360b57cec5SDimitry Andric   RelType getDynRel(RelType type) const override;
370b57cec5SDimitry Andric   RelExpr getRelExpr(RelType type, const Symbol &s,
380b57cec5SDimitry Andric                      const uint8_t *loc) const override;
395ffd83dbSDimitry Andric   void relocate(uint8_t *loc, const Relocation &rel,
405ffd83dbSDimitry Andric                 uint64_t val) const override;
41753f127fSDimitry Andric   bool relaxOnce(int pass) const override;
420b57cec5SDimitry Andric };
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric } // end anonymous namespace
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric const uint64_t dtpOffset = 0x800;
470b57cec5SDimitry Andric 
480b57cec5SDimitry Andric enum Op {
490b57cec5SDimitry Andric   ADDI = 0x13,
500b57cec5SDimitry Andric   AUIPC = 0x17,
510b57cec5SDimitry Andric   JALR = 0x67,
520b57cec5SDimitry Andric   LD = 0x3003,
530b57cec5SDimitry Andric   LW = 0x2003,
540b57cec5SDimitry Andric   SRLI = 0x5013,
550b57cec5SDimitry Andric   SUB = 0x40000033,
560b57cec5SDimitry Andric };
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric enum Reg {
590b57cec5SDimitry Andric   X_RA = 1,
60fcaf7f86SDimitry Andric   X_TP = 4,
610b57cec5SDimitry Andric   X_T0 = 5,
620b57cec5SDimitry Andric   X_T1 = 6,
630b57cec5SDimitry Andric   X_T2 = 7,
640b57cec5SDimitry Andric   X_T3 = 28,
650b57cec5SDimitry Andric };
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric static uint32_t hi20(uint32_t val) { return (val + 0x800) >> 12; }
680b57cec5SDimitry Andric static uint32_t lo12(uint32_t val) { return val & 4095; }
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric static uint32_t itype(uint32_t op, uint32_t rd, uint32_t rs1, uint32_t imm) {
710b57cec5SDimitry Andric   return op | (rd << 7) | (rs1 << 15) | (imm << 20);
720b57cec5SDimitry Andric }
730b57cec5SDimitry Andric static uint32_t rtype(uint32_t op, uint32_t rd, uint32_t rs1, uint32_t rs2) {
740b57cec5SDimitry Andric   return op | (rd << 7) | (rs1 << 15) | (rs2 << 20);
750b57cec5SDimitry Andric }
760b57cec5SDimitry Andric static uint32_t utype(uint32_t op, uint32_t rd, uint32_t imm) {
770b57cec5SDimitry Andric   return op | (rd << 7) | (imm << 12);
780b57cec5SDimitry Andric }
790b57cec5SDimitry Andric 
80fcaf7f86SDimitry Andric // Extract bits v[begin:end], where range is inclusive, and begin must be < 63.
81fcaf7f86SDimitry Andric static uint32_t extractBits(uint64_t v, uint32_t begin, uint32_t end) {
82fcaf7f86SDimitry Andric   return (v & ((1ULL << (begin + 1)) - 1)) >> end;
83fcaf7f86SDimitry Andric }
84fcaf7f86SDimitry Andric 
85fcaf7f86SDimitry Andric static uint32_t setLO12_I(uint32_t insn, uint32_t imm) {
86fcaf7f86SDimitry Andric   return (insn & 0xfffff) | (imm << 20);
87fcaf7f86SDimitry Andric }
88fcaf7f86SDimitry Andric static uint32_t setLO12_S(uint32_t insn, uint32_t imm) {
89fcaf7f86SDimitry Andric   return (insn & 0x1fff07f) | (extractBits(imm, 11, 5) << 25) |
90fcaf7f86SDimitry Andric          (extractBits(imm, 4, 0) << 7);
91fcaf7f86SDimitry Andric }
92fcaf7f86SDimitry Andric 
930b57cec5SDimitry Andric RISCV::RISCV() {
940b57cec5SDimitry Andric   copyRel = R_RISCV_COPY;
950b57cec5SDimitry Andric   pltRel = R_RISCV_JUMP_SLOT;
960b57cec5SDimitry Andric   relativeRel = R_RISCV_RELATIVE;
975ffd83dbSDimitry Andric   iRelativeRel = R_RISCV_IRELATIVE;
980b57cec5SDimitry Andric   if (config->is64) {
990b57cec5SDimitry Andric     symbolicRel = R_RISCV_64;
1000b57cec5SDimitry Andric     tlsModuleIndexRel = R_RISCV_TLS_DTPMOD64;
1010b57cec5SDimitry Andric     tlsOffsetRel = R_RISCV_TLS_DTPREL64;
1020b57cec5SDimitry Andric     tlsGotRel = R_RISCV_TLS_TPREL64;
1030b57cec5SDimitry Andric   } else {
1040b57cec5SDimitry Andric     symbolicRel = R_RISCV_32;
1050b57cec5SDimitry Andric     tlsModuleIndexRel = R_RISCV_TLS_DTPMOD32;
1060b57cec5SDimitry Andric     tlsOffsetRel = R_RISCV_TLS_DTPREL32;
1070b57cec5SDimitry Andric     tlsGotRel = R_RISCV_TLS_TPREL32;
1080b57cec5SDimitry Andric   }
1090b57cec5SDimitry Andric   gotRel = symbolicRel;
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric   // .got[0] = _DYNAMIC
1120b57cec5SDimitry Andric   gotHeaderEntriesNum = 1;
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric   // .got.plt[0] = _dl_runtime_resolve, .got.plt[1] = link_map
1150b57cec5SDimitry Andric   gotPltHeaderEntriesNum = 2;
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric   pltHeaderSize = 32;
118480093f4SDimitry Andric   pltEntrySize = 16;
119480093f4SDimitry Andric   ipltEntrySize = 16;
1200b57cec5SDimitry Andric }
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric static uint32_t getEFlags(InputFile *f) {
1230b57cec5SDimitry Andric   if (config->is64)
124e8d8bef9SDimitry Andric     return cast<ObjFile<ELF64LE>>(f)->getObj().getHeader().e_flags;
125e8d8bef9SDimitry Andric   return cast<ObjFile<ELF32LE>>(f)->getObj().getHeader().e_flags;
1260b57cec5SDimitry Andric }
1270b57cec5SDimitry Andric 
1280b57cec5SDimitry Andric uint32_t RISCV::calcEFlags() const {
129a1517e11SDimitry Andric   // If there are only binary input files (from -b binary), use a
130a1517e11SDimitry Andric   // value of 0 for the ELF header flags.
13181ad6265SDimitry Andric   if (ctx->objectFiles.empty())
132a1517e11SDimitry Andric     return 0;
1330b57cec5SDimitry Andric 
13481ad6265SDimitry Andric   uint32_t target = getEFlags(ctx->objectFiles.front());
1350b57cec5SDimitry Andric 
13681ad6265SDimitry Andric   for (InputFile *f : ctx->objectFiles) {
1370b57cec5SDimitry Andric     uint32_t eflags = getEFlags(f);
1380b57cec5SDimitry Andric     if (eflags & EF_RISCV_RVC)
1390b57cec5SDimitry Andric       target |= EF_RISCV_RVC;
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric     if ((eflags & EF_RISCV_FLOAT_ABI) != (target & EF_RISCV_FLOAT_ABI))
1420b57cec5SDimitry Andric       error(toString(f) +
1430b57cec5SDimitry Andric             ": cannot link object files with different floating-point ABI");
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric     if ((eflags & EF_RISCV_RVE) != (target & EF_RISCV_RVE))
1460b57cec5SDimitry Andric       error(toString(f) +
1470b57cec5SDimitry Andric             ": cannot link object files with different EF_RISCV_RVE");
1480b57cec5SDimitry Andric   }
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric   return target;
1510b57cec5SDimitry Andric }
1520b57cec5SDimitry Andric 
153fe6060f1SDimitry Andric int64_t RISCV::getImplicitAddend(const uint8_t *buf, RelType type) const {
154fe6060f1SDimitry Andric   switch (type) {
155fe6060f1SDimitry Andric   default:
156fe6060f1SDimitry Andric     internalLinkerError(getErrorLocation(buf),
157fe6060f1SDimitry Andric                         "cannot read addend for relocation " + toString(type));
158fe6060f1SDimitry Andric     return 0;
159fe6060f1SDimitry Andric   case R_RISCV_32:
160fe6060f1SDimitry Andric   case R_RISCV_TLS_DTPMOD32:
161fe6060f1SDimitry Andric   case R_RISCV_TLS_DTPREL32:
162fe6060f1SDimitry Andric     return SignExtend64<32>(read32le(buf));
163fe6060f1SDimitry Andric   case R_RISCV_64:
164fe6060f1SDimitry Andric     return read64le(buf);
165fe6060f1SDimitry Andric   case R_RISCV_RELATIVE:
166fe6060f1SDimitry Andric   case R_RISCV_IRELATIVE:
167fe6060f1SDimitry Andric     return config->is64 ? read64le(buf) : read32le(buf);
168fe6060f1SDimitry Andric   case R_RISCV_NONE:
169fe6060f1SDimitry Andric   case R_RISCV_JUMP_SLOT:
170fe6060f1SDimitry Andric     // These relocations are defined as not having an implicit addend.
171fe6060f1SDimitry Andric     return 0;
172fe6060f1SDimitry Andric   }
173fe6060f1SDimitry Andric }
174fe6060f1SDimitry Andric 
1750b57cec5SDimitry Andric void RISCV::writeGotHeader(uint8_t *buf) const {
1760b57cec5SDimitry Andric   if (config->is64)
1770b57cec5SDimitry Andric     write64le(buf, mainPart->dynamic->getVA());
1780b57cec5SDimitry Andric   else
1790b57cec5SDimitry Andric     write32le(buf, mainPart->dynamic->getVA());
1800b57cec5SDimitry Andric }
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric void RISCV::writeGotPlt(uint8_t *buf, const Symbol &s) const {
1830b57cec5SDimitry Andric   if (config->is64)
1840b57cec5SDimitry Andric     write64le(buf, in.plt->getVA());
1850b57cec5SDimitry Andric   else
1860b57cec5SDimitry Andric     write32le(buf, in.plt->getVA());
1870b57cec5SDimitry Andric }
1880b57cec5SDimitry Andric 
189fe6060f1SDimitry Andric void RISCV::writeIgotPlt(uint8_t *buf, const Symbol &s) const {
190fe6060f1SDimitry Andric   if (config->writeAddends) {
191fe6060f1SDimitry Andric     if (config->is64)
192fe6060f1SDimitry Andric       write64le(buf, s.getVA());
193fe6060f1SDimitry Andric     else
194fe6060f1SDimitry Andric       write32le(buf, s.getVA());
195fe6060f1SDimitry Andric   }
196fe6060f1SDimitry Andric }
197fe6060f1SDimitry Andric 
1980b57cec5SDimitry Andric void RISCV::writePltHeader(uint8_t *buf) const {
1990b57cec5SDimitry Andric   // 1: auipc t2, %pcrel_hi(.got.plt)
2000b57cec5SDimitry Andric   // sub t1, t1, t3
2010b57cec5SDimitry Andric   // l[wd] t3, %pcrel_lo(1b)(t2); t3 = _dl_runtime_resolve
2020b57cec5SDimitry Andric   // addi t1, t1, -pltHeaderSize-12; t1 = &.plt[i] - &.plt[0]
2030b57cec5SDimitry Andric   // addi t0, t2, %pcrel_lo(1b)
2040b57cec5SDimitry Andric   // srli t1, t1, (rv64?1:2); t1 = &.got.plt[i] - &.got.plt[0]
2050b57cec5SDimitry Andric   // l[wd] t0, Wordsize(t0); t0 = link_map
2060b57cec5SDimitry Andric   // jr t3
2070b57cec5SDimitry Andric   uint32_t offset = in.gotPlt->getVA() - in.plt->getVA();
2080b57cec5SDimitry Andric   uint32_t load = config->is64 ? LD : LW;
2090b57cec5SDimitry Andric   write32le(buf + 0, utype(AUIPC, X_T2, hi20(offset)));
2100b57cec5SDimitry Andric   write32le(buf + 4, rtype(SUB, X_T1, X_T1, X_T3));
2110b57cec5SDimitry Andric   write32le(buf + 8, itype(load, X_T3, X_T2, lo12(offset)));
2120b57cec5SDimitry Andric   write32le(buf + 12, itype(ADDI, X_T1, X_T1, -target->pltHeaderSize - 12));
2130b57cec5SDimitry Andric   write32le(buf + 16, itype(ADDI, X_T0, X_T2, lo12(offset)));
2140b57cec5SDimitry Andric   write32le(buf + 20, itype(SRLI, X_T1, X_T1, config->is64 ? 1 : 2));
2150b57cec5SDimitry Andric   write32le(buf + 24, itype(load, X_T0, X_T0, config->wordsize));
2160b57cec5SDimitry Andric   write32le(buf + 28, itype(JALR, 0, X_T3, 0));
2170b57cec5SDimitry Andric }
2180b57cec5SDimitry Andric 
219480093f4SDimitry Andric void RISCV::writePlt(uint8_t *buf, const Symbol &sym,
220480093f4SDimitry Andric                      uint64_t pltEntryAddr) const {
2210b57cec5SDimitry Andric   // 1: auipc t3, %pcrel_hi(f@.got.plt)
2220b57cec5SDimitry Andric   // l[wd] t3, %pcrel_lo(1b)(t3)
2230b57cec5SDimitry Andric   // jalr t1, t3
2240b57cec5SDimitry Andric   // nop
225480093f4SDimitry Andric   uint32_t offset = sym.getGotPltVA() - pltEntryAddr;
2260b57cec5SDimitry Andric   write32le(buf + 0, utype(AUIPC, X_T3, hi20(offset)));
2270b57cec5SDimitry Andric   write32le(buf + 4, itype(config->is64 ? LD : LW, X_T3, X_T3, lo12(offset)));
2280b57cec5SDimitry Andric   write32le(buf + 8, itype(JALR, X_T1, X_T3, 0));
2290b57cec5SDimitry Andric   write32le(buf + 12, itype(ADDI, 0, 0, 0));
2300b57cec5SDimitry Andric }
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric RelType RISCV::getDynRel(RelType type) const {
2330b57cec5SDimitry Andric   return type == target->symbolicRel ? type
2340b57cec5SDimitry Andric                                      : static_cast<RelType>(R_RISCV_NONE);
2350b57cec5SDimitry Andric }
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric RelExpr RISCV::getRelExpr(const RelType type, const Symbol &s,
2380b57cec5SDimitry Andric                           const uint8_t *loc) const {
2390b57cec5SDimitry Andric   switch (type) {
240480093f4SDimitry Andric   case R_RISCV_NONE:
241480093f4SDimitry Andric     return R_NONE;
242480093f4SDimitry Andric   case R_RISCV_32:
243480093f4SDimitry Andric   case R_RISCV_64:
244480093f4SDimitry Andric   case R_RISCV_HI20:
245480093f4SDimitry Andric   case R_RISCV_LO12_I:
246480093f4SDimitry Andric   case R_RISCV_LO12_S:
247480093f4SDimitry Andric   case R_RISCV_RVC_LUI:
248480093f4SDimitry Andric     return R_ABS;
2490b57cec5SDimitry Andric   case R_RISCV_ADD8:
2500b57cec5SDimitry Andric   case R_RISCV_ADD16:
2510b57cec5SDimitry Andric   case R_RISCV_ADD32:
2520b57cec5SDimitry Andric   case R_RISCV_ADD64:
2530b57cec5SDimitry Andric   case R_RISCV_SET6:
2540b57cec5SDimitry Andric   case R_RISCV_SET8:
2550b57cec5SDimitry Andric   case R_RISCV_SET16:
2560b57cec5SDimitry Andric   case R_RISCV_SET32:
2570b57cec5SDimitry Andric   case R_RISCV_SUB6:
2580b57cec5SDimitry Andric   case R_RISCV_SUB8:
2590b57cec5SDimitry Andric   case R_RISCV_SUB16:
2600b57cec5SDimitry Andric   case R_RISCV_SUB32:
2610b57cec5SDimitry Andric   case R_RISCV_SUB64:
2620b57cec5SDimitry Andric     return R_RISCV_ADD;
2630b57cec5SDimitry Andric   case R_RISCV_JAL:
2640b57cec5SDimitry Andric   case R_RISCV_BRANCH:
2650b57cec5SDimitry Andric   case R_RISCV_PCREL_HI20:
2660b57cec5SDimitry Andric   case R_RISCV_RVC_BRANCH:
2670b57cec5SDimitry Andric   case R_RISCV_RVC_JUMP:
2680b57cec5SDimitry Andric   case R_RISCV_32_PCREL:
2690b57cec5SDimitry Andric     return R_PC;
2700b57cec5SDimitry Andric   case R_RISCV_CALL:
2710b57cec5SDimitry Andric   case R_RISCV_CALL_PLT:
2720b57cec5SDimitry Andric     return R_PLT_PC;
2730b57cec5SDimitry Andric   case R_RISCV_GOT_HI20:
2740b57cec5SDimitry Andric     return R_GOT_PC;
2750b57cec5SDimitry Andric   case R_RISCV_PCREL_LO12_I:
2760b57cec5SDimitry Andric   case R_RISCV_PCREL_LO12_S:
2770b57cec5SDimitry Andric     return R_RISCV_PC_INDIRECT;
2780b57cec5SDimitry Andric   case R_RISCV_TLS_GD_HI20:
2790b57cec5SDimitry Andric     return R_TLSGD_PC;
2800b57cec5SDimitry Andric   case R_RISCV_TLS_GOT_HI20:
2814824e7fdSDimitry Andric     config->hasTlsIe = true;
2820b57cec5SDimitry Andric     return R_GOT_PC;
2830b57cec5SDimitry Andric   case R_RISCV_TPREL_HI20:
2840b57cec5SDimitry Andric   case R_RISCV_TPREL_LO12_I:
2850b57cec5SDimitry Andric   case R_RISCV_TPREL_LO12_S:
286e8d8bef9SDimitry Andric     return R_TPREL;
28755e4f9d5SDimitry Andric   case R_RISCV_ALIGN:
288753f127fSDimitry Andric     return R_RELAX_HINT;
289fcaf7f86SDimitry Andric   case R_RISCV_TPREL_ADD:
290753f127fSDimitry Andric   case R_RISCV_RELAX:
291753f127fSDimitry Andric     return config->relax ? R_RELAX_HINT : R_NONE;
2920b57cec5SDimitry Andric   default:
293480093f4SDimitry Andric     error(getErrorLocation(loc) + "unknown relocation (" + Twine(type) +
294480093f4SDimitry Andric           ") against symbol " + toString(s));
295480093f4SDimitry Andric     return R_NONE;
2960b57cec5SDimitry Andric   }
2970b57cec5SDimitry Andric }
2980b57cec5SDimitry Andric 
2995ffd83dbSDimitry Andric void RISCV::relocate(uint8_t *loc, const Relocation &rel, uint64_t val) const {
3000b57cec5SDimitry Andric   const unsigned bits = config->wordsize * 8;
3010b57cec5SDimitry Andric 
3025ffd83dbSDimitry Andric   switch (rel.type) {
3030b57cec5SDimitry Andric   case R_RISCV_32:
3040b57cec5SDimitry Andric     write32le(loc, val);
3050b57cec5SDimitry Andric     return;
3060b57cec5SDimitry Andric   case R_RISCV_64:
3070b57cec5SDimitry Andric     write64le(loc, val);
3080b57cec5SDimitry Andric     return;
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric   case R_RISCV_RVC_BRANCH: {
311753f127fSDimitry Andric     checkInt(loc, val, 9, rel);
3125ffd83dbSDimitry Andric     checkAlignment(loc, val, 2, rel);
3130b57cec5SDimitry Andric     uint16_t insn = read16le(loc) & 0xE383;
3140b57cec5SDimitry Andric     uint16_t imm8 = extractBits(val, 8, 8) << 12;
3150b57cec5SDimitry Andric     uint16_t imm4_3 = extractBits(val, 4, 3) << 10;
3160b57cec5SDimitry Andric     uint16_t imm7_6 = extractBits(val, 7, 6) << 5;
3170b57cec5SDimitry Andric     uint16_t imm2_1 = extractBits(val, 2, 1) << 3;
3180b57cec5SDimitry Andric     uint16_t imm5 = extractBits(val, 5, 5) << 2;
3190b57cec5SDimitry Andric     insn |= imm8 | imm4_3 | imm7_6 | imm2_1 | imm5;
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric     write16le(loc, insn);
3220b57cec5SDimitry Andric     return;
3230b57cec5SDimitry Andric   }
3240b57cec5SDimitry Andric 
3250b57cec5SDimitry Andric   case R_RISCV_RVC_JUMP: {
326753f127fSDimitry Andric     checkInt(loc, val, 12, rel);
3275ffd83dbSDimitry Andric     checkAlignment(loc, val, 2, rel);
3280b57cec5SDimitry Andric     uint16_t insn = read16le(loc) & 0xE003;
3290b57cec5SDimitry Andric     uint16_t imm11 = extractBits(val, 11, 11) << 12;
3300b57cec5SDimitry Andric     uint16_t imm4 = extractBits(val, 4, 4) << 11;
3310b57cec5SDimitry Andric     uint16_t imm9_8 = extractBits(val, 9, 8) << 9;
3320b57cec5SDimitry Andric     uint16_t imm10 = extractBits(val, 10, 10) << 8;
3330b57cec5SDimitry Andric     uint16_t imm6 = extractBits(val, 6, 6) << 7;
3340b57cec5SDimitry Andric     uint16_t imm7 = extractBits(val, 7, 7) << 6;
3350b57cec5SDimitry Andric     uint16_t imm3_1 = extractBits(val, 3, 1) << 3;
3360b57cec5SDimitry Andric     uint16_t imm5 = extractBits(val, 5, 5) << 2;
3370b57cec5SDimitry Andric     insn |= imm11 | imm4 | imm9_8 | imm10 | imm6 | imm7 | imm3_1 | imm5;
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric     write16le(loc, insn);
3400b57cec5SDimitry Andric     return;
3410b57cec5SDimitry Andric   }
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric   case R_RISCV_RVC_LUI: {
3440b57cec5SDimitry Andric     int64_t imm = SignExtend64(val + 0x800, bits) >> 12;
3455ffd83dbSDimitry Andric     checkInt(loc, imm, 6, rel);
3460b57cec5SDimitry Andric     if (imm == 0) { // `c.lui rd, 0` is illegal, convert to `c.li rd, 0`
3470b57cec5SDimitry Andric       write16le(loc, (read16le(loc) & 0x0F83) | 0x4000);
3480b57cec5SDimitry Andric     } else {
3490b57cec5SDimitry Andric       uint16_t imm17 = extractBits(val + 0x800, 17, 17) << 12;
3500b57cec5SDimitry Andric       uint16_t imm16_12 = extractBits(val + 0x800, 16, 12) << 2;
3510b57cec5SDimitry Andric       write16le(loc, (read16le(loc) & 0xEF83) | imm17 | imm16_12);
3520b57cec5SDimitry Andric     }
3530b57cec5SDimitry Andric     return;
3540b57cec5SDimitry Andric   }
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric   case R_RISCV_JAL: {
357753f127fSDimitry Andric     checkInt(loc, val, 21, rel);
3585ffd83dbSDimitry Andric     checkAlignment(loc, val, 2, rel);
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric     uint32_t insn = read32le(loc) & 0xFFF;
3610b57cec5SDimitry Andric     uint32_t imm20 = extractBits(val, 20, 20) << 31;
3620b57cec5SDimitry Andric     uint32_t imm10_1 = extractBits(val, 10, 1) << 21;
3630b57cec5SDimitry Andric     uint32_t imm11 = extractBits(val, 11, 11) << 20;
3640b57cec5SDimitry Andric     uint32_t imm19_12 = extractBits(val, 19, 12) << 12;
3650b57cec5SDimitry Andric     insn |= imm20 | imm10_1 | imm11 | imm19_12;
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric     write32le(loc, insn);
3680b57cec5SDimitry Andric     return;
3690b57cec5SDimitry Andric   }
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   case R_RISCV_BRANCH: {
372753f127fSDimitry Andric     checkInt(loc, val, 13, rel);
3735ffd83dbSDimitry Andric     checkAlignment(loc, val, 2, rel);
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric     uint32_t insn = read32le(loc) & 0x1FFF07F;
3760b57cec5SDimitry Andric     uint32_t imm12 = extractBits(val, 12, 12) << 31;
3770b57cec5SDimitry Andric     uint32_t imm10_5 = extractBits(val, 10, 5) << 25;
3780b57cec5SDimitry Andric     uint32_t imm4_1 = extractBits(val, 4, 1) << 8;
3790b57cec5SDimitry Andric     uint32_t imm11 = extractBits(val, 11, 11) << 7;
3800b57cec5SDimitry Andric     insn |= imm12 | imm10_5 | imm4_1 | imm11;
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric     write32le(loc, insn);
3830b57cec5SDimitry Andric     return;
3840b57cec5SDimitry Andric   }
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric   // auipc + jalr pair
3870b57cec5SDimitry Andric   case R_RISCV_CALL:
3880b57cec5SDimitry Andric   case R_RISCV_CALL_PLT: {
3890b57cec5SDimitry Andric     int64_t hi = SignExtend64(val + 0x800, bits) >> 12;
3905ffd83dbSDimitry Andric     checkInt(loc, hi, 20, rel);
3910b57cec5SDimitry Andric     if (isInt<20>(hi)) {
3925ffd83dbSDimitry Andric       relocateNoSym(loc, R_RISCV_PCREL_HI20, val);
3935ffd83dbSDimitry Andric       relocateNoSym(loc + 4, R_RISCV_PCREL_LO12_I, val);
3940b57cec5SDimitry Andric     }
3950b57cec5SDimitry Andric     return;
3960b57cec5SDimitry Andric   }
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric   case R_RISCV_GOT_HI20:
3990b57cec5SDimitry Andric   case R_RISCV_PCREL_HI20:
4000b57cec5SDimitry Andric   case R_RISCV_TLS_GD_HI20:
4010b57cec5SDimitry Andric   case R_RISCV_TLS_GOT_HI20:
4020b57cec5SDimitry Andric   case R_RISCV_TPREL_HI20:
4030b57cec5SDimitry Andric   case R_RISCV_HI20: {
4040b57cec5SDimitry Andric     uint64_t hi = val + 0x800;
4055ffd83dbSDimitry Andric     checkInt(loc, SignExtend64(hi, bits) >> 12, 20, rel);
4060b57cec5SDimitry Andric     write32le(loc, (read32le(loc) & 0xFFF) | (hi & 0xFFFFF000));
4070b57cec5SDimitry Andric     return;
4080b57cec5SDimitry Andric   }
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric   case R_RISCV_PCREL_LO12_I:
4110b57cec5SDimitry Andric   case R_RISCV_TPREL_LO12_I:
4120b57cec5SDimitry Andric   case R_RISCV_LO12_I: {
4130b57cec5SDimitry Andric     uint64_t hi = (val + 0x800) >> 12;
4140b57cec5SDimitry Andric     uint64_t lo = val - (hi << 12);
415fcaf7f86SDimitry Andric     write32le(loc, setLO12_I(read32le(loc), lo & 0xfff));
4160b57cec5SDimitry Andric     return;
4170b57cec5SDimitry Andric   }
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric   case R_RISCV_PCREL_LO12_S:
4200b57cec5SDimitry Andric   case R_RISCV_TPREL_LO12_S:
4210b57cec5SDimitry Andric   case R_RISCV_LO12_S: {
4220b57cec5SDimitry Andric     uint64_t hi = (val + 0x800) >> 12;
4230b57cec5SDimitry Andric     uint64_t lo = val - (hi << 12);
424fcaf7f86SDimitry Andric     write32le(loc, setLO12_S(read32le(loc), lo));
4250b57cec5SDimitry Andric     return;
4260b57cec5SDimitry Andric   }
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric   case R_RISCV_ADD8:
4290b57cec5SDimitry Andric     *loc += val;
4300b57cec5SDimitry Andric     return;
4310b57cec5SDimitry Andric   case R_RISCV_ADD16:
4320b57cec5SDimitry Andric     write16le(loc, read16le(loc) + val);
4330b57cec5SDimitry Andric     return;
4340b57cec5SDimitry Andric   case R_RISCV_ADD32:
4350b57cec5SDimitry Andric     write32le(loc, read32le(loc) + val);
4360b57cec5SDimitry Andric     return;
4370b57cec5SDimitry Andric   case R_RISCV_ADD64:
4380b57cec5SDimitry Andric     write64le(loc, read64le(loc) + val);
4390b57cec5SDimitry Andric     return;
4400b57cec5SDimitry Andric   case R_RISCV_SUB6:
4410b57cec5SDimitry Andric     *loc = (*loc & 0xc0) | (((*loc & 0x3f) - val) & 0x3f);
4420b57cec5SDimitry Andric     return;
4430b57cec5SDimitry Andric   case R_RISCV_SUB8:
4440b57cec5SDimitry Andric     *loc -= val;
4450b57cec5SDimitry Andric     return;
4460b57cec5SDimitry Andric   case R_RISCV_SUB16:
4470b57cec5SDimitry Andric     write16le(loc, read16le(loc) - val);
4480b57cec5SDimitry Andric     return;
4490b57cec5SDimitry Andric   case R_RISCV_SUB32:
4500b57cec5SDimitry Andric     write32le(loc, read32le(loc) - val);
4510b57cec5SDimitry Andric     return;
4520b57cec5SDimitry Andric   case R_RISCV_SUB64:
4530b57cec5SDimitry Andric     write64le(loc, read64le(loc) - val);
4540b57cec5SDimitry Andric     return;
4550b57cec5SDimitry Andric   case R_RISCV_SET6:
4560b57cec5SDimitry Andric     *loc = (*loc & 0xc0) | (val & 0x3f);
4570b57cec5SDimitry Andric     return;
4580b57cec5SDimitry Andric   case R_RISCV_SET8:
4590b57cec5SDimitry Andric     *loc = val;
4600b57cec5SDimitry Andric     return;
4610b57cec5SDimitry Andric   case R_RISCV_SET16:
4620b57cec5SDimitry Andric     write16le(loc, val);
4630b57cec5SDimitry Andric     return;
4640b57cec5SDimitry Andric   case R_RISCV_SET32:
4650b57cec5SDimitry Andric   case R_RISCV_32_PCREL:
4660b57cec5SDimitry Andric     write32le(loc, val);
4670b57cec5SDimitry Andric     return;
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   case R_RISCV_TLS_DTPREL32:
4700b57cec5SDimitry Andric     write32le(loc, val - dtpOffset);
4710b57cec5SDimitry Andric     break;
4720b57cec5SDimitry Andric   case R_RISCV_TLS_DTPREL64:
4730b57cec5SDimitry Andric     write64le(loc, val - dtpOffset);
4740b57cec5SDimitry Andric     break;
4750b57cec5SDimitry Andric 
4760b57cec5SDimitry Andric   case R_RISCV_RELAX:
4770b57cec5SDimitry Andric     return; // Ignored (for now)
4780b57cec5SDimitry Andric 
4790b57cec5SDimitry Andric   default:
480480093f4SDimitry Andric     llvm_unreachable("unknown relocation");
4810b57cec5SDimitry Andric   }
4820b57cec5SDimitry Andric }
4830b57cec5SDimitry Andric 
484753f127fSDimitry Andric namespace {
485753f127fSDimitry Andric struct SymbolAnchor {
486753f127fSDimitry Andric   uint64_t offset;
487753f127fSDimitry Andric   Defined *d;
488753f127fSDimitry Andric   bool end; // true for the anchor of st_value+st_size
489753f127fSDimitry Andric };
490753f127fSDimitry Andric } // namespace
491753f127fSDimitry Andric 
492753f127fSDimitry Andric struct elf::RISCVRelaxAux {
493753f127fSDimitry Andric   // This records symbol start and end offsets which will be adjusted according
494753f127fSDimitry Andric   // to the nearest relocDeltas element.
495753f127fSDimitry Andric   SmallVector<SymbolAnchor, 0> anchors;
496753f127fSDimitry Andric   // For relocations[i], the actual offset is r_offset - (i ? relocDeltas[i-1] :
497753f127fSDimitry Andric   // 0).
498753f127fSDimitry Andric   std::unique_ptr<uint32_t[]> relocDeltas;
499753f127fSDimitry Andric   // For relocations[i], the actual type is relocTypes[i].
500753f127fSDimitry Andric   std::unique_ptr<RelType[]> relocTypes;
501753f127fSDimitry Andric   SmallVector<uint32_t, 0> writes;
502753f127fSDimitry Andric };
503753f127fSDimitry Andric 
504753f127fSDimitry Andric static void initSymbolAnchors() {
505753f127fSDimitry Andric   SmallVector<InputSection *, 0> storage;
506753f127fSDimitry Andric   for (OutputSection *osec : outputSections) {
507753f127fSDimitry Andric     if (!(osec->flags & SHF_EXECINSTR))
508753f127fSDimitry Andric       continue;
509753f127fSDimitry Andric     for (InputSection *sec : getInputSections(*osec, storage)) {
510753f127fSDimitry Andric       sec->relaxAux = make<RISCVRelaxAux>();
511753f127fSDimitry Andric       if (sec->relocations.size()) {
512753f127fSDimitry Andric         sec->relaxAux->relocDeltas =
513753f127fSDimitry Andric             std::make_unique<uint32_t[]>(sec->relocations.size());
514753f127fSDimitry Andric         sec->relaxAux->relocTypes =
515753f127fSDimitry Andric             std::make_unique<RelType[]>(sec->relocations.size());
516753f127fSDimitry Andric       }
517753f127fSDimitry Andric     }
518753f127fSDimitry Andric   }
519753f127fSDimitry Andric   // Store anchors (st_value and st_value+st_size) for symbols relative to text
520753f127fSDimitry Andric   // sections.
521753f127fSDimitry Andric   for (InputFile *file : ctx->objectFiles)
522753f127fSDimitry Andric     for (Symbol *sym : file->getSymbols()) {
523753f127fSDimitry Andric       auto *d = dyn_cast<Defined>(sym);
524753f127fSDimitry Andric       if (!d || d->file != file)
525753f127fSDimitry Andric         continue;
526753f127fSDimitry Andric       if (auto *sec = dyn_cast_or_null<InputSection>(d->section))
527753f127fSDimitry Andric         if (sec->flags & SHF_EXECINSTR && sec->relaxAux) {
528753f127fSDimitry Andric           // If sec is discarded, relaxAux will be nullptr.
529753f127fSDimitry Andric           sec->relaxAux->anchors.push_back({d->value, d, false});
530753f127fSDimitry Andric           sec->relaxAux->anchors.push_back({d->value + d->size, d, true});
531753f127fSDimitry Andric         }
532753f127fSDimitry Andric     }
533753f127fSDimitry Andric   // Sort anchors by offset so that we can find the closest relocation
534753f127fSDimitry Andric   // efficiently. For a zero size symbol, ensure that its start anchor precedes
535753f127fSDimitry Andric   // its end anchor. For two symbols with anchors at the same offset, their
536753f127fSDimitry Andric   // order does not matter.
537753f127fSDimitry Andric   for (OutputSection *osec : outputSections) {
538753f127fSDimitry Andric     if (!(osec->flags & SHF_EXECINSTR))
539753f127fSDimitry Andric       continue;
540753f127fSDimitry Andric     for (InputSection *sec : getInputSections(*osec, storage)) {
541753f127fSDimitry Andric       llvm::sort(sec->relaxAux->anchors, [](auto &a, auto &b) {
542753f127fSDimitry Andric         return std::make_pair(a.offset, a.end) <
543753f127fSDimitry Andric                std::make_pair(b.offset, b.end);
544753f127fSDimitry Andric       });
545753f127fSDimitry Andric     }
546753f127fSDimitry Andric   }
547753f127fSDimitry Andric }
548753f127fSDimitry Andric 
549753f127fSDimitry Andric // Relax R_RISCV_CALL/R_RISCV_CALL_PLT auipc+jalr to c.j, c.jal, or jal.
550753f127fSDimitry Andric static void relaxCall(const InputSection &sec, size_t i, uint64_t loc,
551753f127fSDimitry Andric                       Relocation &r, uint32_t &remove) {
552753f127fSDimitry Andric   const bool rvc = config->eflags & EF_RISCV_RVC;
553753f127fSDimitry Andric   const Symbol &sym = *r.sym;
554753f127fSDimitry Andric   const uint64_t insnPair = read64le(sec.rawData.data() + r.offset);
555753f127fSDimitry Andric   const uint32_t rd = extractBits(insnPair, 32 + 11, 32 + 7);
556753f127fSDimitry Andric   const uint64_t dest =
557753f127fSDimitry Andric       (r.expr == R_PLT_PC ? sym.getPltVA() : sym.getVA()) + r.addend;
558753f127fSDimitry Andric   const int64_t displace = dest - loc;
559753f127fSDimitry Andric 
560753f127fSDimitry Andric   if (rvc && isInt<12>(displace) && rd == 0) {
561753f127fSDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_RVC_JUMP;
562753f127fSDimitry Andric     sec.relaxAux->writes.push_back(0xa001); // c.j
563753f127fSDimitry Andric     remove = 6;
564753f127fSDimitry Andric   } else if (rvc && isInt<12>(displace) && rd == X_RA &&
565753f127fSDimitry Andric              !config->is64) { // RV32C only
566753f127fSDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_RVC_JUMP;
567753f127fSDimitry Andric     sec.relaxAux->writes.push_back(0x2001); // c.jal
568753f127fSDimitry Andric     remove = 6;
569753f127fSDimitry Andric   } else if (isInt<21>(displace)) {
570753f127fSDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_JAL;
571753f127fSDimitry Andric     sec.relaxAux->writes.push_back(0x6f | rd << 7); // jal
572753f127fSDimitry Andric     remove = 4;
573753f127fSDimitry Andric   }
574753f127fSDimitry Andric }
575753f127fSDimitry Andric 
576fcaf7f86SDimitry Andric // Relax local-exec TLS when hi20 is zero.
577fcaf7f86SDimitry Andric static void relaxTlsLe(const InputSection &sec, size_t i, uint64_t loc,
578fcaf7f86SDimitry Andric                        Relocation &r, uint32_t &remove) {
579fcaf7f86SDimitry Andric   uint64_t val = r.sym->getVA(r.addend);
580fcaf7f86SDimitry Andric   if (hi20(val) != 0)
581fcaf7f86SDimitry Andric     return;
582fcaf7f86SDimitry Andric   uint32_t insn = read32le(sec.rawData.data() + r.offset);
583fcaf7f86SDimitry Andric   switch (r.type) {
584fcaf7f86SDimitry Andric   case R_RISCV_TPREL_HI20:
585fcaf7f86SDimitry Andric   case R_RISCV_TPREL_ADD:
586fcaf7f86SDimitry Andric     // Remove lui rd, %tprel_hi(x) and add rd, rd, tp, %tprel_add(x).
587fcaf7f86SDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_RELAX;
588fcaf7f86SDimitry Andric     remove = 4;
589fcaf7f86SDimitry Andric     break;
590fcaf7f86SDimitry Andric   case R_RISCV_TPREL_LO12_I:
591fcaf7f86SDimitry Andric     // addi rd, rd, %tprel_lo(x) => addi rd, tp, st_value(x)
592fcaf7f86SDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_32;
593fcaf7f86SDimitry Andric     insn = (insn & ~(31 << 15)) | (X_TP << 15);
594fcaf7f86SDimitry Andric     sec.relaxAux->writes.push_back(setLO12_I(insn, val));
595fcaf7f86SDimitry Andric     break;
596fcaf7f86SDimitry Andric   case R_RISCV_TPREL_LO12_S:
597fcaf7f86SDimitry Andric     // sw rs, %tprel_lo(x)(rd) => sw rs, st_value(x)(rd)
598fcaf7f86SDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_32;
599fcaf7f86SDimitry Andric     insn = (insn & ~(31 << 15)) | (X_TP << 15);
600fcaf7f86SDimitry Andric     sec.relaxAux->writes.push_back(setLO12_S(insn, val));
601fcaf7f86SDimitry Andric     break;
602fcaf7f86SDimitry Andric   }
603fcaf7f86SDimitry Andric }
604fcaf7f86SDimitry Andric 
605753f127fSDimitry Andric static bool relax(InputSection &sec) {
606753f127fSDimitry Andric   const uint64_t secAddr = sec.getVA();
607753f127fSDimitry Andric   auto &aux = *sec.relaxAux;
608753f127fSDimitry Andric   bool changed = false;
609753f127fSDimitry Andric 
610753f127fSDimitry Andric   // Get st_value delta for symbols relative to this section from the previous
611753f127fSDimitry Andric   // iteration.
612753f127fSDimitry Andric   DenseMap<const Defined *, uint64_t> valueDelta;
613753f127fSDimitry Andric   ArrayRef<SymbolAnchor> sa = makeArrayRef(aux.anchors);
614753f127fSDimitry Andric   uint32_t delta = 0;
615753f127fSDimitry Andric   for (auto it : llvm::enumerate(sec.relocations)) {
616753f127fSDimitry Andric     for (; sa.size() && sa[0].offset <= it.value().offset; sa = sa.slice(1))
617753f127fSDimitry Andric       if (!sa[0].end)
618753f127fSDimitry Andric         valueDelta[sa[0].d] = delta;
619753f127fSDimitry Andric     delta = aux.relocDeltas[it.index()];
620753f127fSDimitry Andric   }
621753f127fSDimitry Andric   for (const SymbolAnchor &sa : sa)
622753f127fSDimitry Andric     if (!sa.end)
623753f127fSDimitry Andric       valueDelta[sa.d] = delta;
624753f127fSDimitry Andric   sa = makeArrayRef(aux.anchors);
625753f127fSDimitry Andric   delta = 0;
626753f127fSDimitry Andric 
627753f127fSDimitry Andric   std::fill_n(aux.relocTypes.get(), sec.relocations.size(), R_RISCV_NONE);
628753f127fSDimitry Andric   aux.writes.clear();
629753f127fSDimitry Andric   for (auto it : llvm::enumerate(sec.relocations)) {
630753f127fSDimitry Andric     Relocation &r = it.value();
631753f127fSDimitry Andric     const size_t i = it.index();
632753f127fSDimitry Andric     const uint64_t loc = secAddr + r.offset - delta;
633753f127fSDimitry Andric     uint32_t &cur = aux.relocDeltas[i], remove = 0;
634753f127fSDimitry Andric     switch (r.type) {
635753f127fSDimitry Andric     case R_RISCV_ALIGN: {
636753f127fSDimitry Andric       const uint64_t nextLoc = loc + r.addend;
637753f127fSDimitry Andric       const uint64_t align = PowerOf2Ceil(r.addend + 2);
638753f127fSDimitry Andric       // All bytes beyond the alignment boundary should be removed.
639753f127fSDimitry Andric       remove = nextLoc - ((loc + align - 1) & -align);
640753f127fSDimitry Andric       assert(static_cast<int32_t>(remove) >= 0 &&
641753f127fSDimitry Andric              "R_RISCV_ALIGN needs expanding the content");
642753f127fSDimitry Andric       break;
643753f127fSDimitry Andric     }
644753f127fSDimitry Andric     case R_RISCV_CALL:
645753f127fSDimitry Andric     case R_RISCV_CALL_PLT:
646753f127fSDimitry Andric       if (i + 1 != sec.relocations.size() &&
647753f127fSDimitry Andric           sec.relocations[i + 1].type == R_RISCV_RELAX)
648753f127fSDimitry Andric         relaxCall(sec, i, loc, r, remove);
649753f127fSDimitry Andric       break;
650fcaf7f86SDimitry Andric     case R_RISCV_TPREL_HI20:
651fcaf7f86SDimitry Andric     case R_RISCV_TPREL_ADD:
652fcaf7f86SDimitry Andric     case R_RISCV_TPREL_LO12_I:
653fcaf7f86SDimitry Andric     case R_RISCV_TPREL_LO12_S:
654fcaf7f86SDimitry Andric       if (i + 1 != sec.relocations.size() &&
655fcaf7f86SDimitry Andric           sec.relocations[i + 1].type == R_RISCV_RELAX)
656fcaf7f86SDimitry Andric         relaxTlsLe(sec, i, loc, r, remove);
657fcaf7f86SDimitry Andric       break;
658753f127fSDimitry Andric     }
659753f127fSDimitry Andric 
660753f127fSDimitry Andric     // For all anchors whose offsets are <= r.offset, they are preceded by
661753f127fSDimitry Andric     // the previous relocation whose `relocDeltas` value equals `delta`.
662753f127fSDimitry Andric     // Decrease their st_value and update their st_size.
663753f127fSDimitry Andric     for (; sa.size() && sa[0].offset <= r.offset; sa = sa.slice(1)) {
664753f127fSDimitry Andric       if (sa[0].end)
665753f127fSDimitry Andric         sa[0].d->size = sa[0].offset - delta - sa[0].d->value;
666753f127fSDimitry Andric       else
667753f127fSDimitry Andric         sa[0].d->value -= delta - valueDelta.find(sa[0].d)->second;
668753f127fSDimitry Andric     }
669753f127fSDimitry Andric     delta += remove;
670753f127fSDimitry Andric     if (delta != cur) {
671753f127fSDimitry Andric       cur = delta;
672753f127fSDimitry Andric       changed = true;
673753f127fSDimitry Andric     }
674753f127fSDimitry Andric   }
675753f127fSDimitry Andric 
676753f127fSDimitry Andric   for (const SymbolAnchor &a : sa) {
677753f127fSDimitry Andric     if (a.end)
678753f127fSDimitry Andric       a.d->size = a.offset - delta - a.d->value;
679753f127fSDimitry Andric     else
680753f127fSDimitry Andric       a.d->value -= delta - valueDelta.find(a.d)->second;
681753f127fSDimitry Andric   }
682753f127fSDimitry Andric   // Inform assignAddresses that the size has changed.
683753f127fSDimitry Andric   if (!isUInt<16>(delta))
684753f127fSDimitry Andric     fatal("section size decrease is too large");
685753f127fSDimitry Andric   sec.bytesDropped = delta;
686753f127fSDimitry Andric   return changed;
687753f127fSDimitry Andric }
688753f127fSDimitry Andric 
689753f127fSDimitry Andric // When relaxing just R_RISCV_ALIGN, relocDeltas is usually changed only once in
690753f127fSDimitry Andric // the absence of a linker script. For call and load/store R_RISCV_RELAX, code
691753f127fSDimitry Andric // shrinkage may reduce displacement and make more relocations eligible for
692753f127fSDimitry Andric // relaxation. Code shrinkage may increase displacement to a call/load/store
693753f127fSDimitry Andric // target at a higher fixed address, invalidating an earlier relaxation. Any
694753f127fSDimitry Andric // change in section sizes can have cascading effect and require another
695753f127fSDimitry Andric // relaxation pass.
696753f127fSDimitry Andric bool RISCV::relaxOnce(int pass) const {
697753f127fSDimitry Andric   llvm::TimeTraceScope timeScope("RISC-V relaxOnce");
698753f127fSDimitry Andric   if (config->relocatable)
699753f127fSDimitry Andric     return false;
700753f127fSDimitry Andric 
701753f127fSDimitry Andric   if (pass == 0)
702753f127fSDimitry Andric     initSymbolAnchors();
703753f127fSDimitry Andric 
704753f127fSDimitry Andric   SmallVector<InputSection *, 0> storage;
705753f127fSDimitry Andric   bool changed = false;
706753f127fSDimitry Andric   for (OutputSection *osec : outputSections) {
707753f127fSDimitry Andric     if (!(osec->flags & SHF_EXECINSTR))
708753f127fSDimitry Andric       continue;
709753f127fSDimitry Andric     for (InputSection *sec : getInputSections(*osec, storage))
710753f127fSDimitry Andric       changed |= relax(*sec);
711753f127fSDimitry Andric   }
712753f127fSDimitry Andric   return changed;
713753f127fSDimitry Andric }
714753f127fSDimitry Andric 
715753f127fSDimitry Andric void elf::riscvFinalizeRelax(int passes) {
716753f127fSDimitry Andric   llvm::TimeTraceScope timeScope("Finalize RISC-V relaxation");
717753f127fSDimitry Andric   log("relaxation passes: " + Twine(passes));
718753f127fSDimitry Andric   SmallVector<InputSection *, 0> storage;
719753f127fSDimitry Andric   for (OutputSection *osec : outputSections) {
720753f127fSDimitry Andric     if (!(osec->flags & SHF_EXECINSTR))
721753f127fSDimitry Andric       continue;
722753f127fSDimitry Andric     for (InputSection *sec : getInputSections(*osec, storage)) {
723753f127fSDimitry Andric       RISCVRelaxAux &aux = *sec->relaxAux;
724753f127fSDimitry Andric       if (!aux.relocDeltas)
725753f127fSDimitry Andric         continue;
726753f127fSDimitry Andric 
727753f127fSDimitry Andric       auto &rels = sec->relocations;
728753f127fSDimitry Andric       ArrayRef<uint8_t> old = sec->rawData;
729753f127fSDimitry Andric       size_t newSize =
730753f127fSDimitry Andric           old.size() - aux.relocDeltas[sec->relocations.size() - 1];
731753f127fSDimitry Andric       size_t writesIdx = 0;
732753f127fSDimitry Andric       uint8_t *p = context().bAlloc.Allocate<uint8_t>(newSize);
733753f127fSDimitry Andric       uint64_t offset = 0;
734753f127fSDimitry Andric       int64_t delta = 0;
735753f127fSDimitry Andric       sec->rawData = makeArrayRef(p, newSize);
736753f127fSDimitry Andric       sec->bytesDropped = 0;
737753f127fSDimitry Andric 
738753f127fSDimitry Andric       // Update section content: remove NOPs for R_RISCV_ALIGN and rewrite
739753f127fSDimitry Andric       // instructions for relaxed relocations.
740753f127fSDimitry Andric       for (size_t i = 0, e = rels.size(); i != e; ++i) {
741753f127fSDimitry Andric         uint32_t remove = aux.relocDeltas[i] - delta;
742753f127fSDimitry Andric         delta = aux.relocDeltas[i];
743fcaf7f86SDimitry Andric         if (remove == 0 && aux.relocTypes[i] == R_RISCV_NONE)
744753f127fSDimitry Andric           continue;
745753f127fSDimitry Andric 
746753f127fSDimitry Andric         // Copy from last location to the current relocated location.
747753f127fSDimitry Andric         const Relocation &r = rels[i];
748753f127fSDimitry Andric         uint64_t size = r.offset - offset;
749753f127fSDimitry Andric         memcpy(p, old.data() + offset, size);
750753f127fSDimitry Andric         p += size;
751753f127fSDimitry Andric 
752753f127fSDimitry Andric         // For R_RISCV_ALIGN, we will place `offset` in a location (among NOPs)
753*6246ae0bSDimitry Andric         // to satisfy the alignment requirement. If both `remove` and r.addend
754*6246ae0bSDimitry Andric         // are multiples of 4, it is as if we have skipped some NOPs. Otherwise
755*6246ae0bSDimitry Andric         // we are in the middle of a 4-byte NOP, and we need to rewrite the NOP
756*6246ae0bSDimitry Andric         // sequence.
757753f127fSDimitry Andric         int64_t skip = 0;
758753f127fSDimitry Andric         if (r.type == R_RISCV_ALIGN) {
759*6246ae0bSDimitry Andric           if (remove % 4 || r.addend % 4) {
760753f127fSDimitry Andric             skip = r.addend - remove;
761753f127fSDimitry Andric             int64_t j = 0;
762753f127fSDimitry Andric             for (; j + 4 <= skip; j += 4)
763753f127fSDimitry Andric               write32le(p + j, 0x00000013); // nop
764753f127fSDimitry Andric             if (j != skip) {
765753f127fSDimitry Andric               assert(j + 2 == skip);
766753f127fSDimitry Andric               write16le(p + j, 0x0001); // c.nop
767753f127fSDimitry Andric             }
768753f127fSDimitry Andric           }
769753f127fSDimitry Andric         } else if (RelType newType = aux.relocTypes[i]) {
770753f127fSDimitry Andric           switch (newType) {
771fcaf7f86SDimitry Andric           case R_RISCV_RELAX:
772fcaf7f86SDimitry Andric             // Used by relaxTlsLe to indicate the relocation is ignored.
773fcaf7f86SDimitry Andric             break;
774753f127fSDimitry Andric           case R_RISCV_RVC_JUMP:
775753f127fSDimitry Andric             skip = 2;
776fcaf7f86SDimitry Andric             write16le(p, aux.writes[writesIdx++]);
777753f127fSDimitry Andric             break;
778753f127fSDimitry Andric           case R_RISCV_JAL:
779753f127fSDimitry Andric             skip = 4;
780fcaf7f86SDimitry Andric             write32le(p, aux.writes[writesIdx++]);
781fcaf7f86SDimitry Andric             break;
782fcaf7f86SDimitry Andric           case R_RISCV_32:
783fcaf7f86SDimitry Andric             // Used by relaxTlsLe to write a uint32_t then suppress the handling
784fcaf7f86SDimitry Andric             // in relocateAlloc.
785fcaf7f86SDimitry Andric             skip = 4;
786fcaf7f86SDimitry Andric             write32le(p, aux.writes[writesIdx++]);
787fcaf7f86SDimitry Andric             aux.relocTypes[i] = R_RISCV_NONE;
788753f127fSDimitry Andric             break;
789753f127fSDimitry Andric           default:
790753f127fSDimitry Andric             llvm_unreachable("unsupported type");
791753f127fSDimitry Andric           }
792753f127fSDimitry Andric         }
793753f127fSDimitry Andric 
794753f127fSDimitry Andric         p += skip;
795753f127fSDimitry Andric         offset = r.offset + skip + remove;
796753f127fSDimitry Andric       }
797753f127fSDimitry Andric       memcpy(p, old.data() + offset, old.size() - offset);
798753f127fSDimitry Andric 
799753f127fSDimitry Andric       // Subtract the previous relocDeltas value from the relocation offset.
800753f127fSDimitry Andric       // For a pair of R_RISCV_CALL/R_RISCV_RELAX with the same offset, decrease
801753f127fSDimitry Andric       // their r_offset by the same delta.
802753f127fSDimitry Andric       delta = 0;
803753f127fSDimitry Andric       for (size_t i = 0, e = rels.size(); i != e;) {
804753f127fSDimitry Andric         uint64_t cur = rels[i].offset;
805753f127fSDimitry Andric         do {
806753f127fSDimitry Andric           rels[i].offset -= delta;
807753f127fSDimitry Andric           if (aux.relocTypes[i] != R_RISCV_NONE)
808753f127fSDimitry Andric             rels[i].type = aux.relocTypes[i];
809753f127fSDimitry Andric         } while (++i != e && rels[i].offset == cur);
810753f127fSDimitry Andric         delta = aux.relocDeltas[i - 1];
811753f127fSDimitry Andric       }
812753f127fSDimitry Andric     }
813753f127fSDimitry Andric   }
814753f127fSDimitry Andric }
815753f127fSDimitry Andric 
8165ffd83dbSDimitry Andric TargetInfo *elf::getRISCVTargetInfo() {
8170b57cec5SDimitry Andric   static RISCV target;
8180b57cec5SDimitry Andric   return &target;
8190b57cec5SDimitry Andric }
820