1 //===-- RISCVAsmBackend.cpp - RISC-V Assembler Backend --------------------===//
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 "RISCVAsmBackend.h"
10 #include "RISCVMCExpr.h"
11 #include "llvm/ADT/APInt.h"
12 #include "llvm/MC/MCAsmInfo.h"
13 #include "llvm/MC/MCAsmLayout.h"
14 #include "llvm/MC/MCAssembler.h"
15 #include "llvm/MC/MCContext.h"
16 #include "llvm/MC/MCDirectives.h"
17 #include "llvm/MC/MCELFObjectWriter.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCObjectWriter.h"
20 #include "llvm/MC/MCSymbol.h"
21 #include "llvm/MC/MCValue.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Endian.h"
24 #include "llvm/Support/EndianStream.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/LEB128.h"
27 #include "llvm/Support/raw_ostream.h"
28 
29 using namespace llvm;
30 
31 static cl::opt<bool> RelaxBranches("riscv-asm-relax-branches", cl::init(true),
32                                    cl::Hidden);
33 // Temporary workaround for old linkers that do not support ULEB128 relocations,
34 // which are abused by DWARF v5 DW_LLE_offset_pair/DW_RLE_offset_pair
35 // implemented in Clang/LLVM.
36 static cl::opt<bool> ULEB128Reloc(
37     "riscv-uleb128-reloc", cl::init(true), cl::Hidden,
38     cl::desc("Emit R_RISCV_SET_ULEB128/E_RISCV_SUB_ULEB128 if appropriate"));
39 
getFixupKind(StringRef Name) const40 std::optional<MCFixupKind> RISCVAsmBackend::getFixupKind(StringRef Name) const {
41   if (STI.getTargetTriple().isOSBinFormatELF()) {
42     unsigned Type;
43     Type = llvm::StringSwitch<unsigned>(Name)
44 #define ELF_RELOC(X, Y) .Case(#X, Y)
45 #include "llvm/BinaryFormat/ELFRelocs/RISCV.def"
46 #undef ELF_RELOC
47                .Case("BFD_RELOC_NONE", ELF::R_RISCV_NONE)
48                .Case("BFD_RELOC_32", ELF::R_RISCV_32)
49                .Case("BFD_RELOC_64", ELF::R_RISCV_64)
50                .Default(-1u);
51     if (Type != -1u)
52       return static_cast<MCFixupKind>(FirstLiteralRelocationKind + Type);
53   }
54   return std::nullopt;
55 }
56 
57 const MCFixupKindInfo &
getFixupKindInfo(MCFixupKind Kind) const58 RISCVAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
59   const static MCFixupKindInfo Infos[] = {
60       // This table *must* be in the order that the fixup_* kinds are defined in
61       // RISCVFixupKinds.h.
62       //
63       // name                      offset bits  flags
64       {"fixup_riscv_hi20", 12, 20, 0},
65       {"fixup_riscv_lo12_i", 20, 12, 0},
66       {"fixup_riscv_12_i", 20, 12, 0},
67       {"fixup_riscv_lo12_s", 0, 32, 0},
68       {"fixup_riscv_pcrel_hi20", 12, 20,
69        MCFixupKindInfo::FKF_IsPCRel | MCFixupKindInfo::FKF_IsTarget},
70       {"fixup_riscv_pcrel_lo12_i", 20, 12,
71        MCFixupKindInfo::FKF_IsPCRel | MCFixupKindInfo::FKF_IsTarget},
72       {"fixup_riscv_pcrel_lo12_s", 0, 32,
73        MCFixupKindInfo::FKF_IsPCRel | MCFixupKindInfo::FKF_IsTarget},
74       {"fixup_riscv_got_hi20", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
75       {"fixup_riscv_tprel_hi20", 12, 20, 0},
76       {"fixup_riscv_tprel_lo12_i", 20, 12, 0},
77       {"fixup_riscv_tprel_lo12_s", 0, 32, 0},
78       {"fixup_riscv_tprel_add", 0, 0, 0},
79       {"fixup_riscv_tls_got_hi20", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
80       {"fixup_riscv_tls_gd_hi20", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
81       {"fixup_riscv_jal", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
82       {"fixup_riscv_branch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
83       {"fixup_riscv_rvc_jump", 2, 11, MCFixupKindInfo::FKF_IsPCRel},
84       {"fixup_riscv_rvc_branch", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
85       {"fixup_riscv_call", 0, 64, MCFixupKindInfo::FKF_IsPCRel},
86       {"fixup_riscv_call_plt", 0, 64, MCFixupKindInfo::FKF_IsPCRel},
87       {"fixup_riscv_relax", 0, 0, 0},
88       {"fixup_riscv_align", 0, 0, 0},
89 
90       {"fixup_riscv_tlsdesc_hi20", 12, 20,
91        MCFixupKindInfo::FKF_IsPCRel | MCFixupKindInfo::FKF_IsTarget},
92       {"fixup_riscv_tlsdesc_load_lo12", 20, 12, 0},
93       {"fixup_riscv_tlsdesc_add_lo12", 20, 12, 0},
94       {"fixup_riscv_tlsdesc_call", 0, 0, 0},
95   };
96   static_assert((std::size(Infos)) == RISCV::NumTargetFixupKinds,
97                 "Not all fixup kinds added to Infos array");
98 
99   // Fixup kinds from .reloc directive are like R_RISCV_NONE. They
100   // do not require any extra processing.
101   if (Kind >= FirstLiteralRelocationKind)
102     return MCAsmBackend::getFixupKindInfo(FK_NONE);
103 
104   if (Kind < FirstTargetFixupKind)
105     return MCAsmBackend::getFixupKindInfo(Kind);
106 
107   assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
108          "Invalid kind!");
109   return Infos[Kind - FirstTargetFixupKind];
110 }
111 
112 // If linker relaxation is enabled, or the relax option had previously been
113 // enabled, always emit relocations even if the fixup can be resolved. This is
114 // necessary for correctness as offsets may change during relaxation.
shouldForceRelocation(const MCAssembler & Asm,const MCFixup & Fixup,const MCValue & Target,const MCSubtargetInfo * STI)115 bool RISCVAsmBackend::shouldForceRelocation(const MCAssembler &Asm,
116                                             const MCFixup &Fixup,
117                                             const MCValue &Target,
118                                             const MCSubtargetInfo *STI) {
119   if (Fixup.getKind() >= FirstLiteralRelocationKind)
120     return true;
121   switch (Fixup.getTargetKind()) {
122   default:
123     break;
124   case FK_Data_1:
125   case FK_Data_2:
126   case FK_Data_4:
127   case FK_Data_8:
128   case FK_Data_leb128:
129     if (Target.isAbsolute())
130       return false;
131     break;
132   case RISCV::fixup_riscv_got_hi20:
133   case RISCV::fixup_riscv_tls_got_hi20:
134   case RISCV::fixup_riscv_tls_gd_hi20:
135   case RISCV::fixup_riscv_tlsdesc_hi20:
136     return true;
137   }
138 
139   return STI->hasFeature(RISCV::FeatureRelax) || ForceRelocs;
140 }
141 
fixupNeedsRelaxationAdvanced(const MCFixup & Fixup,bool Resolved,uint64_t Value,const MCRelaxableFragment * DF,const MCAsmLayout & Layout,const bool WasForced) const142 bool RISCVAsmBackend::fixupNeedsRelaxationAdvanced(const MCFixup &Fixup,
143                                                    bool Resolved,
144                                                    uint64_t Value,
145                                                    const MCRelaxableFragment *DF,
146                                                    const MCAsmLayout &Layout,
147                                                    const bool WasForced) const {
148   if (!RelaxBranches)
149     return false;
150 
151   int64_t Offset = int64_t(Value);
152   unsigned Kind = Fixup.getTargetKind();
153 
154   // Return true if the symbol is actually unresolved.
155   // Resolved could be always false when shouldForceRelocation return true.
156   // We use !WasForced to indicate that the symbol is unresolved and not forced
157   // by shouldForceRelocation.
158   if (!Resolved && !WasForced)
159     return true;
160 
161   switch (Kind) {
162   default:
163     return false;
164   case RISCV::fixup_riscv_rvc_branch:
165     // For compressed branch instructions the immediate must be
166     // in the range [-256, 254].
167     return Offset > 254 || Offset < -256;
168   case RISCV::fixup_riscv_rvc_jump:
169     // For compressed jump instructions the immediate must be
170     // in the range [-2048, 2046].
171     return Offset > 2046 || Offset < -2048;
172   case RISCV::fixup_riscv_branch:
173     // For conditional branch instructions the immediate must be
174     // in the range [-4096, 4095].
175     return !isInt<13>(Offset);
176   }
177 }
178 
relaxInstruction(MCInst & Inst,const MCSubtargetInfo & STI) const179 void RISCVAsmBackend::relaxInstruction(MCInst &Inst,
180                                        const MCSubtargetInfo &STI) const {
181   MCInst Res;
182   switch (Inst.getOpcode()) {
183   default:
184     llvm_unreachable("Opcode not expected!");
185   case RISCV::C_BEQZ:
186   case RISCV::C_BNEZ:
187   case RISCV::C_J:
188   case RISCV::C_JAL: {
189     bool Success = RISCVRVC::uncompress(Res, Inst, STI);
190     assert(Success && "Can't uncompress instruction");
191     (void)Success;
192     break;
193   }
194   case RISCV::BEQ:
195   case RISCV::BNE:
196   case RISCV::BLT:
197   case RISCV::BGE:
198   case RISCV::BLTU:
199   case RISCV::BGEU:
200     Res.setOpcode(getRelaxedOpcode(Inst.getOpcode()));
201     Res.addOperand(Inst.getOperand(0));
202     Res.addOperand(Inst.getOperand(1));
203     Res.addOperand(Inst.getOperand(2));
204     break;
205   }
206   Inst = std::move(Res);
207 }
208 
relaxDwarfLineAddr(MCDwarfLineAddrFragment & DF,MCAsmLayout & Layout,bool & WasRelaxed) const209 bool RISCVAsmBackend::relaxDwarfLineAddr(MCDwarfLineAddrFragment &DF,
210                                          MCAsmLayout &Layout,
211                                          bool &WasRelaxed) const {
212   MCContext &C = Layout.getAssembler().getContext();
213 
214   int64_t LineDelta = DF.getLineDelta();
215   const MCExpr &AddrDelta = DF.getAddrDelta();
216   SmallVectorImpl<char> &Data = DF.getContents();
217   SmallVectorImpl<MCFixup> &Fixups = DF.getFixups();
218   size_t OldSize = Data.size();
219 
220   int64_t Value;
221   bool IsAbsolute = AddrDelta.evaluateKnownAbsolute(Value, Layout);
222   assert(IsAbsolute && "CFA with invalid expression");
223   (void)IsAbsolute;
224 
225   Data.clear();
226   Fixups.clear();
227   raw_svector_ostream OS(Data);
228 
229   // INT64_MAX is a signal that this is actually a DW_LNE_end_sequence.
230   if (LineDelta != INT64_MAX) {
231     OS << uint8_t(dwarf::DW_LNS_advance_line);
232     encodeSLEB128(LineDelta, OS);
233   }
234 
235   unsigned Offset;
236   std::pair<MCFixupKind, MCFixupKind> Fixup;
237 
238   // According to the DWARF specification, the `DW_LNS_fixed_advance_pc` opcode
239   // takes a single unsigned half (unencoded) operand. The maximum encodable
240   // value is therefore 65535.  Set a conservative upper bound for relaxation.
241   if (Value > 60000) {
242     unsigned PtrSize = C.getAsmInfo()->getCodePointerSize();
243 
244     OS << uint8_t(dwarf::DW_LNS_extended_op);
245     encodeULEB128(PtrSize + 1, OS);
246 
247     OS << uint8_t(dwarf::DW_LNE_set_address);
248     Offset = OS.tell();
249     assert((PtrSize == 4 || PtrSize == 8) && "Unexpected pointer size");
250     Fixup = RISCV::getRelocPairForSize(PtrSize);
251     OS.write_zeros(PtrSize);
252   } else {
253     OS << uint8_t(dwarf::DW_LNS_fixed_advance_pc);
254     Offset = OS.tell();
255     Fixup = RISCV::getRelocPairForSize(2);
256     support::endian::write<uint16_t>(OS, 0, llvm::endianness::little);
257   }
258 
259   const MCBinaryExpr &MBE = cast<MCBinaryExpr>(AddrDelta);
260   Fixups.push_back(MCFixup::create(Offset, MBE.getLHS(), std::get<0>(Fixup)));
261   Fixups.push_back(MCFixup::create(Offset, MBE.getRHS(), std::get<1>(Fixup)));
262 
263   if (LineDelta == INT64_MAX) {
264     OS << uint8_t(dwarf::DW_LNS_extended_op);
265     OS << uint8_t(1);
266     OS << uint8_t(dwarf::DW_LNE_end_sequence);
267   } else {
268     OS << uint8_t(dwarf::DW_LNS_copy);
269   }
270 
271   WasRelaxed = OldSize != Data.size();
272   return true;
273 }
274 
relaxDwarfCFA(MCDwarfCallFrameFragment & DF,MCAsmLayout & Layout,bool & WasRelaxed) const275 bool RISCVAsmBackend::relaxDwarfCFA(MCDwarfCallFrameFragment &DF,
276                                     MCAsmLayout &Layout,
277                                     bool &WasRelaxed) const {
278   const MCExpr &AddrDelta = DF.getAddrDelta();
279   SmallVectorImpl<char> &Data = DF.getContents();
280   SmallVectorImpl<MCFixup> &Fixups = DF.getFixups();
281   size_t OldSize = Data.size();
282 
283   int64_t Value;
284   if (AddrDelta.evaluateAsAbsolute(Value, Layout.getAssembler()))
285     return false;
286   bool IsAbsolute = AddrDelta.evaluateKnownAbsolute(Value, Layout);
287   assert(IsAbsolute && "CFA with invalid expression");
288   (void)IsAbsolute;
289 
290   Data.clear();
291   Fixups.clear();
292   raw_svector_ostream OS(Data);
293 
294   assert(
295       Layout.getAssembler().getContext().getAsmInfo()->getMinInstAlignment() ==
296           1 &&
297       "expected 1-byte alignment");
298   if (Value == 0) {
299     WasRelaxed = OldSize != Data.size();
300     return true;
301   }
302 
303   auto AddFixups = [&Fixups, &AddrDelta](unsigned Offset,
304                                          std::pair<unsigned, unsigned> Fixup) {
305     const MCBinaryExpr &MBE = cast<MCBinaryExpr>(AddrDelta);
306     Fixups.push_back(
307         MCFixup::create(Offset, MBE.getLHS(),
308                         static_cast<MCFixupKind>(FirstLiteralRelocationKind +
309                                                  std::get<0>(Fixup))));
310     Fixups.push_back(
311         MCFixup::create(Offset, MBE.getRHS(),
312                         static_cast<MCFixupKind>(FirstLiteralRelocationKind +
313                                                  std::get<1>(Fixup))));
314   };
315 
316   if (isUIntN(6, Value)) {
317     OS << uint8_t(dwarf::DW_CFA_advance_loc);
318     AddFixups(0, {ELF::R_RISCV_SET6, ELF::R_RISCV_SUB6});
319   } else if (isUInt<8>(Value)) {
320     OS << uint8_t(dwarf::DW_CFA_advance_loc1);
321     support::endian::write<uint8_t>(OS, 0, llvm::endianness::little);
322     AddFixups(1, {ELF::R_RISCV_SET8, ELF::R_RISCV_SUB8});
323   } else if (isUInt<16>(Value)) {
324     OS << uint8_t(dwarf::DW_CFA_advance_loc2);
325     support::endian::write<uint16_t>(OS, 0, llvm::endianness::little);
326     AddFixups(1, {ELF::R_RISCV_SET16, ELF::R_RISCV_SUB16});
327   } else if (isUInt<32>(Value)) {
328     OS << uint8_t(dwarf::DW_CFA_advance_loc4);
329     support::endian::write<uint32_t>(OS, 0, llvm::endianness::little);
330     AddFixups(1, {ELF::R_RISCV_SET32, ELF::R_RISCV_SUB32});
331   } else {
332     llvm_unreachable("unsupported CFA encoding");
333   }
334 
335   WasRelaxed = OldSize != Data.size();
336   return true;
337 }
338 
relaxLEB128(MCLEBFragment & LF,MCAsmLayout & Layout,int64_t & Value) const339 std::pair<bool, bool> RISCVAsmBackend::relaxLEB128(MCLEBFragment &LF,
340                                                    MCAsmLayout &Layout,
341                                                    int64_t &Value) const {
342   if (LF.isSigned())
343     return std::make_pair(false, false);
344   const MCExpr &Expr = LF.getValue();
345   if (ULEB128Reloc) {
346     LF.getFixups().push_back(
347         MCFixup::create(0, &Expr, FK_Data_leb128, Expr.getLoc()));
348   }
349   return std::make_pair(Expr.evaluateKnownAbsolute(Value, Layout), false);
350 }
351 
352 // Given a compressed control flow instruction this function returns
353 // the expanded instruction.
getRelaxedOpcode(unsigned Op) const354 unsigned RISCVAsmBackend::getRelaxedOpcode(unsigned Op) const {
355   switch (Op) {
356   default:
357     return Op;
358   case RISCV::C_BEQZ:
359     return RISCV::BEQ;
360   case RISCV::C_BNEZ:
361     return RISCV::BNE;
362   case RISCV::C_J:
363   case RISCV::C_JAL: // fall through.
364     return RISCV::JAL;
365   case RISCV::BEQ:
366     return RISCV::PseudoLongBEQ;
367   case RISCV::BNE:
368     return RISCV::PseudoLongBNE;
369   case RISCV::BLT:
370     return RISCV::PseudoLongBLT;
371   case RISCV::BGE:
372     return RISCV::PseudoLongBGE;
373   case RISCV::BLTU:
374     return RISCV::PseudoLongBLTU;
375   case RISCV::BGEU:
376     return RISCV::PseudoLongBGEU;
377   }
378 }
379 
mayNeedRelaxation(const MCInst & Inst,const MCSubtargetInfo & STI) const380 bool RISCVAsmBackend::mayNeedRelaxation(const MCInst &Inst,
381                                         const MCSubtargetInfo &STI) const {
382   return getRelaxedOpcode(Inst.getOpcode()) != Inst.getOpcode();
383 }
384 
writeNopData(raw_ostream & OS,uint64_t Count,const MCSubtargetInfo * STI) const385 bool RISCVAsmBackend::writeNopData(raw_ostream &OS, uint64_t Count,
386                                    const MCSubtargetInfo *STI) const {
387   // We mostly follow binutils' convention here: align to even boundary with a
388   // 0-fill padding.  We emit up to 1 2-byte nop, though we use c.nop if RVC is
389   // enabled or 0-fill otherwise.  The remainder is now padded with 4-byte nops.
390 
391   // Instructions always are at even addresses.  We must be in a data area or
392   // be unaligned due to some other reason.
393   if (Count % 2) {
394     OS.write("\0", 1);
395     Count -= 1;
396   }
397 
398   bool UseCompressedNop = STI->hasFeature(RISCV::FeatureStdExtC) ||
399                           STI->hasFeature(RISCV::FeatureStdExtZca);
400   // The canonical nop on RVC is c.nop.
401   if (Count % 4 == 2) {
402     OS.write(UseCompressedNop ? "\x01\0" : "\0\0", 2);
403     Count -= 2;
404   }
405 
406   // The canonical nop on RISC-V is addi x0, x0, 0.
407   for (; Count >= 4; Count -= 4)
408     OS.write("\x13\0\0\0", 4);
409 
410   return true;
411 }
412 
adjustFixupValue(const MCFixup & Fixup,uint64_t Value,MCContext & Ctx)413 static uint64_t adjustFixupValue(const MCFixup &Fixup, uint64_t Value,
414                                  MCContext &Ctx) {
415   switch (Fixup.getTargetKind()) {
416   default:
417     llvm_unreachable("Unknown fixup kind!");
418   case RISCV::fixup_riscv_got_hi20:
419   case RISCV::fixup_riscv_tls_got_hi20:
420   case RISCV::fixup_riscv_tls_gd_hi20:
421   case RISCV::fixup_riscv_tlsdesc_hi20:
422     llvm_unreachable("Relocation should be unconditionally forced\n");
423   case FK_Data_1:
424   case FK_Data_2:
425   case FK_Data_4:
426   case FK_Data_8:
427   case FK_Data_leb128:
428     return Value;
429   case RISCV::fixup_riscv_lo12_i:
430   case RISCV::fixup_riscv_pcrel_lo12_i:
431   case RISCV::fixup_riscv_tprel_lo12_i:
432   case RISCV::fixup_riscv_tlsdesc_load_lo12:
433     return Value & 0xfff;
434   case RISCV::fixup_riscv_12_i:
435     if (!isInt<12>(Value)) {
436       Ctx.reportError(Fixup.getLoc(),
437                       "operand must be a constant 12-bit integer");
438     }
439     return Value & 0xfff;
440   case RISCV::fixup_riscv_lo12_s:
441   case RISCV::fixup_riscv_pcrel_lo12_s:
442   case RISCV::fixup_riscv_tprel_lo12_s:
443     return (((Value >> 5) & 0x7f) << 25) | ((Value & 0x1f) << 7);
444   case RISCV::fixup_riscv_hi20:
445   case RISCV::fixup_riscv_pcrel_hi20:
446   case RISCV::fixup_riscv_tprel_hi20:
447     // Add 1 if bit 11 is 1, to compensate for low 12 bits being negative.
448     return ((Value + 0x800) >> 12) & 0xfffff;
449   case RISCV::fixup_riscv_jal: {
450     if (!isInt<21>(Value))
451       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
452     if (Value & 0x1)
453       Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
454     // Need to produce imm[19|10:1|11|19:12] from the 21-bit Value.
455     unsigned Sbit = (Value >> 20) & 0x1;
456     unsigned Hi8 = (Value >> 12) & 0xff;
457     unsigned Mid1 = (Value >> 11) & 0x1;
458     unsigned Lo10 = (Value >> 1) & 0x3ff;
459     // Inst{31} = Sbit;
460     // Inst{30-21} = Lo10;
461     // Inst{20} = Mid1;
462     // Inst{19-12} = Hi8;
463     Value = (Sbit << 19) | (Lo10 << 9) | (Mid1 << 8) | Hi8;
464     return Value;
465   }
466   case RISCV::fixup_riscv_branch: {
467     if (!isInt<13>(Value))
468       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
469     if (Value & 0x1)
470       Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
471     // Need to extract imm[12], imm[10:5], imm[4:1], imm[11] from the 13-bit
472     // Value.
473     unsigned Sbit = (Value >> 12) & 0x1;
474     unsigned Hi1 = (Value >> 11) & 0x1;
475     unsigned Mid6 = (Value >> 5) & 0x3f;
476     unsigned Lo4 = (Value >> 1) & 0xf;
477     // Inst{31} = Sbit;
478     // Inst{30-25} = Mid6;
479     // Inst{11-8} = Lo4;
480     // Inst{7} = Hi1;
481     Value = (Sbit << 31) | (Mid6 << 25) | (Lo4 << 8) | (Hi1 << 7);
482     return Value;
483   }
484   case RISCV::fixup_riscv_call:
485   case RISCV::fixup_riscv_call_plt: {
486     // Jalr will add UpperImm with the sign-extended 12-bit LowerImm,
487     // we need to add 0x800ULL before extract upper bits to reflect the
488     // effect of the sign extension.
489     uint64_t UpperImm = (Value + 0x800ULL) & 0xfffff000ULL;
490     uint64_t LowerImm = Value & 0xfffULL;
491     return UpperImm | ((LowerImm << 20) << 32);
492   }
493   case RISCV::fixup_riscv_rvc_jump: {
494     if (!isInt<12>(Value))
495       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
496     // Need to produce offset[11|4|9:8|10|6|7|3:1|5] from the 11-bit Value.
497     unsigned Bit11  = (Value >> 11) & 0x1;
498     unsigned Bit4   = (Value >> 4) & 0x1;
499     unsigned Bit9_8 = (Value >> 8) & 0x3;
500     unsigned Bit10  = (Value >> 10) & 0x1;
501     unsigned Bit6   = (Value >> 6) & 0x1;
502     unsigned Bit7   = (Value >> 7) & 0x1;
503     unsigned Bit3_1 = (Value >> 1) & 0x7;
504     unsigned Bit5   = (Value >> 5) & 0x1;
505     Value = (Bit11 << 10) | (Bit4 << 9) | (Bit9_8 << 7) | (Bit10 << 6) |
506             (Bit6 << 5) | (Bit7 << 4) | (Bit3_1 << 1) | Bit5;
507     return Value;
508   }
509   case RISCV::fixup_riscv_rvc_branch: {
510     if (!isInt<9>(Value))
511       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
512     // Need to produce offset[8|4:3], [reg 3 bit], offset[7:6|2:1|5]
513     unsigned Bit8   = (Value >> 8) & 0x1;
514     unsigned Bit7_6 = (Value >> 6) & 0x3;
515     unsigned Bit5   = (Value >> 5) & 0x1;
516     unsigned Bit4_3 = (Value >> 3) & 0x3;
517     unsigned Bit2_1 = (Value >> 1) & 0x3;
518     Value = (Bit8 << 12) | (Bit4_3 << 10) | (Bit7_6 << 5) | (Bit2_1 << 3) |
519             (Bit5 << 2);
520     return Value;
521   }
522 
523   }
524 }
525 
evaluateTargetFixup(const MCAssembler & Asm,const MCAsmLayout & Layout,const MCFixup & Fixup,const MCFragment * DF,const MCValue & Target,const MCSubtargetInfo * STI,uint64_t & Value,bool & WasForced)526 bool RISCVAsmBackend::evaluateTargetFixup(
527     const MCAssembler &Asm, const MCAsmLayout &Layout, const MCFixup &Fixup,
528     const MCFragment *DF, const MCValue &Target, const MCSubtargetInfo *STI,
529     uint64_t &Value, bool &WasForced) {
530   const MCFixup *AUIPCFixup;
531   const MCFragment *AUIPCDF;
532   MCValue AUIPCTarget;
533   switch (Fixup.getTargetKind()) {
534   default:
535     llvm_unreachable("Unexpected fixup kind!");
536   case RISCV::fixup_riscv_tlsdesc_hi20:
537   case RISCV::fixup_riscv_pcrel_hi20:
538     AUIPCFixup = &Fixup;
539     AUIPCDF = DF;
540     AUIPCTarget = Target;
541     break;
542   case RISCV::fixup_riscv_pcrel_lo12_i:
543   case RISCV::fixup_riscv_pcrel_lo12_s: {
544     AUIPCFixup = cast<RISCVMCExpr>(Fixup.getValue())->getPCRelHiFixup(&AUIPCDF);
545     if (!AUIPCFixup) {
546       Asm.getContext().reportError(Fixup.getLoc(),
547                                    "could not find corresponding %pcrel_hi");
548       return true;
549     }
550 
551     // MCAssembler::evaluateFixup will emit an error for this case when it sees
552     // the %pcrel_hi, so don't duplicate it when also seeing the %pcrel_lo.
553     const MCExpr *AUIPCExpr = AUIPCFixup->getValue();
554     if (!AUIPCExpr->evaluateAsRelocatable(AUIPCTarget, &Layout, AUIPCFixup))
555       return true;
556     break;
557   }
558   }
559 
560   if (!AUIPCTarget.getSymA() || AUIPCTarget.getSymB())
561     return false;
562 
563   const MCSymbolRefExpr *A = AUIPCTarget.getSymA();
564   const MCSymbol &SA = A->getSymbol();
565   if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined())
566     return false;
567 
568   auto *Writer = Asm.getWriterPtr();
569   if (!Writer)
570     return false;
571 
572   bool IsResolved = Writer->isSymbolRefDifferenceFullyResolvedImpl(
573       Asm, SA, *AUIPCDF, false, true);
574   if (!IsResolved)
575     return false;
576 
577   Value = Layout.getSymbolOffset(SA) + AUIPCTarget.getConstant();
578   Value -= Layout.getFragmentOffset(AUIPCDF) + AUIPCFixup->getOffset();
579 
580   if (shouldForceRelocation(Asm, *AUIPCFixup, AUIPCTarget, STI)) {
581     WasForced = true;
582     return false;
583   }
584 
585   return true;
586 }
587 
handleAddSubRelocations(const MCAsmLayout & Layout,const MCFragment & F,const MCFixup & Fixup,const MCValue & Target,uint64_t & FixedValue) const588 bool RISCVAsmBackend::handleAddSubRelocations(const MCAsmLayout &Layout,
589                                               const MCFragment &F,
590                                               const MCFixup &Fixup,
591                                               const MCValue &Target,
592                                               uint64_t &FixedValue) const {
593   uint64_t FixedValueA, FixedValueB;
594   unsigned TA = 0, TB = 0;
595   switch (Fixup.getKind()) {
596   case llvm::FK_Data_1:
597     TA = ELF::R_RISCV_ADD8;
598     TB = ELF::R_RISCV_SUB8;
599     break;
600   case llvm::FK_Data_2:
601     TA = ELF::R_RISCV_ADD16;
602     TB = ELF::R_RISCV_SUB16;
603     break;
604   case llvm::FK_Data_4:
605     TA = ELF::R_RISCV_ADD32;
606     TB = ELF::R_RISCV_SUB32;
607     break;
608   case llvm::FK_Data_8:
609     TA = ELF::R_RISCV_ADD64;
610     TB = ELF::R_RISCV_SUB64;
611     break;
612   case llvm::FK_Data_leb128:
613     TA = ELF::R_RISCV_SET_ULEB128;
614     TB = ELF::R_RISCV_SUB_ULEB128;
615     break;
616   default:
617     llvm_unreachable("unsupported fixup size");
618   }
619   MCValue A = MCValue::get(Target.getSymA(), nullptr, Target.getConstant());
620   MCValue B = MCValue::get(Target.getSymB());
621   auto FA = MCFixup::create(
622       Fixup.getOffset(), nullptr,
623       static_cast<MCFixupKind>(FirstLiteralRelocationKind + TA));
624   auto FB = MCFixup::create(
625       Fixup.getOffset(), nullptr,
626       static_cast<MCFixupKind>(FirstLiteralRelocationKind + TB));
627   auto &Asm = Layout.getAssembler();
628   Asm.getWriter().recordRelocation(Asm, Layout, &F, FA, A, FixedValueA);
629   Asm.getWriter().recordRelocation(Asm, Layout, &F, FB, B, FixedValueB);
630   FixedValue = FixedValueA - FixedValueB;
631   return true;
632 }
633 
applyFixup(const MCAssembler & Asm,const MCFixup & Fixup,const MCValue & Target,MutableArrayRef<char> Data,uint64_t Value,bool IsResolved,const MCSubtargetInfo * STI) const634 void RISCVAsmBackend::applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
635                                  const MCValue &Target,
636                                  MutableArrayRef<char> Data, uint64_t Value,
637                                  bool IsResolved,
638                                  const MCSubtargetInfo *STI) const {
639   MCFixupKind Kind = Fixup.getKind();
640   if (Kind >= FirstLiteralRelocationKind)
641     return;
642   MCContext &Ctx = Asm.getContext();
643   MCFixupKindInfo Info = getFixupKindInfo(Kind);
644   if (!Value)
645     return; // Doesn't change encoding.
646   // Apply any target-specific value adjustments.
647   Value = adjustFixupValue(Fixup, Value, Ctx);
648 
649   // Shift the value into position.
650   Value <<= Info.TargetOffset;
651 
652   unsigned Offset = Fixup.getOffset();
653   unsigned NumBytes = alignTo(Info.TargetSize + Info.TargetOffset, 8) / 8;
654 
655   assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
656 
657   // For each byte of the fragment that the fixup touches, mask in the
658   // bits from the fixup value.
659   for (unsigned i = 0; i != NumBytes; ++i) {
660     Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
661   }
662 }
663 
664 // Linker relaxation may change code size. We have to insert Nops
665 // for .align directive when linker relaxation enabled. So then Linker
666 // could satisfy alignment by removing Nops.
667 // The function return the total Nops Size we need to insert.
shouldInsertExtraNopBytesForCodeAlign(const MCAlignFragment & AF,unsigned & Size)668 bool RISCVAsmBackend::shouldInsertExtraNopBytesForCodeAlign(
669     const MCAlignFragment &AF, unsigned &Size) {
670   // Calculate Nops Size only when linker relaxation enabled.
671   const MCSubtargetInfo *STI = AF.getSubtargetInfo();
672   if (!STI->hasFeature(RISCV::FeatureRelax))
673     return false;
674 
675   bool UseCompressedNop = STI->hasFeature(RISCV::FeatureStdExtC) ||
676                           STI->hasFeature(RISCV::FeatureStdExtZca);
677   unsigned MinNopLen = UseCompressedNop ? 2 : 4;
678 
679   if (AF.getAlignment() <= MinNopLen) {
680     return false;
681   } else {
682     Size = AF.getAlignment().value() - MinNopLen;
683     return true;
684   }
685 }
686 
687 // We need to insert R_RISCV_ALIGN relocation type to indicate the
688 // position of Nops and the total bytes of the Nops have been inserted
689 // when linker relaxation enabled.
690 // The function insert fixup_riscv_align fixup which eventually will
691 // transfer to R_RISCV_ALIGN relocation type.
shouldInsertFixupForCodeAlign(MCAssembler & Asm,const MCAsmLayout & Layout,MCAlignFragment & AF)692 bool RISCVAsmBackend::shouldInsertFixupForCodeAlign(MCAssembler &Asm,
693                                                     const MCAsmLayout &Layout,
694                                                     MCAlignFragment &AF) {
695   // Insert the fixup only when linker relaxation enabled.
696   const MCSubtargetInfo *STI = AF.getSubtargetInfo();
697   if (!STI->hasFeature(RISCV::FeatureRelax))
698     return false;
699 
700   // Calculate total Nops we need to insert. If there are none to insert
701   // then simply return.
702   unsigned Count;
703   if (!shouldInsertExtraNopBytesForCodeAlign(AF, Count) || (Count == 0))
704     return false;
705 
706   MCContext &Ctx = Asm.getContext();
707   const MCExpr *Dummy = MCConstantExpr::create(0, Ctx);
708   // Create fixup_riscv_align fixup.
709   MCFixup Fixup =
710       MCFixup::create(0, Dummy, MCFixupKind(RISCV::fixup_riscv_align), SMLoc());
711 
712   uint64_t FixedValue = 0;
713   MCValue NopBytes = MCValue::get(Count);
714 
715   Asm.getWriter().recordRelocation(Asm, Layout, &AF, Fixup, NopBytes,
716                                    FixedValue);
717 
718   return true;
719 }
720 
721 std::unique_ptr<MCObjectTargetWriter>
createObjectTargetWriter() const722 RISCVAsmBackend::createObjectTargetWriter() const {
723   return createRISCVELFObjectWriter(OSABI, Is64Bit);
724 }
725 
createRISCVAsmBackend(const Target & T,const MCSubtargetInfo & STI,const MCRegisterInfo & MRI,const MCTargetOptions & Options)726 MCAsmBackend *llvm::createRISCVAsmBackend(const Target &T,
727                                           const MCSubtargetInfo &STI,
728                                           const MCRegisterInfo &MRI,
729                                           const MCTargetOptions &Options) {
730   const Triple &TT = STI.getTargetTriple();
731   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TT.getOS());
732   return new RISCVAsmBackend(STI, OSABI, TT.isArch64Bit(), Options);
733 }
734