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/MCAsmLayout.h"
13 #include "llvm/MC/MCAssembler.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCDirectives.h"
16 #include "llvm/MC/MCELFObjectWriter.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCObjectWriter.h"
19 #include "llvm/MC/MCSymbol.h"
20 #include "llvm/MC/MCValue.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h"
23
24 using namespace llvm;
25
getFixupKind(StringRef Name) const26 Optional<MCFixupKind> RISCVAsmBackend::getFixupKind(StringRef Name) const {
27 if (STI.getTargetTriple().isOSBinFormatELF()) {
28 unsigned Type;
29 Type = llvm::StringSwitch<unsigned>(Name)
30 #define ELF_RELOC(X, Y) .Case(#X, Y)
31 #include "llvm/BinaryFormat/ELFRelocs/RISCV.def"
32 #undef ELF_RELOC
33 .Case("BFD_RELOC_NONE", ELF::R_RISCV_NONE)
34 .Case("BFD_RELOC_32", ELF::R_RISCV_32)
35 .Case("BFD_RELOC_64", ELF::R_RISCV_64)
36 .Default(-1u);
37 if (Type != -1u)
38 return static_cast<MCFixupKind>(FirstLiteralRelocationKind + Type);
39 }
40 return None;
41 }
42
43 const MCFixupKindInfo &
getFixupKindInfo(MCFixupKind Kind) const44 RISCVAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
45 const static MCFixupKindInfo Infos[] = {
46 // This table *must* be in the order that the fixup_* kinds are defined in
47 // RISCVFixupKinds.h.
48 //
49 // name offset bits flags
50 {"fixup_riscv_hi20", 12, 20, 0},
51 {"fixup_riscv_lo12_i", 20, 12, 0},
52 {"fixup_riscv_lo12_s", 0, 32, 0},
53 {"fixup_riscv_pcrel_hi20", 12, 20,
54 MCFixupKindInfo::FKF_IsPCRel | MCFixupKindInfo::FKF_IsTarget},
55 {"fixup_riscv_pcrel_lo12_i", 20, 12,
56 MCFixupKindInfo::FKF_IsPCRel | MCFixupKindInfo::FKF_IsTarget},
57 {"fixup_riscv_pcrel_lo12_s", 0, 32,
58 MCFixupKindInfo::FKF_IsPCRel | MCFixupKindInfo::FKF_IsTarget},
59 {"fixup_riscv_got_hi20", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
60 {"fixup_riscv_tprel_hi20", 12, 20, 0},
61 {"fixup_riscv_tprel_lo12_i", 20, 12, 0},
62 {"fixup_riscv_tprel_lo12_s", 0, 32, 0},
63 {"fixup_riscv_tprel_add", 0, 0, 0},
64 {"fixup_riscv_tls_got_hi20", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
65 {"fixup_riscv_tls_gd_hi20", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
66 {"fixup_riscv_jal", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
67 {"fixup_riscv_branch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
68 {"fixup_riscv_rvc_jump", 2, 11, MCFixupKindInfo::FKF_IsPCRel},
69 {"fixup_riscv_rvc_branch", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
70 {"fixup_riscv_call", 0, 64, MCFixupKindInfo::FKF_IsPCRel},
71 {"fixup_riscv_call_plt", 0, 64, MCFixupKindInfo::FKF_IsPCRel},
72 {"fixup_riscv_relax", 0, 0, 0},
73 {"fixup_riscv_align", 0, 0, 0}};
74 static_assert((array_lengthof(Infos)) == RISCV::NumTargetFixupKinds,
75 "Not all fixup kinds added to Infos array");
76
77 // Fixup kinds from .reloc directive are like R_RISCV_NONE. They
78 // do not require any extra processing.
79 if (Kind >= FirstLiteralRelocationKind)
80 return MCAsmBackend::getFixupKindInfo(FK_NONE);
81
82 if (Kind < FirstTargetFixupKind)
83 return MCAsmBackend::getFixupKindInfo(Kind);
84
85 assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
86 "Invalid kind!");
87 return Infos[Kind - FirstTargetFixupKind];
88 }
89
90 // If linker relaxation is enabled, or the relax option had previously been
91 // enabled, always emit relocations even if the fixup can be resolved. This is
92 // necessary for correctness as offsets may change during relaxation.
shouldForceRelocation(const MCAssembler & Asm,const MCFixup & Fixup,const MCValue & Target)93 bool RISCVAsmBackend::shouldForceRelocation(const MCAssembler &Asm,
94 const MCFixup &Fixup,
95 const MCValue &Target) {
96 if (Fixup.getKind() >= FirstLiteralRelocationKind)
97 return true;
98 switch (Fixup.getTargetKind()) {
99 default:
100 break;
101 case FK_Data_1:
102 case FK_Data_2:
103 case FK_Data_4:
104 case FK_Data_8:
105 if (Target.isAbsolute())
106 return false;
107 break;
108 case RISCV::fixup_riscv_got_hi20:
109 case RISCV::fixup_riscv_tls_got_hi20:
110 case RISCV::fixup_riscv_tls_gd_hi20:
111 return true;
112 }
113
114 return STI.getFeatureBits()[RISCV::FeatureRelax] || ForceRelocs;
115 }
116
fixupNeedsRelaxationAdvanced(const MCFixup & Fixup,bool Resolved,uint64_t Value,const MCRelaxableFragment * DF,const MCAsmLayout & Layout,const bool WasForced) const117 bool RISCVAsmBackend::fixupNeedsRelaxationAdvanced(const MCFixup &Fixup,
118 bool Resolved,
119 uint64_t Value,
120 const MCRelaxableFragment *DF,
121 const MCAsmLayout &Layout,
122 const bool WasForced) const {
123 // Return true if the symbol is actually unresolved.
124 // Resolved could be always false when shouldForceRelocation return true.
125 // We use !WasForced to indicate that the symbol is unresolved and not forced
126 // by shouldForceRelocation.
127 if (!Resolved && !WasForced)
128 return true;
129
130 int64_t Offset = int64_t(Value);
131 switch (Fixup.getTargetKind()) {
132 default:
133 return false;
134 case RISCV::fixup_riscv_rvc_branch:
135 // For compressed branch instructions the immediate must be
136 // in the range [-256, 254].
137 return Offset > 254 || Offset < -256;
138 case RISCV::fixup_riscv_rvc_jump:
139 // For compressed jump instructions the immediate must be
140 // in the range [-2048, 2046].
141 return Offset > 2046 || Offset < -2048;
142 }
143 }
144
relaxInstruction(MCInst & Inst,const MCSubtargetInfo & STI) const145 void RISCVAsmBackend::relaxInstruction(MCInst &Inst,
146 const MCSubtargetInfo &STI) const {
147 // TODO: replace this with call to auto generated uncompressinstr() function.
148 MCInst Res;
149 switch (Inst.getOpcode()) {
150 default:
151 llvm_unreachable("Opcode not expected!");
152 case RISCV::C_BEQZ:
153 // c.beqz $rs1, $imm -> beq $rs1, X0, $imm.
154 Res.setOpcode(RISCV::BEQ);
155 Res.addOperand(Inst.getOperand(0));
156 Res.addOperand(MCOperand::createReg(RISCV::X0));
157 Res.addOperand(Inst.getOperand(1));
158 break;
159 case RISCV::C_BNEZ:
160 // c.bnez $rs1, $imm -> bne $rs1, X0, $imm.
161 Res.setOpcode(RISCV::BNE);
162 Res.addOperand(Inst.getOperand(0));
163 Res.addOperand(MCOperand::createReg(RISCV::X0));
164 Res.addOperand(Inst.getOperand(1));
165 break;
166 case RISCV::C_J:
167 // c.j $imm -> jal X0, $imm.
168 Res.setOpcode(RISCV::JAL);
169 Res.addOperand(MCOperand::createReg(RISCV::X0));
170 Res.addOperand(Inst.getOperand(0));
171 break;
172 case RISCV::C_JAL:
173 // c.jal $imm -> jal X1, $imm.
174 Res.setOpcode(RISCV::JAL);
175 Res.addOperand(MCOperand::createReg(RISCV::X1));
176 Res.addOperand(Inst.getOperand(0));
177 break;
178 }
179 Inst = std::move(Res);
180 }
181
182 // Given a compressed control flow instruction this function returns
183 // the expanded instruction.
getRelaxedOpcode(unsigned Op) const184 unsigned RISCVAsmBackend::getRelaxedOpcode(unsigned Op) const {
185 switch (Op) {
186 default:
187 return Op;
188 case RISCV::C_BEQZ:
189 return RISCV::BEQ;
190 case RISCV::C_BNEZ:
191 return RISCV::BNE;
192 case RISCV::C_J:
193 case RISCV::C_JAL: // fall through.
194 return RISCV::JAL;
195 }
196 }
197
mayNeedRelaxation(const MCInst & Inst,const MCSubtargetInfo & STI) const198 bool RISCVAsmBackend::mayNeedRelaxation(const MCInst &Inst,
199 const MCSubtargetInfo &STI) const {
200 return getRelaxedOpcode(Inst.getOpcode()) != Inst.getOpcode();
201 }
202
writeNopData(raw_ostream & OS,uint64_t Count) const203 bool RISCVAsmBackend::writeNopData(raw_ostream &OS, uint64_t Count) const {
204 bool HasStdExtC = STI.getFeatureBits()[RISCV::FeatureStdExtC];
205 unsigned MinNopLen = HasStdExtC ? 2 : 4;
206
207 if ((Count % MinNopLen) != 0)
208 return false;
209
210 // The canonical nop on RISC-V is addi x0, x0, 0.
211 for (; Count >= 4; Count -= 4)
212 OS.write("\x13\0\0\0", 4);
213
214 // The canonical nop on RVC is c.nop.
215 if (Count && HasStdExtC)
216 OS.write("\x01\0", 2);
217
218 return true;
219 }
220
adjustFixupValue(const MCFixup & Fixup,uint64_t Value,MCContext & Ctx)221 static uint64_t adjustFixupValue(const MCFixup &Fixup, uint64_t Value,
222 MCContext &Ctx) {
223 switch (Fixup.getTargetKind()) {
224 default:
225 llvm_unreachable("Unknown fixup kind!");
226 case RISCV::fixup_riscv_got_hi20:
227 case RISCV::fixup_riscv_tls_got_hi20:
228 case RISCV::fixup_riscv_tls_gd_hi20:
229 llvm_unreachable("Relocation should be unconditionally forced\n");
230 case FK_Data_1:
231 case FK_Data_2:
232 case FK_Data_4:
233 case FK_Data_8:
234 case FK_Data_6b:
235 return Value;
236 case RISCV::fixup_riscv_lo12_i:
237 case RISCV::fixup_riscv_pcrel_lo12_i:
238 case RISCV::fixup_riscv_tprel_lo12_i:
239 return Value & 0xfff;
240 case RISCV::fixup_riscv_lo12_s:
241 case RISCV::fixup_riscv_pcrel_lo12_s:
242 case RISCV::fixup_riscv_tprel_lo12_s:
243 return (((Value >> 5) & 0x7f) << 25) | ((Value & 0x1f) << 7);
244 case RISCV::fixup_riscv_hi20:
245 case RISCV::fixup_riscv_pcrel_hi20:
246 case RISCV::fixup_riscv_tprel_hi20:
247 // Add 1 if bit 11 is 1, to compensate for low 12 bits being negative.
248 return ((Value + 0x800) >> 12) & 0xfffff;
249 case RISCV::fixup_riscv_jal: {
250 if (!isInt<21>(Value))
251 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
252 if (Value & 0x1)
253 Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
254 // Need to produce imm[19|10:1|11|19:12] from the 21-bit Value.
255 unsigned Sbit = (Value >> 20) & 0x1;
256 unsigned Hi8 = (Value >> 12) & 0xff;
257 unsigned Mid1 = (Value >> 11) & 0x1;
258 unsigned Lo10 = (Value >> 1) & 0x3ff;
259 // Inst{31} = Sbit;
260 // Inst{30-21} = Lo10;
261 // Inst{20} = Mid1;
262 // Inst{19-12} = Hi8;
263 Value = (Sbit << 19) | (Lo10 << 9) | (Mid1 << 8) | Hi8;
264 return Value;
265 }
266 case RISCV::fixup_riscv_branch: {
267 if (!isInt<13>(Value))
268 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
269 if (Value & 0x1)
270 Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
271 // Need to extract imm[12], imm[10:5], imm[4:1], imm[11] from the 13-bit
272 // Value.
273 unsigned Sbit = (Value >> 12) & 0x1;
274 unsigned Hi1 = (Value >> 11) & 0x1;
275 unsigned Mid6 = (Value >> 5) & 0x3f;
276 unsigned Lo4 = (Value >> 1) & 0xf;
277 // Inst{31} = Sbit;
278 // Inst{30-25} = Mid6;
279 // Inst{11-8} = Lo4;
280 // Inst{7} = Hi1;
281 Value = (Sbit << 31) | (Mid6 << 25) | (Lo4 << 8) | (Hi1 << 7);
282 return Value;
283 }
284 case RISCV::fixup_riscv_call:
285 case RISCV::fixup_riscv_call_plt: {
286 // Jalr will add UpperImm with the sign-extended 12-bit LowerImm,
287 // we need to add 0x800ULL before extract upper bits to reflect the
288 // effect of the sign extension.
289 uint64_t UpperImm = (Value + 0x800ULL) & 0xfffff000ULL;
290 uint64_t LowerImm = Value & 0xfffULL;
291 return UpperImm | ((LowerImm << 20) << 32);
292 }
293 case RISCV::fixup_riscv_rvc_jump: {
294 // Need to produce offset[11|4|9:8|10|6|7|3:1|5] from the 11-bit Value.
295 unsigned Bit11 = (Value >> 11) & 0x1;
296 unsigned Bit4 = (Value >> 4) & 0x1;
297 unsigned Bit9_8 = (Value >> 8) & 0x3;
298 unsigned Bit10 = (Value >> 10) & 0x1;
299 unsigned Bit6 = (Value >> 6) & 0x1;
300 unsigned Bit7 = (Value >> 7) & 0x1;
301 unsigned Bit3_1 = (Value >> 1) & 0x7;
302 unsigned Bit5 = (Value >> 5) & 0x1;
303 Value = (Bit11 << 10) | (Bit4 << 9) | (Bit9_8 << 7) | (Bit10 << 6) |
304 (Bit6 << 5) | (Bit7 << 4) | (Bit3_1 << 1) | Bit5;
305 return Value;
306 }
307 case RISCV::fixup_riscv_rvc_branch: {
308 // Need to produce offset[8|4:3], [reg 3 bit], offset[7:6|2:1|5]
309 unsigned Bit8 = (Value >> 8) & 0x1;
310 unsigned Bit7_6 = (Value >> 6) & 0x3;
311 unsigned Bit5 = (Value >> 5) & 0x1;
312 unsigned Bit4_3 = (Value >> 3) & 0x3;
313 unsigned Bit2_1 = (Value >> 1) & 0x3;
314 Value = (Bit8 << 12) | (Bit4_3 << 10) | (Bit7_6 << 5) | (Bit2_1 << 3) |
315 (Bit5 << 2);
316 return Value;
317 }
318
319 }
320 }
321
evaluateTargetFixup(const MCAssembler & Asm,const MCAsmLayout & Layout,const MCFixup & Fixup,const MCFragment * DF,const MCValue & Target,uint64_t & Value,bool & WasForced)322 bool RISCVAsmBackend::evaluateTargetFixup(
323 const MCAssembler &Asm, const MCAsmLayout &Layout, const MCFixup &Fixup,
324 const MCFragment *DF, const MCValue &Target, uint64_t &Value,
325 bool &WasForced) {
326 const MCFixup *AUIPCFixup;
327 const MCFragment *AUIPCDF;
328 MCValue AUIPCTarget;
329 switch (Fixup.getTargetKind()) {
330 default:
331 llvm_unreachable("Unexpected fixup kind!");
332 case RISCV::fixup_riscv_pcrel_hi20:
333 AUIPCFixup = &Fixup;
334 AUIPCDF = DF;
335 AUIPCTarget = Target;
336 break;
337 case RISCV::fixup_riscv_pcrel_lo12_i:
338 case RISCV::fixup_riscv_pcrel_lo12_s: {
339 AUIPCFixup = cast<RISCVMCExpr>(Fixup.getValue())->getPCRelHiFixup(&AUIPCDF);
340 if (!AUIPCFixup) {
341 Asm.getContext().reportError(Fixup.getLoc(),
342 "could not find corresponding %pcrel_hi");
343 return true;
344 }
345
346 // MCAssembler::evaluateFixup will emit an error for this case when it sees
347 // the %pcrel_hi, so don't duplicate it when also seeing the %pcrel_lo.
348 const MCExpr *AUIPCExpr = AUIPCFixup->getValue();
349 if (!AUIPCExpr->evaluateAsRelocatable(AUIPCTarget, &Layout, AUIPCFixup))
350 return true;
351 break;
352 }
353 }
354
355 if (!AUIPCTarget.getSymA() || AUIPCTarget.getSymB())
356 return false;
357
358 const MCSymbolRefExpr *A = AUIPCTarget.getSymA();
359 const MCSymbol &SA = A->getSymbol();
360 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined())
361 return false;
362
363 auto *Writer = Asm.getWriterPtr();
364 if (!Writer)
365 return false;
366
367 bool IsResolved = Writer->isSymbolRefDifferenceFullyResolvedImpl(
368 Asm, SA, *AUIPCDF, false, true);
369 if (!IsResolved)
370 return false;
371
372 Value = Layout.getSymbolOffset(SA) + AUIPCTarget.getConstant();
373 Value -= Layout.getFragmentOffset(AUIPCDF) + AUIPCFixup->getOffset();
374
375 if (shouldForceRelocation(Asm, *AUIPCFixup, AUIPCTarget)) {
376 WasForced = true;
377 return false;
378 }
379
380 return true;
381 }
382
applyFixup(const MCAssembler & Asm,const MCFixup & Fixup,const MCValue & Target,MutableArrayRef<char> Data,uint64_t Value,bool IsResolved,const MCSubtargetInfo * STI) const383 void RISCVAsmBackend::applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
384 const MCValue &Target,
385 MutableArrayRef<char> Data, uint64_t Value,
386 bool IsResolved,
387 const MCSubtargetInfo *STI) const {
388 MCFixupKind Kind = Fixup.getKind();
389 if (Kind >= FirstLiteralRelocationKind)
390 return;
391 MCContext &Ctx = Asm.getContext();
392 MCFixupKindInfo Info = getFixupKindInfo(Kind);
393 if (!Value)
394 return; // Doesn't change encoding.
395 // Apply any target-specific value adjustments.
396 Value = adjustFixupValue(Fixup, Value, Ctx);
397
398 // Shift the value into position.
399 Value <<= Info.TargetOffset;
400
401 unsigned Offset = Fixup.getOffset();
402 unsigned NumBytes = alignTo(Info.TargetSize + Info.TargetOffset, 8) / 8;
403
404 assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
405
406 // For each byte of the fragment that the fixup touches, mask in the
407 // bits from the fixup value.
408 for (unsigned i = 0; i != NumBytes; ++i) {
409 Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
410 }
411 }
412
413 // Linker relaxation may change code size. We have to insert Nops
414 // for .align directive when linker relaxation enabled. So then Linker
415 // could satisfy alignment by removing Nops.
416 // The function return the total Nops Size we need to insert.
shouldInsertExtraNopBytesForCodeAlign(const MCAlignFragment & AF,unsigned & Size)417 bool RISCVAsmBackend::shouldInsertExtraNopBytesForCodeAlign(
418 const MCAlignFragment &AF, unsigned &Size) {
419 // Calculate Nops Size only when linker relaxation enabled.
420 if (!STI.getFeatureBits()[RISCV::FeatureRelax])
421 return false;
422
423 bool HasStdExtC = STI.getFeatureBits()[RISCV::FeatureStdExtC];
424 unsigned MinNopLen = HasStdExtC ? 2 : 4;
425
426 if (AF.getAlignment() <= MinNopLen) {
427 return false;
428 } else {
429 Size = AF.getAlignment() - MinNopLen;
430 return true;
431 }
432 }
433
434 // We need to insert R_RISCV_ALIGN relocation type to indicate the
435 // position of Nops and the total bytes of the Nops have been inserted
436 // when linker relaxation enabled.
437 // The function insert fixup_riscv_align fixup which eventually will
438 // transfer to R_RISCV_ALIGN relocation type.
shouldInsertFixupForCodeAlign(MCAssembler & Asm,const MCAsmLayout & Layout,MCAlignFragment & AF)439 bool RISCVAsmBackend::shouldInsertFixupForCodeAlign(MCAssembler &Asm,
440 const MCAsmLayout &Layout,
441 MCAlignFragment &AF) {
442 // Insert the fixup only when linker relaxation enabled.
443 if (!STI.getFeatureBits()[RISCV::FeatureRelax])
444 return false;
445
446 // Calculate total Nops we need to insert. If there are none to insert
447 // then simply return.
448 unsigned Count;
449 if (!shouldInsertExtraNopBytesForCodeAlign(AF, Count) || (Count == 0))
450 return false;
451
452 MCContext &Ctx = Asm.getContext();
453 const MCExpr *Dummy = MCConstantExpr::create(0, Ctx);
454 // Create fixup_riscv_align fixup.
455 MCFixup Fixup =
456 MCFixup::create(0, Dummy, MCFixupKind(RISCV::fixup_riscv_align), SMLoc());
457
458 uint64_t FixedValue = 0;
459 MCValue NopBytes = MCValue::get(Count);
460
461 Asm.getWriter().recordRelocation(Asm, Layout, &AF, Fixup, NopBytes,
462 FixedValue);
463
464 return true;
465 }
466
467 std::unique_ptr<MCObjectTargetWriter>
createObjectTargetWriter() const468 RISCVAsmBackend::createObjectTargetWriter() const {
469 return createRISCVELFObjectWriter(OSABI, Is64Bit);
470 }
471
createRISCVAsmBackend(const Target & T,const MCSubtargetInfo & STI,const MCRegisterInfo & MRI,const MCTargetOptions & Options)472 MCAsmBackend *llvm::createRISCVAsmBackend(const Target &T,
473 const MCSubtargetInfo &STI,
474 const MCRegisterInfo &MRI,
475 const MCTargetOptions &Options) {
476 const Triple &TT = STI.getTargetTriple();
477 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TT.getOS());
478 return new RISCVAsmBackend(STI, OSABI, TT.isArch64Bit(), Options);
479 }
480