xref: /freebsd/contrib/llvm-project/lld/ELF/Arch/RISCV.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
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;
46*1db9f3b2SDimitry 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:
2930b57cec5SDimitry Andric     return R_GOT_PC;
2940b57cec5SDimitry Andric   case R_RISCV_PCREL_LO12_I:
2950b57cec5SDimitry Andric   case R_RISCV_PCREL_LO12_S:
2960b57cec5SDimitry Andric     return R_RISCV_PC_INDIRECT;
2970b57cec5SDimitry Andric   case R_RISCV_TLS_GD_HI20:
2980b57cec5SDimitry Andric     return R_TLSGD_PC;
2990b57cec5SDimitry Andric   case R_RISCV_TLS_GOT_HI20:
3000b57cec5SDimitry Andric     return R_GOT_PC;
3010b57cec5SDimitry Andric   case R_RISCV_TPREL_HI20:
3020b57cec5SDimitry Andric   case R_RISCV_TPREL_LO12_I:
3030b57cec5SDimitry Andric   case R_RISCV_TPREL_LO12_S:
304e8d8bef9SDimitry Andric     return R_TPREL;
30555e4f9d5SDimitry Andric   case R_RISCV_ALIGN:
306753f127fSDimitry Andric     return R_RELAX_HINT;
307fcaf7f86SDimitry Andric   case R_RISCV_TPREL_ADD:
308753f127fSDimitry Andric   case R_RISCV_RELAX:
309753f127fSDimitry Andric     return config->relax ? R_RELAX_HINT : R_NONE;
3105f757f3fSDimitry Andric   case R_RISCV_SET_ULEB128:
311*1db9f3b2SDimitry Andric   case R_RISCV_SUB_ULEB128:
3125f757f3fSDimitry Andric     return R_RISCV_LEB128;
3130b57cec5SDimitry Andric   default:
314480093f4SDimitry Andric     error(getErrorLocation(loc) + "unknown relocation (" + Twine(type) +
315480093f4SDimitry Andric           ") against symbol " + toString(s));
316480093f4SDimitry Andric     return R_NONE;
3170b57cec5SDimitry Andric   }
3180b57cec5SDimitry Andric }
3190b57cec5SDimitry Andric 
3205ffd83dbSDimitry Andric void RISCV::relocate(uint8_t *loc, const Relocation &rel, uint64_t val) const {
3210b57cec5SDimitry Andric   const unsigned bits = config->wordsize * 8;
3220b57cec5SDimitry Andric 
3235ffd83dbSDimitry Andric   switch (rel.type) {
3240b57cec5SDimitry Andric   case R_RISCV_32:
3250b57cec5SDimitry Andric     write32le(loc, val);
3260b57cec5SDimitry Andric     return;
3270b57cec5SDimitry Andric   case R_RISCV_64:
3280b57cec5SDimitry Andric     write64le(loc, val);
3290b57cec5SDimitry Andric     return;
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric   case R_RISCV_RVC_BRANCH: {
332753f127fSDimitry Andric     checkInt(loc, val, 9, rel);
3335ffd83dbSDimitry Andric     checkAlignment(loc, val, 2, rel);
3340b57cec5SDimitry Andric     uint16_t insn = read16le(loc) & 0xE383;
3350b57cec5SDimitry Andric     uint16_t imm8 = extractBits(val, 8, 8) << 12;
3360b57cec5SDimitry Andric     uint16_t imm4_3 = extractBits(val, 4, 3) << 10;
3370b57cec5SDimitry Andric     uint16_t imm7_6 = extractBits(val, 7, 6) << 5;
3380b57cec5SDimitry Andric     uint16_t imm2_1 = extractBits(val, 2, 1) << 3;
3390b57cec5SDimitry Andric     uint16_t imm5 = extractBits(val, 5, 5) << 2;
3400b57cec5SDimitry Andric     insn |= imm8 | imm4_3 | imm7_6 | imm2_1 | imm5;
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric     write16le(loc, insn);
3430b57cec5SDimitry Andric     return;
3440b57cec5SDimitry Andric   }
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric   case R_RISCV_RVC_JUMP: {
347753f127fSDimitry Andric     checkInt(loc, val, 12, rel);
3485ffd83dbSDimitry Andric     checkAlignment(loc, val, 2, rel);
3490b57cec5SDimitry Andric     uint16_t insn = read16le(loc) & 0xE003;
3500b57cec5SDimitry Andric     uint16_t imm11 = extractBits(val, 11, 11) << 12;
3510b57cec5SDimitry Andric     uint16_t imm4 = extractBits(val, 4, 4) << 11;
3520b57cec5SDimitry Andric     uint16_t imm9_8 = extractBits(val, 9, 8) << 9;
3530b57cec5SDimitry Andric     uint16_t imm10 = extractBits(val, 10, 10) << 8;
3540b57cec5SDimitry Andric     uint16_t imm6 = extractBits(val, 6, 6) << 7;
3550b57cec5SDimitry Andric     uint16_t imm7 = extractBits(val, 7, 7) << 6;
3560b57cec5SDimitry Andric     uint16_t imm3_1 = extractBits(val, 3, 1) << 3;
3570b57cec5SDimitry Andric     uint16_t imm5 = extractBits(val, 5, 5) << 2;
3580b57cec5SDimitry Andric     insn |= imm11 | imm4 | imm9_8 | imm10 | imm6 | imm7 | imm3_1 | imm5;
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric     write16le(loc, insn);
3610b57cec5SDimitry Andric     return;
3620b57cec5SDimitry Andric   }
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric   case R_RISCV_RVC_LUI: {
3650b57cec5SDimitry Andric     int64_t imm = SignExtend64(val + 0x800, bits) >> 12;
3665ffd83dbSDimitry Andric     checkInt(loc, imm, 6, rel);
3670b57cec5SDimitry Andric     if (imm == 0) { // `c.lui rd, 0` is illegal, convert to `c.li rd, 0`
3680b57cec5SDimitry Andric       write16le(loc, (read16le(loc) & 0x0F83) | 0x4000);
3690b57cec5SDimitry Andric     } else {
3700b57cec5SDimitry Andric       uint16_t imm17 = extractBits(val + 0x800, 17, 17) << 12;
3710b57cec5SDimitry Andric       uint16_t imm16_12 = extractBits(val + 0x800, 16, 12) << 2;
3720b57cec5SDimitry Andric       write16le(loc, (read16le(loc) & 0xEF83) | imm17 | imm16_12);
3730b57cec5SDimitry Andric     }
3740b57cec5SDimitry Andric     return;
3750b57cec5SDimitry Andric   }
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric   case R_RISCV_JAL: {
378753f127fSDimitry Andric     checkInt(loc, val, 21, rel);
3795ffd83dbSDimitry Andric     checkAlignment(loc, val, 2, rel);
3800b57cec5SDimitry Andric 
3810b57cec5SDimitry Andric     uint32_t insn = read32le(loc) & 0xFFF;
3820b57cec5SDimitry Andric     uint32_t imm20 = extractBits(val, 20, 20) << 31;
3830b57cec5SDimitry Andric     uint32_t imm10_1 = extractBits(val, 10, 1) << 21;
3840b57cec5SDimitry Andric     uint32_t imm11 = extractBits(val, 11, 11) << 20;
3850b57cec5SDimitry Andric     uint32_t imm19_12 = extractBits(val, 19, 12) << 12;
3860b57cec5SDimitry Andric     insn |= imm20 | imm10_1 | imm11 | imm19_12;
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric     write32le(loc, insn);
3890b57cec5SDimitry Andric     return;
3900b57cec5SDimitry Andric   }
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric   case R_RISCV_BRANCH: {
393753f127fSDimitry Andric     checkInt(loc, val, 13, rel);
3945ffd83dbSDimitry Andric     checkAlignment(loc, val, 2, rel);
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric     uint32_t insn = read32le(loc) & 0x1FFF07F;
3970b57cec5SDimitry Andric     uint32_t imm12 = extractBits(val, 12, 12) << 31;
3980b57cec5SDimitry Andric     uint32_t imm10_5 = extractBits(val, 10, 5) << 25;
3990b57cec5SDimitry Andric     uint32_t imm4_1 = extractBits(val, 4, 1) << 8;
4000b57cec5SDimitry Andric     uint32_t imm11 = extractBits(val, 11, 11) << 7;
4010b57cec5SDimitry Andric     insn |= imm12 | imm10_5 | imm4_1 | imm11;
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric     write32le(loc, insn);
4040b57cec5SDimitry Andric     return;
4050b57cec5SDimitry Andric   }
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric   // auipc + jalr pair
4080b57cec5SDimitry Andric   case R_RISCV_CALL:
4090b57cec5SDimitry Andric   case R_RISCV_CALL_PLT: {
4100b57cec5SDimitry Andric     int64_t hi = SignExtend64(val + 0x800, bits) >> 12;
4115ffd83dbSDimitry Andric     checkInt(loc, hi, 20, rel);
4120b57cec5SDimitry Andric     if (isInt<20>(hi)) {
4135ffd83dbSDimitry Andric       relocateNoSym(loc, R_RISCV_PCREL_HI20, val);
4145ffd83dbSDimitry Andric       relocateNoSym(loc + 4, R_RISCV_PCREL_LO12_I, val);
4150b57cec5SDimitry Andric     }
4160b57cec5SDimitry Andric     return;
4170b57cec5SDimitry Andric   }
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric   case R_RISCV_GOT_HI20:
4200b57cec5SDimitry Andric   case R_RISCV_PCREL_HI20:
4210b57cec5SDimitry Andric   case R_RISCV_TLS_GD_HI20:
4220b57cec5SDimitry Andric   case R_RISCV_TLS_GOT_HI20:
4230b57cec5SDimitry Andric   case R_RISCV_TPREL_HI20:
4240b57cec5SDimitry Andric   case R_RISCV_HI20: {
4250b57cec5SDimitry Andric     uint64_t hi = val + 0x800;
4265ffd83dbSDimitry Andric     checkInt(loc, SignExtend64(hi, bits) >> 12, 20, rel);
4270b57cec5SDimitry Andric     write32le(loc, (read32le(loc) & 0xFFF) | (hi & 0xFFFFF000));
4280b57cec5SDimitry Andric     return;
4290b57cec5SDimitry Andric   }
4300b57cec5SDimitry Andric 
4310b57cec5SDimitry Andric   case R_RISCV_PCREL_LO12_I:
4320b57cec5SDimitry Andric   case R_RISCV_TPREL_LO12_I:
4330b57cec5SDimitry Andric   case R_RISCV_LO12_I: {
4340b57cec5SDimitry Andric     uint64_t hi = (val + 0x800) >> 12;
4350b57cec5SDimitry Andric     uint64_t lo = val - (hi << 12);
436fcaf7f86SDimitry Andric     write32le(loc, setLO12_I(read32le(loc), lo & 0xfff));
4370b57cec5SDimitry Andric     return;
4380b57cec5SDimitry Andric   }
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric   case R_RISCV_PCREL_LO12_S:
4410b57cec5SDimitry Andric   case R_RISCV_TPREL_LO12_S:
4420b57cec5SDimitry Andric   case R_RISCV_LO12_S: {
4430b57cec5SDimitry Andric     uint64_t hi = (val + 0x800) >> 12;
4440b57cec5SDimitry Andric     uint64_t lo = val - (hi << 12);
445fcaf7f86SDimitry Andric     write32le(loc, setLO12_S(read32le(loc), lo));
4460b57cec5SDimitry Andric     return;
4470b57cec5SDimitry Andric   }
4480b57cec5SDimitry Andric 
44906c3fb27SDimitry Andric   case INTERNAL_R_RISCV_GPREL_I:
45006c3fb27SDimitry Andric   case INTERNAL_R_RISCV_GPREL_S: {
45106c3fb27SDimitry Andric     Defined *gp = ElfSym::riscvGlobalPointer;
45206c3fb27SDimitry Andric     int64_t displace = SignExtend64(val - gp->getVA(), bits);
45306c3fb27SDimitry Andric     checkInt(loc, displace, 12, rel);
45406c3fb27SDimitry Andric     uint32_t insn = (read32le(loc) & ~(31 << 15)) | (X_GP << 15);
45506c3fb27SDimitry Andric     if (rel.type == INTERNAL_R_RISCV_GPREL_I)
45606c3fb27SDimitry Andric       insn = setLO12_I(insn, displace);
45706c3fb27SDimitry Andric     else
45806c3fb27SDimitry Andric       insn = setLO12_S(insn, displace);
45906c3fb27SDimitry Andric     write32le(loc, insn);
46006c3fb27SDimitry Andric     return;
46106c3fb27SDimitry Andric   }
46206c3fb27SDimitry Andric 
4630b57cec5SDimitry Andric   case R_RISCV_ADD8:
4640b57cec5SDimitry Andric     *loc += val;
4650b57cec5SDimitry Andric     return;
4660b57cec5SDimitry Andric   case R_RISCV_ADD16:
4670b57cec5SDimitry Andric     write16le(loc, read16le(loc) + val);
4680b57cec5SDimitry Andric     return;
4690b57cec5SDimitry Andric   case R_RISCV_ADD32:
4700b57cec5SDimitry Andric     write32le(loc, read32le(loc) + val);
4710b57cec5SDimitry Andric     return;
4720b57cec5SDimitry Andric   case R_RISCV_ADD64:
4730b57cec5SDimitry Andric     write64le(loc, read64le(loc) + val);
4740b57cec5SDimitry Andric     return;
4750b57cec5SDimitry Andric   case R_RISCV_SUB6:
4760b57cec5SDimitry Andric     *loc = (*loc & 0xc0) | (((*loc & 0x3f) - val) & 0x3f);
4770b57cec5SDimitry Andric     return;
4780b57cec5SDimitry Andric   case R_RISCV_SUB8:
4790b57cec5SDimitry Andric     *loc -= val;
4800b57cec5SDimitry Andric     return;
4810b57cec5SDimitry Andric   case R_RISCV_SUB16:
4820b57cec5SDimitry Andric     write16le(loc, read16le(loc) - val);
4830b57cec5SDimitry Andric     return;
4840b57cec5SDimitry Andric   case R_RISCV_SUB32:
4850b57cec5SDimitry Andric     write32le(loc, read32le(loc) - val);
4860b57cec5SDimitry Andric     return;
4870b57cec5SDimitry Andric   case R_RISCV_SUB64:
4880b57cec5SDimitry Andric     write64le(loc, read64le(loc) - val);
4890b57cec5SDimitry Andric     return;
4900b57cec5SDimitry Andric   case R_RISCV_SET6:
4910b57cec5SDimitry Andric     *loc = (*loc & 0xc0) | (val & 0x3f);
4920b57cec5SDimitry Andric     return;
4930b57cec5SDimitry Andric   case R_RISCV_SET8:
4940b57cec5SDimitry Andric     *loc = val;
4950b57cec5SDimitry Andric     return;
4960b57cec5SDimitry Andric   case R_RISCV_SET16:
4970b57cec5SDimitry Andric     write16le(loc, val);
4980b57cec5SDimitry Andric     return;
4990b57cec5SDimitry Andric   case R_RISCV_SET32:
5000b57cec5SDimitry Andric   case R_RISCV_32_PCREL:
50106c3fb27SDimitry Andric   case R_RISCV_PLT32:
5020b57cec5SDimitry Andric     write32le(loc, val);
5030b57cec5SDimitry Andric     return;
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric   case R_RISCV_TLS_DTPREL32:
5060b57cec5SDimitry Andric     write32le(loc, val - dtpOffset);
5070b57cec5SDimitry Andric     break;
5080b57cec5SDimitry Andric   case R_RISCV_TLS_DTPREL64:
5090b57cec5SDimitry Andric     write64le(loc, val - dtpOffset);
5100b57cec5SDimitry Andric     break;
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric   case R_RISCV_RELAX:
5130b57cec5SDimitry Andric     return; // Ignored (for now)
5140b57cec5SDimitry Andric 
5150b57cec5SDimitry Andric   default:
516480093f4SDimitry Andric     llvm_unreachable("unknown relocation");
5170b57cec5SDimitry Andric   }
5180b57cec5SDimitry Andric }
5190b57cec5SDimitry Andric 
520*1db9f3b2SDimitry Andric void RISCV::relocateAlloc(InputSectionBase &sec, uint8_t *buf) const {
521*1db9f3b2SDimitry Andric   uint64_t secAddr = sec.getOutputSection()->addr;
522*1db9f3b2SDimitry Andric   if (auto *s = dyn_cast<InputSection>(&sec))
523*1db9f3b2SDimitry Andric     secAddr += s->outSecOff;
524*1db9f3b2SDimitry Andric   else if (auto *ehIn = dyn_cast<EhInputSection>(&sec))
525*1db9f3b2SDimitry Andric     secAddr += ehIn->getParent()->outSecOff;
526*1db9f3b2SDimitry Andric   for (size_t i = 0, size = sec.relocs().size(); i != size; ++i) {
527*1db9f3b2SDimitry Andric     const Relocation &rel = sec.relocs()[i];
528*1db9f3b2SDimitry Andric     uint8_t *loc = buf + rel.offset;
529*1db9f3b2SDimitry Andric     const uint64_t val =
530*1db9f3b2SDimitry Andric         sec.getRelocTargetVA(sec.file, rel.type, rel.addend,
531*1db9f3b2SDimitry Andric                              secAddr + rel.offset, *rel.sym, rel.expr);
532*1db9f3b2SDimitry Andric 
533*1db9f3b2SDimitry Andric     switch (rel.expr) {
534*1db9f3b2SDimitry Andric     case R_RELAX_HINT:
535*1db9f3b2SDimitry Andric       break;
536*1db9f3b2SDimitry Andric     case R_RISCV_LEB128:
537*1db9f3b2SDimitry Andric       if (i + 1 < size) {
538*1db9f3b2SDimitry Andric         const Relocation &rel1 = sec.relocs()[i + 1];
539*1db9f3b2SDimitry Andric         if (rel.type == R_RISCV_SET_ULEB128 &&
540*1db9f3b2SDimitry Andric             rel1.type == R_RISCV_SUB_ULEB128 && rel.offset == rel1.offset) {
541*1db9f3b2SDimitry Andric           auto val = rel.sym->getVA(rel.addend) - rel1.sym->getVA(rel1.addend);
542*1db9f3b2SDimitry Andric           if (overwriteULEB128(loc, val) >= 0x80)
543*1db9f3b2SDimitry Andric             errorOrWarn(sec.getLocation(rel.offset) + ": ULEB128 value " +
544*1db9f3b2SDimitry Andric                         Twine(val) + " exceeds available space; references '" +
545*1db9f3b2SDimitry Andric                         lld::toString(*rel.sym) + "'");
546*1db9f3b2SDimitry Andric           ++i;
547*1db9f3b2SDimitry Andric           continue;
548*1db9f3b2SDimitry Andric         }
549*1db9f3b2SDimitry Andric       }
550*1db9f3b2SDimitry Andric       errorOrWarn(sec.getLocation(rel.offset) +
551*1db9f3b2SDimitry Andric                   ": R_RISCV_SET_ULEB128 not paired with R_RISCV_SUB_SET128");
552*1db9f3b2SDimitry Andric       return;
553*1db9f3b2SDimitry Andric     default:
554*1db9f3b2SDimitry Andric       relocate(loc, rel, val);
555*1db9f3b2SDimitry Andric       break;
556*1db9f3b2SDimitry Andric     }
557*1db9f3b2SDimitry Andric   }
558*1db9f3b2SDimitry Andric }
559*1db9f3b2SDimitry Andric 
560753f127fSDimitry Andric namespace {
561753f127fSDimitry Andric struct SymbolAnchor {
562753f127fSDimitry Andric   uint64_t offset;
563753f127fSDimitry Andric   Defined *d;
564753f127fSDimitry Andric   bool end; // true for the anchor of st_value+st_size
565753f127fSDimitry Andric };
566753f127fSDimitry Andric } // namespace
567753f127fSDimitry Andric 
568753f127fSDimitry Andric struct elf::RISCVRelaxAux {
569753f127fSDimitry Andric   // This records symbol start and end offsets which will be adjusted according
570753f127fSDimitry Andric   // to the nearest relocDeltas element.
571753f127fSDimitry Andric   SmallVector<SymbolAnchor, 0> anchors;
572753f127fSDimitry Andric   // For relocations[i], the actual offset is r_offset - (i ? relocDeltas[i-1] :
573753f127fSDimitry Andric   // 0).
574753f127fSDimitry Andric   std::unique_ptr<uint32_t[]> relocDeltas;
575753f127fSDimitry Andric   // For relocations[i], the actual type is relocTypes[i].
576753f127fSDimitry Andric   std::unique_ptr<RelType[]> relocTypes;
577753f127fSDimitry Andric   SmallVector<uint32_t, 0> writes;
578753f127fSDimitry Andric };
579753f127fSDimitry Andric 
580753f127fSDimitry Andric static void initSymbolAnchors() {
581753f127fSDimitry Andric   SmallVector<InputSection *, 0> storage;
582753f127fSDimitry Andric   for (OutputSection *osec : outputSections) {
583753f127fSDimitry Andric     if (!(osec->flags & SHF_EXECINSTR))
584753f127fSDimitry Andric       continue;
585753f127fSDimitry Andric     for (InputSection *sec : getInputSections(*osec, storage)) {
586753f127fSDimitry Andric       sec->relaxAux = make<RISCVRelaxAux>();
587bdd1243dSDimitry Andric       if (sec->relocs().size()) {
588753f127fSDimitry Andric         sec->relaxAux->relocDeltas =
589bdd1243dSDimitry Andric             std::make_unique<uint32_t[]>(sec->relocs().size());
590753f127fSDimitry Andric         sec->relaxAux->relocTypes =
591bdd1243dSDimitry Andric             std::make_unique<RelType[]>(sec->relocs().size());
592753f127fSDimitry Andric       }
593753f127fSDimitry Andric     }
594753f127fSDimitry Andric   }
595753f127fSDimitry Andric   // Store anchors (st_value and st_value+st_size) for symbols relative to text
596753f127fSDimitry Andric   // sections.
59706c3fb27SDimitry Andric   //
59806c3fb27SDimitry Andric   // For a defined symbol foo, we may have `d->file != file` with --wrap=foo.
59906c3fb27SDimitry Andric   // We should process foo, as the defining object file's symbol table may not
60006c3fb27SDimitry Andric   // contain foo after redirectSymbols changed the foo entry to __wrap_foo. To
60106c3fb27SDimitry Andric   // avoid adding a Defined that is undefined in one object file, use
60206c3fb27SDimitry Andric   // `!d->scriptDefined` to exclude symbols that are definitely not wrapped.
60306c3fb27SDimitry Andric   //
60406c3fb27SDimitry Andric   // `relaxAux->anchors` may contain duplicate symbols, but that is fine.
605bdd1243dSDimitry Andric   for (InputFile *file : ctx.objectFiles)
606753f127fSDimitry Andric     for (Symbol *sym : file->getSymbols()) {
607753f127fSDimitry Andric       auto *d = dyn_cast<Defined>(sym);
60806c3fb27SDimitry Andric       if (!d || (d->file != file && !d->scriptDefined))
609753f127fSDimitry Andric         continue;
610753f127fSDimitry Andric       if (auto *sec = dyn_cast_or_null<InputSection>(d->section))
611753f127fSDimitry Andric         if (sec->flags & SHF_EXECINSTR && sec->relaxAux) {
612753f127fSDimitry Andric           // If sec is discarded, relaxAux will be nullptr.
613753f127fSDimitry Andric           sec->relaxAux->anchors.push_back({d->value, d, false});
614753f127fSDimitry Andric           sec->relaxAux->anchors.push_back({d->value + d->size, d, true});
615753f127fSDimitry Andric         }
616753f127fSDimitry Andric     }
617753f127fSDimitry Andric   // Sort anchors by offset so that we can find the closest relocation
618753f127fSDimitry Andric   // efficiently. For a zero size symbol, ensure that its start anchor precedes
619753f127fSDimitry Andric   // its end anchor. For two symbols with anchors at the same offset, their
620753f127fSDimitry Andric   // order does not matter.
621753f127fSDimitry Andric   for (OutputSection *osec : outputSections) {
622753f127fSDimitry Andric     if (!(osec->flags & SHF_EXECINSTR))
623753f127fSDimitry Andric       continue;
624753f127fSDimitry Andric     for (InputSection *sec : getInputSections(*osec, storage)) {
625753f127fSDimitry Andric       llvm::sort(sec->relaxAux->anchors, [](auto &a, auto &b) {
626753f127fSDimitry Andric         return std::make_pair(a.offset, a.end) <
627753f127fSDimitry Andric                std::make_pair(b.offset, b.end);
628753f127fSDimitry Andric       });
629753f127fSDimitry Andric     }
630753f127fSDimitry Andric   }
631753f127fSDimitry Andric }
632753f127fSDimitry Andric 
633753f127fSDimitry Andric // Relax R_RISCV_CALL/R_RISCV_CALL_PLT auipc+jalr to c.j, c.jal, or jal.
634753f127fSDimitry Andric static void relaxCall(const InputSection &sec, size_t i, uint64_t loc,
635753f127fSDimitry Andric                       Relocation &r, uint32_t &remove) {
6365f757f3fSDimitry Andric   const bool rvc = getEFlags(sec.file) & EF_RISCV_RVC;
637753f127fSDimitry Andric   const Symbol &sym = *r.sym;
638bdd1243dSDimitry Andric   const uint64_t insnPair = read64le(sec.content().data() + r.offset);
639753f127fSDimitry Andric   const uint32_t rd = extractBits(insnPair, 32 + 11, 32 + 7);
640753f127fSDimitry Andric   const uint64_t dest =
641753f127fSDimitry Andric       (r.expr == R_PLT_PC ? sym.getPltVA() : sym.getVA()) + r.addend;
642753f127fSDimitry Andric   const int64_t displace = dest - loc;
643753f127fSDimitry Andric 
644753f127fSDimitry Andric   if (rvc && isInt<12>(displace) && rd == 0) {
645753f127fSDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_RVC_JUMP;
646753f127fSDimitry Andric     sec.relaxAux->writes.push_back(0xa001); // c.j
647753f127fSDimitry Andric     remove = 6;
648753f127fSDimitry Andric   } else if (rvc && isInt<12>(displace) && rd == X_RA &&
649753f127fSDimitry Andric              !config->is64) { // RV32C only
650753f127fSDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_RVC_JUMP;
651753f127fSDimitry Andric     sec.relaxAux->writes.push_back(0x2001); // c.jal
652753f127fSDimitry Andric     remove = 6;
653753f127fSDimitry Andric   } else if (isInt<21>(displace)) {
654753f127fSDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_JAL;
655753f127fSDimitry Andric     sec.relaxAux->writes.push_back(0x6f | rd << 7); // jal
656753f127fSDimitry Andric     remove = 4;
657753f127fSDimitry Andric   }
658753f127fSDimitry Andric }
659753f127fSDimitry Andric 
660fcaf7f86SDimitry Andric // Relax local-exec TLS when hi20 is zero.
661fcaf7f86SDimitry Andric static void relaxTlsLe(const InputSection &sec, size_t i, uint64_t loc,
662fcaf7f86SDimitry Andric                        Relocation &r, uint32_t &remove) {
663fcaf7f86SDimitry Andric   uint64_t val = r.sym->getVA(r.addend);
664fcaf7f86SDimitry Andric   if (hi20(val) != 0)
665fcaf7f86SDimitry Andric     return;
666bdd1243dSDimitry Andric   uint32_t insn = read32le(sec.content().data() + r.offset);
667fcaf7f86SDimitry Andric   switch (r.type) {
668fcaf7f86SDimitry Andric   case R_RISCV_TPREL_HI20:
669fcaf7f86SDimitry Andric   case R_RISCV_TPREL_ADD:
670fcaf7f86SDimitry Andric     // Remove lui rd, %tprel_hi(x) and add rd, rd, tp, %tprel_add(x).
671fcaf7f86SDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_RELAX;
672fcaf7f86SDimitry Andric     remove = 4;
673fcaf7f86SDimitry Andric     break;
674fcaf7f86SDimitry Andric   case R_RISCV_TPREL_LO12_I:
675fcaf7f86SDimitry Andric     // addi rd, rd, %tprel_lo(x) => addi rd, tp, st_value(x)
676fcaf7f86SDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_32;
677fcaf7f86SDimitry Andric     insn = (insn & ~(31 << 15)) | (X_TP << 15);
678fcaf7f86SDimitry Andric     sec.relaxAux->writes.push_back(setLO12_I(insn, val));
679fcaf7f86SDimitry Andric     break;
680fcaf7f86SDimitry Andric   case R_RISCV_TPREL_LO12_S:
681fcaf7f86SDimitry Andric     // sw rs, %tprel_lo(x)(rd) => sw rs, st_value(x)(rd)
682fcaf7f86SDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_32;
683fcaf7f86SDimitry Andric     insn = (insn & ~(31 << 15)) | (X_TP << 15);
684fcaf7f86SDimitry Andric     sec.relaxAux->writes.push_back(setLO12_S(insn, val));
685fcaf7f86SDimitry Andric     break;
686fcaf7f86SDimitry Andric   }
687fcaf7f86SDimitry Andric }
688fcaf7f86SDimitry Andric 
68906c3fb27SDimitry Andric static void relaxHi20Lo12(const InputSection &sec, size_t i, uint64_t loc,
69006c3fb27SDimitry Andric                           Relocation &r, uint32_t &remove) {
69106c3fb27SDimitry Andric   const Defined *gp = ElfSym::riscvGlobalPointer;
69206c3fb27SDimitry Andric   if (!gp)
69306c3fb27SDimitry Andric     return;
69406c3fb27SDimitry Andric 
69506c3fb27SDimitry Andric   if (!isInt<12>(r.sym->getVA(r.addend) - gp->getVA()))
69606c3fb27SDimitry Andric     return;
69706c3fb27SDimitry Andric 
69806c3fb27SDimitry Andric   switch (r.type) {
69906c3fb27SDimitry Andric   case R_RISCV_HI20:
70006c3fb27SDimitry Andric     // Remove lui rd, %hi20(x).
70106c3fb27SDimitry Andric     sec.relaxAux->relocTypes[i] = R_RISCV_RELAX;
70206c3fb27SDimitry Andric     remove = 4;
70306c3fb27SDimitry Andric     break;
70406c3fb27SDimitry Andric   case R_RISCV_LO12_I:
70506c3fb27SDimitry Andric     sec.relaxAux->relocTypes[i] = INTERNAL_R_RISCV_GPREL_I;
70606c3fb27SDimitry Andric     break;
70706c3fb27SDimitry Andric   case R_RISCV_LO12_S:
70806c3fb27SDimitry Andric     sec.relaxAux->relocTypes[i] = INTERNAL_R_RISCV_GPREL_S;
70906c3fb27SDimitry Andric     break;
71006c3fb27SDimitry Andric   }
71106c3fb27SDimitry Andric }
71206c3fb27SDimitry Andric 
713753f127fSDimitry Andric static bool relax(InputSection &sec) {
714753f127fSDimitry Andric   const uint64_t secAddr = sec.getVA();
715753f127fSDimitry Andric   auto &aux = *sec.relaxAux;
716753f127fSDimitry Andric   bool changed = false;
717bdd1243dSDimitry Andric   ArrayRef<SymbolAnchor> sa = ArrayRef(aux.anchors);
71806c3fb27SDimitry Andric   uint64_t delta = 0;
719753f127fSDimitry Andric 
720bdd1243dSDimitry Andric   std::fill_n(aux.relocTypes.get(), sec.relocs().size(), R_RISCV_NONE);
721753f127fSDimitry Andric   aux.writes.clear();
722bdd1243dSDimitry Andric   for (auto [i, r] : llvm::enumerate(sec.relocs())) {
723753f127fSDimitry Andric     const uint64_t loc = secAddr + r.offset - delta;
724753f127fSDimitry Andric     uint32_t &cur = aux.relocDeltas[i], remove = 0;
725753f127fSDimitry Andric     switch (r.type) {
726753f127fSDimitry Andric     case R_RISCV_ALIGN: {
727753f127fSDimitry Andric       const uint64_t nextLoc = loc + r.addend;
728753f127fSDimitry Andric       const uint64_t align = PowerOf2Ceil(r.addend + 2);
729753f127fSDimitry Andric       // All bytes beyond the alignment boundary should be removed.
730753f127fSDimitry Andric       remove = nextLoc - ((loc + align - 1) & -align);
731753f127fSDimitry Andric       assert(static_cast<int32_t>(remove) >= 0 &&
732753f127fSDimitry Andric              "R_RISCV_ALIGN needs expanding the content");
733753f127fSDimitry Andric       break;
734753f127fSDimitry Andric     }
735753f127fSDimitry Andric     case R_RISCV_CALL:
736753f127fSDimitry Andric     case R_RISCV_CALL_PLT:
737bdd1243dSDimitry Andric       if (i + 1 != sec.relocs().size() &&
738bdd1243dSDimitry Andric           sec.relocs()[i + 1].type == R_RISCV_RELAX)
739753f127fSDimitry Andric         relaxCall(sec, i, loc, r, remove);
740753f127fSDimitry Andric       break;
741fcaf7f86SDimitry Andric     case R_RISCV_TPREL_HI20:
742fcaf7f86SDimitry Andric     case R_RISCV_TPREL_ADD:
743fcaf7f86SDimitry Andric     case R_RISCV_TPREL_LO12_I:
744fcaf7f86SDimitry Andric     case R_RISCV_TPREL_LO12_S:
745bdd1243dSDimitry Andric       if (i + 1 != sec.relocs().size() &&
746bdd1243dSDimitry Andric           sec.relocs()[i + 1].type == R_RISCV_RELAX)
747fcaf7f86SDimitry Andric         relaxTlsLe(sec, i, loc, r, remove);
748fcaf7f86SDimitry Andric       break;
74906c3fb27SDimitry Andric     case R_RISCV_HI20:
75006c3fb27SDimitry Andric     case R_RISCV_LO12_I:
75106c3fb27SDimitry Andric     case R_RISCV_LO12_S:
75206c3fb27SDimitry Andric       if (i + 1 != sec.relocs().size() &&
75306c3fb27SDimitry Andric           sec.relocs()[i + 1].type == R_RISCV_RELAX)
75406c3fb27SDimitry Andric         relaxHi20Lo12(sec, i, loc, r, remove);
75506c3fb27SDimitry Andric       break;
756753f127fSDimitry Andric     }
757753f127fSDimitry Andric 
758753f127fSDimitry Andric     // For all anchors whose offsets are <= r.offset, they are preceded by
759753f127fSDimitry Andric     // the previous relocation whose `relocDeltas` value equals `delta`.
760753f127fSDimitry Andric     // Decrease their st_value and update their st_size.
761753f127fSDimitry Andric     for (; sa.size() && sa[0].offset <= r.offset; sa = sa.slice(1)) {
762753f127fSDimitry Andric       if (sa[0].end)
763753f127fSDimitry Andric         sa[0].d->size = sa[0].offset - delta - sa[0].d->value;
764753f127fSDimitry Andric       else
76506c3fb27SDimitry Andric         sa[0].d->value = sa[0].offset - delta;
766753f127fSDimitry Andric     }
767753f127fSDimitry Andric     delta += remove;
768753f127fSDimitry Andric     if (delta != cur) {
769753f127fSDimitry Andric       cur = delta;
770753f127fSDimitry Andric       changed = true;
771753f127fSDimitry Andric     }
772753f127fSDimitry Andric   }
773753f127fSDimitry Andric 
774753f127fSDimitry Andric   for (const SymbolAnchor &a : sa) {
775753f127fSDimitry Andric     if (a.end)
776753f127fSDimitry Andric       a.d->size = a.offset - delta - a.d->value;
777753f127fSDimitry Andric     else
77806c3fb27SDimitry Andric       a.d->value = a.offset - delta;
779753f127fSDimitry Andric   }
780753f127fSDimitry Andric   // Inform assignAddresses that the size has changed.
78106c3fb27SDimitry Andric   if (!isUInt<32>(delta))
78206c3fb27SDimitry Andric     fatal("section size decrease is too large: " + Twine(delta));
783753f127fSDimitry Andric   sec.bytesDropped = delta;
784753f127fSDimitry Andric   return changed;
785753f127fSDimitry Andric }
786753f127fSDimitry Andric 
787753f127fSDimitry Andric // When relaxing just R_RISCV_ALIGN, relocDeltas is usually changed only once in
788753f127fSDimitry Andric // the absence of a linker script. For call and load/store R_RISCV_RELAX, code
789753f127fSDimitry Andric // shrinkage may reduce displacement and make more relocations eligible for
790753f127fSDimitry Andric // relaxation. Code shrinkage may increase displacement to a call/load/store
791753f127fSDimitry Andric // target at a higher fixed address, invalidating an earlier relaxation. Any
792753f127fSDimitry Andric // change in section sizes can have cascading effect and require another
793753f127fSDimitry Andric // relaxation pass.
794753f127fSDimitry Andric bool RISCV::relaxOnce(int pass) const {
795753f127fSDimitry Andric   llvm::TimeTraceScope timeScope("RISC-V relaxOnce");
796753f127fSDimitry Andric   if (config->relocatable)
797753f127fSDimitry Andric     return false;
798753f127fSDimitry Andric 
799753f127fSDimitry Andric   if (pass == 0)
800753f127fSDimitry Andric     initSymbolAnchors();
801753f127fSDimitry Andric 
802753f127fSDimitry Andric   SmallVector<InputSection *, 0> storage;
803753f127fSDimitry Andric   bool changed = false;
804753f127fSDimitry Andric   for (OutputSection *osec : outputSections) {
805753f127fSDimitry Andric     if (!(osec->flags & SHF_EXECINSTR))
806753f127fSDimitry Andric       continue;
807753f127fSDimitry Andric     for (InputSection *sec : getInputSections(*osec, storage))
808753f127fSDimitry Andric       changed |= relax(*sec);
809753f127fSDimitry Andric   }
810753f127fSDimitry Andric   return changed;
811753f127fSDimitry Andric }
812753f127fSDimitry Andric 
813753f127fSDimitry Andric void elf::riscvFinalizeRelax(int passes) {
814753f127fSDimitry Andric   llvm::TimeTraceScope timeScope("Finalize RISC-V relaxation");
815753f127fSDimitry Andric   log("relaxation passes: " + Twine(passes));
816753f127fSDimitry Andric   SmallVector<InputSection *, 0> storage;
817753f127fSDimitry Andric   for (OutputSection *osec : outputSections) {
818753f127fSDimitry Andric     if (!(osec->flags & SHF_EXECINSTR))
819753f127fSDimitry Andric       continue;
820753f127fSDimitry Andric     for (InputSection *sec : getInputSections(*osec, storage)) {
821753f127fSDimitry Andric       RISCVRelaxAux &aux = *sec->relaxAux;
822753f127fSDimitry Andric       if (!aux.relocDeltas)
823753f127fSDimitry Andric         continue;
824753f127fSDimitry Andric 
825bdd1243dSDimitry Andric       MutableArrayRef<Relocation> rels = sec->relocs();
826bdd1243dSDimitry Andric       ArrayRef<uint8_t> old = sec->content();
827bdd1243dSDimitry Andric       size_t newSize = old.size() - aux.relocDeltas[rels.size() - 1];
828753f127fSDimitry Andric       size_t writesIdx = 0;
829753f127fSDimitry Andric       uint8_t *p = context().bAlloc.Allocate<uint8_t>(newSize);
830753f127fSDimitry Andric       uint64_t offset = 0;
831753f127fSDimitry Andric       int64_t delta = 0;
832bdd1243dSDimitry Andric       sec->content_ = p;
833bdd1243dSDimitry Andric       sec->size = newSize;
834753f127fSDimitry Andric       sec->bytesDropped = 0;
835753f127fSDimitry Andric 
836753f127fSDimitry Andric       // Update section content: remove NOPs for R_RISCV_ALIGN and rewrite
837753f127fSDimitry Andric       // instructions for relaxed relocations.
838753f127fSDimitry Andric       for (size_t i = 0, e = rels.size(); i != e; ++i) {
839753f127fSDimitry Andric         uint32_t remove = aux.relocDeltas[i] - delta;
840753f127fSDimitry Andric         delta = aux.relocDeltas[i];
841fcaf7f86SDimitry Andric         if (remove == 0 && aux.relocTypes[i] == R_RISCV_NONE)
842753f127fSDimitry Andric           continue;
843753f127fSDimitry Andric 
844753f127fSDimitry Andric         // Copy from last location to the current relocated location.
845753f127fSDimitry Andric         const Relocation &r = rels[i];
846753f127fSDimitry Andric         uint64_t size = r.offset - offset;
847753f127fSDimitry Andric         memcpy(p, old.data() + offset, size);
848753f127fSDimitry Andric         p += size;
849753f127fSDimitry Andric 
850753f127fSDimitry Andric         // For R_RISCV_ALIGN, we will place `offset` in a location (among NOPs)
8516246ae0bSDimitry Andric         // to satisfy the alignment requirement. If both `remove` and r.addend
8526246ae0bSDimitry Andric         // are multiples of 4, it is as if we have skipped some NOPs. Otherwise
8536246ae0bSDimitry Andric         // we are in the middle of a 4-byte NOP, and we need to rewrite the NOP
8546246ae0bSDimitry Andric         // sequence.
855753f127fSDimitry Andric         int64_t skip = 0;
856753f127fSDimitry Andric         if (r.type == R_RISCV_ALIGN) {
8576246ae0bSDimitry Andric           if (remove % 4 || r.addend % 4) {
858753f127fSDimitry Andric             skip = r.addend - remove;
859753f127fSDimitry Andric             int64_t j = 0;
860753f127fSDimitry Andric             for (; j + 4 <= skip; j += 4)
861753f127fSDimitry Andric               write32le(p + j, 0x00000013); // nop
862753f127fSDimitry Andric             if (j != skip) {
863753f127fSDimitry Andric               assert(j + 2 == skip);
864753f127fSDimitry Andric               write16le(p + j, 0x0001); // c.nop
865753f127fSDimitry Andric             }
866753f127fSDimitry Andric           }
867753f127fSDimitry Andric         } else if (RelType newType = aux.relocTypes[i]) {
868753f127fSDimitry Andric           switch (newType) {
86906c3fb27SDimitry Andric           case INTERNAL_R_RISCV_GPREL_I:
87006c3fb27SDimitry Andric           case INTERNAL_R_RISCV_GPREL_S:
87106c3fb27SDimitry Andric             break;
872fcaf7f86SDimitry Andric           case R_RISCV_RELAX:
873fcaf7f86SDimitry Andric             // Used by relaxTlsLe to indicate the relocation is ignored.
874fcaf7f86SDimitry Andric             break;
875753f127fSDimitry Andric           case R_RISCV_RVC_JUMP:
876753f127fSDimitry Andric             skip = 2;
877fcaf7f86SDimitry Andric             write16le(p, aux.writes[writesIdx++]);
878753f127fSDimitry Andric             break;
879753f127fSDimitry Andric           case R_RISCV_JAL:
880753f127fSDimitry Andric             skip = 4;
881fcaf7f86SDimitry Andric             write32le(p, aux.writes[writesIdx++]);
882fcaf7f86SDimitry Andric             break;
883fcaf7f86SDimitry Andric           case R_RISCV_32:
884fcaf7f86SDimitry Andric             // Used by relaxTlsLe to write a uint32_t then suppress the handling
885fcaf7f86SDimitry Andric             // in relocateAlloc.
886fcaf7f86SDimitry Andric             skip = 4;
887fcaf7f86SDimitry Andric             write32le(p, aux.writes[writesIdx++]);
888fcaf7f86SDimitry Andric             aux.relocTypes[i] = R_RISCV_NONE;
889753f127fSDimitry Andric             break;
890753f127fSDimitry Andric           default:
891753f127fSDimitry Andric             llvm_unreachable("unsupported type");
892753f127fSDimitry Andric           }
893753f127fSDimitry Andric         }
894753f127fSDimitry Andric 
895753f127fSDimitry Andric         p += skip;
896753f127fSDimitry Andric         offset = r.offset + skip + remove;
897753f127fSDimitry Andric       }
898753f127fSDimitry Andric       memcpy(p, old.data() + offset, old.size() - offset);
899753f127fSDimitry Andric 
900753f127fSDimitry Andric       // Subtract the previous relocDeltas value from the relocation offset.
901753f127fSDimitry Andric       // For a pair of R_RISCV_CALL/R_RISCV_RELAX with the same offset, decrease
902753f127fSDimitry Andric       // their r_offset by the same delta.
903753f127fSDimitry Andric       delta = 0;
904753f127fSDimitry Andric       for (size_t i = 0, e = rels.size(); i != e;) {
905753f127fSDimitry Andric         uint64_t cur = rels[i].offset;
906753f127fSDimitry Andric         do {
907753f127fSDimitry Andric           rels[i].offset -= delta;
908753f127fSDimitry Andric           if (aux.relocTypes[i] != R_RISCV_NONE)
909753f127fSDimitry Andric             rels[i].type = aux.relocTypes[i];
910753f127fSDimitry Andric         } while (++i != e && rels[i].offset == cur);
911753f127fSDimitry Andric         delta = aux.relocDeltas[i - 1];
912753f127fSDimitry Andric       }
913753f127fSDimitry Andric     }
914753f127fSDimitry Andric   }
915753f127fSDimitry Andric }
916753f127fSDimitry Andric 
917bdd1243dSDimitry Andric namespace {
918bdd1243dSDimitry Andric // Representation of the merged .riscv.attributes input sections. The psABI
919bdd1243dSDimitry Andric // specifies merge policy for attributes. E.g. if we link an object without an
920bdd1243dSDimitry Andric // extension with an object with the extension, the output Tag_RISCV_arch shall
921bdd1243dSDimitry Andric // contain the extension. Some tools like objdump parse .riscv.attributes and
922bdd1243dSDimitry Andric // disabling some instructions if the first Tag_RISCV_arch does not contain an
923bdd1243dSDimitry Andric // extension.
924bdd1243dSDimitry Andric class RISCVAttributesSection final : public SyntheticSection {
925bdd1243dSDimitry Andric public:
926bdd1243dSDimitry Andric   RISCVAttributesSection()
927bdd1243dSDimitry Andric       : SyntheticSection(0, SHT_RISCV_ATTRIBUTES, 1, ".riscv.attributes") {}
928bdd1243dSDimitry Andric 
929bdd1243dSDimitry Andric   size_t getSize() const override { return size; }
930bdd1243dSDimitry Andric   void writeTo(uint8_t *buf) override;
931bdd1243dSDimitry Andric 
932bdd1243dSDimitry Andric   static constexpr StringRef vendor = "riscv";
933bdd1243dSDimitry Andric   DenseMap<unsigned, unsigned> intAttr;
934bdd1243dSDimitry Andric   DenseMap<unsigned, StringRef> strAttr;
935bdd1243dSDimitry Andric   size_t size = 0;
936bdd1243dSDimitry Andric };
937bdd1243dSDimitry Andric } // namespace
938bdd1243dSDimitry Andric 
939bdd1243dSDimitry Andric static void mergeArch(RISCVISAInfo::OrderedExtensionMap &mergedExts,
940bdd1243dSDimitry Andric                       unsigned &mergedXlen, const InputSectionBase *sec,
941bdd1243dSDimitry Andric                       StringRef s) {
9421ac55f4cSDimitry Andric   auto maybeInfo = RISCVISAInfo::parseNormalizedArchString(s);
943bdd1243dSDimitry Andric   if (!maybeInfo) {
944bdd1243dSDimitry Andric     errorOrWarn(toString(sec) + ": " + s + ": " +
945bdd1243dSDimitry Andric                 llvm::toString(maybeInfo.takeError()));
946bdd1243dSDimitry Andric     return;
947bdd1243dSDimitry Andric   }
948bdd1243dSDimitry Andric 
949bdd1243dSDimitry Andric   // Merge extensions.
950bdd1243dSDimitry Andric   RISCVISAInfo &info = **maybeInfo;
951bdd1243dSDimitry Andric   if (mergedExts.empty()) {
952bdd1243dSDimitry Andric     mergedExts = info.getExtensions();
953bdd1243dSDimitry Andric     mergedXlen = info.getXLen();
954bdd1243dSDimitry Andric   } else {
955bdd1243dSDimitry Andric     for (const auto &ext : info.getExtensions()) {
956bdd1243dSDimitry Andric       if (auto it = mergedExts.find(ext.first); it != mergedExts.end()) {
957bdd1243dSDimitry Andric         if (std::tie(it->second.MajorVersion, it->second.MinorVersion) >=
958bdd1243dSDimitry Andric             std::tie(ext.second.MajorVersion, ext.second.MinorVersion))
959bdd1243dSDimitry Andric           continue;
960bdd1243dSDimitry Andric       }
961bdd1243dSDimitry Andric       mergedExts[ext.first] = ext.second;
962bdd1243dSDimitry Andric     }
963bdd1243dSDimitry Andric   }
964bdd1243dSDimitry Andric }
965bdd1243dSDimitry Andric 
966bdd1243dSDimitry Andric static RISCVAttributesSection *
967bdd1243dSDimitry Andric mergeAttributesSection(const SmallVector<InputSectionBase *, 0> &sections) {
968bdd1243dSDimitry Andric   RISCVISAInfo::OrderedExtensionMap exts;
969bdd1243dSDimitry Andric   const InputSectionBase *firstStackAlign = nullptr;
970bdd1243dSDimitry Andric   unsigned firstStackAlignValue = 0, xlen = 0;
971bdd1243dSDimitry Andric   bool hasArch = false;
972bdd1243dSDimitry Andric 
973bdd1243dSDimitry Andric   in.riscvAttributes = std::make_unique<RISCVAttributesSection>();
974bdd1243dSDimitry Andric   auto &merged = static_cast<RISCVAttributesSection &>(*in.riscvAttributes);
975bdd1243dSDimitry Andric 
976bdd1243dSDimitry Andric   // Collect all tags values from attributes section.
977bdd1243dSDimitry Andric   const auto &attributesTags = RISCVAttrs::getRISCVAttributeTags();
978bdd1243dSDimitry Andric   for (const InputSectionBase *sec : sections) {
979bdd1243dSDimitry Andric     RISCVAttributeParser parser;
9805f757f3fSDimitry Andric     if (Error e = parser.parse(sec->content(), llvm::endianness::little))
981bdd1243dSDimitry Andric       warn(toString(sec) + ": " + llvm::toString(std::move(e)));
982bdd1243dSDimitry Andric     for (const auto &tag : attributesTags) {
983bdd1243dSDimitry Andric       switch (RISCVAttrs::AttrType(tag.attr)) {
984bdd1243dSDimitry Andric         // Integer attributes.
985bdd1243dSDimitry Andric       case RISCVAttrs::STACK_ALIGN:
986bdd1243dSDimitry Andric         if (auto i = parser.getAttributeValue(tag.attr)) {
987bdd1243dSDimitry Andric           auto r = merged.intAttr.try_emplace(tag.attr, *i);
988bdd1243dSDimitry Andric           if (r.second) {
989bdd1243dSDimitry Andric             firstStackAlign = sec;
990bdd1243dSDimitry Andric             firstStackAlignValue = *i;
991bdd1243dSDimitry Andric           } else if (r.first->second != *i) {
992bdd1243dSDimitry Andric             errorOrWarn(toString(sec) + " has stack_align=" + Twine(*i) +
993bdd1243dSDimitry Andric                         " but " + toString(firstStackAlign) +
994bdd1243dSDimitry Andric                         " has stack_align=" + Twine(firstStackAlignValue));
995bdd1243dSDimitry Andric           }
996bdd1243dSDimitry Andric         }
997bdd1243dSDimitry Andric         continue;
998bdd1243dSDimitry Andric       case RISCVAttrs::UNALIGNED_ACCESS:
999bdd1243dSDimitry Andric         if (auto i = parser.getAttributeValue(tag.attr))
1000bdd1243dSDimitry Andric           merged.intAttr[tag.attr] |= *i;
1001bdd1243dSDimitry Andric         continue;
1002bdd1243dSDimitry Andric 
1003bdd1243dSDimitry Andric         // String attributes.
1004bdd1243dSDimitry Andric       case RISCVAttrs::ARCH:
1005bdd1243dSDimitry Andric         if (auto s = parser.getAttributeString(tag.attr)) {
1006bdd1243dSDimitry Andric           hasArch = true;
1007bdd1243dSDimitry Andric           mergeArch(exts, xlen, sec, *s);
1008bdd1243dSDimitry Andric         }
1009bdd1243dSDimitry Andric         continue;
1010bdd1243dSDimitry Andric 
1011bdd1243dSDimitry Andric         // Attributes which use the default handling.
1012bdd1243dSDimitry Andric       case RISCVAttrs::PRIV_SPEC:
1013bdd1243dSDimitry Andric       case RISCVAttrs::PRIV_SPEC_MINOR:
1014bdd1243dSDimitry Andric       case RISCVAttrs::PRIV_SPEC_REVISION:
1015bdd1243dSDimitry Andric         break;
1016bdd1243dSDimitry Andric       }
1017bdd1243dSDimitry Andric 
1018bdd1243dSDimitry Andric       // Fallback for deprecated priv_spec* and other unknown attributes: retain
1019bdd1243dSDimitry Andric       // the attribute if all input sections agree on the value. GNU ld uses 0
1020bdd1243dSDimitry Andric       // and empty strings as default values which are not dumped to the output.
1021bdd1243dSDimitry Andric       // TODO Adjust after resolution to
1022bdd1243dSDimitry Andric       // https://github.com/riscv-non-isa/riscv-elf-psabi-doc/issues/352
1023bdd1243dSDimitry Andric       if (tag.attr % 2 == 0) {
1024bdd1243dSDimitry Andric         if (auto i = parser.getAttributeValue(tag.attr)) {
1025bdd1243dSDimitry Andric           auto r = merged.intAttr.try_emplace(tag.attr, *i);
1026bdd1243dSDimitry Andric           if (!r.second && r.first->second != *i)
1027bdd1243dSDimitry Andric             r.first->second = 0;
1028bdd1243dSDimitry Andric         }
1029bdd1243dSDimitry Andric       } else if (auto s = parser.getAttributeString(tag.attr)) {
1030bdd1243dSDimitry Andric         auto r = merged.strAttr.try_emplace(tag.attr, *s);
1031bdd1243dSDimitry Andric         if (!r.second && r.first->second != *s)
1032bdd1243dSDimitry Andric           r.first->second = {};
1033bdd1243dSDimitry Andric       }
1034bdd1243dSDimitry Andric     }
1035bdd1243dSDimitry Andric   }
1036bdd1243dSDimitry Andric 
1037bdd1243dSDimitry Andric   if (hasArch) {
1038bdd1243dSDimitry Andric     if (auto result = RISCVISAInfo::postProcessAndChecking(
1039bdd1243dSDimitry Andric             std::make_unique<RISCVISAInfo>(xlen, exts))) {
1040bdd1243dSDimitry Andric       merged.strAttr.try_emplace(RISCVAttrs::ARCH,
1041bdd1243dSDimitry Andric                                  saver().save((*result)->toString()));
1042bdd1243dSDimitry Andric     } else {
1043bdd1243dSDimitry Andric       errorOrWarn(llvm::toString(result.takeError()));
1044bdd1243dSDimitry Andric     }
1045bdd1243dSDimitry Andric   }
1046bdd1243dSDimitry Andric 
1047bdd1243dSDimitry Andric   // The total size of headers: format-version [ <section-length> "vendor-name"
1048bdd1243dSDimitry Andric   // [ <file-tag> <size>.
1049bdd1243dSDimitry Andric   size_t size = 5 + merged.vendor.size() + 1 + 5;
1050bdd1243dSDimitry Andric   for (auto &attr : merged.intAttr)
1051bdd1243dSDimitry Andric     if (attr.second != 0)
1052bdd1243dSDimitry Andric       size += getULEB128Size(attr.first) + getULEB128Size(attr.second);
1053bdd1243dSDimitry Andric   for (auto &attr : merged.strAttr)
1054bdd1243dSDimitry Andric     if (!attr.second.empty())
1055bdd1243dSDimitry Andric       size += getULEB128Size(attr.first) + attr.second.size() + 1;
1056bdd1243dSDimitry Andric   merged.size = size;
1057bdd1243dSDimitry Andric   return &merged;
1058bdd1243dSDimitry Andric }
1059bdd1243dSDimitry Andric 
1060bdd1243dSDimitry Andric void RISCVAttributesSection::writeTo(uint8_t *buf) {
1061bdd1243dSDimitry Andric   const size_t size = getSize();
1062bdd1243dSDimitry Andric   uint8_t *const end = buf + size;
1063bdd1243dSDimitry Andric   *buf = ELFAttrs::Format_Version;
1064bdd1243dSDimitry Andric   write32(buf + 1, size - 1);
1065bdd1243dSDimitry Andric   buf += 5;
1066bdd1243dSDimitry Andric 
1067bdd1243dSDimitry Andric   memcpy(buf, vendor.data(), vendor.size());
1068bdd1243dSDimitry Andric   buf += vendor.size() + 1;
1069bdd1243dSDimitry Andric 
1070bdd1243dSDimitry Andric   *buf = ELFAttrs::File;
1071bdd1243dSDimitry Andric   write32(buf + 1, end - buf);
1072bdd1243dSDimitry Andric   buf += 5;
1073bdd1243dSDimitry Andric 
1074bdd1243dSDimitry Andric   for (auto &attr : intAttr) {
1075bdd1243dSDimitry Andric     if (attr.second == 0)
1076bdd1243dSDimitry Andric       continue;
1077bdd1243dSDimitry Andric     buf += encodeULEB128(attr.first, buf);
1078bdd1243dSDimitry Andric     buf += encodeULEB128(attr.second, buf);
1079bdd1243dSDimitry Andric   }
1080bdd1243dSDimitry Andric   for (auto &attr : strAttr) {
1081bdd1243dSDimitry Andric     if (attr.second.empty())
1082bdd1243dSDimitry Andric       continue;
1083bdd1243dSDimitry Andric     buf += encodeULEB128(attr.first, buf);
1084bdd1243dSDimitry Andric     memcpy(buf, attr.second.data(), attr.second.size());
1085bdd1243dSDimitry Andric     buf += attr.second.size() + 1;
1086bdd1243dSDimitry Andric   }
1087bdd1243dSDimitry Andric }
1088bdd1243dSDimitry Andric 
1089bdd1243dSDimitry Andric void elf::mergeRISCVAttributesSections() {
1090bdd1243dSDimitry Andric   // Find the first input SHT_RISCV_ATTRIBUTES; return if not found.
1091bdd1243dSDimitry Andric   size_t place =
1092bdd1243dSDimitry Andric       llvm::find_if(ctx.inputSections,
1093bdd1243dSDimitry Andric                     [](auto *s) { return s->type == SHT_RISCV_ATTRIBUTES; }) -
1094bdd1243dSDimitry Andric       ctx.inputSections.begin();
1095bdd1243dSDimitry Andric   if (place == ctx.inputSections.size())
1096bdd1243dSDimitry Andric     return;
1097bdd1243dSDimitry Andric 
1098bdd1243dSDimitry Andric   // Extract all SHT_RISCV_ATTRIBUTES sections into `sections`.
1099bdd1243dSDimitry Andric   SmallVector<InputSectionBase *, 0> sections;
1100bdd1243dSDimitry Andric   llvm::erase_if(ctx.inputSections, [&](InputSectionBase *s) {
1101bdd1243dSDimitry Andric     if (s->type != SHT_RISCV_ATTRIBUTES)
1102bdd1243dSDimitry Andric       return false;
1103bdd1243dSDimitry Andric     sections.push_back(s);
1104bdd1243dSDimitry Andric     return true;
1105bdd1243dSDimitry Andric   });
1106bdd1243dSDimitry Andric 
1107bdd1243dSDimitry Andric   // Add the merged section.
1108bdd1243dSDimitry Andric   ctx.inputSections.insert(ctx.inputSections.begin() + place,
1109bdd1243dSDimitry Andric                            mergeAttributesSection(sections));
1110bdd1243dSDimitry Andric }
1111bdd1243dSDimitry Andric 
11125ffd83dbSDimitry Andric TargetInfo *elf::getRISCVTargetInfo() {
11130b57cec5SDimitry Andric   static RISCV target;
11140b57cec5SDimitry Andric   return &target;
11150b57cec5SDimitry Andric }
1116