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