LLVM 19.0.0git
RISCVAsmBackend.cpp
Go to the documentation of this file.
1//===-- RISCVAsmBackend.cpp - RISC-V 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/MCAssembler.h"
14#include "llvm/MC/MCContext.h"
17#include "llvm/MC/MCExpr.h"
19#include "llvm/MC/MCSymbol.h"
20#include "llvm/MC/MCValue.h"
22#include "llvm/Support/Endian.h"
25#include "llvm/Support/LEB128.h"
27
28using namespace llvm;
29
30static cl::opt<bool> RelaxBranches("riscv-asm-relax-branches", cl::init(true),
32// Temporary workaround for old linkers that do not support ULEB128 relocations,
33// which are abused by DWARF v5 DW_LLE_offset_pair/DW_RLE_offset_pair
34// implemented in Clang/LLVM.
36 "riscv-uleb128-reloc", cl::init(true), cl::Hidden,
37 cl::desc("Emit R_RISCV_SET_ULEB128/E_RISCV_SUB_ULEB128 if appropriate"));
38
39std::optional<MCFixupKind> RISCVAsmBackend::getFixupKind(StringRef Name) const {
41 unsigned Type;
43#define ELF_RELOC(X, Y) .Case(#X, Y)
44#include "llvm/BinaryFormat/ELFRelocs/RISCV.def"
45#undef ELF_RELOC
46 .Case("BFD_RELOC_NONE", ELF::R_RISCV_NONE)
47 .Case("BFD_RELOC_32", ELF::R_RISCV_32)
48 .Case("BFD_RELOC_64", ELF::R_RISCV_64)
49 .Default(-1u);
50 if (Type != -1u)
51 return static_cast<MCFixupKind>(FirstLiteralRelocationKind + Type);
52 }
53 return std::nullopt;
54}
55
56const MCFixupKindInfo &
58 const static MCFixupKindInfo Infos[] = {
59 // This table *must* be in the order that the fixup_* kinds are defined in
60 // RISCVFixupKinds.h.
61 //
62 // name offset bits flags
63 {"fixup_riscv_hi20", 12, 20, 0},
64 {"fixup_riscv_lo12_i", 20, 12, 0},
65 {"fixup_riscv_12_i", 20, 12, 0},
66 {"fixup_riscv_lo12_s", 0, 32, 0},
67 {"fixup_riscv_pcrel_hi20", 12, 20,
69 {"fixup_riscv_pcrel_lo12_i", 20, 12,
71 {"fixup_riscv_pcrel_lo12_s", 0, 32,
73 {"fixup_riscv_got_hi20", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
74 {"fixup_riscv_tprel_hi20", 12, 20, 0},
75 {"fixup_riscv_tprel_lo12_i", 20, 12, 0},
76 {"fixup_riscv_tprel_lo12_s", 0, 32, 0},
77 {"fixup_riscv_tprel_add", 0, 0, 0},
78 {"fixup_riscv_tls_got_hi20", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
79 {"fixup_riscv_tls_gd_hi20", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
80 {"fixup_riscv_jal", 12, 20, MCFixupKindInfo::FKF_IsPCRel},
81 {"fixup_riscv_branch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
82 {"fixup_riscv_rvc_jump", 2, 11, MCFixupKindInfo::FKF_IsPCRel},
83 {"fixup_riscv_rvc_branch", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
84 {"fixup_riscv_call", 0, 64, MCFixupKindInfo::FKF_IsPCRel},
85 {"fixup_riscv_call_plt", 0, 64, MCFixupKindInfo::FKF_IsPCRel},
86 {"fixup_riscv_relax", 0, 0, 0},
87 {"fixup_riscv_align", 0, 0, 0},
88
89 {"fixup_riscv_tlsdesc_hi20", 12, 20,
91 {"fixup_riscv_tlsdesc_load_lo12", 20, 12, 0},
92 {"fixup_riscv_tlsdesc_add_lo12", 20, 12, 0},
93 {"fixup_riscv_tlsdesc_call", 0, 0, 0},
94 };
95 static_assert((std::size(Infos)) == RISCV::NumTargetFixupKinds,
96 "Not all fixup kinds added to Infos array");
97
98 // Fixup kinds from .reloc directive are like R_RISCV_NONE. They
99 // do not require any extra processing.
100 if (Kind >= FirstLiteralRelocationKind)
102
103 if (Kind < FirstTargetFixupKind)
105
106 assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
107 "Invalid kind!");
108 return Infos[Kind - FirstTargetFixupKind];
109}
110
111// If linker relaxation is enabled, or the relax option had previously been
112// enabled, always emit relocations even if the fixup can be resolved. This is
113// necessary for correctness as offsets may change during relaxation.
115 const MCFixup &Fixup,
116 const MCValue &Target,
117 const MCSubtargetInfo *STI) {
118 if (Fixup.getKind() >= FirstLiteralRelocationKind)
119 return true;
120 switch (Fixup.getTargetKind()) {
121 default:
122 break;
123 case FK_Data_1:
124 case FK_Data_2:
125 case FK_Data_4:
126 case FK_Data_8:
127 case FK_Data_leb128:
128 if (Target.isAbsolute())
129 return false;
130 break;
135 return true;
136 }
137
138 return STI->hasFeature(RISCV::FeatureRelax) || ForceRelocs;
139}
140
142 const MCAssembler &Asm, const MCFixup &Fixup, bool Resolved, uint64_t Value,
143 const MCRelaxableFragment *DF, const bool WasForced) const {
144 if (!RelaxBranches)
145 return false;
146
147 int64_t Offset = int64_t(Value);
148 unsigned Kind = Fixup.getTargetKind();
149
150 // Return true if the symbol is actually unresolved.
151 // Resolved could be always false when shouldForceRelocation return true.
152 // We use !WasForced to indicate that the symbol is unresolved and not forced
153 // by shouldForceRelocation.
154 if (!Resolved && !WasForced)
155 return true;
156
157 switch (Kind) {
158 default:
159 return false;
161 // For compressed branch instructions the immediate must be
162 // in the range [-256, 254].
163 return Offset > 254 || Offset < -256;
165 // For compressed jump instructions the immediate must be
166 // in the range [-2048, 2046].
167 return Offset > 2046 || Offset < -2048;
169 // For conditional branch instructions the immediate must be
170 // in the range [-4096, 4095].
171 return !isInt<13>(Offset);
172 }
173}
174
176 const MCSubtargetInfo &STI) const {
177 MCInst Res;
178 switch (Inst.getOpcode()) {
179 default:
180 llvm_unreachable("Opcode not expected!");
181 case RISCV::C_BEQZ:
182 case RISCV::C_BNEZ:
183 case RISCV::C_J:
184 case RISCV::C_JAL: {
185 [[maybe_unused]] bool Success = RISCVRVC::uncompress(Res, Inst, STI);
186 assert(Success && "Can't uncompress instruction");
187 break;
188 }
189 case RISCV::BEQ:
190 case RISCV::BNE:
191 case RISCV::BLT:
192 case RISCV::BGE:
193 case RISCV::BLTU:
194 case RISCV::BGEU:
196 Res.addOperand(Inst.getOperand(0));
197 Res.addOperand(Inst.getOperand(1));
198 Res.addOperand(Inst.getOperand(2));
199 break;
200 }
201 Inst = std::move(Res);
202}
203
206 bool &WasRelaxed) const {
207 MCContext &C = Asm.getContext();
208
209 int64_t LineDelta = DF.getLineDelta();
210 const MCExpr &AddrDelta = DF.getAddrDelta();
211 SmallVectorImpl<char> &Data = DF.getContents();
212 SmallVectorImpl<MCFixup> &Fixups = DF.getFixups();
213 size_t OldSize = Data.size();
214
215 int64_t Value;
216 [[maybe_unused]] bool IsAbsolute =
217 AddrDelta.evaluateKnownAbsolute(Value, Asm);
218 assert(IsAbsolute && "CFA with invalid expression");
219
220 Data.clear();
221 Fixups.clear();
223
224 // INT64_MAX is a signal that this is actually a DW_LNE_end_sequence.
225 if (LineDelta != INT64_MAX) {
226 OS << uint8_t(dwarf::DW_LNS_advance_line);
227 encodeSLEB128(LineDelta, OS);
228 }
229
230 unsigned Offset;
231 std::pair<MCFixupKind, MCFixupKind> Fixup;
232
233 // According to the DWARF specification, the `DW_LNS_fixed_advance_pc` opcode
234 // takes a single unsigned half (unencoded) operand. The maximum encodable
235 // value is therefore 65535. Set a conservative upper bound for relaxation.
236 if (Value > 60000) {
237 unsigned PtrSize = C.getAsmInfo()->getCodePointerSize();
238
239 OS << uint8_t(dwarf::DW_LNS_extended_op);
240 encodeULEB128(PtrSize + 1, OS);
241
242 OS << uint8_t(dwarf::DW_LNE_set_address);
243 Offset = OS.tell();
244 assert((PtrSize == 4 || PtrSize == 8) && "Unexpected pointer size");
246 OS.write_zeros(PtrSize);
247 } else {
248 OS << uint8_t(dwarf::DW_LNS_fixed_advance_pc);
249 Offset = OS.tell();
251 support::endian::write<uint16_t>(OS, 0, llvm::endianness::little);
252 }
253
254 const MCBinaryExpr &MBE = cast<MCBinaryExpr>(AddrDelta);
255 Fixups.push_back(MCFixup::create(Offset, MBE.getLHS(), std::get<0>(Fixup)));
256 Fixups.push_back(MCFixup::create(Offset, MBE.getRHS(), std::get<1>(Fixup)));
257
258 if (LineDelta == INT64_MAX) {
259 OS << uint8_t(dwarf::DW_LNS_extended_op);
260 OS << uint8_t(1);
261 OS << uint8_t(dwarf::DW_LNE_end_sequence);
262 } else {
263 OS << uint8_t(dwarf::DW_LNS_copy);
264 }
265
266 WasRelaxed = OldSize != Data.size();
267 return true;
268}
269
272 bool &WasRelaxed) const {
273 const MCExpr &AddrDelta = DF.getAddrDelta();
274 SmallVectorImpl<char> &Data = DF.getContents();
275 SmallVectorImpl<MCFixup> &Fixups = DF.getFixups();
276 size_t OldSize = Data.size();
277
278 int64_t Value;
279 if (AddrDelta.evaluateAsAbsolute(Value, Asm))
280 return false;
281 [[maybe_unused]] bool IsAbsolute =
282 AddrDelta.evaluateKnownAbsolute(Value, Asm);
283 assert(IsAbsolute && "CFA with invalid expression");
284
285 Data.clear();
286 Fixups.clear();
288
289 assert(Asm.getContext().getAsmInfo()->getMinInstAlignment() == 1 &&
290 "expected 1-byte alignment");
291 if (Value == 0) {
292 WasRelaxed = OldSize != Data.size();
293 return true;
294 }
295
296 auto AddFixups = [&Fixups, &AddrDelta](unsigned Offset,
297 std::pair<unsigned, unsigned> Fixup) {
298 const MCBinaryExpr &MBE = cast<MCBinaryExpr>(AddrDelta);
299 Fixups.push_back(
302 std::get<0>(Fixup))));
303 Fixups.push_back(
306 std::get<1>(Fixup))));
307 };
308
309 if (isUIntN(6, Value)) {
310 OS << uint8_t(dwarf::DW_CFA_advance_loc);
311 AddFixups(0, {ELF::R_RISCV_SET6, ELF::R_RISCV_SUB6});
312 } else if (isUInt<8>(Value)) {
313 OS << uint8_t(dwarf::DW_CFA_advance_loc1);
314 support::endian::write<uint8_t>(OS, 0, llvm::endianness::little);
315 AddFixups(1, {ELF::R_RISCV_SET8, ELF::R_RISCV_SUB8});
316 } else if (isUInt<16>(Value)) {
317 OS << uint8_t(dwarf::DW_CFA_advance_loc2);
318 support::endian::write<uint16_t>(OS, 0, llvm::endianness::little);
319 AddFixups(1, {ELF::R_RISCV_SET16, ELF::R_RISCV_SUB16});
320 } else if (isUInt<32>(Value)) {
321 OS << uint8_t(dwarf::DW_CFA_advance_loc4);
322 support::endian::write<uint32_t>(OS, 0, llvm::endianness::little);
323 AddFixups(1, {ELF::R_RISCV_SET32, ELF::R_RISCV_SUB32});
324 } else {
325 llvm_unreachable("unsupported CFA encoding");
326 }
327
328 WasRelaxed = OldSize != Data.size();
329 return true;
330}
331
332std::pair<bool, bool> RISCVAsmBackend::relaxLEB128(const MCAssembler &Asm,
333 MCLEBFragment &LF,
334 int64_t &Value) const {
335 if (LF.isSigned())
336 return std::make_pair(false, false);
337 const MCExpr &Expr = LF.getValue();
338 if (ULEB128Reloc) {
339 LF.getFixups().push_back(
340 MCFixup::create(0, &Expr, FK_Data_leb128, Expr.getLoc()));
341 }
342 return std::make_pair(Expr.evaluateKnownAbsolute(Value, Asm), false);
343}
344
345// Given a compressed control flow instruction this function returns
346// the expanded instruction.
347unsigned RISCVAsmBackend::getRelaxedOpcode(unsigned Op) const {
348 switch (Op) {
349 default:
350 return Op;
351 case RISCV::C_BEQZ:
352 return RISCV::BEQ;
353 case RISCV::C_BNEZ:
354 return RISCV::BNE;
355 case RISCV::C_J:
356 case RISCV::C_JAL: // fall through.
357 return RISCV::JAL;
358 case RISCV::BEQ:
359 return RISCV::PseudoLongBEQ;
360 case RISCV::BNE:
361 return RISCV::PseudoLongBNE;
362 case RISCV::BLT:
363 return RISCV::PseudoLongBLT;
364 case RISCV::BGE:
365 return RISCV::PseudoLongBGE;
366 case RISCV::BLTU:
367 return RISCV::PseudoLongBLTU;
368 case RISCV::BGEU:
369 return RISCV::PseudoLongBGEU;
370 }
371}
372
374 const MCSubtargetInfo &STI) const {
375 return getRelaxedOpcode(Inst.getOpcode()) != Inst.getOpcode();
376}
377
379 const MCSubtargetInfo *STI) const {
380 // We mostly follow binutils' convention here: align to even boundary with a
381 // 0-fill padding. We emit up to 1 2-byte nop, though we use c.nop if RVC is
382 // enabled or 0-fill otherwise. The remainder is now padded with 4-byte nops.
383
384 // Instructions always are at even addresses. We must be in a data area or
385 // be unaligned due to some other reason.
386 if (Count % 2) {
387 OS.write("\0", 1);
388 Count -= 1;
389 }
390
391 bool UseCompressedNop = STI->hasFeature(RISCV::FeatureStdExtC) ||
392 STI->hasFeature(RISCV::FeatureStdExtZca);
393 // The canonical nop on RVC is c.nop.
394 if (Count % 4 == 2) {
395 OS.write(UseCompressedNop ? "\x01\0" : "\0\0", 2);
396 Count -= 2;
397 }
398
399 // The canonical nop on RISC-V is addi x0, x0, 0.
400 for (; Count >= 4; Count -= 4)
401 OS.write("\x13\0\0\0", 4);
402
403 return true;
404}
405
407 MCContext &Ctx) {
408 switch (Fixup.getTargetKind()) {
409 default:
410 llvm_unreachable("Unknown fixup kind!");
415 llvm_unreachable("Relocation should be unconditionally forced\n");
416 case FK_Data_1:
417 case FK_Data_2:
418 case FK_Data_4:
419 case FK_Data_8:
420 case FK_Data_leb128:
421 return Value;
426 return Value & 0xfff;
428 if (!isInt<12>(Value)) {
429 Ctx.reportError(Fixup.getLoc(),
430 "operand must be a constant 12-bit integer");
431 }
432 return Value & 0xfff;
436 return (((Value >> 5) & 0x7f) << 25) | ((Value & 0x1f) << 7);
440 // Add 1 if bit 11 is 1, to compensate for low 12 bits being negative.
441 return ((Value + 0x800) >> 12) & 0xfffff;
443 if (!isInt<21>(Value))
444 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
445 if (Value & 0x1)
446 Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
447 // Need to produce imm[19|10:1|11|19:12] from the 21-bit Value.
448 unsigned Sbit = (Value >> 20) & 0x1;
449 unsigned Hi8 = (Value >> 12) & 0xff;
450 unsigned Mid1 = (Value >> 11) & 0x1;
451 unsigned Lo10 = (Value >> 1) & 0x3ff;
452 // Inst{31} = Sbit;
453 // Inst{30-21} = Lo10;
454 // Inst{20} = Mid1;
455 // Inst{19-12} = Hi8;
456 Value = (Sbit << 19) | (Lo10 << 9) | (Mid1 << 8) | Hi8;
457 return Value;
458 }
460 if (!isInt<13>(Value))
461 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
462 if (Value & 0x1)
463 Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
464 // Need to extract imm[12], imm[10:5], imm[4:1], imm[11] from the 13-bit
465 // Value.
466 unsigned Sbit = (Value >> 12) & 0x1;
467 unsigned Hi1 = (Value >> 11) & 0x1;
468 unsigned Mid6 = (Value >> 5) & 0x3f;
469 unsigned Lo4 = (Value >> 1) & 0xf;
470 // Inst{31} = Sbit;
471 // Inst{30-25} = Mid6;
472 // Inst{11-8} = Lo4;
473 // Inst{7} = Hi1;
474 Value = (Sbit << 31) | (Mid6 << 25) | (Lo4 << 8) | (Hi1 << 7);
475 return Value;
476 }
479 // Jalr will add UpperImm with the sign-extended 12-bit LowerImm,
480 // we need to add 0x800ULL before extract upper bits to reflect the
481 // effect of the sign extension.
482 uint64_t UpperImm = (Value + 0x800ULL) & 0xfffff000ULL;
483 uint64_t LowerImm = Value & 0xfffULL;
484 return UpperImm | ((LowerImm << 20) << 32);
485 }
487 if (!isInt<12>(Value))
488 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
489 // Need to produce offset[11|4|9:8|10|6|7|3:1|5] from the 11-bit Value.
490 unsigned Bit11 = (Value >> 11) & 0x1;
491 unsigned Bit4 = (Value >> 4) & 0x1;
492 unsigned Bit9_8 = (Value >> 8) & 0x3;
493 unsigned Bit10 = (Value >> 10) & 0x1;
494 unsigned Bit6 = (Value >> 6) & 0x1;
495 unsigned Bit7 = (Value >> 7) & 0x1;
496 unsigned Bit3_1 = (Value >> 1) & 0x7;
497 unsigned Bit5 = (Value >> 5) & 0x1;
498 Value = (Bit11 << 10) | (Bit4 << 9) | (Bit9_8 << 7) | (Bit10 << 6) |
499 (Bit6 << 5) | (Bit7 << 4) | (Bit3_1 << 1) | Bit5;
500 return Value;
501 }
503 if (!isInt<9>(Value))
504 Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
505 // Need to produce offset[8|4:3], [reg 3 bit], offset[7:6|2:1|5]
506 unsigned Bit8 = (Value >> 8) & 0x1;
507 unsigned Bit7_6 = (Value >> 6) & 0x3;
508 unsigned Bit5 = (Value >> 5) & 0x1;
509 unsigned Bit4_3 = (Value >> 3) & 0x3;
510 unsigned Bit2_1 = (Value >> 1) & 0x3;
511 Value = (Bit8 << 12) | (Bit4_3 << 10) | (Bit7_6 << 5) | (Bit2_1 << 3) |
512 (Bit5 << 2);
513 return Value;
514 }
515
516 }
517}
518
520 const MCFixup &Fixup,
521 const MCFragment *DF,
522 const MCValue &Target,
523 const MCSubtargetInfo *STI,
524 uint64_t &Value, bool &WasForced) {
525 const MCFixup *AUIPCFixup;
526 const MCFragment *AUIPCDF;
527 MCValue AUIPCTarget;
528 switch (Fixup.getTargetKind()) {
529 default:
530 llvm_unreachable("Unexpected fixup kind!");
533 AUIPCFixup = &Fixup;
534 AUIPCDF = DF;
535 AUIPCTarget = Target;
536 break;
539 AUIPCFixup = cast<RISCVMCExpr>(Fixup.getValue())->getPCRelHiFixup(&AUIPCDF);
540 if (!AUIPCFixup) {
541 Asm.getContext().reportError(Fixup.getLoc(),
542 "could not find corresponding %pcrel_hi");
543 return true;
544 }
545
546 // MCAssembler::evaluateFixup will emit an error for this case when it sees
547 // the %pcrel_hi, so don't duplicate it when also seeing the %pcrel_lo.
548 const MCExpr *AUIPCExpr = AUIPCFixup->getValue();
549 if (!AUIPCExpr->evaluateAsRelocatable(AUIPCTarget, &Asm, AUIPCFixup))
550 return true;
551 break;
552 }
553 }
554
555 if (!AUIPCTarget.getSymA() || AUIPCTarget.getSymB())
556 return false;
557
558 const MCSymbolRefExpr *A = AUIPCTarget.getSymA();
559 const MCSymbol &SA = A->getSymbol();
560 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined())
561 return false;
562
563 auto *Writer = Asm.getWriterPtr();
564 if (!Writer)
565 return false;
566
567 bool IsResolved = Writer->isSymbolRefDifferenceFullyResolvedImpl(
568 Asm, SA, *AUIPCDF, false, true);
569 if (!IsResolved)
570 return false;
571
572 Value = Asm.getSymbolOffset(SA) + AUIPCTarget.getConstant();
573 Value -= Asm.getFragmentOffset(*AUIPCDF) + AUIPCFixup->getOffset();
574
575 if (shouldForceRelocation(Asm, *AUIPCFixup, AUIPCTarget, STI)) {
576 WasForced = true;
577 return false;
578 }
579
580 return true;
581}
582
584 const MCFragment &F,
585 const MCFixup &Fixup,
586 const MCValue &Target,
587 uint64_t &FixedValue) const {
588 uint64_t FixedValueA, FixedValueB;
589 unsigned TA = 0, TB = 0;
590 switch (Fixup.getKind()) {
591 case llvm::FK_Data_1:
592 TA = ELF::R_RISCV_ADD8;
593 TB = ELF::R_RISCV_SUB8;
594 break;
595 case llvm::FK_Data_2:
596 TA = ELF::R_RISCV_ADD16;
597 TB = ELF::R_RISCV_SUB16;
598 break;
599 case llvm::FK_Data_4:
600 TA = ELF::R_RISCV_ADD32;
601 TB = ELF::R_RISCV_SUB32;
602 break;
603 case llvm::FK_Data_8:
604 TA = ELF::R_RISCV_ADD64;
605 TB = ELF::R_RISCV_SUB64;
606 break;
608 TA = ELF::R_RISCV_SET_ULEB128;
609 TB = ELF::R_RISCV_SUB_ULEB128;
610 break;
611 default:
612 llvm_unreachable("unsupported fixup size");
613 }
614 MCValue A = MCValue::get(Target.getSymA(), nullptr, Target.getConstant());
615 MCValue B = MCValue::get(Target.getSymB());
616 auto FA = MCFixup::create(
617 Fixup.getOffset(), nullptr,
618 static_cast<MCFixupKind>(FirstLiteralRelocationKind + TA));
619 auto FB = MCFixup::create(
620 Fixup.getOffset(), nullptr,
621 static_cast<MCFixupKind>(FirstLiteralRelocationKind + TB));
622 auto &Assembler = const_cast<MCAssembler &>(Asm);
623 Asm.getWriter().recordRelocation(Assembler, &F, FA, A, FixedValueA);
624 Asm.getWriter().recordRelocation(Assembler, &F, FB, B, FixedValueB);
625 FixedValue = FixedValueA - FixedValueB;
626 return true;
627}
628
630 const MCValue &Target,
632 bool IsResolved,
633 const MCSubtargetInfo *STI) const {
634 MCFixupKind Kind = Fixup.getKind();
635 if (Kind >= FirstLiteralRelocationKind)
636 return;
637 MCContext &Ctx = Asm.getContext();
639 if (!Value)
640 return; // Doesn't change encoding.
641 // Apply any target-specific value adjustments.
643
644 // Shift the value into position.
645 Value <<= Info.TargetOffset;
646
647 unsigned Offset = Fixup.getOffset();
648 unsigned NumBytes = alignTo(Info.TargetSize + Info.TargetOffset, 8) / 8;
649
650 assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
651
652 // For each byte of the fragment that the fixup touches, mask in the
653 // bits from the fixup value.
654 for (unsigned i = 0; i != NumBytes; ++i) {
655 Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
656 }
657}
658
659// Linker relaxation may change code size. We have to insert Nops
660// for .align directive when linker relaxation enabled. So then Linker
661// could satisfy alignment by removing Nops.
662// The function return the total Nops Size we need to insert.
664 const MCAlignFragment &AF, unsigned &Size) {
665 // Calculate Nops Size only when linker relaxation enabled.
666 const MCSubtargetInfo *STI = AF.getSubtargetInfo();
667 if (!STI->hasFeature(RISCV::FeatureRelax))
668 return false;
669
670 bool UseCompressedNop = STI->hasFeature(RISCV::FeatureStdExtC) ||
671 STI->hasFeature(RISCV::FeatureStdExtZca);
672 unsigned MinNopLen = UseCompressedNop ? 2 : 4;
673
674 if (AF.getAlignment() <= MinNopLen) {
675 return false;
676 } else {
677 Size = AF.getAlignment().value() - MinNopLen;
678 return true;
679 }
680}
681
682// We need to insert R_RISCV_ALIGN relocation type to indicate the
683// position of Nops and the total bytes of the Nops have been inserted
684// when linker relaxation enabled.
685// The function insert fixup_riscv_align fixup which eventually will
686// transfer to R_RISCV_ALIGN relocation type.
688 MCAlignFragment &AF) {
689 // Insert the fixup only when linker relaxation enabled.
690 const MCSubtargetInfo *STI = AF.getSubtargetInfo();
691 if (!STI->hasFeature(RISCV::FeatureRelax))
692 return false;
693
694 // Calculate total Nops we need to insert. If there are none to insert
695 // then simply return.
696 unsigned Count;
697 if (!shouldInsertExtraNopBytesForCodeAlign(AF, Count) || (Count == 0))
698 return false;
699
700 MCContext &Ctx = Asm.getContext();
701 const MCExpr *Dummy = MCConstantExpr::create(0, Ctx);
702 // Create fixup_riscv_align fixup.
703 MCFixup Fixup =
705
706 uint64_t FixedValue = 0;
707 MCValue NopBytes = MCValue::get(Count);
708
709 Asm.getWriter().recordRelocation(Asm, &AF, Fixup, NopBytes, FixedValue);
710
711 return true;
712}
713
714std::unique_ptr<MCObjectTargetWriter>
716 return createRISCVELFObjectWriter(OSABI, Is64Bit);
717}
718
720 const MCSubtargetInfo &STI,
721 const MCRegisterInfo &MRI,
722 const MCTargetOptions &Options) {
723 const Triple &TT = STI.getTargetTriple();
724 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TT.getOS());
725 return new RISCVAsmBackend(STI, OSABI, TT.isArch64Bit(), Options);
726}
unsigned const MachineRegisterInfo * MRI
static uint64_t adjustFixupValue(const MCFixup &Fixup, const MCValue &Target, uint64_t Value, MCContext &Ctx, const Triple &TheTriple, bool IsResolved)
#define Success
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
static RegisterPass< DebugifyFunctionPass > DF("debugify-function", "Attach debug info to a function")
std::string Name
uint64_t Size
static LVOptions Options
Definition: LVOptions.cpp:25
#define F(x, y, z)
Definition: MD5.cpp:55
PowerPC TLS Dynamic Call Fixup
static cl::opt< bool > RelaxBranches("riscv-asm-relax-branches", cl::init(true), cl::Hidden)
static cl::opt< bool > ULEB128Reloc("riscv-uleb128-reloc", cl::init(true), cl::Hidden, cl::desc("Emit R_RISCV_SET_ULEB128/E_RISCV_SUB_ULEB128 if appropriate"))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This class represents an Operation in the Expression.
Align getAlignment() const
Definition: MCFragment.h:313
const MCSubtargetInfo * getSubtargetInfo() const
Definition: MCFragment.h:327
Generic interface to target specific assembler backends.
Definition: MCAsmBackend.h:42
virtual const MCFixupKindInfo & getFixupKindInfo(MCFixupKind Kind) const
Get information on a fixup kind.
Binary assembler expressions.
Definition: MCExpr.h:488
const MCExpr * getLHS() const
Get the left-hand side expression of the binary operator.
Definition: MCExpr.h:635
const MCExpr * getRHS() const
Get the right-hand side expression of the binary operator.
Definition: MCExpr.h:638
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:193
Context object for machine code objects.
Definition: MCContext.h:83
void reportError(SMLoc L, const Twine &Msg)
Definition: MCContext.cpp:1069
SmallVectorImpl< MCFixup > & getFixups()
Definition: MCFragment.h:212
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:34
bool evaluateKnownAbsolute(int64_t &Res, const MCAssembler &Asm) const
Aggressive variant of evaluateAsRelocatable when relocations are unavailable (e.g.
Definition: MCExpr.cpp:565
bool evaluateAsRelocatable(MCValue &Res, const MCAssembler *Asm, const MCFixup *Fixup) const
Try to evaluate the expression to a relocatable value, i.e.
Definition: MCExpr.cpp:789
SMLoc getLoc() const
Definition: MCExpr.h:79
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:71
const MCExpr * getValue() const
Definition: MCFixup.h:105
uint32_t getOffset() const
Definition: MCFixup.h:102
static MCFixup create(uint32_t Offset, const MCExpr *Value, MCFixupKind Kind, SMLoc Loc=SMLoc())
Definition: MCFixup.h:87
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
unsigned getOpcode() const
Definition: MCInst.h:198
void addOperand(const MCOperand Op)
Definition: MCInst.h:210
void setOpcode(unsigned Op)
Definition: MCInst.h:197
const MCOperand & getOperand(unsigned i) const
Definition: MCInst.h:206
bool isSigned() const
Definition: MCFragment.h:433
const MCExpr & getValue() const
Definition: MCFragment.h:430
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
A relaxable fragment holds on to its MCInst, since it may need to be relaxed during the assembler lay...
Definition: MCFragment.h:261
Generic base class for all target subtargets.
bool hasFeature(unsigned Feature) const
const Triple & getTargetTriple() const
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:188
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
bool isUndefined(bool SetUsed=true) const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
Definition: MCSymbol.h:259
This represents an "assembler immediate".
Definition: MCValue.h:36
int64_t getConstant() const
Definition: MCValue.h:43
static MCValue get(const MCSymbolRefExpr *SymA, const MCSymbolRefExpr *SymB=nullptr, int64_t Val=0, uint32_t RefKind=0)
Definition: MCValue.h:59
const MCSymbolRefExpr * getSymB() const
Definition: MCValue.h:45
const MCSymbolRefExpr * getSymA() const
Definition: MCValue.h:44
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:307
bool relaxDwarfLineAddr(const MCAssembler &Asm, MCDwarfLineAddrFragment &DF, bool &WasRelaxed) const override
std::pair< bool, bool > relaxLEB128(const MCAssembler &Asm, MCLEBFragment &LF, int64_t &Value) const override
std::unique_ptr< MCObjectTargetWriter > createObjectTargetWriter() const override
bool relaxDwarfCFA(const MCAssembler &Asm, MCDwarfCallFrameFragment &DF, bool &WasRelaxed) const override
void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup, const MCValue &Target, MutableArrayRef< char > Data, uint64_t Value, bool IsResolved, const MCSubtargetInfo *STI) const override
Apply the Value for given Fixup into the provided data fragment, at the offset specified by the fixup...
void relaxInstruction(MCInst &Inst, const MCSubtargetInfo &STI) const override
Relax the instruction in the given fragment to the next wider instruction.
bool evaluateTargetFixup(const MCAssembler &Asm, const MCFixup &Fixup, const MCFragment *DF, const MCValue &Target, const MCSubtargetInfo *STI, uint64_t &Value, bool &WasForced) override
const MCFixupKindInfo & getFixupKindInfo(MCFixupKind Kind) const override
Get information on a fixup kind.
bool fixupNeedsRelaxationAdvanced(const MCAssembler &Asm, const MCFixup &Fixup, bool Resolved, uint64_t Value, const MCRelaxableFragment *DF, const bool WasForced) const override
Target specific predicate for whether a given fixup requires the associated instruction to be relaxed...
bool shouldInsertExtraNopBytesForCodeAlign(const MCAlignFragment &AF, unsigned &Size) override
Hook to check if extra nop bytes must be inserted for alignment directive.
bool mayNeedRelaxation(const MCInst &Inst, const MCSubtargetInfo &STI) const override
Check whether the given instruction may need relaxation.
bool writeNopData(raw_ostream &OS, uint64_t Count, const MCSubtargetInfo *STI) const override
Write an (optimal) nop sequence of Count bytes to the given output.
unsigned getRelaxedOpcode(unsigned Op) const
bool handleAddSubRelocations(const MCAssembler &Asm, const MCFragment &F, const MCFixup &Fixup, const MCValue &Target, uint64_t &FixedValue) const override
bool shouldInsertFixupForCodeAlign(MCAssembler &Asm, MCAlignFragment &AF) override
Hook which indicates if the target requires a fixup to be generated when handling an align directive ...
bool shouldForceRelocation(const MCAssembler &Asm, const MCFixup &Fixup, const MCValue &Target, const MCSubtargetInfo *STI) override
Hook to check if a relocation is needed for some target specific reason.
unsigned getNumFixupKinds() const override
Get the number of target specific fixup kinds.
std::optional< MCFixupKind > getFixupKind(StringRef Name) const override
Map a relocation name used in .reloc to a fixup kind.
Represents a location in source code.
Definition: SMLoc.h:23
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:44
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:69
R Default(T Value)
Definition: StringSwitch.h:182
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition: Triple.h:719
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
raw_ostream & write_zeros(unsigned NumZeros)
write_zeros - Insert 'NumZeros' nulls.
uint64_t tell() const
tell - Return the current offset with the file.
Definition: raw_ostream.h:147
raw_ostream & write(unsigned char C)
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:691
#define INT64_MAX
Definition: DataTypes.h:71
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
bool uncompress(MCInst &OutInst, const MCInst &MI, const MCSubtargetInfo &STI)
static std::pair< MCFixupKind, MCFixupKind > getRelocPairForSize(unsigned Size)
@ fixup_riscv_tprel_lo12_s
@ fixup_riscv_tls_got_hi20
@ fixup_riscv_pcrel_lo12_i
@ fixup_riscv_pcrel_lo12_s
@ fixup_riscv_tprel_lo12_i
@ fixup_riscv_tlsdesc_load_lo12
@ fixup_riscv_tlsdesc_hi20
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::unique_ptr< MCObjectTargetWriter > createRISCVELFObjectWriter(uint8_t OSABI, bool Is64Bit)
@ Offset
Definition: DWP.cpp:480
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:255
MCFixupKind
Extensible enumeration to represent the type of a fixup.
Definition: MCFixup.h:21
@ FirstTargetFixupKind
Definition: MCFixup.h:45
@ FirstLiteralRelocationKind
The range [FirstLiteralRelocationKind, MaxTargetFixupKind) is used for relocations coming from ....
Definition: MCFixup.h:50
@ FK_Data_8
A eight-byte fixup.
Definition: MCFixup.h:26
@ FK_Data_1
A one-byte fixup.
Definition: MCFixup.h:23
@ FK_Data_4
A four-byte fixup.
Definition: MCFixup.h:25
@ FK_NONE
A no-op fixup.
Definition: MCFixup.h:22
@ FK_Data_leb128
A leb128 fixup.
Definition: MCFixup.h:27
@ FK_Data_2
A two-byte fixup.
Definition: MCFixup.h:24
MCAsmBackend * createRISCVAsmBackend(const Target &T, const MCSubtargetInfo &STI, const MCRegisterInfo &MRI, const MCTargetOptions &Options)
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
DWARFExpression::Operation Op
unsigned encodeSLEB128(int64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a SLEB128 value to an output stream.
Definition: LEB128.h:23
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition: LEB128.h:80
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85
Target independent information on a fixup kind.
@ FKF_IsTarget
Should this fixup be evaluated in a target dependent manner?
@ FKF_IsPCRel
Is this fixup kind PCrelative? This is used by the assembler backend to evaluate fixup values in a ta...