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