xref: /freebsd/contrib/llvm-project/lld/ELF/Arch/RISCV.cpp (revision 297eecfb02bb25902531dbb5c3b9a88caf8adf29)
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"
14bdd1243dSDimitry Andric #include "llvm/Support/ELFAttributes.h"
15bdd1243dSDimitry Andric #include "llvm/Support/LEB128.h"
16bdd1243dSDimitry Andric #include "llvm/Support/RISCVAttributeParser.h"
17bdd1243dSDimitry Andric #include "llvm/Support/RISCVAttributes.h"
18bdd1243dSDimitry Andric #include "llvm/Support/RISCVISAInfo.h"
19753f127fSDimitry Andric #include "llvm/Support/TimeProfiler.h"
200b57cec5SDimitry Andric 
210b57cec5SDimitry Andric using namespace llvm;
220b57cec5SDimitry Andric using namespace llvm::object;
230b57cec5SDimitry Andric using namespace llvm::support::endian;
240b57cec5SDimitry Andric using namespace llvm::ELF;
255ffd83dbSDimitry Andric using namespace lld;
265ffd83dbSDimitry Andric using namespace lld::elf;
270b57cec5SDimitry Andric 
280b57cec5SDimitry Andric namespace {
290b57cec5SDimitry Andric 
300b57cec5SDimitry Andric class RISCV final : public TargetInfo {
310b57cec5SDimitry Andric public:
320b57cec5SDimitry Andric   RISCV();
330b57cec5SDimitry Andric   uint32_t calcEFlags() const override;
34fe6060f1SDimitry Andric   int64_t getImplicitAddend(const uint8_t *buf, RelType type) const override;
350b57cec5SDimitry Andric   void writeGotHeader(uint8_t *buf) const override;
360b57cec5SDimitry Andric   void writeGotPlt(uint8_t *buf, const Symbol &s) const override;
37fe6060f1SDimitry Andric   void writeIgotPlt(uint8_t *buf, const Symbol &s) const override;
380b57cec5SDimitry Andric   void writePltHeader(uint8_t *buf) const override;
39480093f4SDimitry Andric   void writePlt(uint8_t *buf, const Symbol &sym,
40480093f4SDimitry Andric                 uint64_t pltEntryAddr) const override;
410b57cec5SDimitry Andric   RelType getDynRel(RelType type) const override;
420b57cec5SDimitry Andric   RelExpr getRelExpr(RelType type, const Symbol &s,
430b57cec5SDimitry Andric                      const uint8_t *loc) const override;
445ffd83dbSDimitry Andric   void relocate(uint8_t *loc, const Relocation &rel,
455ffd83dbSDimitry Andric                 uint64_t val) const override;
461db9f3b2SDimitry Andric   void relocateAlloc(InputSectionBase &sec, uint8_t *buf) const override;
47753f127fSDimitry Andric   bool relaxOnce(int pass) const override;
480b57cec5SDimitry Andric };
490b57cec5SDimitry Andric 
500b57cec5SDimitry Andric } // end anonymous namespace
510b57cec5SDimitry Andric 
5206c3fb27SDimitry Andric // These are internal relocation numbers for GP relaxation. They aren't part
5306c3fb27SDimitry Andric // of the psABI spec.
5406c3fb27SDimitry Andric #define INTERNAL_R_RISCV_GPREL_I 256
5506c3fb27SDimitry Andric #define INTERNAL_R_RISCV_GPREL_S 257
5606c3fb27SDimitry Andric 
570b57cec5SDimitry Andric const uint64_t dtpOffset = 0x800;
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric enum Op {
600b57cec5SDimitry Andric   ADDI = 0x13,
610b57cec5SDimitry Andric   AUIPC = 0x17,
620b57cec5SDimitry Andric   JALR = 0x67,
630b57cec5SDimitry Andric   LD = 0x3003,
640b57cec5SDimitry Andric   LW = 0x2003,
650b57cec5SDimitry Andric   SRLI = 0x5013,
660b57cec5SDimitry Andric   SUB = 0x40000033,
670b57cec5SDimitry Andric };
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric enum Reg {
700b57cec5SDimitry Andric   X_RA = 1,
7106c3fb27SDimitry Andric   X_GP = 3,
72fcaf7f86SDimitry Andric   X_TP = 4,
730b57cec5SDimitry Andric   X_T0 = 5,
740b57cec5SDimitry Andric   X_T1 = 6,
750b57cec5SDimitry Andric   X_T2 = 7,
760b57cec5SDimitry Andric   X_T3 = 28,
770b57cec5SDimitry Andric };
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric static uint32_t hi20(uint32_t val) { return (val + 0x800) >> 12; }
800b57cec5SDimitry Andric static uint32_t lo12(uint32_t val) { return val & 4095; }
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric static uint32_t itype(uint32_t op, uint32_t rd, uint32_t rs1, uint32_t imm) {
830b57cec5SDimitry Andric   return op | (rd << 7) | (rs1 << 15) | (imm << 20);
840b57cec5SDimitry Andric }
850b57cec5SDimitry Andric static uint32_t rtype(uint32_t op, uint32_t rd, uint32_t rs1, uint32_t rs2) {
860b57cec5SDimitry Andric   return op | (rd << 7) | (rs1 << 15) | (rs2 << 20);
870b57cec5SDimitry Andric }
880b57cec5SDimitry Andric static uint32_t utype(uint32_t op, uint32_t rd, uint32_t imm) {
890b57cec5SDimitry Andric   return op | (rd << 7) | (imm << 12);
900b57cec5SDimitry Andric }
910b57cec5SDimitry Andric 
92fcaf7f86SDimitry Andric // Extract bits v[begin:end], where range is inclusive, and begin must be < 63.
93fcaf7f86SDimitry Andric static uint32_t extractBits(uint64_t v, uint32_t begin, uint32_t end) {
94fcaf7f86SDimitry Andric   return (v & ((1ULL << (begin + 1)) - 1)) >> end;
95fcaf7f86SDimitry Andric }
96fcaf7f86SDimitry Andric 
97fcaf7f86SDimitry Andric static uint32_t setLO12_I(uint32_t insn, uint32_t imm) {
98fcaf7f86SDimitry Andric   return (insn & 0xfffff) | (imm << 20);
99fcaf7f86SDimitry Andric }
100fcaf7f86SDimitry Andric static uint32_t setLO12_S(uint32_t insn, uint32_t imm) {
101fcaf7f86SDimitry Andric   return (insn & 0x1fff07f) | (extractBits(imm, 11, 5) << 25) |
102fcaf7f86SDimitry Andric          (extractBits(imm, 4, 0) << 7);
103fcaf7f86SDimitry Andric }
104fcaf7f86SDimitry Andric 
1050b57cec5SDimitry Andric RISCV::RISCV() {
1060b57cec5SDimitry Andric   copyRel = R_RISCV_COPY;
1070b57cec5SDimitry Andric   pltRel = R_RISCV_JUMP_SLOT;
1080b57cec5SDimitry Andric   relativeRel = R_RISCV_RELATIVE;
1095ffd83dbSDimitry Andric   iRelativeRel = R_RISCV_IRELATIVE;
1100b57cec5SDimitry Andric   if (config->is64) {
1110b57cec5SDimitry Andric     symbolicRel = R_RISCV_64;
1120b57cec5SDimitry Andric     tlsModuleIndexRel = R_RISCV_TLS_DTPMOD64;
1130b57cec5SDimitry Andric     tlsOffsetRel = R_RISCV_TLS_DTPREL64;
1140b57cec5SDimitry Andric     tlsGotRel = R_RISCV_TLS_TPREL64;
1150b57cec5SDimitry Andric   } else {
1160b57cec5SDimitry Andric     symbolicRel = R_RISCV_32;
1170b57cec5SDimitry Andric     tlsModuleIndexRel = R_RISCV_TLS_DTPMOD32;
1180b57cec5SDimitry Andric     tlsOffsetRel = R_RISCV_TLS_DTPREL32;
1190b57cec5SDimitry Andric     tlsGotRel = R_RISCV_TLS_TPREL32;
1200b57cec5SDimitry Andric   }
1210b57cec5SDimitry Andric   gotRel = symbolicRel;
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric   // .got[0] = _DYNAMIC
1240b57cec5SDimitry Andric   gotHeaderEntriesNum = 1;
1250b57cec5SDimitry Andric 
1260b57cec5SDimitry Andric   // .got.plt[0] = _dl_runtime_resolve, .got.plt[1] = link_map
1270b57cec5SDimitry Andric   gotPltHeaderEntriesNum = 2;
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric   pltHeaderSize = 32;
130480093f4SDimitry Andric   pltEntrySize = 16;
131480093f4SDimitry Andric   ipltEntrySize = 16;
1320b57cec5SDimitry Andric }
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric static uint32_t getEFlags(InputFile *f) {
1350b57cec5SDimitry Andric   if (config->is64)
136e8d8bef9SDimitry Andric     return cast<ObjFile<ELF64LE>>(f)->getObj().getHeader().e_flags;
137e8d8bef9SDimitry Andric   return cast<ObjFile<ELF32LE>>(f)->getObj().getHeader().e_flags;
1380b57cec5SDimitry Andric }
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric uint32_t RISCV::calcEFlags() const {
141a1517e11SDimitry Andric   // If there are only binary input files (from -b binary), use a
142a1517e11SDimitry Andric   // value of 0 for the ELF header flags.
143bdd1243dSDimitry Andric   if (ctx.objectFiles.empty())
144a1517e11SDimitry Andric     return 0;
1450b57cec5SDimitry Andric 
146bdd1243dSDimitry Andric   uint32_t target = getEFlags(ctx.objectFiles.front());
1470b57cec5SDimitry Andric 
148bdd1243dSDimitry Andric   for (InputFile *f : ctx.objectFiles) {
1490b57cec5SDimitry Andric     uint32_t eflags = getEFlags(f);
1500b57cec5SDimitry Andric     if (eflags & EF_RISCV_RVC)
1510b57cec5SDimitry Andric       target |= EF_RISCV_RVC;
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric     if ((eflags & EF_RISCV_FLOAT_ABI) != (target & EF_RISCV_FLOAT_ABI))
154bdd1243dSDimitry Andric       error(
155bdd1243dSDimitry Andric           toString(f) +
156bdd1243dSDimitry Andric           ": cannot link object files with different floating-point ABI from " +
157bdd1243dSDimitry Andric           toString(ctx.objectFiles[0]));
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric     if ((eflags & EF_RISCV_RVE) != (target & EF_RISCV_RVE))
1600b57cec5SDimitry Andric       error(toString(f) +
1610b57cec5SDimitry Andric             ": cannot link object files with different EF_RISCV_RVE");
1620b57cec5SDimitry Andric   }
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric   return target;
1650b57cec5SDimitry Andric }
1660b57cec5SDimitry Andric 
167fe6060f1SDimitry Andric int64_t RISCV::getImplicitAddend(const uint8_t *buf, RelType type) const {
168fe6060f1SDimitry Andric   switch (type) {
169fe6060f1SDimitry Andric   default:
170fe6060f1SDimitry Andric     internalLinkerError(getErrorLocation(buf),
171fe6060f1SDimitry Andric                         "cannot read addend for relocation " + toString(type));
172fe6060f1SDimitry Andric     return 0;
173fe6060f1SDimitry Andric   case R_RISCV_32:
174fe6060f1SDimitry Andric   case R_RISCV_TLS_DTPMOD32:
175fe6060f1SDimitry Andric   case R_RISCV_TLS_DTPREL32:
176bdd1243dSDimitry Andric   case R_RISCV_TLS_TPREL32:
177fe6060f1SDimitry Andric     return SignExtend64<32>(read32le(buf));
178fe6060f1SDimitry Andric   case R_RISCV_64:
179bdd1243dSDimitry Andric   case R_RISCV_TLS_DTPMOD64:
180bdd1243dSDimitry Andric   case R_RISCV_TLS_DTPREL64:
181bdd1243dSDimitry Andric   case R_RISCV_TLS_TPREL64:
182fe6060f1SDimitry Andric     return read64le(buf);
183fe6060f1SDimitry Andric   case R_RISCV_RELATIVE:
184fe6060f1SDimitry Andric   case R_RISCV_IRELATIVE:
185fe6060f1SDimitry Andric     return config->is64 ? read64le(buf) : read32le(buf);
186fe6060f1SDimitry Andric   case R_RISCV_NONE:
187fe6060f1SDimitry Andric   case R_RISCV_JUMP_SLOT:
188fe6060f1SDimitry Andric     // These relocations are defined as not having an implicit addend.
189fe6060f1SDimitry Andric     return 0;
190fe6060f1SDimitry Andric   }
191fe6060f1SDimitry Andric }
192fe6060f1SDimitry Andric 
1930b57cec5SDimitry Andric void RISCV::writeGotHeader(uint8_t *buf) const {
1940b57cec5SDimitry Andric   if (config->is64)
1950b57cec5SDimitry Andric     write64le(buf, mainPart->dynamic->getVA());
1960b57cec5SDimitry Andric   else
1970b57cec5SDimitry Andric     write32le(buf, mainPart->dynamic->getVA());
1980b57cec5SDimitry Andric }
1990b57cec5SDimitry Andric 
2000b57cec5SDimitry Andric void RISCV::writeGotPlt(uint8_t *buf, const Symbol &s) const {
2010b57cec5SDimitry Andric   if (config->is64)
2020b57cec5SDimitry Andric     write64le(buf, in.plt->getVA());
2030b57cec5SDimitry Andric   else
2040b57cec5SDimitry Andric     write32le(buf, in.plt->getVA());
2050b57cec5SDimitry Andric }
2060b57cec5SDimitry Andric 
207fe6060f1SDimitry Andric void RISCV::writeIgotPlt(uint8_t *buf, const Symbol &s) const {
208fe6060f1SDimitry Andric   if (config->writeAddends) {
209fe6060f1SDimitry Andric     if (config->is64)
210fe6060f1SDimitry Andric       write64le(buf, s.getVA());
211fe6060f1SDimitry Andric     else
212fe6060f1SDimitry Andric       write32le(buf, s.getVA());
213fe6060f1SDimitry Andric   }
214fe6060f1SDimitry Andric }
215fe6060f1SDimitry Andric 
2160b57cec5SDimitry Andric void RISCV::writePltHeader(uint8_t *buf) const {
2170b57cec5SDimitry Andric   // 1: auipc t2, %pcrel_hi(.got.plt)
2180b57cec5SDimitry Andric   // sub t1, t1, t3
2190b57cec5SDimitry Andric   // l[wd] t3, %pcrel_lo(1b)(t2); t3 = _dl_runtime_resolve
2200b57cec5SDimitry Andric   // addi t1, t1, -pltHeaderSize-12; t1 = &.plt[i] - &.plt[0]
2210b57cec5SDimitry Andric   // addi t0, t2, %pcrel_lo(1b)
2220b57cec5SDimitry Andric   // srli t1, t1, (rv64?1:2); t1 = &.got.plt[i] - &.got.plt[0]
2230b57cec5SDimitry Andric   // l[wd] t0, Wordsize(t0); t0 = link_map
2240b57cec5SDimitry Andric   // jr t3
2250b57cec5SDimitry Andric   uint32_t offset = in.gotPlt->getVA() - in.plt->getVA();
2260b57cec5SDimitry Andric   uint32_t load = config->is64 ? LD : LW;
2270b57cec5SDimitry Andric   write32le(buf + 0, utype(AUIPC, X_T2, hi20(offset)));
2280b57cec5SDimitry Andric   write32le(buf + 4, rtype(SUB, X_T1, X_T1, X_T3));
2290b57cec5SDimitry Andric   write32le(buf + 8, itype(load, X_T3, X_T2, lo12(offset)));
2300b57cec5SDimitry Andric   write32le(buf + 12, itype(ADDI, X_T1, X_T1, -target->pltHeaderSize - 12));
2310b57cec5SDimitry Andric   write32le(buf + 16, itype(ADDI, X_T0, X_T2, lo12(offset)));
2320b57cec5SDimitry Andric   write32le(buf + 20, itype(SRLI, X_T1, X_T1, config->is64 ? 1 : 2));
2330b57cec5SDimitry Andric   write32le(buf + 24, itype(load, X_T0, X_T0, config->wordsize));
2340b57cec5SDimitry Andric   write32le(buf + 28, itype(JALR, 0, X_T3, 0));
2350b57cec5SDimitry Andric }
2360b57cec5SDimitry Andric 
237480093f4SDimitry Andric void RISCV::writePlt(uint8_t *buf, const Symbol &sym,
238480093f4SDimitry Andric                      uint64_t pltEntryAddr) const {
2390b57cec5SDimitry Andric   // 1: auipc t3, %pcrel_hi(f@.got.plt)
2400b57cec5SDimitry Andric   // l[wd] t3, %pcrel_lo(1b)(t3)
2410b57cec5SDimitry Andric   // jalr t1, t3
2420b57cec5SDimitry Andric   // nop
243480093f4SDimitry Andric   uint32_t offset = sym.getGotPltVA() - pltEntryAddr;
2440b57cec5SDimitry Andric   write32le(buf + 0, utype(AUIPC, X_T3, hi20(offset)));
2450b57cec5SDimitry Andric   write32le(buf + 4, itype(config->is64 ? LD : LW, X_T3, X_T3, lo12(offset)));
2460b57cec5SDimitry Andric   write32le(buf + 8, itype(JALR, X_T1, X_T3, 0));
2470b57cec5SDimitry Andric   write32le(buf + 12, itype(ADDI, 0, 0, 0));
2480b57cec5SDimitry Andric }
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric RelType RISCV::getDynRel(RelType type) const {
2510b57cec5SDimitry Andric   return type == target->symbolicRel ? type
2520b57cec5SDimitry Andric                                      : static_cast<RelType>(R_RISCV_NONE);
2530b57cec5SDimitry Andric }
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric RelExpr RISCV::getRelExpr(const RelType type, const Symbol &s,
2560b57cec5SDimitry Andric                           const uint8_t *loc) const {
2570b57cec5SDimitry Andric   switch (type) {
258480093f4SDimitry Andric   case R_RISCV_NONE:
259480093f4SDimitry Andric     return R_NONE;
260480093f4SDimitry Andric   case R_RISCV_32:
261480093f4SDimitry Andric   case R_RISCV_64:
262480093f4SDimitry Andric   case R_RISCV_HI20:
263480093f4SDimitry Andric   case R_RISCV_LO12_I:
264480093f4SDimitry Andric   case R_RISCV_LO12_S:
265480093f4SDimitry Andric   case R_RISCV_RVC_LUI:
266480093f4SDimitry Andric     return R_ABS;
2670b57cec5SDimitry Andric   case R_RISCV_ADD8:
2680b57cec5SDimitry Andric   case R_RISCV_ADD16:
2690b57cec5SDimitry Andric   case R_RISCV_ADD32:
2700b57cec5SDimitry Andric   case R_RISCV_ADD64:
2710b57cec5SDimitry Andric   case R_RISCV_SET6:
2720b57cec5SDimitry Andric   case R_RISCV_SET8:
2730b57cec5SDimitry Andric   case R_RISCV_SET16:
2740b57cec5SDimitry Andric   case R_RISCV_SET32:
2750b57cec5SDimitry Andric   case R_RISCV_SUB6:
2760b57cec5SDimitry Andric   case R_RISCV_SUB8:
2770b57cec5SDimitry Andric   case R_RISCV_SUB16:
2780b57cec5SDimitry Andric   case R_RISCV_SUB32:
2790b57cec5SDimitry Andric   case R_RISCV_SUB64:
2800b57cec5SDimitry Andric     return R_RISCV_ADD;
2810b57cec5SDimitry Andric   case R_RISCV_JAL:
2820b57cec5SDimitry Andric   case R_RISCV_BRANCH:
2830b57cec5SDimitry Andric   case R_RISCV_PCREL_HI20:
2840b57cec5SDimitry Andric   case R_RISCV_RVC_BRANCH:
2850b57cec5SDimitry Andric   case R_RISCV_RVC_JUMP:
2860b57cec5SDimitry Andric   case R_RISCV_32_PCREL:
2870b57cec5SDimitry Andric     return R_PC;
2880b57cec5SDimitry Andric   case R_RISCV_CALL:
2890b57cec5SDimitry Andric   case R_RISCV_CALL_PLT:
29006c3fb27SDimitry Andric   case R_RISCV_PLT32:
2910b57cec5SDimitry Andric     return R_PLT_PC;
2920b57cec5SDimitry Andric   case R_RISCV_GOT_HI20:
293*297eecfbSDimitry Andric   case R_RISCV_GOT32_PCREL:
2940b57cec5SDimitry Andric     return R_GOT_PC;
2950b57cec5SDimitry Andric   case R_RISCV_PCREL_LO12_I:
2960b57cec5SDimitry Andric   case R_RISCV_PCREL_LO12_S:
2970b57cec5SDimitry Andric     return R_RISCV_PC_INDIRECT;
2980b57cec5SDimitry Andric   case R_RISCV_TLS_GD_HI20:
2990b57cec5SDimitry Andric     return R_TLSGD_PC;
3000b57cec5SDimitry Andric   case R_RISCV_TLS_GOT_HI20:
3010b57cec5SDimitry Andric     return R_GOT_PC;
3020b57cec5SDimitry Andric   case R_RISCV_TPREL_HI20:
3030b57cec5SDimitry Andric   case R_RISCV_TPREL_LO12_I:
3040b57cec5SDimitry Andric   case R_RISCV_TPREL_LO12_S:
305e8d8bef9SDimitry Andric     return R_TPREL;
30655e4f9d5SDimitry Andric   case R_RISCV_ALIGN:
307753f127fSDimitry Andric     return R_RELAX_HINT;
308fcaf7f86SDimitry Andric   case R_RISCV_TPREL_ADD:
309753f127fSDimitry Andric   case R_RISCV_RELAX:
310753f127fSDimitry Andric     return config->relax ? R_RELAX_HINT : R_NONE;
3115f757f3fSDimitry Andric   case R_RISCV_SET_ULEB128:
3121db9f3b2SDimitry Andric   case R_RISCV_SUB_ULEB128:
3135f757f3fSDimitry Andric     return R_RISCV_LEB128;
3140b57cec5SDimitry Andric   default:
315480093f4SDimitry Andric     error(getErrorLocation(loc) + "unknown relocation (" + Twine(type) +
316480093f4SDimitry Andric           ") against symbol " + toString(s));
317480093f4SDimitry Andric     return R_NONE;
3180b57cec5SDimitry Andric   }
3190b57cec5SDimitry Andric }
3200b57cec5SDimitry Andric 
3215ffd83dbSDimitry Andric void RISCV::relocate(uint8_t *loc, const Relocation &rel, uint64_t val) const {
3220b57cec5SDimitry Andric   const unsigned bits = config->wordsize * 8;
3230b57cec5SDimitry Andric 
3245ffd83dbSDimitry Andric   switch (rel.type) {
3250b57cec5SDimitry Andric   case R_RISCV_32:
3260b57cec5SDimitry Andric     write32le(loc, val);
3270b57cec5SDimitry Andric     return;
3280b57cec5SDimitry Andric   case R_RISCV_64:
3290b57cec5SDimitry Andric     write64le(loc, val);
3300b57cec5SDimitry Andric     return;
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric   case R_RISCV_RVC_BRANCH: {
333753f127fSDimitry Andric     checkInt(loc, val, 9, rel);
3345ffd83dbSDimitry Andric     checkAlignment(loc, val, 2, rel);
3350b57cec5SDimitry Andric     uint16_t insn = read16le(loc) & 0xE383;
3360b57cec5SDimitry Andric     uint16_t imm8 = extractBits(val, 8, 8) << 12;
3370b57cec5SDimitry Andric     uint16_t imm4_3 = extractBits(val, 4, 3) << 10;
3380b57cec5SDimitry Andric     uint16_t imm7_6 = extractBits(val, 7, 6) << 5;
3390b57cec5SDimitry Andric     uint16_t imm2_1 = extractBits(val, 2, 1) << 3;
3400b57cec5SDimitry Andric     uint16_t imm5 = extractBits(val, 5, 5) << 2;
3410b57cec5SDimitry Andric     insn |= imm8 | imm4_3 | imm7_6 | imm2_1 | imm5;
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric     write16le(loc, insn);
3440b57cec5SDimitry Andric     return;
3450b57cec5SDimitry Andric   }
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric   case R_RISCV_RVC_JUMP: {
348753f127fSDimitry Andric     checkInt(loc, val, 12, rel);
3495ffd83dbSDimitry Andric     checkAlignment(loc, val, 2, rel);
3500b57cec5SDimitry Andric     uint16_t insn = read16le(loc) & 0xE003;
3510b57cec5SDimitry Andric     uint16_t imm11 = extractBits(val, 11, 11) << 12;
3520b57cec5SDimitry Andric     uint16_t imm4 = extractBits(val, 4, 4) << 11;
3530b57cec5SDimitry Andric     uint16_t imm9_8 = extractBits(val, 9, 8) << 9;
3540b57cec5SDimitry Andric     uint16_t imm10 = extractBits(val, 10, 10) << 8;
3550b57cec5SDimitry Andric     uint16_t imm6 = extractBits(val, 6, 6) << 7;
3560b57cec5SDimitry Andric     uint16_t imm7 = extractBits(val, 7, 7) << 6;
3570b57cec5SDimitry Andric     uint16_t imm3_1 = extractBits(val, 3, 1) << 3;
3580b57cec5SDimitry Andric     uint16_t imm5 = extractBits(val, 5, 5) << 2;
3590b57cec5SDimitry Andric     insn |= imm11 | imm4 | imm9_8 | imm10 | imm6 | imm7 | imm3_1 | imm5;
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric     write16le(loc, insn);
3620b57cec5SDimitry Andric     return;
3630b57cec5SDimitry Andric   }
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric   case R_RISCV_RVC_LUI: {
3660b57cec5SDimitry Andric     int64_t imm = SignExtend64(val + 0x800, bits) >> 12;
3675ffd83dbSDimitry Andric     checkInt(loc, imm, 6, rel);
3680b57cec5SDimitry Andric     if (imm == 0) { // `c.lui rd, 0` is illegal, convert to `c.li rd, 0`
3690b57cec5SDimitry Andric       write16le(loc, (read16le(loc) & 0x0F83) | 0x4000);
3700b57cec5SDimitry Andric     } else {
3710b57cec5SDimitry Andric       uint16_t imm17 = extractBits(val + 0x800, 17, 17) << 12;
3720b57cec5SDimitry Andric       uint16_t imm16_12 = extractBits(val + 0x800, 16, 12) << 2;
3730b57cec5SDimitry Andric       write16le(loc, (read16le(loc) & 0xEF83) | imm17 | imm16_12);
3740b57cec5SDimitry Andric     }
3750b57cec5SDimitry Andric     return;
3760b57cec5SDimitry Andric   }
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric   case R_RISCV_JAL: {
379753f127fSDimitry Andric     checkInt(loc, val, 21, rel);
3805ffd83dbSDimitry Andric     checkAlignment(loc, val, 2, rel);
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric     uint32_t insn = read32le(loc) & 0xFFF;
3830b57cec5SDimitry Andric     uint32_t imm20 = extractBits(val, 20, 20) << 31;
3840b57cec5SDimitry Andric     uint32_t imm10_1 = extractBits(val, 10, 1) << 21;
3850b57cec5SDimitry Andric     uint32_t imm11 = extractBits(val, 11, 11) << 20;
3860b57cec5SDimitry Andric     uint32_t imm19_12 = extractBits(val, 19, 12) << 12;
3870b57cec5SDimitry Andric     insn |= imm20 | imm10_1 | imm11 | imm19_12;
3880b57cec5SDimitry Andric 
3890b57cec5SDimitry Andric     write32le(loc, insn);
3900b57cec5SDimitry Andric     return;
3910b57cec5SDimitry Andric   }
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric   case R_RISCV_BRANCH: {
394753f127fSDimitry Andric     checkInt(loc, val, 13, rel);
3955ffd83dbSDimitry Andric     checkAlignment(loc, val, 2, rel);
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric     uint32_t insn = read32le(loc) & 0x1FFF07F;
3980b57cec5SDimitry Andric     uint32_t imm12 = extractBits(val, 12, 12) << 31;
3990b57cec5SDimitry Andric     uint32_t imm10_5 = extractBits(val, 10, 5) << 25;
4000b57cec5SDimitry Andric     uint32_t imm4_1 = extractBits(val, 4, 1) << 8;
4010b57cec5SDimitry Andric     uint32_t imm11 = extractBits(val, 11, 11) << 7;
4020b57cec5SDimitry Andric     insn |= imm12 | imm10_5 | imm4_1 | imm11;
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric     write32le(loc, insn);
4050b57cec5SDimitry Andric     return;
4060b57cec5SDimitry Andric   }
4070b57cec5SDimitry Andric 
4080b57cec5SDimitry Andric   // auipc + jalr pair
4090b57cec5SDimitry Andric   case R_RISCV_CALL:
4100b57cec5SDimitry Andric   case R_RISCV_CALL_PLT: {
4110b57cec5SDimitry Andric     int64_t hi = SignExtend64(val + 0x800, bits) >> 12;
4125ffd83dbSDimitry Andric     checkInt(loc, hi, 20, rel);
4130b57cec5SDimitry Andric     if (isInt<20>(hi)) {
4145ffd83dbSDimitry Andric       relocateNoSym(loc, R_RISCV_PCREL_HI20, val);
4155ffd83dbSDimitry Andric       relocateNoSym(loc + 4, R_RISCV_PCREL_LO12_I, val);
4160b57cec5SDimitry Andric     }
4170b57cec5SDimitry Andric     return;
4180b57cec5SDimitry Andric   }
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric   case R_RISCV_GOT_HI20:
4210b57cec5SDimitry Andric   case R_RISCV_PCREL_HI20:
4220b57cec5SDimitry Andric   case R_RISCV_TLS_GD_HI20:
4230b57cec5SDimitry Andric   case R_RISCV_TLS_GOT_HI20:
4240b57cec5SDimitry Andric   case R_RISCV_TPREL_HI20:
4250b57cec5SDimitry Andric   case R_RISCV_HI20: {
4260b57cec5SDimitry Andric     uint64_t hi = val + 0x800;
4275ffd83dbSDimitry Andric     checkInt(loc, SignExtend64(hi, bits) >> 12, 20, rel);
4280b57cec5SDimitry Andric     write32le(loc, (read32le(loc) & 0xFFF) | (hi & 0xFFFFF000));
4290b57cec5SDimitry Andric     return;
4300b57cec5SDimitry Andric   }
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric   case R_RISCV_PCREL_LO12_I:
4330b57cec5SDimitry Andric   case R_RISCV_TPREL_LO12_I:
4340b57cec5SDimitry Andric   case R_RISCV_LO12_I: {
4350b57cec5SDimitry Andric     uint64_t hi = (val + 0x800) >> 12;
4360b57cec5SDimitry Andric     uint64_t lo = val - (hi << 12);
437fcaf7f86SDimitry Andric     write32le(loc, setLO12_I(read32le(loc), lo & 0xfff));
4380b57cec5SDimitry Andric     return;
4390b57cec5SDimitry Andric   }
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric   case R_RISCV_PCREL_LO12_S:
4420b57cec5SDimitry Andric   case R_RISCV_TPREL_LO12_S:
4430b57cec5SDimitry Andric   case R_RISCV_LO12_S: {
4440b57cec5SDimitry Andric     uint64_t hi = (val + 0x800) >> 12;
4450b57cec5SDimitry Andric     uint64_t lo = val - (hi << 12);
446fcaf7f86SDimitry Andric     write32le(loc, setLO12_S(read32le(loc), lo));
4470b57cec5SDimitry Andric     return;
4480b57cec5SDimitry Andric   }
4490b57cec5SDimitry Andric 
45006c3fb27SDimitry Andric   case INTERNAL_R_RISCV_GPREL_I:
45106c3fb27SDimitry Andric   case INTERNAL_R_RISCV_GPREL_S: {
45206c3fb27SDimitry Andric     Defined *gp = ElfSym::riscvGlobalPointer;
45306c3fb27SDimitry Andric     int64_t displace = SignExtend64(val - gp->getVA(), bits);
45406c3fb27SDimitry Andric     checkInt(loc, displace, 12, rel);
45506c3fb27SDimitry Andric     uint32_t insn = (read32le(loc) & ~(31 << 15)) | (X_GP << 15);
45606c3fb27SDimitry Andric     if (rel.type == INTERNAL_R_RISCV_GPREL_I)
45706c3fb27SDimitry Andric       insn = setLO12_I(insn, displace);
45806c3fb27SDimitry Andric     else
45906c3fb27SDimitry Andric       insn = setLO12_S(insn, displace);
46006c3fb27SDimitry Andric     write32le(loc, insn);
46106c3fb27SDimitry Andric     return;
46206c3fb27SDimitry Andric   }
46306c3fb27SDimitry Andric 
4640b57cec5SDimitry Andric   case R_RISCV_ADD8:
4650b57cec5SDimitry Andric     *loc += val;
4660b57cec5SDimitry Andric     return;
4670b57cec5SDimitry Andric   case R_RISCV_ADD16:
4680b57cec5SDimitry Andric     write16le(loc, read16le(loc) + val);
4690b57cec5SDimitry Andric     return;
4700b57cec5SDimitry Andric   case R_RISCV_ADD32:
4710b57cec5SDimitry Andric     write32le(loc, read32le(loc) + val);
4720b57cec5SDimitry Andric     return;
4730b57cec5SDimitry Andric   case R_RISCV_ADD64:
4740b57cec5SDimitry Andric     write64le(loc, read64le(loc) + val);
4750b57cec5SDimitry Andric     return;
4760b57cec5SDimitry Andric   case R_RISCV_SUB6:
4770b57cec5SDimitry Andric     *loc = (*loc & 0xc0) | (((*loc & 0x3f) - val) & 0x3f);
4780b57cec5SDimitry Andric     return;
4790b57cec5SDimitry Andric   case R_RISCV_SUB8:
4800b57cec5SDimitry Andric     *loc -= val;
4810b57cec5SDimitry Andric     return;
4820b57cec5SDimitry Andric   case R_RISCV_SUB16:
4830b57cec5SDimitry Andric     write16le(loc, read16le(loc) - val);
4840b57cec5SDimitry Andric     return;
4850b57cec5SDimitry Andric   case R_RISCV_SUB32:
4860b57cec5SDimitry Andric     write32le(loc, read32le(loc) - val);
4870b57cec5SDimitry Andric     return;
4880b57cec5SDimitry Andric   case R_RISCV_SUB64:
4890b57cec5SDimitry Andric     write64le(loc, read64le(loc) - val);
4900b57cec5SDimitry Andric     return;
4910b57cec5SDimitry Andric   case R_RISCV_SET6:
4920b57cec5SDimitry Andric     *loc = (*loc & 0xc0) | (val & 0x3f);
4930b57cec5SDimitry Andric     return;
4940b57cec5SDimitry Andric   case R_RISCV_SET8:
4950b57cec5SDimitry Andric     *loc = val;
4960b57cec5SDimitry Andric     return;
4970b57cec5SDimitry Andric   case R_RISCV_SET16:
4980b57cec5SDimitry Andric     write16le(loc, val);
4990b57cec5SDimitry Andric     return;
5000b57cec5SDimitry Andric   case R_RISCV_SET32:
5010b57cec5SDimitry Andric   case R_RISCV_32_PCREL:
50206c3fb27SDimitry Andric   case R_RISCV_PLT32:
503*297eecfbSDimitry Andric   case R_RISCV_GOT32_PCREL:
504*297eecfbSDimitry Andric     checkInt(loc, val, 32, rel);
5050b57cec5SDimitry Andric     write32le(loc, val);
5060b57cec5SDimitry Andric     return;
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric   case R_RISCV_TLS_DTPREL32:
5090b57cec5SDimitry Andric     write32le(loc, val - dtpOffset);
5100b57cec5SDimitry Andric     break;
5110b57cec5SDimitry Andric   case R_RISCV_TLS_DTPREL64:
5120b57cec5SDimitry Andric     write64le(loc, val - dtpOffset);
5130b57cec5SDimitry Andric     break;
5140b57cec5SDimitry Andric 
5150b57cec5SDimitry Andric   case R_RISCV_RELAX:
5160b57cec5SDimitry Andric     return; // Ignored (for now)
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   default:
519480093f4SDimitry Andric     llvm_unreachable("unknown relocation");
5200b57cec5SDimitry Andric   }
5210b57cec5SDimitry Andric }
5220b57cec5SDimitry Andric 
5231db9f3b2SDimitry Andric void RISCV::relocateAlloc(InputSectionBase &sec, uint8_t *buf) const {
5241db9f3b2SDimitry Andric   uint64_t secAddr = sec.getOutputSection()->addr;
5251db9f3b2SDimitry Andric   if (auto *s = dyn_cast<InputSection>(&sec))
5261db9f3b2SDimitry Andric     secAddr += s->outSecOff;
5271db9f3b2SDimitry Andric   else if (auto *ehIn = dyn_cast<EhInputSection>(&sec))
5281db9f3b2SDimitry Andric     secAddr += ehIn->getParent()->outSecOff;
5291db9f3b2SDimitry Andric   for (size_t i = 0, size = sec.relocs().size(); i != size; ++i) {
5301db9f3b2SDimitry Andric     const Relocation &rel = sec.relocs()[i];
5311db9f3b2SDimitry Andric     uint8_t *loc = buf + rel.offset;
5321db9f3b2SDimitry Andric     const uint64_t val =
5331db9f3b2SDimitry Andric         sec.getRelocTargetVA(sec.file, rel.type, rel.addend,
5341db9f3b2SDimitry Andric                              secAddr + rel.offset, *rel.sym, rel.expr);
5351db9f3b2SDimitry Andric 
5361db9f3b2SDimitry Andric     switch (rel.expr) {
5371db9f3b2SDimitry Andric     case R_RELAX_HINT:
5381db9f3b2SDimitry Andric       break;
5391db9f3b2SDimitry Andric     case R_RISCV_LEB128:
5401db9f3b2SDimitry Andric       if (i + 1 < size) {
5411db9f3b2SDimitry Andric         const Relocation &rel1 = sec.relocs()[i + 1];
5421db9f3b2SDimitry Andric         if (rel.type == R_RISCV_SET_ULEB128 &&
5431db9f3b2SDimitry Andric             rel1.type == R_RISCV_SUB_ULEB128 && rel.offset == rel1.offset) {
5441db9f3b2SDimitry Andric           auto val = rel.sym->getVA(rel.addend) - rel1.sym->getVA(rel1.addend);
5451db9f3b2SDimitry Andric           if (overwriteULEB128(loc, val) >= 0x80)
5461db9f3b2SDimitry Andric             errorOrWarn(sec.getLocation(rel.offset) + ": ULEB128 value " +
5471db9f3b2SDimitry Andric                         Twine(val) + " exceeds available space; references '" +
5481db9f3b2SDimitry Andric                         lld::toString(*rel.sym) + "'");
5491db9f3b2SDimitry Andric           ++i;
5501db9f3b2SDimitry Andric           continue;
5511db9f3b2SDimitry Andric         }
5521db9f3b2SDimitry Andric       }
5531db9f3b2SDimitry Andric       errorOrWarn(sec.getLocation(rel.offset) +
5541db9f3b2SDimitry Andric                   ": R_RISCV_SET_ULEB128 not paired with R_RISCV_SUB_SET128");
5551db9f3b2SDimitry Andric       return;
5561db9f3b2SDimitry Andric     default:
5571db9f3b2SDimitry Andric       relocate(loc, rel, val);
5581db9f3b2SDimitry Andric       break;
5591db9f3b2SDimitry Andric     }
5601db9f3b2SDimitry Andric   }
5611db9f3b2SDimitry Andric }
5621db9f3b2SDimitry Andric 
563753f127fSDimitry Andric namespace {
564753f127fSDimitry Andric struct SymbolAnchor {
565753f127fSDimitry Andric   uint64_t offset;
566753f127fSDimitry Andric   Defined *d;
567753f127fSDimitry Andric   bool end; // true for the anchor of st_value+st_size
568753f127fSDimitry Andric };
569753f127fSDimitry Andric } // namespace
570753f127fSDimitry Andric 
571753f127fSDimitry Andric struct elf::RISCVRelaxAux {
572753f127fSDimitry Andric   // This records symbol start and end offsets which will be adjusted according
573753f127fSDimitry Andric   // to the nearest relocDeltas element.
574753f127fSDimitry Andric   SmallVector<SymbolAnchor, 0> anchors;
575753f127fSDimitry Andric   // For relocations[i], the actual offset is r_offset - (i ? relocDeltas[i-1] :
576753f127fSDimitry Andric   // 0).
577753f127fSDimitry Andric   std::unique_ptr<uint32_t[]> relocDeltas;
578753f127fSDimitry Andric   // For relocations[i], the actual type is relocTypes[i].
579753f127fSDimitry Andric   std::unique_ptr<RelType[]> relocTypes;
580753f127fSDimitry Andric   SmallVector<uint32_t, 0> writes;
581753f127fSDimitry Andric };
582753f127fSDimitry Andric 
583753f127fSDimitry Andric static void initSymbolAnchors() {
584753f127fSDimitry Andric   SmallVector<InputSection *, 0> storage;
585753f127fSDimitry Andric   for (OutputSection *osec : outputSections) {
586753f127fSDimitry Andric     if (!(osec->flags & SHF_EXECINSTR))
587753f127fSDimitry Andric       continue;
588753f127fSDimitry Andric     for (InputSection *sec : getInputSections(*osec, storage)) {
589753f127fSDimitry Andric       sec->relaxAux = make<RISCVRelaxAux>();
590bdd1243dSDimitry Andric       if (sec->relocs().size()) {
591753f127fSDimitry Andric         sec->relaxAux->relocDeltas =
592bdd1243dSDimitry Andric             std::make_unique<uint32_t[]>(sec->relocs().size());
593753f127fSDimitry Andric         sec->relaxAux->relocTypes =
594bdd1243dSDimitry Andric             std::make_unique<RelType[]>(sec->relocs().size());
595753f127fSDimitry Andric       }
596753f127fSDimitry Andric     }
597753f127fSDimitry Andric   }
598753f127fSDimitry Andric   // Store anchors (st_value and st_value+st_size) for symbols relative to text
599753f127fSDimitry Andric   // sections.
60006c3fb27SDimitry Andric   //
60106c3fb27SDimitry Andric   // For a defined symbol foo, we may have `d->file != file` with --wrap=foo.
60206c3fb27SDimitry Andric   // We should process foo, as the defining object file's symbol table may not
60306c3fb27SDimitry Andric   // contain foo after redirectSymbols changed the foo entry to __wrap_foo. To
60406c3fb27SDimitry Andric   // avoid adding a Defined that is undefined in one object file, use
60506c3fb27SDimitry Andric   // `!d->scriptDefined` to exclude symbols that are definitely not wrapped.
60606c3fb27SDimitry Andric   //
60706c3fb27SDimitry Andric   // `relaxAux->anchors` may contain duplicate symbols, but that is fine.
608bdd1243dSDimitry Andric   for (InputFile *file : ctx.objectFiles)
609753f127fSDimitry Andric     for (Symbol *sym : file->getSymbols()) {
610753f127fSDimitry Andric       auto *d = dyn_cast<Defined>(sym);
61106c3fb27SDimitry Andric       if (!d || (d->file != file && !d->scriptDefined))
612753f127fSDimitry Andric         continue;
613753f127fSDimitry Andric       if (auto *sec = dyn_cast_or_null<InputSection>(d->section))
614753f127fSDimitry Andric         if (sec->flags & SHF_EXECINSTR && sec->relaxAux) {
615753f127fSDimitry Andric           // If sec is discarded, relaxAux will be nullptr.
616753f127fSDimitry Andric           sec->relaxAux->anchors.push_back({d->value, d, false});
617753f127fSDimitry Andric           sec->relaxAux->anchors.push_back({d->value + d->size, d, true});
618753f127fSDimitry Andric         }
619753f127fSDimitry Andric     }
620753f127fSDimitry Andric   // Sort anchors by offset so that we can find the closest relocation
621753f127fSDimitry Andric   // efficiently. For a zero size symbol, ensure that its start anchor precedes
622753f127fSDimitry Andric   // its end anchor. For two symbols with anchors at the same offset, their
623753f127fSDimitry Andric   // order does not matter.
624753f127fSDimitry Andric   for (OutputSection *osec : outputSections) {
625753f127fSDimitry Andric     if (!(osec->flags & SHF_EXECINSTR))
626753f127fSDimitry Andric       continue;
627753f127fSDimitry Andric     for (InputSection *sec : getInputSections(*osec, storage)) {
628753f127fSDimitry Andric       llvm::sort(sec->relaxAux->anchors, [](auto &a, auto &b) {
629753f127fSDimitry Andric         return std::make_pair(a.offset, a.end) <
630753f127fSDimitry Andric                std::make_pair(b.offset, b.end);
631753f127fSDimitry Andric       });
632753f127fSDimitry Andric     }
633753f127fSDimitry Andric   }
634753f127fSDimitry Andric }
635753f127fSDimitry Andric 
636753f127fSDimitry Andric // Relax R_RISCV_CALL/R_RISCV_CALL_PLT auipc+jalr to c.j, c.jal, or jal.
637753f127fSDimitry Andric static void relaxCall(const InputSection &sec, size_t i, uint64_t loc,
638753f127fSDimitry Andric                       Relocation &r, uint32_t &remove) {
6395f757f3fSDimitry Andric   const bool rvc = getEFlags(sec.file) & EF_RISCV_RVC;
640753f127fSDimitry Andric   const Symbol &sym = *r.sym;
641bdd1243dSDimitry Andric   const uint64_t insnPair = read64le(sec.content().data() + r.offset);
642753f127fSDimitry Andric   const uint32_t rd = extractBits(insnPair, 32 + 11, 32 + 7);
643753f127fSDimitry Andric   const uint64_t dest =
644753f127fSDimitry Andric       (r.expr == R_PLT_PC ? sym.getPltVA() : sym.getVA()) + r.addend;
645753f127fSDimitry Andric   const int64_t displace = dest - loc;
646753f127fSDimitry Andric 
647753f127fSDimitry Andric   if (rvc && isInt<12>(displace) && rd == 0) {
648753f127fSDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_RVC_JUMP;
649753f127fSDimitry Andric     sec.relaxAux->writes.push_back(0xa001); // c.j
650753f127fSDimitry Andric     remove = 6;
651753f127fSDimitry Andric   } else if (rvc && isInt<12>(displace) && rd == X_RA &&
652753f127fSDimitry Andric              !config->is64) { // RV32C only
653753f127fSDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_RVC_JUMP;
654753f127fSDimitry Andric     sec.relaxAux->writes.push_back(0x2001); // c.jal
655753f127fSDimitry Andric     remove = 6;
656753f127fSDimitry Andric   } else if (isInt<21>(displace)) {
657753f127fSDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_JAL;
658753f127fSDimitry Andric     sec.relaxAux->writes.push_back(0x6f | rd << 7); // jal
659753f127fSDimitry Andric     remove = 4;
660753f127fSDimitry Andric   }
661753f127fSDimitry Andric }
662753f127fSDimitry Andric 
663fcaf7f86SDimitry Andric // Relax local-exec TLS when hi20 is zero.
664fcaf7f86SDimitry Andric static void relaxTlsLe(const InputSection &sec, size_t i, uint64_t loc,
665fcaf7f86SDimitry Andric                        Relocation &r, uint32_t &remove) {
666fcaf7f86SDimitry Andric   uint64_t val = r.sym->getVA(r.addend);
667fcaf7f86SDimitry Andric   if (hi20(val) != 0)
668fcaf7f86SDimitry Andric     return;
669bdd1243dSDimitry Andric   uint32_t insn = read32le(sec.content().data() + r.offset);
670fcaf7f86SDimitry Andric   switch (r.type) {
671fcaf7f86SDimitry Andric   case R_RISCV_TPREL_HI20:
672fcaf7f86SDimitry Andric   case R_RISCV_TPREL_ADD:
673fcaf7f86SDimitry Andric     // Remove lui rd, %tprel_hi(x) and add rd, rd, tp, %tprel_add(x).
674fcaf7f86SDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_RELAX;
675fcaf7f86SDimitry Andric     remove = 4;
676fcaf7f86SDimitry Andric     break;
677fcaf7f86SDimitry Andric   case R_RISCV_TPREL_LO12_I:
678fcaf7f86SDimitry Andric     // addi rd, rd, %tprel_lo(x) => addi rd, tp, st_value(x)
679fcaf7f86SDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_32;
680fcaf7f86SDimitry Andric     insn = (insn & ~(31 << 15)) | (X_TP << 15);
681fcaf7f86SDimitry Andric     sec.relaxAux->writes.push_back(setLO12_I(insn, val));
682fcaf7f86SDimitry Andric     break;
683fcaf7f86SDimitry Andric   case R_RISCV_TPREL_LO12_S:
684fcaf7f86SDimitry Andric     // sw rs, %tprel_lo(x)(rd) => sw rs, st_value(x)(rd)
685fcaf7f86SDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_32;
686fcaf7f86SDimitry Andric     insn = (insn & ~(31 << 15)) | (X_TP << 15);
687fcaf7f86SDimitry Andric     sec.relaxAux->writes.push_back(setLO12_S(insn, val));
688fcaf7f86SDimitry Andric     break;
689fcaf7f86SDimitry Andric   }
690fcaf7f86SDimitry Andric }
691fcaf7f86SDimitry Andric 
69206c3fb27SDimitry Andric static void relaxHi20Lo12(const InputSection &sec, size_t i, uint64_t loc,
69306c3fb27SDimitry Andric                           Relocation &r, uint32_t &remove) {
69406c3fb27SDimitry Andric   const Defined *gp = ElfSym::riscvGlobalPointer;
69506c3fb27SDimitry Andric   if (!gp)
69606c3fb27SDimitry Andric     return;
69706c3fb27SDimitry Andric 
69806c3fb27SDimitry Andric   if (!isInt<12>(r.sym->getVA(r.addend) - gp->getVA()))
69906c3fb27SDimitry Andric     return;
70006c3fb27SDimitry Andric 
70106c3fb27SDimitry Andric   switch (r.type) {
70206c3fb27SDimitry Andric   case R_RISCV_HI20:
70306c3fb27SDimitry Andric     // Remove lui rd, %hi20(x).
70406c3fb27SDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_RELAX;
70506c3fb27SDimitry Andric     remove = 4;
70606c3fb27SDimitry Andric     break;
70706c3fb27SDimitry Andric   case R_RISCV_LO12_I:
70806c3fb27SDimitry Andric     sec.relaxAux->relocTypes[i] = INTERNAL_R_RISCV_GPREL_I;
70906c3fb27SDimitry Andric     break;
71006c3fb27SDimitry Andric   case R_RISCV_LO12_S:
71106c3fb27SDimitry Andric     sec.relaxAux->relocTypes[i] = INTERNAL_R_RISCV_GPREL_S;
71206c3fb27SDimitry Andric     break;
71306c3fb27SDimitry Andric   }
71406c3fb27SDimitry Andric }
71506c3fb27SDimitry Andric 
716753f127fSDimitry Andric static bool relax(InputSection &sec) {
717753f127fSDimitry Andric   const uint64_t secAddr = sec.getVA();
718753f127fSDimitry Andric   auto &aux = *sec.relaxAux;
719753f127fSDimitry Andric   bool changed = false;
720bdd1243dSDimitry Andric   ArrayRef<SymbolAnchor> sa = ArrayRef(aux.anchors);
72106c3fb27SDimitry Andric   uint64_t delta = 0;
722753f127fSDimitry Andric 
723bdd1243dSDimitry Andric   std::fill_n(aux.relocTypes.get(), sec.relocs().size(), R_RISCV_NONE);
724753f127fSDimitry Andric   aux.writes.clear();
725bdd1243dSDimitry Andric   for (auto [i, r] : llvm::enumerate(sec.relocs())) {
726753f127fSDimitry Andric     const uint64_t loc = secAddr + r.offset - delta;
727753f127fSDimitry Andric     uint32_t &cur = aux.relocDeltas[i], remove = 0;
728753f127fSDimitry Andric     switch (r.type) {
729753f127fSDimitry Andric     case R_RISCV_ALIGN: {
730753f127fSDimitry Andric       const uint64_t nextLoc = loc + r.addend;
731753f127fSDimitry Andric       const uint64_t align = PowerOf2Ceil(r.addend + 2);
732753f127fSDimitry Andric       // All bytes beyond the alignment boundary should be removed.
733753f127fSDimitry Andric       remove = nextLoc - ((loc + align - 1) & -align);
734753f127fSDimitry Andric       assert(static_cast<int32_t>(remove) >= 0 &&
735753f127fSDimitry Andric              "R_RISCV_ALIGN needs expanding the content");
736753f127fSDimitry Andric       break;
737753f127fSDimitry Andric     }
738753f127fSDimitry Andric     case R_RISCV_CALL:
739753f127fSDimitry Andric     case R_RISCV_CALL_PLT:
740bdd1243dSDimitry Andric       if (i + 1 != sec.relocs().size() &&
741bdd1243dSDimitry Andric           sec.relocs()[i + 1].type == R_RISCV_RELAX)
742753f127fSDimitry Andric         relaxCall(sec, i, loc, r, remove);
743753f127fSDimitry Andric       break;
744fcaf7f86SDimitry Andric     case R_RISCV_TPREL_HI20:
745fcaf7f86SDimitry Andric     case R_RISCV_TPREL_ADD:
746fcaf7f86SDimitry Andric     case R_RISCV_TPREL_LO12_I:
747fcaf7f86SDimitry Andric     case R_RISCV_TPREL_LO12_S:
748bdd1243dSDimitry Andric       if (i + 1 != sec.relocs().size() &&
749bdd1243dSDimitry Andric           sec.relocs()[i + 1].type == R_RISCV_RELAX)
750fcaf7f86SDimitry Andric         relaxTlsLe(sec, i, loc, r, remove);
751fcaf7f86SDimitry Andric       break;
75206c3fb27SDimitry Andric     case R_RISCV_HI20:
75306c3fb27SDimitry Andric     case R_RISCV_LO12_I:
75406c3fb27SDimitry Andric     case R_RISCV_LO12_S:
75506c3fb27SDimitry Andric       if (i + 1 != sec.relocs().size() &&
75606c3fb27SDimitry Andric           sec.relocs()[i + 1].type == R_RISCV_RELAX)
75706c3fb27SDimitry Andric         relaxHi20Lo12(sec, i, loc, r, remove);
75806c3fb27SDimitry Andric       break;
759753f127fSDimitry Andric     }
760753f127fSDimitry Andric 
761753f127fSDimitry Andric     // For all anchors whose offsets are <= r.offset, they are preceded by
762753f127fSDimitry Andric     // the previous relocation whose `relocDeltas` value equals `delta`.
763753f127fSDimitry Andric     // Decrease their st_value and update their st_size.
764753f127fSDimitry Andric     for (; sa.size() && sa[0].offset <= r.offset; sa = sa.slice(1)) {
765753f127fSDimitry Andric       if (sa[0].end)
766753f127fSDimitry Andric         sa[0].d->size = sa[0].offset - delta - sa[0].d->value;
767753f127fSDimitry Andric       else
76806c3fb27SDimitry Andric         sa[0].d->value = sa[0].offset - delta;
769753f127fSDimitry Andric     }
770753f127fSDimitry Andric     delta += remove;
771753f127fSDimitry Andric     if (delta != cur) {
772753f127fSDimitry Andric       cur = delta;
773753f127fSDimitry Andric       changed = true;
774753f127fSDimitry Andric     }
775753f127fSDimitry Andric   }
776753f127fSDimitry Andric 
777753f127fSDimitry Andric   for (const SymbolAnchor &a : sa) {
778753f127fSDimitry Andric     if (a.end)
779753f127fSDimitry Andric       a.d->size = a.offset - delta - a.d->value;
780753f127fSDimitry Andric     else
78106c3fb27SDimitry Andric       a.d->value = a.offset - delta;
782753f127fSDimitry Andric   }
783753f127fSDimitry Andric   // Inform assignAddresses that the size has changed.
78406c3fb27SDimitry Andric   if (!isUInt<32>(delta))
78506c3fb27SDimitry Andric     fatal("section size decrease is too large: " + Twine(delta));
786753f127fSDimitry Andric   sec.bytesDropped = delta;
787753f127fSDimitry Andric   return changed;
788753f127fSDimitry Andric }
789753f127fSDimitry Andric 
790753f127fSDimitry Andric // When relaxing just R_RISCV_ALIGN, relocDeltas is usually changed only once in
791753f127fSDimitry Andric // the absence of a linker script. For call and load/store R_RISCV_RELAX, code
792753f127fSDimitry Andric // shrinkage may reduce displacement and make more relocations eligible for
793753f127fSDimitry Andric // relaxation. Code shrinkage may increase displacement to a call/load/store
794753f127fSDimitry Andric // target at a higher fixed address, invalidating an earlier relaxation. Any
795753f127fSDimitry Andric // change in section sizes can have cascading effect and require another
796753f127fSDimitry Andric // relaxation pass.
797753f127fSDimitry Andric bool RISCV::relaxOnce(int pass) const {
798753f127fSDimitry Andric   llvm::TimeTraceScope timeScope("RISC-V relaxOnce");
799753f127fSDimitry Andric   if (config->relocatable)
800753f127fSDimitry Andric     return false;
801753f127fSDimitry Andric 
802753f127fSDimitry Andric   if (pass == 0)
803753f127fSDimitry Andric     initSymbolAnchors();
804753f127fSDimitry Andric 
805753f127fSDimitry Andric   SmallVector<InputSection *, 0> storage;
806753f127fSDimitry Andric   bool changed = false;
807753f127fSDimitry Andric   for (OutputSection *osec : outputSections) {
808753f127fSDimitry Andric     if (!(osec->flags & SHF_EXECINSTR))
809753f127fSDimitry Andric       continue;
810753f127fSDimitry Andric     for (InputSection *sec : getInputSections(*osec, storage))
811753f127fSDimitry Andric       changed |= relax(*sec);
812753f127fSDimitry Andric   }
813753f127fSDimitry Andric   return changed;
814753f127fSDimitry Andric }
815753f127fSDimitry Andric 
816753f127fSDimitry Andric void elf::riscvFinalizeRelax(int passes) {
817753f127fSDimitry Andric   llvm::TimeTraceScope timeScope("Finalize RISC-V relaxation");
818753f127fSDimitry Andric   log("relaxation passes: " + Twine(passes));
819753f127fSDimitry Andric   SmallVector<InputSection *, 0> storage;
820753f127fSDimitry Andric   for (OutputSection *osec : outputSections) {
821753f127fSDimitry Andric     if (!(osec->flags & SHF_EXECINSTR))
822753f127fSDimitry Andric       continue;
823753f127fSDimitry Andric     for (InputSection *sec : getInputSections(*osec, storage)) {
824753f127fSDimitry Andric       RISCVRelaxAux &aux = *sec->relaxAux;
825753f127fSDimitry Andric       if (!aux.relocDeltas)
826753f127fSDimitry Andric         continue;
827753f127fSDimitry Andric 
828bdd1243dSDimitry Andric       MutableArrayRef<Relocation> rels = sec->relocs();
829bdd1243dSDimitry Andric       ArrayRef<uint8_t> old = sec->content();
830bdd1243dSDimitry Andric       size_t newSize = old.size() - aux.relocDeltas[rels.size() - 1];
831753f127fSDimitry Andric       size_t writesIdx = 0;
832753f127fSDimitry Andric       uint8_t *p = context().bAlloc.Allocate<uint8_t>(newSize);
833753f127fSDimitry Andric       uint64_t offset = 0;
834753f127fSDimitry Andric       int64_t delta = 0;
835bdd1243dSDimitry Andric       sec->content_ = p;
836bdd1243dSDimitry Andric       sec->size = newSize;
837753f127fSDimitry Andric       sec->bytesDropped = 0;
838753f127fSDimitry Andric 
839753f127fSDimitry Andric       // Update section content: remove NOPs for R_RISCV_ALIGN and rewrite
840753f127fSDimitry Andric       // instructions for relaxed relocations.
841753f127fSDimitry Andric       for (size_t i = 0, e = rels.size(); i != e; ++i) {
842753f127fSDimitry Andric         uint32_t remove = aux.relocDeltas[i] - delta;
843753f127fSDimitry Andric         delta = aux.relocDeltas[i];
844fcaf7f86SDimitry Andric         if (remove == 0 && aux.relocTypes[i] == R_RISCV_NONE)
845753f127fSDimitry Andric           continue;
846753f127fSDimitry Andric 
847753f127fSDimitry Andric         // Copy from last location to the current relocated location.
848753f127fSDimitry Andric         const Relocation &r = rels[i];
849753f127fSDimitry Andric         uint64_t size = r.offset - offset;
850753f127fSDimitry Andric         memcpy(p, old.data() + offset, size);
851753f127fSDimitry Andric         p += size;
852753f127fSDimitry Andric 
853753f127fSDimitry Andric         // For R_RISCV_ALIGN, we will place `offset` in a location (among NOPs)
8546246ae0bSDimitry Andric         // to satisfy the alignment requirement. If both `remove` and r.addend
8556246ae0bSDimitry Andric         // are multiples of 4, it is as if we have skipped some NOPs. Otherwise
8566246ae0bSDimitry Andric         // we are in the middle of a 4-byte NOP, and we need to rewrite the NOP
8576246ae0bSDimitry Andric         // sequence.
858753f127fSDimitry Andric         int64_t skip = 0;
859753f127fSDimitry Andric         if (r.type == R_RISCV_ALIGN) {
8606246ae0bSDimitry Andric           if (remove % 4 || r.addend % 4) {
861753f127fSDimitry Andric             skip = r.addend - remove;
862753f127fSDimitry Andric             int64_t j = 0;
863753f127fSDimitry Andric             for (; j + 4 <= skip; j += 4)
864753f127fSDimitry Andric               write32le(p + j, 0x00000013); // nop
865753f127fSDimitry Andric             if (j != skip) {
866753f127fSDimitry Andric               assert(j + 2 == skip);
867753f127fSDimitry Andric               write16le(p + j, 0x0001); // c.nop
868753f127fSDimitry Andric             }
869753f127fSDimitry Andric           }
870753f127fSDimitry Andric         } else if (RelType newType = aux.relocTypes[i]) {
871753f127fSDimitry Andric           switch (newType) {
87206c3fb27SDimitry Andric           case INTERNAL_R_RISCV_GPREL_I:
87306c3fb27SDimitry Andric           case INTERNAL_R_RISCV_GPREL_S:
87406c3fb27SDimitry Andric             break;
875fcaf7f86SDimitry Andric           case R_RISCV_RELAX:
876fcaf7f86SDimitry Andric             // Used by relaxTlsLe to indicate the relocation is ignored.
877fcaf7f86SDimitry Andric             break;
878753f127fSDimitry Andric           case R_RISCV_RVC_JUMP:
879753f127fSDimitry Andric             skip = 2;
880fcaf7f86SDimitry Andric             write16le(p, aux.writes[writesIdx++]);
881753f127fSDimitry Andric             break;
882753f127fSDimitry Andric           case R_RISCV_JAL:
883753f127fSDimitry Andric             skip = 4;
884fcaf7f86SDimitry Andric             write32le(p, aux.writes[writesIdx++]);
885fcaf7f86SDimitry Andric             break;
886fcaf7f86SDimitry Andric           case R_RISCV_32:
887fcaf7f86SDimitry Andric             // Used by relaxTlsLe to write a uint32_t then suppress the handling
888fcaf7f86SDimitry Andric             // in relocateAlloc.
889fcaf7f86SDimitry Andric             skip = 4;
890fcaf7f86SDimitry Andric             write32le(p, aux.writes[writesIdx++]);
891fcaf7f86SDimitry Andric             aux.relocTypes[i] = R_RISCV_NONE;
892753f127fSDimitry Andric             break;
893753f127fSDimitry Andric           default:
894753f127fSDimitry Andric             llvm_unreachable("unsupported type");
895753f127fSDimitry Andric           }
896753f127fSDimitry Andric         }
897753f127fSDimitry Andric 
898753f127fSDimitry Andric         p += skip;
899753f127fSDimitry Andric         offset = r.offset + skip + remove;
900753f127fSDimitry Andric       }
901753f127fSDimitry Andric       memcpy(p, old.data() + offset, old.size() - offset);
902753f127fSDimitry Andric 
903753f127fSDimitry Andric       // Subtract the previous relocDeltas value from the relocation offset.
904753f127fSDimitry Andric       // For a pair of R_RISCV_CALL/R_RISCV_RELAX with the same offset, decrease
905753f127fSDimitry Andric       // their r_offset by the same delta.
906753f127fSDimitry Andric       delta = 0;
907753f127fSDimitry Andric       for (size_t i = 0, e = rels.size(); i != e;) {
908753f127fSDimitry Andric         uint64_t cur = rels[i].offset;
909753f127fSDimitry Andric         do {
910753f127fSDimitry Andric           rels[i].offset -= delta;
911753f127fSDimitry Andric           if (aux.relocTypes[i] != R_RISCV_NONE)
912753f127fSDimitry Andric             rels[i].type = aux.relocTypes[i];
913753f127fSDimitry Andric         } while (++i != e && rels[i].offset == cur);
914753f127fSDimitry Andric         delta = aux.relocDeltas[i - 1];
915753f127fSDimitry Andric       }
916753f127fSDimitry Andric     }
917753f127fSDimitry Andric   }
918753f127fSDimitry Andric }
919753f127fSDimitry Andric 
920bdd1243dSDimitry Andric namespace {
921bdd1243dSDimitry Andric // Representation of the merged .riscv.attributes input sections. The psABI
922bdd1243dSDimitry Andric // specifies merge policy for attributes. E.g. if we link an object without an
923bdd1243dSDimitry Andric // extension with an object with the extension, the output Tag_RISCV_arch shall
924bdd1243dSDimitry Andric // contain the extension. Some tools like objdump parse .riscv.attributes and
925bdd1243dSDimitry Andric // disabling some instructions if the first Tag_RISCV_arch does not contain an
926bdd1243dSDimitry Andric // extension.
927bdd1243dSDimitry Andric class RISCVAttributesSection final : public SyntheticSection {
928bdd1243dSDimitry Andric public:
929bdd1243dSDimitry Andric   RISCVAttributesSection()
930bdd1243dSDimitry Andric       : SyntheticSection(0, SHT_RISCV_ATTRIBUTES, 1, ".riscv.attributes") {}
931bdd1243dSDimitry Andric 
932bdd1243dSDimitry Andric   size_t getSize() const override { return size; }
933bdd1243dSDimitry Andric   void writeTo(uint8_t *buf) override;
934bdd1243dSDimitry Andric 
935bdd1243dSDimitry Andric   static constexpr StringRef vendor = "riscv";
936bdd1243dSDimitry Andric   DenseMap<unsigned, unsigned> intAttr;
937bdd1243dSDimitry Andric   DenseMap<unsigned, StringRef> strAttr;
938bdd1243dSDimitry Andric   size_t size = 0;
939bdd1243dSDimitry Andric };
940bdd1243dSDimitry Andric } // namespace
941bdd1243dSDimitry Andric 
942bdd1243dSDimitry Andric static void mergeArch(RISCVISAInfo::OrderedExtensionMap &mergedExts,
943bdd1243dSDimitry Andric                       unsigned &mergedXlen, const InputSectionBase *sec,
944bdd1243dSDimitry Andric                       StringRef s) {
9451ac55f4cSDimitry Andric   auto maybeInfo = RISCVISAInfo::parseNormalizedArchString(s);
946bdd1243dSDimitry Andric   if (!maybeInfo) {
947bdd1243dSDimitry Andric     errorOrWarn(toString(sec) + ": " + s + ": " +
948bdd1243dSDimitry Andric                 llvm::toString(maybeInfo.takeError()));
949bdd1243dSDimitry Andric     return;
950bdd1243dSDimitry Andric   }
951bdd1243dSDimitry Andric 
952bdd1243dSDimitry Andric   // Merge extensions.
953bdd1243dSDimitry Andric   RISCVISAInfo &info = **maybeInfo;
954bdd1243dSDimitry Andric   if (mergedExts.empty()) {
955bdd1243dSDimitry Andric     mergedExts = info.getExtensions();
956bdd1243dSDimitry Andric     mergedXlen = info.getXLen();
957bdd1243dSDimitry Andric   } else {
958bdd1243dSDimitry Andric     for (const auto &ext : info.getExtensions()) {
959bdd1243dSDimitry Andric       if (auto it = mergedExts.find(ext.first); it != mergedExts.end()) {
960*297eecfbSDimitry Andric         if (std::tie(it->second.Major, it->second.Minor) >=
961*297eecfbSDimitry Andric             std::tie(ext.second.Major, ext.second.Minor))
962bdd1243dSDimitry Andric           continue;
963bdd1243dSDimitry Andric       }
964bdd1243dSDimitry Andric       mergedExts[ext.first] = ext.second;
965bdd1243dSDimitry Andric     }
966bdd1243dSDimitry Andric   }
967bdd1243dSDimitry Andric }
968bdd1243dSDimitry Andric 
969bdd1243dSDimitry Andric static RISCVAttributesSection *
970bdd1243dSDimitry Andric mergeAttributesSection(const SmallVector<InputSectionBase *, 0> &sections) {
971bdd1243dSDimitry Andric   RISCVISAInfo::OrderedExtensionMap exts;
972bdd1243dSDimitry Andric   const InputSectionBase *firstStackAlign = nullptr;
973bdd1243dSDimitry Andric   unsigned firstStackAlignValue = 0, xlen = 0;
974bdd1243dSDimitry Andric   bool hasArch = false;
975bdd1243dSDimitry Andric 
976bdd1243dSDimitry Andric   in.riscvAttributes = std::make_unique<RISCVAttributesSection>();
977bdd1243dSDimitry Andric   auto &merged = static_cast<RISCVAttributesSection &>(*in.riscvAttributes);
978bdd1243dSDimitry Andric 
979bdd1243dSDimitry Andric   // Collect all tags values from attributes section.
980bdd1243dSDimitry Andric   const auto &attributesTags = RISCVAttrs::getRISCVAttributeTags();
981bdd1243dSDimitry Andric   for (const InputSectionBase *sec : sections) {
982bdd1243dSDimitry Andric     RISCVAttributeParser parser;
9835f757f3fSDimitry Andric     if (Error e = parser.parse(sec->content(), llvm::endianness::little))
984bdd1243dSDimitry Andric       warn(toString(sec) + ": " + llvm::toString(std::move(e)));
985bdd1243dSDimitry Andric     for (const auto &tag : attributesTags) {
986bdd1243dSDimitry Andric       switch (RISCVAttrs::AttrType(tag.attr)) {
987bdd1243dSDimitry Andric         // Integer attributes.
988bdd1243dSDimitry Andric       case RISCVAttrs::STACK_ALIGN:
989bdd1243dSDimitry Andric         if (auto i = parser.getAttributeValue(tag.attr)) {
990bdd1243dSDimitry Andric           auto r = merged.intAttr.try_emplace(tag.attr, *i);
991bdd1243dSDimitry Andric           if (r.second) {
992bdd1243dSDimitry Andric             firstStackAlign = sec;
993bdd1243dSDimitry Andric             firstStackAlignValue = *i;
994bdd1243dSDimitry Andric           } else if (r.first->second != *i) {
995bdd1243dSDimitry Andric             errorOrWarn(toString(sec) + " has stack_align=" + Twine(*i) +
996bdd1243dSDimitry Andric                         " but " + toString(firstStackAlign) +
997bdd1243dSDimitry Andric                         " has stack_align=" + Twine(firstStackAlignValue));
998bdd1243dSDimitry Andric           }
999bdd1243dSDimitry Andric         }
1000bdd1243dSDimitry Andric         continue;
1001bdd1243dSDimitry Andric       case RISCVAttrs::UNALIGNED_ACCESS:
1002bdd1243dSDimitry Andric         if (auto i = parser.getAttributeValue(tag.attr))
1003bdd1243dSDimitry Andric           merged.intAttr[tag.attr] |= *i;
1004bdd1243dSDimitry Andric         continue;
1005bdd1243dSDimitry Andric 
1006bdd1243dSDimitry Andric         // String attributes.
1007bdd1243dSDimitry Andric       case RISCVAttrs::ARCH:
1008bdd1243dSDimitry Andric         if (auto s = parser.getAttributeString(tag.attr)) {
1009bdd1243dSDimitry Andric           hasArch = true;
1010bdd1243dSDimitry Andric           mergeArch(exts, xlen, sec, *s);
1011bdd1243dSDimitry Andric         }
1012bdd1243dSDimitry Andric         continue;
1013bdd1243dSDimitry Andric 
1014bdd1243dSDimitry Andric         // Attributes which use the default handling.
1015bdd1243dSDimitry Andric       case RISCVAttrs::PRIV_SPEC:
1016bdd1243dSDimitry Andric       case RISCVAttrs::PRIV_SPEC_MINOR:
1017bdd1243dSDimitry Andric       case RISCVAttrs::PRIV_SPEC_REVISION:
1018bdd1243dSDimitry Andric         break;
1019bdd1243dSDimitry Andric       }
1020bdd1243dSDimitry Andric 
1021bdd1243dSDimitry Andric       // Fallback for deprecated priv_spec* and other unknown attributes: retain
1022bdd1243dSDimitry Andric       // the attribute if all input sections agree on the value. GNU ld uses 0
1023bdd1243dSDimitry Andric       // and empty strings as default values which are not dumped to the output.
1024bdd1243dSDimitry Andric       // TODO Adjust after resolution to
1025bdd1243dSDimitry Andric       // https://github.com/riscv-non-isa/riscv-elf-psabi-doc/issues/352
1026bdd1243dSDimitry Andric       if (tag.attr % 2 == 0) {
1027bdd1243dSDimitry Andric         if (auto i = parser.getAttributeValue(tag.attr)) {
1028bdd1243dSDimitry Andric           auto r = merged.intAttr.try_emplace(tag.attr, *i);
1029bdd1243dSDimitry Andric           if (!r.second && r.first->second != *i)
1030bdd1243dSDimitry Andric             r.first->second = 0;
1031bdd1243dSDimitry Andric         }
1032bdd1243dSDimitry Andric       } else if (auto s = parser.getAttributeString(tag.attr)) {
1033bdd1243dSDimitry Andric         auto r = merged.strAttr.try_emplace(tag.attr, *s);
1034bdd1243dSDimitry Andric         if (!r.second && r.first->second != *s)
1035bdd1243dSDimitry Andric           r.first->second = {};
1036bdd1243dSDimitry Andric       }
1037bdd1243dSDimitry Andric     }
1038bdd1243dSDimitry Andric   }
1039bdd1243dSDimitry Andric 
1040bdd1243dSDimitry Andric   if (hasArch) {
1041bdd1243dSDimitry Andric     if (auto result = RISCVISAInfo::postProcessAndChecking(
1042bdd1243dSDimitry Andric             std::make_unique<RISCVISAInfo>(xlen, exts))) {
1043bdd1243dSDimitry Andric       merged.strAttr.try_emplace(RISCVAttrs::ARCH,
1044bdd1243dSDimitry Andric                                  saver().save((*result)->toString()));
1045bdd1243dSDimitry Andric     } else {
1046bdd1243dSDimitry Andric       errorOrWarn(llvm::toString(result.takeError()));
1047bdd1243dSDimitry Andric     }
1048bdd1243dSDimitry Andric   }
1049bdd1243dSDimitry Andric 
1050bdd1243dSDimitry Andric   // The total size of headers: format-version [ <section-length> "vendor-name"
1051bdd1243dSDimitry Andric   // [ <file-tag> <size>.
1052bdd1243dSDimitry Andric   size_t size = 5 + merged.vendor.size() + 1 + 5;
1053bdd1243dSDimitry Andric   for (auto &attr : merged.intAttr)
1054bdd1243dSDimitry Andric     if (attr.second != 0)
1055bdd1243dSDimitry Andric       size += getULEB128Size(attr.first) + getULEB128Size(attr.second);
1056bdd1243dSDimitry Andric   for (auto &attr : merged.strAttr)
1057bdd1243dSDimitry Andric     if (!attr.second.empty())
1058bdd1243dSDimitry Andric       size += getULEB128Size(attr.first) + attr.second.size() + 1;
1059bdd1243dSDimitry Andric   merged.size = size;
1060bdd1243dSDimitry Andric   return &merged;
1061bdd1243dSDimitry Andric }
1062bdd1243dSDimitry Andric 
1063bdd1243dSDimitry Andric void RISCVAttributesSection::writeTo(uint8_t *buf) {
1064bdd1243dSDimitry Andric   const size_t size = getSize();
1065bdd1243dSDimitry Andric   uint8_t *const end = buf + size;
1066bdd1243dSDimitry Andric   *buf = ELFAttrs::Format_Version;
1067bdd1243dSDimitry Andric   write32(buf + 1, size - 1);
1068bdd1243dSDimitry Andric   buf += 5;
1069bdd1243dSDimitry Andric 
1070bdd1243dSDimitry Andric   memcpy(buf, vendor.data(), vendor.size());
1071bdd1243dSDimitry Andric   buf += vendor.size() + 1;
1072bdd1243dSDimitry Andric 
1073bdd1243dSDimitry Andric   *buf = ELFAttrs::File;
1074bdd1243dSDimitry Andric   write32(buf + 1, end - buf);
1075bdd1243dSDimitry Andric   buf += 5;
1076bdd1243dSDimitry Andric 
1077bdd1243dSDimitry Andric   for (auto &attr : intAttr) {
1078bdd1243dSDimitry Andric     if (attr.second == 0)
1079bdd1243dSDimitry Andric       continue;
1080bdd1243dSDimitry Andric     buf += encodeULEB128(attr.first, buf);
1081bdd1243dSDimitry Andric     buf += encodeULEB128(attr.second, buf);
1082bdd1243dSDimitry Andric   }
1083bdd1243dSDimitry Andric   for (auto &attr : strAttr) {
1084bdd1243dSDimitry Andric     if (attr.second.empty())
1085bdd1243dSDimitry Andric       continue;
1086bdd1243dSDimitry Andric     buf += encodeULEB128(attr.first, buf);
1087bdd1243dSDimitry Andric     memcpy(buf, attr.second.data(), attr.second.size());
1088bdd1243dSDimitry Andric     buf += attr.second.size() + 1;
1089bdd1243dSDimitry Andric   }
1090bdd1243dSDimitry Andric }
1091bdd1243dSDimitry Andric 
1092bdd1243dSDimitry Andric void elf::mergeRISCVAttributesSections() {
1093bdd1243dSDimitry Andric   // Find the first input SHT_RISCV_ATTRIBUTES; return if not found.
1094bdd1243dSDimitry Andric   size_t place =
1095bdd1243dSDimitry Andric       llvm::find_if(ctx.inputSections,
1096bdd1243dSDimitry Andric                     [](auto *s) { return s->type == SHT_RISCV_ATTRIBUTES; }) -
1097bdd1243dSDimitry Andric       ctx.inputSections.begin();
1098bdd1243dSDimitry Andric   if (place == ctx.inputSections.size())
1099bdd1243dSDimitry Andric     return;
1100bdd1243dSDimitry Andric 
1101bdd1243dSDimitry Andric   // Extract all SHT_RISCV_ATTRIBUTES sections into `sections`.
1102bdd1243dSDimitry Andric   SmallVector<InputSectionBase *, 0> sections;
1103bdd1243dSDimitry Andric   llvm::erase_if(ctx.inputSections, [&](InputSectionBase *s) {
1104bdd1243dSDimitry Andric     if (s->type != SHT_RISCV_ATTRIBUTES)
1105bdd1243dSDimitry Andric       return false;
1106bdd1243dSDimitry Andric     sections.push_back(s);
1107bdd1243dSDimitry Andric     return true;
1108bdd1243dSDimitry Andric   });
1109bdd1243dSDimitry Andric 
1110bdd1243dSDimitry Andric   // Add the merged section.
1111bdd1243dSDimitry Andric   ctx.inputSections.insert(ctx.inputSections.begin() + place,
1112bdd1243dSDimitry Andric                            mergeAttributesSection(sections));
1113bdd1243dSDimitry Andric }
1114bdd1243dSDimitry Andric 
11155ffd83dbSDimitry Andric TargetInfo *elf::getRISCVTargetInfo() {
11160b57cec5SDimitry Andric   static RISCV target;
11170b57cec5SDimitry Andric   return &target;
11180b57cec5SDimitry Andric }
1119