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