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,
356                                    const MCSubtargetInfo *STI) const {
357   bool HasStdExtC = STI->getFeatureBits()[RISCV::FeatureStdExtC];
358   unsigned MinNopLen = HasStdExtC ? 2 : 4;
359 
360   if ((Count % MinNopLen) != 0)
361     return false;
362 
363   // The canonical nop on RISC-V is addi x0, x0, 0.
364   for (; Count >= 4; Count -= 4)
365     OS.write("\x13\0\0\0", 4);
366 
367   // The canonical nop on RVC is c.nop.
368   if (Count && HasStdExtC)
369     OS.write("\x01\0", 2);
370 
371   return true;
372 }
373 
374 static uint64_t adjustFixupValue(const MCFixup &Fixup, uint64_t Value,
375                                  MCContext &Ctx) {
376   switch (Fixup.getTargetKind()) {
377   default:
378     llvm_unreachable("Unknown fixup kind!");
379   case RISCV::fixup_riscv_got_hi20:
380   case RISCV::fixup_riscv_tls_got_hi20:
381   case RISCV::fixup_riscv_tls_gd_hi20:
382     llvm_unreachable("Relocation should be unconditionally forced\n");
383   case RISCV::fixup_riscv_set_8:
384   case RISCV::fixup_riscv_add_8:
385   case RISCV::fixup_riscv_sub_8:
386   case RISCV::fixup_riscv_set_16:
387   case RISCV::fixup_riscv_add_16:
388   case RISCV::fixup_riscv_sub_16:
389   case RISCV::fixup_riscv_set_32:
390   case RISCV::fixup_riscv_add_32:
391   case RISCV::fixup_riscv_sub_32:
392   case RISCV::fixup_riscv_add_64:
393   case RISCV::fixup_riscv_sub_64:
394   case FK_Data_1:
395   case FK_Data_2:
396   case FK_Data_4:
397   case FK_Data_8:
398   case FK_Data_6b:
399     return Value;
400   case RISCV::fixup_riscv_set_6b:
401     return Value & 0x03;
402   case RISCV::fixup_riscv_lo12_i:
403   case RISCV::fixup_riscv_pcrel_lo12_i:
404   case RISCV::fixup_riscv_tprel_lo12_i:
405     return Value & 0xfff;
406   case RISCV::fixup_riscv_lo12_s:
407   case RISCV::fixup_riscv_pcrel_lo12_s:
408   case RISCV::fixup_riscv_tprel_lo12_s:
409     return (((Value >> 5) & 0x7f) << 25) | ((Value & 0x1f) << 7);
410   case RISCV::fixup_riscv_hi20:
411   case RISCV::fixup_riscv_pcrel_hi20:
412   case RISCV::fixup_riscv_tprel_hi20:
413     // Add 1 if bit 11 is 1, to compensate for low 12 bits being negative.
414     return ((Value + 0x800) >> 12) & 0xfffff;
415   case RISCV::fixup_riscv_jal: {
416     if (!isInt<21>(Value))
417       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
418     if (Value & 0x1)
419       Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
420     // Need to produce imm[19|10:1|11|19:12] from the 21-bit Value.
421     unsigned Sbit = (Value >> 20) & 0x1;
422     unsigned Hi8 = (Value >> 12) & 0xff;
423     unsigned Mid1 = (Value >> 11) & 0x1;
424     unsigned Lo10 = (Value >> 1) & 0x3ff;
425     // Inst{31} = Sbit;
426     // Inst{30-21} = Lo10;
427     // Inst{20} = Mid1;
428     // Inst{19-12} = Hi8;
429     Value = (Sbit << 19) | (Lo10 << 9) | (Mid1 << 8) | Hi8;
430     return Value;
431   }
432   case RISCV::fixup_riscv_branch: {
433     if (!isInt<13>(Value))
434       Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
435     if (Value & 0x1)
436       Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
437     // Need to extract imm[12], imm[10:5], imm[4:1], imm[11] from the 13-bit
438     // Value.
439     unsigned Sbit = (Value >> 12) & 0x1;
440     unsigned Hi1 = (Value >> 11) & 0x1;
441     unsigned Mid6 = (Value >> 5) & 0x3f;
442     unsigned Lo4 = (Value >> 1) & 0xf;
443     // Inst{31} = Sbit;
444     // Inst{30-25} = Mid6;
445     // Inst{11-8} = Lo4;
446     // Inst{7} = Hi1;
447     Value = (Sbit << 31) | (Mid6 << 25) | (Lo4 << 8) | (Hi1 << 7);
448     return Value;
449   }
450   case RISCV::fixup_riscv_call:
451   case RISCV::fixup_riscv_call_plt: {
452     // Jalr will add UpperImm with the sign-extended 12-bit LowerImm,
453     // we need to add 0x800ULL before extract upper bits to reflect the
454     // effect of the sign extension.
455     uint64_t UpperImm = (Value + 0x800ULL) & 0xfffff000ULL;
456     uint64_t LowerImm = Value & 0xfffULL;
457     return UpperImm | ((LowerImm << 20) << 32);
458   }
459   case RISCV::fixup_riscv_rvc_jump: {
460     // Need to produce offset[11|4|9:8|10|6|7|3:1|5] from the 11-bit Value.
461     unsigned Bit11  = (Value >> 11) & 0x1;
462     unsigned Bit4   = (Value >> 4) & 0x1;
463     unsigned Bit9_8 = (Value >> 8) & 0x3;
464     unsigned Bit10  = (Value >> 10) & 0x1;
465     unsigned Bit6   = (Value >> 6) & 0x1;
466     unsigned Bit7   = (Value >> 7) & 0x1;
467     unsigned Bit3_1 = (Value >> 1) & 0x7;
468     unsigned Bit5   = (Value >> 5) & 0x1;
469     Value = (Bit11 << 10) | (Bit4 << 9) | (Bit9_8 << 7) | (Bit10 << 6) |
470             (Bit6 << 5) | (Bit7 << 4) | (Bit3_1 << 1) | Bit5;
471     return Value;
472   }
473   case RISCV::fixup_riscv_rvc_branch: {
474     // Need to produce offset[8|4:3], [reg 3 bit], offset[7:6|2:1|5]
475     unsigned Bit8   = (Value >> 8) & 0x1;
476     unsigned Bit7_6 = (Value >> 6) & 0x3;
477     unsigned Bit5   = (Value >> 5) & 0x1;
478     unsigned Bit4_3 = (Value >> 3) & 0x3;
479     unsigned Bit2_1 = (Value >> 1) & 0x3;
480     Value = (Bit8 << 12) | (Bit4_3 << 10) | (Bit7_6 << 5) | (Bit2_1 << 3) |
481             (Bit5 << 2);
482     return Value;
483   }
484 
485   }
486 }
487 
488 bool RISCVAsmBackend::evaluateTargetFixup(
489     const MCAssembler &Asm, const MCAsmLayout &Layout, const MCFixup &Fixup,
490     const MCFragment *DF, const MCValue &Target, uint64_t &Value,
491     bool &WasForced) {
492   const MCFixup *AUIPCFixup;
493   const MCFragment *AUIPCDF;
494   MCValue AUIPCTarget;
495   switch (Fixup.getTargetKind()) {
496   default:
497     llvm_unreachable("Unexpected fixup kind!");
498   case RISCV::fixup_riscv_pcrel_hi20:
499     AUIPCFixup = &Fixup;
500     AUIPCDF = DF;
501     AUIPCTarget = Target;
502     break;
503   case RISCV::fixup_riscv_pcrel_lo12_i:
504   case RISCV::fixup_riscv_pcrel_lo12_s: {
505     AUIPCFixup = cast<RISCVMCExpr>(Fixup.getValue())->getPCRelHiFixup(&AUIPCDF);
506     if (!AUIPCFixup) {
507       Asm.getContext().reportError(Fixup.getLoc(),
508                                    "could not find corresponding %pcrel_hi");
509       return true;
510     }
511 
512     // MCAssembler::evaluateFixup will emit an error for this case when it sees
513     // the %pcrel_hi, so don't duplicate it when also seeing the %pcrel_lo.
514     const MCExpr *AUIPCExpr = AUIPCFixup->getValue();
515     if (!AUIPCExpr->evaluateAsRelocatable(AUIPCTarget, &Layout, AUIPCFixup))
516       return true;
517     break;
518   }
519   }
520 
521   if (!AUIPCTarget.getSymA() || AUIPCTarget.getSymB())
522     return false;
523 
524   const MCSymbolRefExpr *A = AUIPCTarget.getSymA();
525   const MCSymbol &SA = A->getSymbol();
526   if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined())
527     return false;
528 
529   auto *Writer = Asm.getWriterPtr();
530   if (!Writer)
531     return false;
532 
533   bool IsResolved = Writer->isSymbolRefDifferenceFullyResolvedImpl(
534       Asm, SA, *AUIPCDF, false, true);
535   if (!IsResolved)
536     return false;
537 
538   Value = Layout.getSymbolOffset(SA) + AUIPCTarget.getConstant();
539   Value -= Layout.getFragmentOffset(AUIPCDF) + AUIPCFixup->getOffset();
540 
541   if (shouldForceRelocation(Asm, *AUIPCFixup, AUIPCTarget)) {
542     WasForced = true;
543     return false;
544   }
545 
546   return true;
547 }
548 
549 void RISCVAsmBackend::applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
550                                  const MCValue &Target,
551                                  MutableArrayRef<char> Data, uint64_t Value,
552                                  bool IsResolved,
553                                  const MCSubtargetInfo *STI) const {
554   MCFixupKind Kind = Fixup.getKind();
555   if (Kind >= FirstLiteralRelocationKind)
556     return;
557   MCContext &Ctx = Asm.getContext();
558   MCFixupKindInfo Info = getFixupKindInfo(Kind);
559   if (!Value)
560     return; // Doesn't change encoding.
561   // Apply any target-specific value adjustments.
562   Value = adjustFixupValue(Fixup, Value, Ctx);
563 
564   // Shift the value into position.
565   Value <<= Info.TargetOffset;
566 
567   unsigned Offset = Fixup.getOffset();
568   unsigned NumBytes = alignTo(Info.TargetSize + Info.TargetOffset, 8) / 8;
569 
570   assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
571 
572   // For each byte of the fragment that the fixup touches, mask in the
573   // bits from the fixup value.
574   for (unsigned i = 0; i != NumBytes; ++i) {
575     Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
576   }
577 }
578 
579 // Linker relaxation may change code size. We have to insert Nops
580 // for .align directive when linker relaxation enabled. So then Linker
581 // could satisfy alignment by removing Nops.
582 // The function return the total Nops Size we need to insert.
583 bool RISCVAsmBackend::shouldInsertExtraNopBytesForCodeAlign(
584     const MCAlignFragment &AF, unsigned &Size) {
585   // Calculate Nops Size only when linker relaxation enabled.
586   const MCSubtargetInfo *STI = AF.getSubtargetInfo();
587   if (!STI->getFeatureBits()[RISCV::FeatureRelax])
588     return false;
589 
590   bool HasStdExtC = STI->getFeatureBits()[RISCV::FeatureStdExtC];
591   unsigned MinNopLen = HasStdExtC ? 2 : 4;
592 
593   if (AF.getAlignment() <= MinNopLen) {
594     return false;
595   } else {
596     Size = AF.getAlignment().value() - MinNopLen;
597     return true;
598   }
599 }
600 
601 // We need to insert R_RISCV_ALIGN relocation type to indicate the
602 // position of Nops and the total bytes of the Nops have been inserted
603 // when linker relaxation enabled.
604 // The function insert fixup_riscv_align fixup which eventually will
605 // transfer to R_RISCV_ALIGN relocation type.
606 bool RISCVAsmBackend::shouldInsertFixupForCodeAlign(MCAssembler &Asm,
607                                                     const MCAsmLayout &Layout,
608                                                     MCAlignFragment &AF) {
609   // Insert the fixup only when linker relaxation enabled.
610   const MCSubtargetInfo *STI = AF.getSubtargetInfo();
611   if (!STI->getFeatureBits()[RISCV::FeatureRelax])
612     return false;
613 
614   // Calculate total Nops we need to insert. If there are none to insert
615   // then simply return.
616   unsigned Count;
617   if (!shouldInsertExtraNopBytesForCodeAlign(AF, Count) || (Count == 0))
618     return false;
619 
620   MCContext &Ctx = Asm.getContext();
621   const MCExpr *Dummy = MCConstantExpr::create(0, Ctx);
622   // Create fixup_riscv_align fixup.
623   MCFixup Fixup =
624       MCFixup::create(0, Dummy, MCFixupKind(RISCV::fixup_riscv_align), SMLoc());
625 
626   uint64_t FixedValue = 0;
627   MCValue NopBytes = MCValue::get(Count);
628 
629   Asm.getWriter().recordRelocation(Asm, Layout, &AF, Fixup, NopBytes,
630                                    FixedValue);
631 
632   return true;
633 }
634 
635 std::unique_ptr<MCObjectTargetWriter>
636 RISCVAsmBackend::createObjectTargetWriter() const {
637   return createRISCVELFObjectWriter(OSABI, Is64Bit);
638 }
639 
640 MCAsmBackend *llvm::createRISCVAsmBackend(const Target &T,
641                                           const MCSubtargetInfo &STI,
642                                           const MCRegisterInfo &MRI,
643                                           const MCTargetOptions &Options) {
644   const Triple &TT = STI.getTargetTriple();
645   uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TT.getOS());
646   return new RISCVAsmBackend(STI, OSABI, TT.isArch64Bit(), Options);
647 }
648