xref: /freebsd/contrib/llvm-project/lld/ELF/Arch/RISCV.cpp (revision 56727255ad47072ec2cc81b4ae728a099697b0e4)
1 //===- RISCV.cpp ----------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "InputFiles.h"
10 #include "OutputSections.h"
11 #include "Symbols.h"
12 #include "SyntheticSections.h"
13 #include "Target.h"
14 #include "llvm/Support/ELFAttributes.h"
15 #include "llvm/Support/LEB128.h"
16 #include "llvm/Support/RISCVAttributeParser.h"
17 #include "llvm/Support/RISCVAttributes.h"
18 #include "llvm/Support/RISCVISAInfo.h"
19 #include "llvm/Support/TimeProfiler.h"
20 
21 using namespace llvm;
22 using namespace llvm::object;
23 using namespace llvm::support::endian;
24 using namespace llvm::ELF;
25 using namespace lld;
26 using namespace lld::elf;
27 
28 namespace {
29 
30 class RISCV final : public TargetInfo {
31 public:
32   RISCV();
33   uint32_t calcEFlags() const override;
34   int64_t getImplicitAddend(const uint8_t *buf, RelType type) const override;
35   void writeGotHeader(uint8_t *buf) const override;
36   void writeGotPlt(uint8_t *buf, const Symbol &s) const override;
37   void writeIgotPlt(uint8_t *buf, const Symbol &s) const override;
38   void writePltHeader(uint8_t *buf) const override;
39   void writePlt(uint8_t *buf, const Symbol &sym,
40                 uint64_t pltEntryAddr) const override;
41   RelType getDynRel(RelType type) const override;
42   RelExpr getRelExpr(RelType type, const Symbol &s,
43                      const uint8_t *loc) const override;
44   void relocate(uint8_t *loc, const Relocation &rel,
45                 uint64_t val) const override;
46   void relocateAlloc(InputSectionBase &sec, uint8_t *buf) const override;
47   bool relaxOnce(int pass) const override;
48   void finalizeRelax(int passes) const override;
49 };
50 
51 } // end anonymous namespace
52 
53 // These are internal relocation numbers for GP relaxation. They aren't part
54 // of the psABI spec.
55 #define INTERNAL_R_RISCV_GPREL_I 256
56 #define INTERNAL_R_RISCV_GPREL_S 257
57 
58 const uint64_t dtpOffset = 0x800;
59 
60 enum Op {
61   ADDI = 0x13,
62   AUIPC = 0x17,
63   JALR = 0x67,
64   LD = 0x3003,
65   LUI = 0x37,
66   LW = 0x2003,
67   SRLI = 0x5013,
68   SUB = 0x40000033,
69 };
70 
71 enum Reg {
72   X_RA = 1,
73   X_GP = 3,
74   X_TP = 4,
75   X_T0 = 5,
76   X_T1 = 6,
77   X_T2 = 7,
78   X_A0 = 10,
79   X_T3 = 28,
80 };
81 
82 static uint32_t hi20(uint32_t val) { return (val + 0x800) >> 12; }
83 static uint32_t lo12(uint32_t val) { return val & 4095; }
84 
85 static uint32_t itype(uint32_t op, uint32_t rd, uint32_t rs1, uint32_t imm) {
86   return op | (rd << 7) | (rs1 << 15) | (imm << 20);
87 }
88 static uint32_t rtype(uint32_t op, uint32_t rd, uint32_t rs1, uint32_t rs2) {
89   return op | (rd << 7) | (rs1 << 15) | (rs2 << 20);
90 }
91 static uint32_t utype(uint32_t op, uint32_t rd, uint32_t imm) {
92   return op | (rd << 7) | (imm << 12);
93 }
94 
95 // Extract bits v[begin:end], where range is inclusive, and begin must be < 63.
96 static uint32_t extractBits(uint64_t v, uint32_t begin, uint32_t end) {
97   return (v & ((1ULL << (begin + 1)) - 1)) >> end;
98 }
99 
100 static uint32_t setLO12_I(uint32_t insn, uint32_t imm) {
101   return (insn & 0xfffff) | (imm << 20);
102 }
103 static uint32_t setLO12_S(uint32_t insn, uint32_t imm) {
104   return (insn & 0x1fff07f) | (extractBits(imm, 11, 5) << 25) |
105          (extractBits(imm, 4, 0) << 7);
106 }
107 
108 RISCV::RISCV() {
109   copyRel = R_RISCV_COPY;
110   pltRel = R_RISCV_JUMP_SLOT;
111   relativeRel = R_RISCV_RELATIVE;
112   iRelativeRel = R_RISCV_IRELATIVE;
113   if (config->is64) {
114     symbolicRel = R_RISCV_64;
115     tlsModuleIndexRel = R_RISCV_TLS_DTPMOD64;
116     tlsOffsetRel = R_RISCV_TLS_DTPREL64;
117     tlsGotRel = R_RISCV_TLS_TPREL64;
118   } else {
119     symbolicRel = R_RISCV_32;
120     tlsModuleIndexRel = R_RISCV_TLS_DTPMOD32;
121     tlsOffsetRel = R_RISCV_TLS_DTPREL32;
122     tlsGotRel = R_RISCV_TLS_TPREL32;
123   }
124   gotRel = symbolicRel;
125   tlsDescRel = R_RISCV_TLSDESC;
126 
127   // .got[0] = _DYNAMIC
128   gotHeaderEntriesNum = 1;
129 
130   // .got.plt[0] = _dl_runtime_resolve, .got.plt[1] = link_map
131   gotPltHeaderEntriesNum = 2;
132 
133   pltHeaderSize = 32;
134   pltEntrySize = 16;
135   ipltEntrySize = 16;
136 }
137 
138 static uint32_t getEFlags(InputFile *f) {
139   if (config->is64)
140     return cast<ObjFile<ELF64LE>>(f)->getObj().getHeader().e_flags;
141   return cast<ObjFile<ELF32LE>>(f)->getObj().getHeader().e_flags;
142 }
143 
144 uint32_t RISCV::calcEFlags() const {
145   // If there are only binary input files (from -b binary), use a
146   // value of 0 for the ELF header flags.
147   if (ctx.objectFiles.empty())
148     return 0;
149 
150   uint32_t target = getEFlags(ctx.objectFiles.front());
151 
152   for (InputFile *f : ctx.objectFiles) {
153     uint32_t eflags = getEFlags(f);
154     if (eflags & EF_RISCV_RVC)
155       target |= EF_RISCV_RVC;
156 
157     if ((eflags & EF_RISCV_FLOAT_ABI) != (target & EF_RISCV_FLOAT_ABI))
158       error(
159           toString(f) +
160           ": cannot link object files with different floating-point ABI from " +
161           toString(ctx.objectFiles[0]));
162 
163     if ((eflags & EF_RISCV_RVE) != (target & EF_RISCV_RVE))
164       error(toString(f) +
165             ": cannot link object files with different EF_RISCV_RVE");
166   }
167 
168   return target;
169 }
170 
171 int64_t RISCV::getImplicitAddend(const uint8_t *buf, RelType type) const {
172   switch (type) {
173   default:
174     internalLinkerError(getErrorLocation(buf),
175                         "cannot read addend for relocation " + toString(type));
176     return 0;
177   case R_RISCV_32:
178   case R_RISCV_TLS_DTPMOD32:
179   case R_RISCV_TLS_DTPREL32:
180   case R_RISCV_TLS_TPREL32:
181     return SignExtend64<32>(read32le(buf));
182   case R_RISCV_64:
183   case R_RISCV_TLS_DTPMOD64:
184   case R_RISCV_TLS_DTPREL64:
185   case R_RISCV_TLS_TPREL64:
186     return read64le(buf);
187   case R_RISCV_RELATIVE:
188   case R_RISCV_IRELATIVE:
189     return config->is64 ? read64le(buf) : read32le(buf);
190   case R_RISCV_NONE:
191   case R_RISCV_JUMP_SLOT:
192     // These relocations are defined as not having an implicit addend.
193     return 0;
194   case R_RISCV_TLSDESC:
195     return config->is64 ? read64le(buf + 8) : read32le(buf + 4);
196   }
197 }
198 
199 void RISCV::writeGotHeader(uint8_t *buf) const {
200   if (config->is64)
201     write64le(buf, mainPart->dynamic->getVA());
202   else
203     write32le(buf, mainPart->dynamic->getVA());
204 }
205 
206 void RISCV::writeGotPlt(uint8_t *buf, const Symbol &s) const {
207   if (config->is64)
208     write64le(buf, in.plt->getVA());
209   else
210     write32le(buf, in.plt->getVA());
211 }
212 
213 void RISCV::writeIgotPlt(uint8_t *buf, const Symbol &s) const {
214   if (config->writeAddends) {
215     if (config->is64)
216       write64le(buf, s.getVA());
217     else
218       write32le(buf, s.getVA());
219   }
220 }
221 
222 void RISCV::writePltHeader(uint8_t *buf) const {
223   // 1: auipc t2, %pcrel_hi(.got.plt)
224   // sub t1, t1, t3
225   // l[wd] t3, %pcrel_lo(1b)(t2); t3 = _dl_runtime_resolve
226   // addi t1, t1, -pltHeaderSize-12; t1 = &.plt[i] - &.plt[0]
227   // addi t0, t2, %pcrel_lo(1b)
228   // srli t1, t1, (rv64?1:2); t1 = &.got.plt[i] - &.got.plt[0]
229   // l[wd] t0, Wordsize(t0); t0 = link_map
230   // jr t3
231   uint32_t offset = in.gotPlt->getVA() - in.plt->getVA();
232   uint32_t load = config->is64 ? LD : LW;
233   write32le(buf + 0, utype(AUIPC, X_T2, hi20(offset)));
234   write32le(buf + 4, rtype(SUB, X_T1, X_T1, X_T3));
235   write32le(buf + 8, itype(load, X_T3, X_T2, lo12(offset)));
236   write32le(buf + 12, itype(ADDI, X_T1, X_T1, -target->pltHeaderSize - 12));
237   write32le(buf + 16, itype(ADDI, X_T0, X_T2, lo12(offset)));
238   write32le(buf + 20, itype(SRLI, X_T1, X_T1, config->is64 ? 1 : 2));
239   write32le(buf + 24, itype(load, X_T0, X_T0, config->wordsize));
240   write32le(buf + 28, itype(JALR, 0, X_T3, 0));
241 }
242 
243 void RISCV::writePlt(uint8_t *buf, const Symbol &sym,
244                      uint64_t pltEntryAddr) const {
245   // 1: auipc t3, %pcrel_hi(f@.got.plt)
246   // l[wd] t3, %pcrel_lo(1b)(t3)
247   // jalr t1, t3
248   // nop
249   uint32_t offset = sym.getGotPltVA() - pltEntryAddr;
250   write32le(buf + 0, utype(AUIPC, X_T3, hi20(offset)));
251   write32le(buf + 4, itype(config->is64 ? LD : LW, X_T3, X_T3, lo12(offset)));
252   write32le(buf + 8, itype(JALR, X_T1, X_T3, 0));
253   write32le(buf + 12, itype(ADDI, 0, 0, 0));
254 }
255 
256 RelType RISCV::getDynRel(RelType type) const {
257   return type == target->symbolicRel ? type
258                                      : static_cast<RelType>(R_RISCV_NONE);
259 }
260 
261 RelExpr RISCV::getRelExpr(const RelType type, const Symbol &s,
262                           const uint8_t *loc) const {
263   switch (type) {
264   case R_RISCV_NONE:
265     return R_NONE;
266   case R_RISCV_32:
267   case R_RISCV_64:
268   case R_RISCV_HI20:
269   case R_RISCV_LO12_I:
270   case R_RISCV_LO12_S:
271   case R_RISCV_RVC_LUI:
272     return R_ABS;
273   case R_RISCV_ADD8:
274   case R_RISCV_ADD16:
275   case R_RISCV_ADD32:
276   case R_RISCV_ADD64:
277   case R_RISCV_SET6:
278   case R_RISCV_SET8:
279   case R_RISCV_SET16:
280   case R_RISCV_SET32:
281   case R_RISCV_SUB6:
282   case R_RISCV_SUB8:
283   case R_RISCV_SUB16:
284   case R_RISCV_SUB32:
285   case R_RISCV_SUB64:
286     return R_RISCV_ADD;
287   case R_RISCV_JAL:
288   case R_RISCV_BRANCH:
289   case R_RISCV_PCREL_HI20:
290   case R_RISCV_RVC_BRANCH:
291   case R_RISCV_RVC_JUMP:
292   case R_RISCV_32_PCREL:
293     return R_PC;
294   case R_RISCV_CALL:
295   case R_RISCV_CALL_PLT:
296   case R_RISCV_PLT32:
297     return R_PLT_PC;
298   case R_RISCV_GOT_HI20:
299   case R_RISCV_GOT32_PCREL:
300     return R_GOT_PC;
301   case R_RISCV_PCREL_LO12_I:
302   case R_RISCV_PCREL_LO12_S:
303     return R_RISCV_PC_INDIRECT;
304   case R_RISCV_TLSDESC_HI20:
305   case R_RISCV_TLSDESC_LOAD_LO12:
306   case R_RISCV_TLSDESC_ADD_LO12:
307     return R_TLSDESC_PC;
308   case R_RISCV_TLSDESC_CALL:
309     return R_TLSDESC_CALL;
310   case R_RISCV_TLS_GD_HI20:
311     return R_TLSGD_PC;
312   case R_RISCV_TLS_GOT_HI20:
313     return R_GOT_PC;
314   case R_RISCV_TPREL_HI20:
315   case R_RISCV_TPREL_LO12_I:
316   case R_RISCV_TPREL_LO12_S:
317     return R_TPREL;
318   case R_RISCV_ALIGN:
319     return R_RELAX_HINT;
320   case R_RISCV_TPREL_ADD:
321   case R_RISCV_RELAX:
322     return config->relax ? R_RELAX_HINT : R_NONE;
323   case R_RISCV_SET_ULEB128:
324   case R_RISCV_SUB_ULEB128:
325     return R_RISCV_LEB128;
326   default:
327     error(getErrorLocation(loc) + "unknown relocation (" + Twine(type) +
328           ") against symbol " + toString(s));
329     return R_NONE;
330   }
331 }
332 
333 void RISCV::relocate(uint8_t *loc, const Relocation &rel, uint64_t val) const {
334   const unsigned bits = config->wordsize * 8;
335 
336   switch (rel.type) {
337   case R_RISCV_32:
338     write32le(loc, val);
339     return;
340   case R_RISCV_64:
341     write64le(loc, val);
342     return;
343 
344   case R_RISCV_RVC_BRANCH: {
345     checkInt(loc, val, 9, rel);
346     checkAlignment(loc, val, 2, rel);
347     uint16_t insn = read16le(loc) & 0xE383;
348     uint16_t imm8 = extractBits(val, 8, 8) << 12;
349     uint16_t imm4_3 = extractBits(val, 4, 3) << 10;
350     uint16_t imm7_6 = extractBits(val, 7, 6) << 5;
351     uint16_t imm2_1 = extractBits(val, 2, 1) << 3;
352     uint16_t imm5 = extractBits(val, 5, 5) << 2;
353     insn |= imm8 | imm4_3 | imm7_6 | imm2_1 | imm5;
354 
355     write16le(loc, insn);
356     return;
357   }
358 
359   case R_RISCV_RVC_JUMP: {
360     checkInt(loc, val, 12, rel);
361     checkAlignment(loc, val, 2, rel);
362     uint16_t insn = read16le(loc) & 0xE003;
363     uint16_t imm11 = extractBits(val, 11, 11) << 12;
364     uint16_t imm4 = extractBits(val, 4, 4) << 11;
365     uint16_t imm9_8 = extractBits(val, 9, 8) << 9;
366     uint16_t imm10 = extractBits(val, 10, 10) << 8;
367     uint16_t imm6 = extractBits(val, 6, 6) << 7;
368     uint16_t imm7 = extractBits(val, 7, 7) << 6;
369     uint16_t imm3_1 = extractBits(val, 3, 1) << 3;
370     uint16_t imm5 = extractBits(val, 5, 5) << 2;
371     insn |= imm11 | imm4 | imm9_8 | imm10 | imm6 | imm7 | imm3_1 | imm5;
372 
373     write16le(loc, insn);
374     return;
375   }
376 
377   case R_RISCV_RVC_LUI: {
378     int64_t imm = SignExtend64(val + 0x800, bits) >> 12;
379     checkInt(loc, imm, 6, rel);
380     if (imm == 0) { // `c.lui rd, 0` is illegal, convert to `c.li rd, 0`
381       write16le(loc, (read16le(loc) & 0x0F83) | 0x4000);
382     } else {
383       uint16_t imm17 = extractBits(val + 0x800, 17, 17) << 12;
384       uint16_t imm16_12 = extractBits(val + 0x800, 16, 12) << 2;
385       write16le(loc, (read16le(loc) & 0xEF83) | imm17 | imm16_12);
386     }
387     return;
388   }
389 
390   case R_RISCV_JAL: {
391     checkInt(loc, val, 21, rel);
392     checkAlignment(loc, val, 2, rel);
393 
394     uint32_t insn = read32le(loc) & 0xFFF;
395     uint32_t imm20 = extractBits(val, 20, 20) << 31;
396     uint32_t imm10_1 = extractBits(val, 10, 1) << 21;
397     uint32_t imm11 = extractBits(val, 11, 11) << 20;
398     uint32_t imm19_12 = extractBits(val, 19, 12) << 12;
399     insn |= imm20 | imm10_1 | imm11 | imm19_12;
400 
401     write32le(loc, insn);
402     return;
403   }
404 
405   case R_RISCV_BRANCH: {
406     checkInt(loc, val, 13, rel);
407     checkAlignment(loc, val, 2, rel);
408 
409     uint32_t insn = read32le(loc) & 0x1FFF07F;
410     uint32_t imm12 = extractBits(val, 12, 12) << 31;
411     uint32_t imm10_5 = extractBits(val, 10, 5) << 25;
412     uint32_t imm4_1 = extractBits(val, 4, 1) << 8;
413     uint32_t imm11 = extractBits(val, 11, 11) << 7;
414     insn |= imm12 | imm10_5 | imm4_1 | imm11;
415 
416     write32le(loc, insn);
417     return;
418   }
419 
420   // auipc + jalr pair
421   case R_RISCV_CALL:
422   case R_RISCV_CALL_PLT: {
423     int64_t hi = SignExtend64(val + 0x800, bits) >> 12;
424     checkInt(loc, hi, 20, rel);
425     if (isInt<20>(hi)) {
426       relocateNoSym(loc, R_RISCV_PCREL_HI20, val);
427       relocateNoSym(loc + 4, R_RISCV_PCREL_LO12_I, val);
428     }
429     return;
430   }
431 
432   case R_RISCV_GOT_HI20:
433   case R_RISCV_PCREL_HI20:
434   case R_RISCV_TLSDESC_HI20:
435   case R_RISCV_TLS_GD_HI20:
436   case R_RISCV_TLS_GOT_HI20:
437   case R_RISCV_TPREL_HI20:
438   case R_RISCV_HI20: {
439     uint64_t hi = val + 0x800;
440     checkInt(loc, SignExtend64(hi, bits) >> 12, 20, rel);
441     write32le(loc, (read32le(loc) & 0xFFF) | (hi & 0xFFFFF000));
442     return;
443   }
444 
445   case R_RISCV_PCREL_LO12_I:
446   case R_RISCV_TLSDESC_LOAD_LO12:
447   case R_RISCV_TLSDESC_ADD_LO12:
448   case R_RISCV_TPREL_LO12_I:
449   case R_RISCV_LO12_I: {
450     uint64_t hi = (val + 0x800) >> 12;
451     uint64_t lo = val - (hi << 12);
452     write32le(loc, setLO12_I(read32le(loc), lo & 0xfff));
453     return;
454   }
455 
456   case R_RISCV_PCREL_LO12_S:
457   case R_RISCV_TPREL_LO12_S:
458   case R_RISCV_LO12_S: {
459     uint64_t hi = (val + 0x800) >> 12;
460     uint64_t lo = val - (hi << 12);
461     write32le(loc, setLO12_S(read32le(loc), lo));
462     return;
463   }
464 
465   case INTERNAL_R_RISCV_GPREL_I:
466   case INTERNAL_R_RISCV_GPREL_S: {
467     Defined *gp = ElfSym::riscvGlobalPointer;
468     int64_t displace = SignExtend64(val - gp->getVA(), bits);
469     checkInt(loc, displace, 12, rel);
470     uint32_t insn = (read32le(loc) & ~(31 << 15)) | (X_GP << 15);
471     if (rel.type == INTERNAL_R_RISCV_GPREL_I)
472       insn = setLO12_I(insn, displace);
473     else
474       insn = setLO12_S(insn, displace);
475     write32le(loc, insn);
476     return;
477   }
478 
479   case R_RISCV_ADD8:
480     *loc += val;
481     return;
482   case R_RISCV_ADD16:
483     write16le(loc, read16le(loc) + val);
484     return;
485   case R_RISCV_ADD32:
486     write32le(loc, read32le(loc) + val);
487     return;
488   case R_RISCV_ADD64:
489     write64le(loc, read64le(loc) + val);
490     return;
491   case R_RISCV_SUB6:
492     *loc = (*loc & 0xc0) | (((*loc & 0x3f) - val) & 0x3f);
493     return;
494   case R_RISCV_SUB8:
495     *loc -= val;
496     return;
497   case R_RISCV_SUB16:
498     write16le(loc, read16le(loc) - val);
499     return;
500   case R_RISCV_SUB32:
501     write32le(loc, read32le(loc) - val);
502     return;
503   case R_RISCV_SUB64:
504     write64le(loc, read64le(loc) - val);
505     return;
506   case R_RISCV_SET6:
507     *loc = (*loc & 0xc0) | (val & 0x3f);
508     return;
509   case R_RISCV_SET8:
510     *loc = val;
511     return;
512   case R_RISCV_SET16:
513     write16le(loc, val);
514     return;
515   case R_RISCV_SET32:
516   case R_RISCV_32_PCREL:
517   case R_RISCV_PLT32:
518   case R_RISCV_GOT32_PCREL:
519     checkInt(loc, val, 32, rel);
520     write32le(loc, val);
521     return;
522 
523   case R_RISCV_TLS_DTPREL32:
524     write32le(loc, val - dtpOffset);
525     break;
526   case R_RISCV_TLS_DTPREL64:
527     write64le(loc, val - dtpOffset);
528     break;
529 
530   case R_RISCV_RELAX:
531     return;
532   case R_RISCV_TLSDESC:
533     // The addend is stored in the second word.
534     if (config->is64)
535       write64le(loc + 8, val);
536     else
537       write32le(loc + 4, val);
538     break;
539   default:
540     llvm_unreachable("unknown relocation");
541   }
542 }
543 
544 static bool relaxable(ArrayRef<Relocation> relocs, size_t i) {
545   return i + 1 != relocs.size() && relocs[i + 1].type == R_RISCV_RELAX;
546 }
547 
548 static void tlsdescToIe(uint8_t *loc, const Relocation &rel, uint64_t val) {
549   switch (rel.type) {
550   case R_RISCV_TLSDESC_HI20:
551   case R_RISCV_TLSDESC_LOAD_LO12:
552     write32le(loc, 0x00000013); // nop
553     break;
554   case R_RISCV_TLSDESC_ADD_LO12:
555     write32le(loc, utype(AUIPC, X_A0, hi20(val))); // auipc a0,<hi20>
556     break;
557   case R_RISCV_TLSDESC_CALL:
558     if (config->is64)
559       write32le(loc, itype(LD, X_A0, X_A0, lo12(val))); // ld a0,<lo12>(a0)
560     else
561       write32le(loc, itype(LW, X_A0, X_A0, lo12(val))); // lw a0,<lo12>(a0)
562     break;
563   default:
564     llvm_unreachable("unsupported relocation for TLSDESC to IE");
565   }
566 }
567 
568 static void tlsdescToLe(uint8_t *loc, const Relocation &rel, uint64_t val) {
569   switch (rel.type) {
570   case R_RISCV_TLSDESC_HI20:
571   case R_RISCV_TLSDESC_LOAD_LO12:
572     write32le(loc, 0x00000013); // nop
573     return;
574   case R_RISCV_TLSDESC_ADD_LO12:
575     if (isInt<12>(val))
576       write32le(loc, 0x00000013); // nop
577     else
578       write32le(loc, utype(LUI, X_A0, hi20(val))); // lui a0,<hi20>
579     return;
580   case R_RISCV_TLSDESC_CALL:
581     if (isInt<12>(val))
582       write32le(loc, itype(ADDI, X_A0, 0, val)); // addi a0,zero,<lo12>
583     else
584       write32le(loc, itype(ADDI, X_A0, X_A0, lo12(val))); // addi a0,a0,<lo12>
585     return;
586   default:
587     llvm_unreachable("unsupported relocation for TLSDESC to LE");
588   }
589 }
590 
591 void RISCV::relocateAlloc(InputSectionBase &sec, uint8_t *buf) const {
592   uint64_t secAddr = sec.getOutputSection()->addr;
593   if (auto *s = dyn_cast<InputSection>(&sec))
594     secAddr += s->outSecOff;
595   else if (auto *ehIn = dyn_cast<EhInputSection>(&sec))
596     secAddr += ehIn->getParent()->outSecOff;
597   uint64_t tlsdescVal = 0;
598   bool tlsdescRelax = false, isToLe = false;
599   const ArrayRef<Relocation> relocs = sec.relocs();
600   for (size_t i = 0, size = relocs.size(); i != size; ++i) {
601     const Relocation &rel = relocs[i];
602     uint8_t *loc = buf + rel.offset;
603     uint64_t val =
604         sec.getRelocTargetVA(sec.file, rel.type, rel.addend,
605                              secAddr + rel.offset, *rel.sym, rel.expr);
606 
607     switch (rel.expr) {
608     case R_RELAX_HINT:
609       continue;
610     case R_TLSDESC_PC:
611       // For R_RISCV_TLSDESC_HI20, store &got(sym)-PC to be used by the
612       // following two instructions L[DW] and ADDI.
613       if (rel.type == R_RISCV_TLSDESC_HI20)
614         tlsdescVal = val;
615       else
616         val = tlsdescVal;
617       break;
618     case R_RELAX_TLS_GD_TO_IE:
619       // Only R_RISCV_TLSDESC_HI20 reaches here. tlsdescVal will be finalized
620       // after we see R_RISCV_TLSDESC_ADD_LO12 in the R_RELAX_TLS_GD_TO_LE case.
621       // The net effect is that tlsdescVal will be smaller than `val` to take
622       // into account of NOP instructions (in the absence of R_RISCV_RELAX)
623       // before AUIPC.
624       tlsdescVal = val + rel.offset;
625       isToLe = false;
626       tlsdescRelax = relaxable(relocs, i);
627       if (!tlsdescRelax)
628         tlsdescToIe(loc, rel, val);
629       continue;
630     case R_RELAX_TLS_GD_TO_LE:
631       // See the comment in handleTlsRelocation. For TLSDESC=>IE,
632       // R_RISCV_TLSDESC_{LOAD_LO12,ADD_LO12,CALL} also reach here. If isToIe is
633       // true, this is actually TLSDESC=>IE optimization.
634       if (rel.type == R_RISCV_TLSDESC_HI20) {
635         tlsdescVal = val;
636         isToLe = true;
637         tlsdescRelax = relaxable(relocs, i);
638       } else {
639         if (!isToLe && rel.type == R_RISCV_TLSDESC_ADD_LO12)
640           tlsdescVal -= rel.offset;
641         val = tlsdescVal;
642       }
643       // When NOP conversion is eligible and relaxation applies, don't write a
644       // NOP in case an unrelated instruction follows the current instruction.
645       if (tlsdescRelax &&
646           (rel.type == R_RISCV_TLSDESC_HI20 ||
647            rel.type == R_RISCV_TLSDESC_LOAD_LO12 ||
648            (rel.type == R_RISCV_TLSDESC_ADD_LO12 && isToLe && !hi20(val))))
649         continue;
650       if (isToLe)
651         tlsdescToLe(loc, rel, val);
652       else
653         tlsdescToIe(loc, rel, val);
654       continue;
655     case R_RISCV_LEB128:
656       if (i + 1 < size) {
657         const Relocation &rel1 = relocs[i + 1];
658         if (rel.type == R_RISCV_SET_ULEB128 &&
659             rel1.type == R_RISCV_SUB_ULEB128 && rel.offset == rel1.offset) {
660           auto val = rel.sym->getVA(rel.addend) - rel1.sym->getVA(rel1.addend);
661           if (overwriteULEB128(loc, val) >= 0x80)
662             errorOrWarn(sec.getLocation(rel.offset) + ": ULEB128 value " +
663                         Twine(val) + " exceeds available space; references '" +
664                         lld::toString(*rel.sym) + "'");
665           ++i;
666           continue;
667         }
668       }
669       errorOrWarn(sec.getLocation(rel.offset) +
670                   ": R_RISCV_SET_ULEB128 not paired with R_RISCV_SUB_SET128");
671       return;
672     default:
673       break;
674     }
675     relocate(loc, rel, val);
676   }
677 }
678 
679 void elf::initSymbolAnchors() {
680   SmallVector<InputSection *, 0> storage;
681   for (OutputSection *osec : outputSections) {
682     if (!(osec->flags & SHF_EXECINSTR))
683       continue;
684     for (InputSection *sec : getInputSections(*osec, storage)) {
685       sec->relaxAux = make<RelaxAux>();
686       if (sec->relocs().size()) {
687         sec->relaxAux->relocDeltas =
688             std::make_unique<uint32_t[]>(sec->relocs().size());
689         sec->relaxAux->relocTypes =
690             std::make_unique<RelType[]>(sec->relocs().size());
691       }
692     }
693   }
694   // Store anchors (st_value and st_value+st_size) for symbols relative to text
695   // sections.
696   //
697   // For a defined symbol foo, we may have `d->file != file` with --wrap=foo.
698   // We should process foo, as the defining object file's symbol table may not
699   // contain foo after redirectSymbols changed the foo entry to __wrap_foo. To
700   // avoid adding a Defined that is undefined in one object file, use
701   // `!d->scriptDefined` to exclude symbols that are definitely not wrapped.
702   //
703   // `relaxAux->anchors` may contain duplicate symbols, but that is fine.
704   for (InputFile *file : ctx.objectFiles)
705     for (Symbol *sym : file->getSymbols()) {
706       auto *d = dyn_cast<Defined>(sym);
707       if (!d || (d->file != file && !d->scriptDefined))
708         continue;
709       if (auto *sec = dyn_cast_or_null<InputSection>(d->section))
710         if (sec->flags & SHF_EXECINSTR && sec->relaxAux) {
711           // If sec is discarded, relaxAux will be nullptr.
712           sec->relaxAux->anchors.push_back({d->value, d, false});
713           sec->relaxAux->anchors.push_back({d->value + d->size, d, true});
714         }
715     }
716   // Sort anchors by offset so that we can find the closest relocation
717   // efficiently. For a zero size symbol, ensure that its start anchor precedes
718   // its end anchor. For two symbols with anchors at the same offset, their
719   // order does not matter.
720   for (OutputSection *osec : outputSections) {
721     if (!(osec->flags & SHF_EXECINSTR))
722       continue;
723     for (InputSection *sec : getInputSections(*osec, storage)) {
724       llvm::sort(sec->relaxAux->anchors, [](auto &a, auto &b) {
725         return std::make_pair(a.offset, a.end) <
726                std::make_pair(b.offset, b.end);
727       });
728     }
729   }
730 }
731 
732 // Relax R_RISCV_CALL/R_RISCV_CALL_PLT auipc+jalr to c.j, c.jal, or jal.
733 static void relaxCall(const InputSection &sec, size_t i, uint64_t loc,
734                       Relocation &r, uint32_t &remove) {
735   const bool rvc = getEFlags(sec.file) & EF_RISCV_RVC;
736   const Symbol &sym = *r.sym;
737   const uint64_t insnPair = read64le(sec.content().data() + r.offset);
738   const uint32_t rd = extractBits(insnPair, 32 + 11, 32 + 7);
739   const uint64_t dest =
740       (r.expr == R_PLT_PC ? sym.getPltVA() : sym.getVA()) + r.addend;
741   const int64_t displace = dest - loc;
742 
743   if (rvc && isInt<12>(displace) && rd == 0) {
744     sec.relaxAux->relocTypes[i] = R_RISCV_RVC_JUMP;
745     sec.relaxAux->writes.push_back(0xa001); // c.j
746     remove = 6;
747   } else if (rvc && isInt<12>(displace) && rd == X_RA &&
748              !config->is64) { // RV32C only
749     sec.relaxAux->relocTypes[i] = R_RISCV_RVC_JUMP;
750     sec.relaxAux->writes.push_back(0x2001); // c.jal
751     remove = 6;
752   } else if (isInt<21>(displace)) {
753     sec.relaxAux->relocTypes[i] = R_RISCV_JAL;
754     sec.relaxAux->writes.push_back(0x6f | rd << 7); // jal
755     remove = 4;
756   }
757 }
758 
759 // Relax local-exec TLS when hi20 is zero.
760 static void relaxTlsLe(const InputSection &sec, size_t i, uint64_t loc,
761                        Relocation &r, uint32_t &remove) {
762   uint64_t val = r.sym->getVA(r.addend);
763   if (hi20(val) != 0)
764     return;
765   uint32_t insn = read32le(sec.content().data() + r.offset);
766   switch (r.type) {
767   case R_RISCV_TPREL_HI20:
768   case R_RISCV_TPREL_ADD:
769     // Remove lui rd, %tprel_hi(x) and add rd, rd, tp, %tprel_add(x).
770     sec.relaxAux->relocTypes[i] = R_RISCV_RELAX;
771     remove = 4;
772     break;
773   case R_RISCV_TPREL_LO12_I:
774     // addi rd, rd, %tprel_lo(x) => addi rd, tp, st_value(x)
775     sec.relaxAux->relocTypes[i] = R_RISCV_32;
776     insn = (insn & ~(31 << 15)) | (X_TP << 15);
777     sec.relaxAux->writes.push_back(setLO12_I(insn, val));
778     break;
779   case R_RISCV_TPREL_LO12_S:
780     // sw rs, %tprel_lo(x)(rd) => sw rs, st_value(x)(rd)
781     sec.relaxAux->relocTypes[i] = R_RISCV_32;
782     insn = (insn & ~(31 << 15)) | (X_TP << 15);
783     sec.relaxAux->writes.push_back(setLO12_S(insn, val));
784     break;
785   }
786 }
787 
788 static void relaxHi20Lo12(const InputSection &sec, size_t i, uint64_t loc,
789                           Relocation &r, uint32_t &remove) {
790   const Defined *gp = ElfSym::riscvGlobalPointer;
791   if (!gp)
792     return;
793 
794   if (!isInt<12>(r.sym->getVA(r.addend) - gp->getVA()))
795     return;
796 
797   switch (r.type) {
798   case R_RISCV_HI20:
799     // Remove lui rd, %hi20(x).
800     sec.relaxAux->relocTypes[i] = R_RISCV_RELAX;
801     remove = 4;
802     break;
803   case R_RISCV_LO12_I:
804     sec.relaxAux->relocTypes[i] = INTERNAL_R_RISCV_GPREL_I;
805     break;
806   case R_RISCV_LO12_S:
807     sec.relaxAux->relocTypes[i] = INTERNAL_R_RISCV_GPREL_S;
808     break;
809   }
810 }
811 
812 static bool relax(InputSection &sec) {
813   const uint64_t secAddr = sec.getVA();
814   const MutableArrayRef<Relocation> relocs = sec.relocs();
815   auto &aux = *sec.relaxAux;
816   bool changed = false;
817   ArrayRef<SymbolAnchor> sa = ArrayRef(aux.anchors);
818   uint64_t delta = 0;
819   bool tlsdescRelax = false, toLeShortForm = false;
820 
821   std::fill_n(aux.relocTypes.get(), relocs.size(), R_RISCV_NONE);
822   aux.writes.clear();
823   for (auto [i, r] : llvm::enumerate(relocs)) {
824     const uint64_t loc = secAddr + r.offset - delta;
825     uint32_t &cur = aux.relocDeltas[i], remove = 0;
826     switch (r.type) {
827     case R_RISCV_ALIGN: {
828       const uint64_t nextLoc = loc + r.addend;
829       const uint64_t align = PowerOf2Ceil(r.addend + 2);
830       // All bytes beyond the alignment boundary should be removed.
831       remove = nextLoc - ((loc + align - 1) & -align);
832       // If we can't satisfy this alignment, we've found a bad input.
833       if (LLVM_UNLIKELY(static_cast<int32_t>(remove) < 0)) {
834         errorOrWarn(getErrorLocation((const uint8_t*)loc) +
835                     "insufficient padding bytes for " + lld::toString(r.type) +
836                     ": " + Twine(r.addend) + " bytes available "
837                     "for requested alignment of " + Twine(align) + " bytes");
838         remove = 0;
839       }
840       break;
841     }
842     case R_RISCV_CALL:
843     case R_RISCV_CALL_PLT:
844       if (relaxable(relocs, i))
845         relaxCall(sec, i, loc, r, remove);
846       break;
847     case R_RISCV_TPREL_HI20:
848     case R_RISCV_TPREL_ADD:
849     case R_RISCV_TPREL_LO12_I:
850     case R_RISCV_TPREL_LO12_S:
851       if (relaxable(relocs, i))
852         relaxTlsLe(sec, i, loc, r, remove);
853       break;
854     case R_RISCV_HI20:
855     case R_RISCV_LO12_I:
856     case R_RISCV_LO12_S:
857       if (relaxable(relocs, i))
858         relaxHi20Lo12(sec, i, loc, r, remove);
859       break;
860     case R_RISCV_TLSDESC_HI20:
861       // For TLSDESC=>LE, we can use the short form if hi20 is zero.
862       tlsdescRelax = relaxable(relocs, i);
863       toLeShortForm = tlsdescRelax && r.expr == R_RELAX_TLS_GD_TO_LE &&
864                       !hi20(r.sym->getVA(r.addend));
865       [[fallthrough]];
866     case R_RISCV_TLSDESC_LOAD_LO12:
867       // For TLSDESC=>LE/IE, AUIPC and L[DW] are removed if relaxable.
868       if (tlsdescRelax && r.expr != R_TLSDESC_PC)
869         remove = 4;
870       break;
871     case R_RISCV_TLSDESC_ADD_LO12:
872       if (toLeShortForm)
873         remove = 4;
874       break;
875     }
876 
877     // For all anchors whose offsets are <= r.offset, they are preceded by
878     // the previous relocation whose `relocDeltas` value equals `delta`.
879     // Decrease their st_value and update their st_size.
880     for (; sa.size() && sa[0].offset <= r.offset; sa = sa.slice(1)) {
881       if (sa[0].end)
882         sa[0].d->size = sa[0].offset - delta - sa[0].d->value;
883       else
884         sa[0].d->value = sa[0].offset - delta;
885     }
886     delta += remove;
887     if (delta != cur) {
888       cur = delta;
889       changed = true;
890     }
891   }
892 
893   for (const SymbolAnchor &a : sa) {
894     if (a.end)
895       a.d->size = a.offset - delta - a.d->value;
896     else
897       a.d->value = a.offset - delta;
898   }
899   // Inform assignAddresses that the size has changed.
900   if (!isUInt<32>(delta))
901     fatal("section size decrease is too large: " + Twine(delta));
902   sec.bytesDropped = delta;
903   return changed;
904 }
905 
906 // When relaxing just R_RISCV_ALIGN, relocDeltas is usually changed only once in
907 // the absence of a linker script. For call and load/store R_RISCV_RELAX, code
908 // shrinkage may reduce displacement and make more relocations eligible for
909 // relaxation. Code shrinkage may increase displacement to a call/load/store
910 // target at a higher fixed address, invalidating an earlier relaxation. Any
911 // change in section sizes can have cascading effect and require another
912 // relaxation pass.
913 bool RISCV::relaxOnce(int pass) const {
914   llvm::TimeTraceScope timeScope("RISC-V relaxOnce");
915   if (config->relocatable)
916     return false;
917 
918   if (pass == 0)
919     initSymbolAnchors();
920 
921   SmallVector<InputSection *, 0> storage;
922   bool changed = false;
923   for (OutputSection *osec : outputSections) {
924     if (!(osec->flags & SHF_EXECINSTR))
925       continue;
926     for (InputSection *sec : getInputSections(*osec, storage))
927       changed |= relax(*sec);
928   }
929   return changed;
930 }
931 
932 void RISCV::finalizeRelax(int passes) const {
933   llvm::TimeTraceScope timeScope("Finalize RISC-V relaxation");
934   log("relaxation passes: " + Twine(passes));
935   SmallVector<InputSection *, 0> storage;
936   for (OutputSection *osec : outputSections) {
937     if (!(osec->flags & SHF_EXECINSTR))
938       continue;
939     for (InputSection *sec : getInputSections(*osec, storage)) {
940       RelaxAux &aux = *sec->relaxAux;
941       if (!aux.relocDeltas)
942         continue;
943 
944       MutableArrayRef<Relocation> rels = sec->relocs();
945       ArrayRef<uint8_t> old = sec->content();
946       size_t newSize = old.size() - aux.relocDeltas[rels.size() - 1];
947       size_t writesIdx = 0;
948       uint8_t *p = context().bAlloc.Allocate<uint8_t>(newSize);
949       uint64_t offset = 0;
950       int64_t delta = 0;
951       sec->content_ = p;
952       sec->size = newSize;
953       sec->bytesDropped = 0;
954 
955       // Update section content: remove NOPs for R_RISCV_ALIGN and rewrite
956       // instructions for relaxed relocations.
957       for (size_t i = 0, e = rels.size(); i != e; ++i) {
958         uint32_t remove = aux.relocDeltas[i] - delta;
959         delta = aux.relocDeltas[i];
960         if (remove == 0 && aux.relocTypes[i] == R_RISCV_NONE)
961           continue;
962 
963         // Copy from last location to the current relocated location.
964         const Relocation &r = rels[i];
965         uint64_t size = r.offset - offset;
966         memcpy(p, old.data() + offset, size);
967         p += size;
968 
969         // For R_RISCV_ALIGN, we will place `offset` in a location (among NOPs)
970         // to satisfy the alignment requirement. If both `remove` and r.addend
971         // are multiples of 4, it is as if we have skipped some NOPs. Otherwise
972         // we are in the middle of a 4-byte NOP, and we need to rewrite the NOP
973         // sequence.
974         int64_t skip = 0;
975         if (r.type == R_RISCV_ALIGN) {
976           if (remove % 4 || r.addend % 4) {
977             skip = r.addend - remove;
978             int64_t j = 0;
979             for (; j + 4 <= skip; j += 4)
980               write32le(p + j, 0x00000013); // nop
981             if (j != skip) {
982               assert(j + 2 == skip);
983               write16le(p + j, 0x0001); // c.nop
984             }
985           }
986         } else if (RelType newType = aux.relocTypes[i]) {
987           switch (newType) {
988           case INTERNAL_R_RISCV_GPREL_I:
989           case INTERNAL_R_RISCV_GPREL_S:
990             break;
991           case R_RISCV_RELAX:
992             // Used by relaxTlsLe to indicate the relocation is ignored.
993             break;
994           case R_RISCV_RVC_JUMP:
995             skip = 2;
996             write16le(p, aux.writes[writesIdx++]);
997             break;
998           case R_RISCV_JAL:
999             skip = 4;
1000             write32le(p, aux.writes[writesIdx++]);
1001             break;
1002           case R_RISCV_32:
1003             // Used by relaxTlsLe to write a uint32_t then suppress the handling
1004             // in relocateAlloc.
1005             skip = 4;
1006             write32le(p, aux.writes[writesIdx++]);
1007             aux.relocTypes[i] = R_RISCV_NONE;
1008             break;
1009           default:
1010             llvm_unreachable("unsupported type");
1011           }
1012         }
1013 
1014         p += skip;
1015         offset = r.offset + skip + remove;
1016       }
1017       memcpy(p, old.data() + offset, old.size() - offset);
1018 
1019       // Subtract the previous relocDeltas value from the relocation offset.
1020       // For a pair of R_RISCV_CALL/R_RISCV_RELAX with the same offset, decrease
1021       // their r_offset by the same delta.
1022       delta = 0;
1023       for (size_t i = 0, e = rels.size(); i != e;) {
1024         uint64_t cur = rels[i].offset;
1025         do {
1026           rels[i].offset -= delta;
1027           if (aux.relocTypes[i] != R_RISCV_NONE)
1028             rels[i].type = aux.relocTypes[i];
1029         } while (++i != e && rels[i].offset == cur);
1030         delta = aux.relocDeltas[i - 1];
1031       }
1032     }
1033   }
1034 }
1035 
1036 namespace {
1037 // Representation of the merged .riscv.attributes input sections. The psABI
1038 // specifies merge policy for attributes. E.g. if we link an object without an
1039 // extension with an object with the extension, the output Tag_RISCV_arch shall
1040 // contain the extension. Some tools like objdump parse .riscv.attributes and
1041 // disabling some instructions if the first Tag_RISCV_arch does not contain an
1042 // extension.
1043 class RISCVAttributesSection final : public SyntheticSection {
1044 public:
1045   RISCVAttributesSection()
1046       : SyntheticSection(0, SHT_RISCV_ATTRIBUTES, 1, ".riscv.attributes") {}
1047 
1048   size_t getSize() const override { return size; }
1049   void writeTo(uint8_t *buf) override;
1050 
1051   static constexpr StringRef vendor = "riscv";
1052   DenseMap<unsigned, unsigned> intAttr;
1053   DenseMap<unsigned, StringRef> strAttr;
1054   size_t size = 0;
1055 };
1056 } // namespace
1057 
1058 static void mergeArch(RISCVISAInfo::OrderedExtensionMap &mergedExts,
1059                       unsigned &mergedXlen, const InputSectionBase *sec,
1060                       StringRef s) {
1061   auto maybeInfo = RISCVISAInfo::parseNormalizedArchString(s);
1062   if (!maybeInfo) {
1063     errorOrWarn(toString(sec) + ": " + s + ": " +
1064                 llvm::toString(maybeInfo.takeError()));
1065     return;
1066   }
1067 
1068   // Merge extensions.
1069   RISCVISAInfo &info = **maybeInfo;
1070   if (mergedExts.empty()) {
1071     mergedExts = info.getExtensions();
1072     mergedXlen = info.getXLen();
1073   } else {
1074     for (const auto &ext : info.getExtensions()) {
1075       if (auto it = mergedExts.find(ext.first); it != mergedExts.end()) {
1076         if (std::tie(it->second.Major, it->second.Minor) >=
1077             std::tie(ext.second.Major, ext.second.Minor))
1078           continue;
1079       }
1080       mergedExts[ext.first] = ext.second;
1081     }
1082   }
1083 }
1084 
1085 static RISCVAttributesSection *
1086 mergeAttributesSection(const SmallVector<InputSectionBase *, 0> &sections) {
1087   RISCVISAInfo::OrderedExtensionMap exts;
1088   const InputSectionBase *firstStackAlign = nullptr;
1089   unsigned firstStackAlignValue = 0, xlen = 0;
1090   bool hasArch = false;
1091 
1092   in.riscvAttributes = std::make_unique<RISCVAttributesSection>();
1093   auto &merged = static_cast<RISCVAttributesSection &>(*in.riscvAttributes);
1094 
1095   // Collect all tags values from attributes section.
1096   const auto &attributesTags = RISCVAttrs::getRISCVAttributeTags();
1097   for (const InputSectionBase *sec : sections) {
1098     RISCVAttributeParser parser;
1099     if (Error e = parser.parse(sec->content(), llvm::endianness::little))
1100       warn(toString(sec) + ": " + llvm::toString(std::move(e)));
1101     for (const auto &tag : attributesTags) {
1102       switch (RISCVAttrs::AttrType(tag.attr)) {
1103         // Integer attributes.
1104       case RISCVAttrs::STACK_ALIGN:
1105         if (auto i = parser.getAttributeValue(tag.attr)) {
1106           auto r = merged.intAttr.try_emplace(tag.attr, *i);
1107           if (r.second) {
1108             firstStackAlign = sec;
1109             firstStackAlignValue = *i;
1110           } else if (r.first->second != *i) {
1111             errorOrWarn(toString(sec) + " has stack_align=" + Twine(*i) +
1112                         " but " + toString(firstStackAlign) +
1113                         " has stack_align=" + Twine(firstStackAlignValue));
1114           }
1115         }
1116         continue;
1117       case RISCVAttrs::UNALIGNED_ACCESS:
1118         if (auto i = parser.getAttributeValue(tag.attr))
1119           merged.intAttr[tag.attr] |= *i;
1120         continue;
1121 
1122         // String attributes.
1123       case RISCVAttrs::ARCH:
1124         if (auto s = parser.getAttributeString(tag.attr)) {
1125           hasArch = true;
1126           mergeArch(exts, xlen, sec, *s);
1127         }
1128         continue;
1129 
1130         // Attributes which use the default handling.
1131       case RISCVAttrs::PRIV_SPEC:
1132       case RISCVAttrs::PRIV_SPEC_MINOR:
1133       case RISCVAttrs::PRIV_SPEC_REVISION:
1134         break;
1135       }
1136 
1137       // Fallback for deprecated priv_spec* and other unknown attributes: retain
1138       // the attribute if all input sections agree on the value. GNU ld uses 0
1139       // and empty strings as default values which are not dumped to the output.
1140       // TODO Adjust after resolution to
1141       // https://github.com/riscv-non-isa/riscv-elf-psabi-doc/issues/352
1142       if (tag.attr % 2 == 0) {
1143         if (auto i = parser.getAttributeValue(tag.attr)) {
1144           auto r = merged.intAttr.try_emplace(tag.attr, *i);
1145           if (!r.second && r.first->second != *i)
1146             r.first->second = 0;
1147         }
1148       } else if (auto s = parser.getAttributeString(tag.attr)) {
1149         auto r = merged.strAttr.try_emplace(tag.attr, *s);
1150         if (!r.second && r.first->second != *s)
1151           r.first->second = {};
1152       }
1153     }
1154   }
1155 
1156   if (hasArch) {
1157     if (auto result = RISCVISAInfo::postProcessAndChecking(
1158             std::make_unique<RISCVISAInfo>(xlen, exts))) {
1159       merged.strAttr.try_emplace(RISCVAttrs::ARCH,
1160                                  saver().save((*result)->toString()));
1161     } else {
1162       errorOrWarn(llvm::toString(result.takeError()));
1163     }
1164   }
1165 
1166   // The total size of headers: format-version [ <section-length> "vendor-name"
1167   // [ <file-tag> <size>.
1168   size_t size = 5 + merged.vendor.size() + 1 + 5;
1169   for (auto &attr : merged.intAttr)
1170     if (attr.second != 0)
1171       size += getULEB128Size(attr.first) + getULEB128Size(attr.second);
1172   for (auto &attr : merged.strAttr)
1173     if (!attr.second.empty())
1174       size += getULEB128Size(attr.first) + attr.second.size() + 1;
1175   merged.size = size;
1176   return &merged;
1177 }
1178 
1179 void RISCVAttributesSection::writeTo(uint8_t *buf) {
1180   const size_t size = getSize();
1181   uint8_t *const end = buf + size;
1182   *buf = ELFAttrs::Format_Version;
1183   write32(buf + 1, size - 1);
1184   buf += 5;
1185 
1186   memcpy(buf, vendor.data(), vendor.size());
1187   buf += vendor.size() + 1;
1188 
1189   *buf = ELFAttrs::File;
1190   write32(buf + 1, end - buf);
1191   buf += 5;
1192 
1193   for (auto &attr : intAttr) {
1194     if (attr.second == 0)
1195       continue;
1196     buf += encodeULEB128(attr.first, buf);
1197     buf += encodeULEB128(attr.second, buf);
1198   }
1199   for (auto &attr : strAttr) {
1200     if (attr.second.empty())
1201       continue;
1202     buf += encodeULEB128(attr.first, buf);
1203     memcpy(buf, attr.second.data(), attr.second.size());
1204     buf += attr.second.size() + 1;
1205   }
1206 }
1207 
1208 void elf::mergeRISCVAttributesSections() {
1209   // Find the first input SHT_RISCV_ATTRIBUTES; return if not found.
1210   size_t place =
1211       llvm::find_if(ctx.inputSections,
1212                     [](auto *s) { return s->type == SHT_RISCV_ATTRIBUTES; }) -
1213       ctx.inputSections.begin();
1214   if (place == ctx.inputSections.size())
1215     return;
1216 
1217   // Extract all SHT_RISCV_ATTRIBUTES sections into `sections`.
1218   SmallVector<InputSectionBase *, 0> sections;
1219   llvm::erase_if(ctx.inputSections, [&](InputSectionBase *s) {
1220     if (s->type != SHT_RISCV_ATTRIBUTES)
1221       return false;
1222     sections.push_back(s);
1223     return true;
1224   });
1225 
1226   // Add the merged section.
1227   ctx.inputSections.insert(ctx.inputSections.begin() + place,
1228                            mergeAttributesSection(sections));
1229 }
1230 
1231 TargetInfo *elf::getRISCVTargetInfo() {
1232   static RISCV target;
1233   return &target;
1234 }
1235