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