LLVM 24.0.0git
RISCVMCCodeEmitter.cpp
Go to the documentation of this file.
1//===-- RISCVMCCodeEmitter.cpp - Convert RISC-V code to machine code ------===//
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// This file implements the RISCVMCCodeEmitter class.
10//
11//===----------------------------------------------------------------------===//
12
17#include "llvm/ADT/Statistic.h"
18#include "llvm/MC/MCAsmInfo.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCExpr.h"
22#include "llvm/MC/MCInst.h"
24#include "llvm/MC/MCInstrInfo.h"
27#include "llvm/MC/MCSymbol.h"
30
31using namespace llvm;
32
33#define DEBUG_TYPE "mccodeemitter"
34
35STATISTIC(MCNumEmitted, "Number of MC instructions emitted");
36STATISTIC(MCNumFixups, "Number of MC fixups created");
37
38namespace {
39class RISCVMCCodeEmitter : public MCCodeEmitter {
40 RISCVMCCodeEmitter(const RISCVMCCodeEmitter &) = delete;
41 void operator=(const RISCVMCCodeEmitter &) = delete;
42 MCContext &Ctx;
43 MCInstrInfo const &MCII;
44
45public:
46 RISCVMCCodeEmitter(MCContext &ctx, MCInstrInfo const &MCII)
47 : Ctx(ctx), MCII(MCII) {}
48
49 ~RISCVMCCodeEmitter() override = default;
50
51 void encodeInstruction(const MCInst &MI, SmallVectorImpl<char> &CB,
52 SmallVectorImpl<MCFixup> &Fixups,
53 const MCSubtargetInfo &STI) const override;
54
55 void expandFunctionCall(const MCInst &MI, SmallVectorImpl<char> &CB,
56 SmallVectorImpl<MCFixup> &Fixups,
57 const MCSubtargetInfo &STI) const;
58
59 void expandTLSDESCCall(const MCInst &MI, SmallVectorImpl<char> &CB,
60 SmallVectorImpl<MCFixup> &Fixups,
61 const MCSubtargetInfo &STI) const;
62
63 void expandAddTPRel(const MCInst &MI, SmallVectorImpl<char> &CB,
64 SmallVectorImpl<MCFixup> &Fixups,
65 const MCSubtargetInfo &STI) const;
66
67 void expandLongCondBr(const MCInst &MI, SmallVectorImpl<char> &CB,
68 SmallVectorImpl<MCFixup> &Fixups,
69 const MCSubtargetInfo &STI) const;
70
71 void expandFunctionCallLpad(const MCInst &MI, SmallVectorImpl<char> &CB,
72 SmallVectorImpl<MCFixup> &Fixups,
73 const MCSubtargetInfo &STI) const;
74
75 void expandQCLongCondBrImm(const MCInst &MI, SmallVectorImpl<char> &CB,
76 SmallVectorImpl<MCFixup> &Fixups,
77 const MCSubtargetInfo &STI, unsigned Size) const;
78
79 void expandPseudoQCAccess(const MCInst &MI, SmallVectorImpl<char> &CB,
80 SmallVectorImpl<MCFixup> &Fixups,
81 const MCSubtargetInfo &STI) const;
82
83 /// TableGen'erated function for getting the binary encoding for an
84 /// instruction.
85 uint64_t getBinaryCodeForInstr(const MCInst &MI,
86 SmallVectorImpl<MCFixup> &Fixups,
87 const MCSubtargetInfo &STI) const;
88
89 /// Return binary encoding of operand. If the machine operand requires
90 /// relocation, record the relocation and return zero.
91 uint64_t getMachineOpValue(const MCInst &MI, const MCOperand &MO,
92 SmallVectorImpl<MCFixup> &Fixups,
93 const MCSubtargetInfo &STI) const;
94
95 uint64_t getImmOpValueMinus1(const MCInst &MI, unsigned OpNo,
96 SmallVectorImpl<MCFixup> &Fixups,
97 const MCSubtargetInfo &STI) const;
98
99 uint64_t getImmOpValueSlist(const MCInst &MI, unsigned OpNo,
100 SmallVectorImpl<MCFixup> &Fixups,
101 const MCSubtargetInfo &STI) const;
102
103 template <unsigned N>
104 unsigned getImmOpValueAsrN(const MCInst &MI, unsigned OpNo,
105 SmallVectorImpl<MCFixup> &Fixups,
106 const MCSubtargetInfo &STI) const;
107
108 uint64_t getImmOpValueZibi(const MCInst &MI, unsigned OpNo,
109 SmallVectorImpl<MCFixup> &Fixups,
110 const MCSubtargetInfo &STI) const;
111
112 uint64_t getImmOpValue(const MCInst &MI, unsigned OpNo,
113 SmallVectorImpl<MCFixup> &Fixups,
114 const MCSubtargetInfo &STI) const;
115
116 unsigned getYBNDSWImmOpValue(const MCInst &MI, unsigned OpNo,
117 SmallVectorImpl<MCFixup> &Fixups,
118 const MCSubtargetInfo &STI) const;
119
120 unsigned getVMaskReg(const MCInst &MI, unsigned OpNo,
121 SmallVectorImpl<MCFixup> &Fixups,
122 const MCSubtargetInfo &STI) const;
123
124 unsigned getRlistOpValue(const MCInst &MI, unsigned OpNo,
125 SmallVectorImpl<MCFixup> &Fixups,
126 const MCSubtargetInfo &STI) const;
127
128 unsigned getRlistS0OpValue(const MCInst &MI, unsigned OpNo,
129 SmallVectorImpl<MCFixup> &Fixups,
130 const MCSubtargetInfo &STI) const;
131};
132} // end anonymous namespace
133
135 MCContext &Ctx) {
136 return new RISCVMCCodeEmitter(Ctx, MCII);
137}
138
140 const MCExpr *Value, uint16_t Kind) {
141 bool PCRel = false;
142 switch (Kind) {
143 case ELF::R_RISCV_CALL_PLT:
156 PCRel = true;
157 }
158 Fixups.push_back(MCFixup::create(Offset, Value, Kind, PCRel));
159}
160
161// Expand PseudoCALL(Reg), PseudoTAIL and PseudoJump to AUIPC and JALR with
162// relocation types. We expand those pseudo-instructions while encoding them,
163// meaning AUIPC and JALR won't go through RISC-V MC to MC compressed
164// instruction transformation. This is acceptable because AUIPC has no 16-bit
165// form and C_JALR has no immediate operand field. We let linker relaxation
166// deal with it. When linker relaxation is enabled, AUIPC and JALR have a
167// chance to relax to JAL.
168// If the C extension is enabled, JAL has a chance relax to C_JAL.
169void RISCVMCCodeEmitter::expandFunctionCall(const MCInst &MI,
172 const MCSubtargetInfo &STI) const {
173 MCInst TmpInst;
174 MCOperand Func;
175 MCRegister Ra;
176 if (MI.getOpcode() == RISCV::PseudoTAIL) {
177 Func = MI.getOperand(0);
179 } else if (MI.getOpcode() == RISCV::PseudoTAILReg) {
180 Func = MI.getOperand(1);
181 Ra = MI.getOperand(0).getReg();
182 } else if (MI.getOpcode() == RISCV::PseudoCALLReg) {
183 Func = MI.getOperand(1);
184 Ra = MI.getOperand(0).getReg();
185 } else if (MI.getOpcode() == RISCV::PseudoCALL) {
186 Func = MI.getOperand(0);
187 Ra = RISCV::X1;
188 } else if (MI.getOpcode() == RISCV::PseudoJump) {
189 Func = MI.getOperand(1);
190 Ra = MI.getOperand(0).getReg();
191 }
192 uint32_t Binary;
193
194 assert(Func.isExpr() && "Expected expression");
195
196 const MCExpr *CallExpr = Func.getExpr();
197
199 MCOperand FuncOp = MCOperand::createExpr(CallExpr);
200 if (MI.getOpcode() == RISCV::PseudoTAIL ||
201 MI.getOpcode() == RISCV::PseudoTAILReg ||
202 MI.getOpcode() == RISCV::PseudoJump)
203 // Emit JAL X0, Func
204 TmpInst = MCInstBuilder(RISCV::JAL).addReg(RISCV::X0).addOperand(FuncOp);
205 else
206 // Emit JAL Ra, Func
207 TmpInst = MCInstBuilder(RISCV::JAL).addReg(Ra).addOperand(FuncOp);
208 Binary = getBinaryCodeForInstr(TmpInst, Fixups, STI);
210 return;
211 }
212 // Emit AUIPC Ra, Func with R_RISCV_CALL relocation type.
213 TmpInst = MCInstBuilder(RISCV::AUIPC).addReg(Ra).addExpr(CallExpr);
214 Binary = getBinaryCodeForInstr(TmpInst, Fixups, STI);
216
217 if (MI.getOpcode() == RISCV::PseudoTAIL ||
218 MI.getOpcode() == RISCV::PseudoTAILReg ||
219 MI.getOpcode() == RISCV::PseudoJump)
220 // Emit JALR X0, Ra, 0
221 TmpInst = MCInstBuilder(RISCV::JALR).addReg(RISCV::X0).addReg(Ra).addImm(0);
222 else
223 // Emit JALR Ra, Ra, 0
224 TmpInst = MCInstBuilder(RISCV::JALR).addReg(Ra).addReg(Ra).addImm(0);
225 Binary = getBinaryCodeForInstr(TmpInst, Fixups, STI);
227}
228
229// Expand to AUIPC+JALR+LPAD (direct) or JALR+LPAD (indirect).
230// R_RISCV_RELAX is not emitted for the call because linker relaxation could
231// convert it to c.jal/cm.jalt, which would misalign the following LPAD.
232void RISCVMCCodeEmitter::expandFunctionCallLpad(
233 const MCInst &MI, SmallVectorImpl<char> &CB,
234 SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &STI) const {
235 bool IsIndirect = MI.getOpcode() == RISCV::PseudoCALLIndirectLpadAlign;
236 MCInst TmpInst;
237 uint32_t Binary;
238
239 if (!IsIndirect) {
240 const MCOperand &Func = MI.getOperand(0);
241 assert(Func.isExpr() && "Expected expression for call target");
242
243 // Use a STI without FeatureRelax so getImmOpValue does not mark the
244 // R_RISCV_CALL_PLT fixup as LinkerRelaxable (which would emit
245 // R_RISCV_RELAX).
246 MCSubtargetInfo NoRelaxSTI(STI);
247 if (STI.hasFeature(RISCV::FeatureRelax))
248 NoRelaxSTI.ToggleFeature(RISCV::FeatureRelax);
249
250 TmpInst =
251 MCInstBuilder(RISCV::AUIPC).addReg(RISCV::X1).addExpr(Func.getExpr());
252 Binary = getBinaryCodeForInstr(TmpInst, Fixups, NoRelaxSTI);
254
255 TmpInst = MCInstBuilder(RISCV::JALR)
256 .addReg(RISCV::X1)
257 .addReg(RISCV::X1)
258 .addImm(0);
259 Binary = getBinaryCodeForInstr(TmpInst, Fixups, STI);
261 } else {
262 TmpInst = MCInstBuilder(RISCV::JALR)
263 .addReg(RISCV::X1)
264 .addReg(MI.getOperand(0).getReg())
265 .addImm(0);
266 Binary = getBinaryCodeForInstr(TmpInst, Fixups, STI);
268 }
269
270 // LPAD is encoded as AUIPC X0, label.
271 TmpInst = MCInstBuilder(RISCV::AUIPC)
272 .addReg(RISCV::X0)
273 .addImm(MI.getOperand(1).getImm());
274 Binary = getBinaryCodeForInstr(TmpInst, Fixups, STI);
276}
277
278void RISCVMCCodeEmitter::expandTLSDESCCall(const MCInst &MI,
279 SmallVectorImpl<char> &CB,
280 SmallVectorImpl<MCFixup> &Fixups,
281 const MCSubtargetInfo &STI) const {
282 MCOperand SrcSymbol = MI.getOperand(3);
283 assert(SrcSymbol.isExpr() &&
284 "Expected expression as first input to TLSDESCCALL");
285 const auto *Expr = dyn_cast<MCSpecifierExpr>(SrcSymbol.getExpr());
286 MCRegister Link = MI.getOperand(0).getReg();
287 MCRegister Dest = MI.getOperand(1).getReg();
288 int64_t Imm = MI.getOperand(2).getImm();
289 addFixup(Fixups, 0, Expr, ELF::R_RISCV_TLSDESC_CALL);
290 MCInst Call =
291 MCInstBuilder(RISCV::JALR).addReg(Link).addReg(Dest).addImm(Imm);
292
293 uint32_t Binary = getBinaryCodeForInstr(Call, Fixups, STI);
295}
296
297// Expand PseudoAddTPRel to a simple ADD with the correct relocation.
298void RISCVMCCodeEmitter::expandAddTPRel(const MCInst &MI,
299 SmallVectorImpl<char> &CB,
300 SmallVectorImpl<MCFixup> &Fixups,
301 const MCSubtargetInfo &STI) const {
302 MCOperand DestReg = MI.getOperand(0);
303 MCOperand SrcReg = MI.getOperand(1);
304 MCOperand TPReg = MI.getOperand(2);
305 assert(TPReg.isReg() && TPReg.getReg() == RISCV::X4 &&
306 "Expected thread pointer as second input to TP-relative add");
307
308 MCOperand SrcSymbol = MI.getOperand(3);
309 assert(SrcSymbol.isExpr() &&
310 "Expected expression as third input to TP-relative add");
311
312 const auto *Expr = dyn_cast<MCSpecifierExpr>(SrcSymbol.getExpr());
313 assert(Expr && Expr->getSpecifier() == ELF::R_RISCV_TPREL_ADD &&
314 "Expected tprel_add relocation on TP-relative symbol");
315
316 addFixup(Fixups, 0, Expr, ELF::R_RISCV_TPREL_ADD);
317 if (STI.hasFeature(RISCV::FeatureRelax))
318 Fixups.back().setLinkerRelaxable();
319
320 // Emit a normal ADD instruction with the given operands.
321 MCInst TmpInst = MCInstBuilder(RISCV::ADD)
322 .addOperand(DestReg)
323 .addOperand(SrcReg)
324 .addOperand(TPReg);
325 uint32_t Binary = getBinaryCodeForInstr(TmpInst, Fixups, STI);
327}
328
329static unsigned getInvertedBranchOp(unsigned BrOp) {
330 switch (BrOp) {
331 default:
332 llvm_unreachable("Unexpected branch opcode!");
333 case RISCV::PseudoLongBEQ:
334 return RISCV::BNE;
335 case RISCV::PseudoLongBNE:
336 return RISCV::BEQ;
337 case RISCV::PseudoLongBEQI:
338 return RISCV::BNEI;
339 case RISCV::PseudoLongBNEI:
340 return RISCV::BEQI;
341 case RISCV::PseudoLongBLT:
342 return RISCV::BGE;
343 case RISCV::PseudoLongBGE:
344 return RISCV::BLT;
345 case RISCV::PseudoLongBLTU:
346 return RISCV::BGEU;
347 case RISCV::PseudoLongBGEU:
348 return RISCV::BLTU;
349 case RISCV::PseudoLongQC_BEQI:
350 return RISCV::QC_BNEI;
351 case RISCV::PseudoLongQC_BNEI:
352 return RISCV::QC_BEQI;
353 case RISCV::PseudoLongQC_BLTI:
354 return RISCV::QC_BGEI;
355 case RISCV::PseudoLongQC_BGEI:
356 return RISCV::QC_BLTI;
357 case RISCV::PseudoLongQC_BLTUI:
358 return RISCV::QC_BGEUI;
359 case RISCV::PseudoLongQC_BGEUI:
360 return RISCV::QC_BLTUI;
361 case RISCV::PseudoLongQC_E_BEQI:
362 return RISCV::QC_E_BNEI;
363 case RISCV::PseudoLongQC_E_BNEI:
364 return RISCV::QC_E_BEQI;
365 case RISCV::PseudoLongQC_E_BLTI:
366 return RISCV::QC_E_BGEI;
367 case RISCV::PseudoLongQC_E_BGEI:
368 return RISCV::QC_E_BLTI;
369 case RISCV::PseudoLongQC_E_BLTUI:
370 return RISCV::QC_E_BGEUI;
371 case RISCV::PseudoLongQC_E_BGEUI:
372 return RISCV::QC_E_BLTUI;
373 case RISCV::PseudoLongCV_BEQIMM:
374 return RISCV::CV_BNEIMM;
375 case RISCV::PseudoLongCV_BNEIMM:
376 return RISCV::CV_BEQIMM;
377 }
378}
379
380// Expand PseudoLongBxx to an inverted conditional branch and an unconditional
381// jump.
382void RISCVMCCodeEmitter::expandLongCondBr(const MCInst &MI,
383 SmallVectorImpl<char> &CB,
384 SmallVectorImpl<MCFixup> &Fixups,
385 const MCSubtargetInfo &STI) const {
386 MCRegister SrcReg1 = MI.getOperand(0).getReg();
387 const MCOperand &Src2 = MI.getOperand(1);
388 const MCOperand &SrcSymbol = MI.getOperand(2);
389 unsigned Opcode = MI.getOpcode();
390 bool IsEqTest =
391 Opcode == RISCV::PseudoLongBNE || Opcode == RISCV::PseudoLongBEQ;
392 // With +relax, RISCVAsmBackend::relaxInstruction(MCFragment &) appends
393 // operand 3, a symbol after the JAL. Otherwise, the skip distance is a
394 // constant and the JAL must not be relaxed.
395 bool HasSkip = MI.getNumOperands() > 3;
396 auto SkipTarget = [&](int64_t Dist) {
397 return HasSkip ? MI.getOperand(3) : MCOperand::createImm(Dist);
398 };
399
400 bool UseCompressedBr = false;
401 if (IsEqTest && STI.hasFeature(RISCV::FeatureStdExtZca)) {
402 MCRegister SrcReg2 = Src2.getReg();
403 if (RISCV::X8 <= SrcReg1.id() && SrcReg1.id() <= RISCV::X15 &&
404 SrcReg2.id() == RISCV::X0) {
405 UseCompressedBr = true;
406 } else if (RISCV::X8 <= SrcReg2.id() && SrcReg2.id() <= RISCV::X15 &&
407 SrcReg1.id() == RISCV::X0) {
408 std::swap(SrcReg1, SrcReg2);
409 UseCompressedBr = true;
410 }
411 }
412
413 uint32_t Offset;
414 if (UseCompressedBr) {
415 unsigned InvOpc =
416 Opcode == RISCV::PseudoLongBNE ? RISCV::C_BEQZ : RISCV::C_BNEZ;
417 MCInst TmpInst =
418 MCInstBuilder(InvOpc).addReg(SrcReg1).addOperand(SkipTarget(6));
419 uint16_t Binary = getBinaryCodeForInstr(TmpInst, Fixups, STI);
421 Offset = 2;
422 } else {
423 unsigned InvOpc = getInvertedBranchOp(Opcode);
424 MCInst TmpInst =
425 MCInstBuilder(InvOpc).addReg(SrcReg1).addOperand(Src2).addOperand(
426 SkipTarget(8));
427 uint32_t Binary = getBinaryCodeForInstr(TmpInst, Fixups, STI);
429 Offset = 4;
430 }
431
432 // Save the number fixups.
433 size_t FixupStartIndex = Fixups.size();
434
435 // Emit an unconditional jump to the destination.
436 MCInst TmpInst =
437 MCInstBuilder(RISCV::JAL).addReg(RISCV::X0).addOperand(SrcSymbol);
438 uint32_t Binary = getBinaryCodeForInstr(TmpInst, Fixups, STI);
440
441 // Drop any fixup added so we can add the correct one.
442 Fixups.resize(FixupStartIndex);
443
444 if (SrcSymbol.isExpr()) {
445 addFixup(Fixups, Offset, SrcSymbol.getExpr(), RISCV::fixup_riscv_jal);
446 if (HasSkip)
447 Fixups.back().setLinkerRelaxable();
448 }
449}
450
451// Expand PseudoLongQC_(E_)Bxxx to an inverted conditional branch and an
452// unconditional jump.
453void RISCVMCCodeEmitter::expandQCLongCondBrImm(const MCInst &MI,
454 SmallVectorImpl<char> &CB,
455 SmallVectorImpl<MCFixup> &Fixups,
456 const MCSubtargetInfo &STI,
457 unsigned Size) const {
458 MCRegister SrcReg1 = MI.getOperand(0).getReg();
459 auto BrImm = MI.getOperand(1).getImm();
460 MCOperand SrcSymbol = MI.getOperand(2);
461 unsigned Opcode = MI.getOpcode();
462 uint32_t Offset;
463 unsigned InvOpc = getInvertedBranchOp(Opcode);
464 // Emit inverted conditional branch to operand 3 (see expandLongCondBr) if
465 // present, otherwise with offset 8 (QC.BXXX(4) + JAL(4)) or
466 // 10 (QC.E.BXXX(6) + JAL(4)).
467 bool HasSkip = MI.getNumOperands() > 3;
468 MCOperand Skip = HasSkip ? MI.getOperand(3) : MCOperand::createImm(Size + 4);
469 MCInst TmpBr =
470 MCInstBuilder(InvOpc).addReg(SrcReg1).addImm(BrImm).addOperand(Skip);
471 if (Size == 4) {
472 uint32_t BrBinary = getBinaryCodeForInstr(TmpBr, Fixups, STI);
474 } else {
475 uint64_t BrBinary =
476 getBinaryCodeForInstr(TmpBr, Fixups, STI) & 0xffff'ffff'ffffu;
477 SmallVector<char, 8> Encoding;
479 assert(Encoding[6] == 0 && Encoding[7] == 0 &&
480 "Unexpected encoding for 48-bit instruction");
481 Encoding.truncate(6);
482 CB.append(Encoding);
483 }
484 Offset = Size;
485 // Save the number fixups.
486 size_t FixupStartIndex = Fixups.size();
487 // Emit an unconditional jump to the destination.
488 MCInst TmpJ =
489 MCInstBuilder(RISCV::JAL).addReg(RISCV::X0).addOperand(SrcSymbol);
490 uint32_t JBinary = getBinaryCodeForInstr(TmpJ, Fixups, STI);
492 // Drop any fixup added so we can add the correct one.
493 Fixups.resize(FixupStartIndex);
494 if (SrcSymbol.isExpr()) {
495 addFixup(Fixups, Offset, SrcSymbol.getExpr(), RISCV::fixup_riscv_jal);
496 if (HasSkip)
497 Fixups.back().setLinkerRelaxable();
498 }
499}
500
501void RISCVMCCodeEmitter::expandPseudoQCAccess(
502 const MCInst &MI, SmallVectorImpl<char> &CB,
503 SmallVectorImpl<MCFixup> &Fixups, const MCSubtargetInfo &STI) const {
504 unsigned AccessOpc;
505
506 switch (MI.getOpcode()) {
507#define QC_ACCESS_CASE(_Suffix) \
508 case RISCV::PseudoQCAccess##_Suffix: \
509 AccessOpc = RISCV::_Suffix; \
510 break;
511 // clang-format off
513 QC_ACCESS_CASE(LBU)
515 QC_ACCESS_CASE(LHU)
520 QC_ACCESS_CASE(C_LBU)
521 QC_ACCESS_CASE(C_LH)
522 QC_ACCESS_CASE(C_LHU)
523 QC_ACCESS_CASE(C_LW)
524 QC_ACCESS_CASE(C_SB)
525 QC_ACCESS_CASE(C_SH)
526 QC_ACCESS_CASE(C_SW)
527 // clang-format on
528 default:
529 llvm_unreachable("Unhandled QC Access Opcode");
530 };
531
532 MCInst TmpAccess = MCInstBuilder(AccessOpc)
533 .addOperand(MI.getOperand(0))
534 .addOperand(MI.getOperand(1))
535 .addOperand(MI.getOperand(2));
536 unsigned Size = MCII.get(AccessOpc).getSize();
537 uint16_t FixupKind;
538 switch (Size) {
539 default:
540 llvm_unreachable("Unhandled QC Access Instruction Size");
541 case 2: {
542 uint16_t AccessBinary = getBinaryCodeForInstr(TmpAccess, Fixups, STI);
545 break;
546 }
547 case 4: {
548 uint32_t AccessBinary = getBinaryCodeForInstr(TmpAccess, Fixups, STI);
551 break;
552 }
553 }
554 // Only emit the qc.access fixup if linker relaxation is enabled. The pass has
555 // already checked for this before using the Pseudos, but the user may have
556 // written the instructions directly in assembly.
557 if (!STI.hasFeature(RISCV::FeatureRelax))
558 return;
559
560 const MCOperand &AccessSymbol = MI.getOperand(3);
561 assert(AccessSymbol.isExpr() && "Expected expression in PseudoQCAccess");
562
563 const auto *AccessExpr = cast<MCSpecifierExpr>(AccessSymbol.getExpr());
564 assert(AccessExpr->getSpecifier() == RISCV::S_QC_ACCESS &&
565 "Expected qc.access specifier on symbol");
566
567 addFixup(Fixups, /*Offset=*/0, AccessExpr, FixupKind);
568 // The added fixup is always linker relaxable.
569 Fixups.back().setLinkerRelaxable();
570}
571
572void RISCVMCCodeEmitter::encodeInstruction(const MCInst &MI,
573 SmallVectorImpl<char> &CB,
574 SmallVectorImpl<MCFixup> &Fixups,
575 const MCSubtargetInfo &STI) const {
576 const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
577 // Get byte count of instruction.
578 unsigned Size = Desc.getSize();
579
580 // RISCVInstrInfo::getInstSizeInBytes expects that the total size of the
581 // expanded instructions for each pseudo is correct in the Size field of the
582 // tablegen definition for the pseudo.
583 switch (MI.getOpcode()) {
584 default:
585 break;
586 case RISCV::PseudoCALLReg:
587 case RISCV::PseudoCALL:
588 case RISCV::PseudoTAIL:
589 case RISCV::PseudoTAILReg:
590 case RISCV::PseudoJump:
591 expandFunctionCall(MI, CB, Fixups, STI);
592 MCNumEmitted += 2;
593 return;
594 case RISCV::PseudoCALLLpadAlign:
595 expandFunctionCallLpad(MI, CB, Fixups, STI);
596 MCNumEmitted += 3; // AUIPC + JALR + LPAD
597 return;
598 case RISCV::PseudoCALLIndirectLpadAlign:
599 expandFunctionCallLpad(MI, CB, Fixups, STI);
600 MCNumEmitted += 2; // JALR + LPAD
601 return;
602 case RISCV::PseudoAddTPRel:
603 expandAddTPRel(MI, CB, Fixups, STI);
604 MCNumEmitted += 1;
605 return;
606 case RISCV::PseudoLongBEQ:
607 case RISCV::PseudoLongBNE:
608 case RISCV::PseudoLongBEQI:
609 case RISCV::PseudoLongBNEI:
610 case RISCV::PseudoLongBLT:
611 case RISCV::PseudoLongBGE:
612 case RISCV::PseudoLongBLTU:
613 case RISCV::PseudoLongBGEU:
614 expandLongCondBr(MI, CB, Fixups, STI);
615 MCNumEmitted += 2;
616 return;
617 case RISCV::PseudoLongQC_BEQI:
618 case RISCV::PseudoLongQC_BNEI:
619 case RISCV::PseudoLongQC_BLTI:
620 case RISCV::PseudoLongQC_BGEI:
621 case RISCV::PseudoLongQC_BLTUI:
622 case RISCV::PseudoLongQC_BGEUI:
623 case RISCV::PseudoLongCV_BEQIMM:
624 case RISCV::PseudoLongCV_BNEIMM:
625 expandQCLongCondBrImm(MI, CB, Fixups, STI, 4);
626 MCNumEmitted += 2;
627 return;
628 case RISCV::PseudoLongQC_E_BEQI:
629 case RISCV::PseudoLongQC_E_BNEI:
630 case RISCV::PseudoLongQC_E_BLTI:
631 case RISCV::PseudoLongQC_E_BGEI:
632 case RISCV::PseudoLongQC_E_BLTUI:
633 case RISCV::PseudoLongQC_E_BGEUI:
634 expandQCLongCondBrImm(MI, CB, Fixups, STI, 6);
635 MCNumEmitted += 2;
636 return;
637 case RISCV::PseudoTLSDESCCall:
638 expandTLSDESCCall(MI, CB, Fixups, STI);
639 MCNumEmitted += 1;
640 return;
641 case RISCV::PseudoQCAccessLB:
642 case RISCV::PseudoQCAccessLBU:
643 case RISCV::PseudoQCAccessLH:
644 case RISCV::PseudoQCAccessLHU:
645 case RISCV::PseudoQCAccessLW:
646 case RISCV::PseudoQCAccessSB:
647 case RISCV::PseudoQCAccessSH:
648 case RISCV::PseudoQCAccessSW:
649 case RISCV::PseudoQCAccessC_LBU:
650 case RISCV::PseudoQCAccessC_LH:
651 case RISCV::PseudoQCAccessC_LHU:
652 case RISCV::PseudoQCAccessC_LW:
653 case RISCV::PseudoQCAccessC_SB:
654 case RISCV::PseudoQCAccessC_SH:
655 case RISCV::PseudoQCAccessC_SW:
656 expandPseudoQCAccess(MI, CB, Fixups, STI);
657 MCNumEmitted += 1;
658 return;
659 }
660
661 switch (Size) {
662 default:
663 llvm_unreachable("Unhandled encodeInstruction length!");
664 case 2: {
665 uint16_t Bits = getBinaryCodeForInstr(MI, Fixups, STI);
667 break;
668 }
669 case 4: {
670 uint32_t Bits = getBinaryCodeForInstr(MI, Fixups, STI);
672 break;
673 }
674 case 6: {
675 uint64_t Bits = getBinaryCodeForInstr(MI, Fixups, STI) & 0xffff'ffff'ffffu;
676 SmallVector<char, 8> Encoding;
678 assert(Encoding[6] == 0 && Encoding[7] == 0 &&
679 "Unexpected encoding for 48-bit instruction");
680 Encoding.truncate(6);
681 CB.append(Encoding);
682 break;
683 }
684 case 8: {
685 uint64_t Bits = getBinaryCodeForInstr(MI, Fixups, STI);
687 break;
688 }
689 }
690
691 ++MCNumEmitted; // Keep track of the # of mi's emitted.
692}
693
695RISCVMCCodeEmitter::getMachineOpValue(const MCInst &MI, const MCOperand &MO,
696 SmallVectorImpl<MCFixup> &Fixups,
697 const MCSubtargetInfo &STI) const {
698
699 if (MO.isReg())
700 return Ctx.getRegisterInfo()->getEncodingValue(MO.getReg());
701
702 if (MO.isImm())
703 return MO.getImm();
704
705 llvm_unreachable("Unhandled expression!");
706 return 0;
707}
708
710RISCVMCCodeEmitter::getImmOpValueMinus1(const MCInst &MI, unsigned OpNo,
711 SmallVectorImpl<MCFixup> &Fixups,
712 const MCSubtargetInfo &STI) const {
713 const MCOperand &MO = MI.getOperand(OpNo);
714
715 if (MO.isImm()) {
716 uint64_t Res = MO.getImm();
717 return (Res - 1);
718 }
719
720 llvm_unreachable("Unhandled expression!");
721 return 0;
722}
723
725RISCVMCCodeEmitter::getImmOpValueSlist(const MCInst &MI, unsigned OpNo,
726 SmallVectorImpl<MCFixup> &Fixups,
727 const MCSubtargetInfo &STI) const {
728 const MCOperand &MO = MI.getOperand(OpNo);
729 assert(MO.isImm() && "Slist operand must be immediate");
730
731 uint64_t Res = MO.getImm();
732 switch (Res) {
733 case 0:
734 return 0;
735 case 1:
736 return 1;
737 case 2:
738 return 2;
739 case 4:
740 return 3;
741 case 8:
742 return 4;
743 case 16:
744 return 5;
745 case 15:
746 return 6;
747 case 31:
748 return 7;
749 default:
750 llvm_unreachable("Unhandled Slist value!");
751 }
752}
753
754template <unsigned N>
755unsigned
756RISCVMCCodeEmitter::getImmOpValueAsrN(const MCInst &MI, unsigned OpNo,
757 SmallVectorImpl<MCFixup> &Fixups,
758 const MCSubtargetInfo &STI) const {
759 const MCOperand &MO = MI.getOperand(OpNo);
760
761 if (MO.isImm()) {
762 uint64_t Res = MO.getImm();
763 assert((Res & ((1 << N) - 1)) == 0 && "LSB is non-zero");
764 return Res >> N;
765 }
766
767 return getImmOpValue(MI, OpNo, Fixups, STI);
768}
769
771RISCVMCCodeEmitter::getImmOpValueZibi(const MCInst &MI, unsigned OpNo,
772 SmallVectorImpl<MCFixup> &Fixups,
773 const MCSubtargetInfo &STI) const {
774 const MCOperand &MO = MI.getOperand(OpNo);
775 assert(MO.isImm() && "Zibi operand must be an immediate");
776 int64_t Res = MO.getImm();
777 if (Res == -1)
778 return 0;
779
780 return Res;
781}
782
783uint64_t RISCVMCCodeEmitter::getImmOpValue(const MCInst &MI, unsigned OpNo,
784 SmallVectorImpl<MCFixup> &Fixups,
785 const MCSubtargetInfo &STI) const {
786 bool EnableRelax = STI.hasFeature(RISCV::FeatureRelax);
787 const MCOperand &MO = MI.getOperand(OpNo);
788
789 MCInstrDesc const &Desc = MCII.get(MI.getOpcode());
790 unsigned MIFrm = RISCVII::getFormat(Desc.TSFlags);
791
792 // If the destination is an immediate, there is nothing to do.
793 if (MO.isImm())
794 return MO.getImm();
795
796 assert(MO.isExpr() &&
797 "getImmOpValue expects only expressions or immediates");
798 const MCExpr *Expr = MO.getExpr();
799 MCExpr::ExprKind Kind = Expr->getKind();
800
801 // `RelaxCandidate` must be set to `true` in two cases:
802 // - The fixup's relocation gets a R_RISCV_RELAX relocation
803 // - The underlying instruction may be relaxed to an instruction that gets a
804 // `R_RISCV_RELAX` relocation.
805 //
806 // The actual emission of `R_RISCV_RELAX` will be handled in
807 // `RISCVAsmBackend::applyFixup`.
808 bool RelaxCandidate = false;
809 auto AsmRelaxToLinkerRelaxable = [&]() -> void {
810 if (!STI.hasFeature(RISCV::FeatureExactAssembly))
811 RelaxCandidate = true;
812 };
813
815 if (Kind == MCExpr::Specifier) {
816 const auto *RVExpr = cast<MCSpecifierExpr>(Expr);
817 FixupKind = RVExpr->getSpecifier();
818 switch (RVExpr->getSpecifier()) {
819 default:
821 "invalid specifier");
822 break;
823 case ELF::R_RISCV_TPREL_ADD:
824 // tprel_add is only used to indicate that a relocation should be emitted
825 // for an add instruction used in TP-relative addressing. It should not be
826 // expanded as if representing an actual instruction operand and so to
827 // encounter it here is an error.
829 "ELF::R_RISCV_TPREL_ADD should not represent an instruction operand");
831 // The same logic for tprel_add applies to S_QC_ACCESS, for similar
832 // reasons, but we use a specifier becuase %qc.access() gets expanded
833 // differently depending on the underlying instruction.
835 "S_QC_ACCESS should not represent an instruction operand");
836 case RISCV::S_LO:
837 if (MIFrm == RISCVII::InstFormatI)
839 else if (MIFrm == RISCVII::InstFormatS)
841 else
842 llvm_unreachable("VK_LO used with unexpected instruction format");
843 RelaxCandidate = true;
844 break;
845 case ELF::R_RISCV_HI20:
847 RelaxCandidate = true;
848 break;
850 if (MIFrm == RISCVII::InstFormatI)
852 else if (MIFrm == RISCVII::InstFormatS)
854 else
855 llvm_unreachable("VK_PCREL_LO used with unexpected instruction format");
856 RelaxCandidate = true;
857 break;
860 RelaxCandidate = true;
861 break;
862 case RISCV::S_GOT_HI:
863 FixupKind = ELF::R_RISCV_GOT_HI20;
864 RelaxCandidate = true;
865 break;
867 if (MIFrm == RISCVII::InstFormatI)
868 FixupKind = ELF::R_RISCV_TPREL_LO12_I;
869 else if (MIFrm == RISCVII::InstFormatS)
870 FixupKind = ELF::R_RISCV_TPREL_LO12_S;
871 else
872 llvm_unreachable("VK_TPREL_LO used with unexpected instruction format");
873 RelaxCandidate = true;
874 break;
878 break;
879 }
881 RelaxCandidate = true;
882 break;
885 RelaxCandidate = true;
886 break;
887 case ELF::R_RISCV_GOT_HI20:
888 case ELF::R_RISCV_TPREL_HI20:
889 case ELF::R_RISCV_TLSDESC_HI20:
890 RelaxCandidate = true;
891 break;
892 }
893 } else if (Kind == MCExpr::SymbolRef || Kind == MCExpr::Binary) {
894 // FIXME: Sub kind binary exprs have chance of underflow.
895 if (MIFrm == RISCVII::InstFormatJ) {
897 RelaxCandidate = true;
898 } else if (MIFrm == RISCVII::InstFormatB) {
900 // Relaxes to B<cc>; JAL, with fixup_riscv_jal
901 AsmRelaxToLinkerRelaxable();
902 } else if (MIFrm == RISCVII::InstFormatCJ) {
904 // Relaxes to JAL with fixup_riscv_jal
905 AsmRelaxToLinkerRelaxable();
906 } else if (MIFrm == RISCVII::InstFormatCB) {
908 // Relaxes to B<cc>; JAL, with fixup_riscv_jal
909 AsmRelaxToLinkerRelaxable();
910 } else if (MIFrm == RISCVII::InstFormatCI) {
912 // Relaxes to `QC.E.LI` with fixup_riscv_qc_e_32
913 if (STI.hasFeature(RISCV::FeatureVendorXqcili))
914 AsmRelaxToLinkerRelaxable();
915 } else if (MIFrm == RISCVII::InstFormatI) {
917 } else if (MIFrm == RISCVII::InstFormatQC_EB) {
919 // Relaxes to QC.E.B<cc>I; JAL, with fixup_riscv_jal
920 AsmRelaxToLinkerRelaxable();
921 } else if (MIFrm == RISCVII::InstFormatQC_EAI) {
923 RelaxCandidate = true;
924 } else if (MIFrm == RISCVII::InstFormatQC_EJ) {
926 RelaxCandidate = true;
927 } else if (MIFrm == RISCVII::InstFormatNDS_BRANCH_10) {
929 }
930 }
931
932 assert(FixupKind != RISCV::fixup_riscv_invalid && "Unhandled expression!");
933
934 addFixup(Fixups, 0, Expr, FixupKind);
935 // If linker relaxation is enabled and supported by this relocation, set a bit
936 // so that the assembler knows the size of the instruction is not fixed/known,
937 // and the relocation will need a R_RISCV_RELAX relocation.
938 if (EnableRelax && RelaxCandidate)
939 Fixups.back().setLinkerRelaxable();
940 ++MCNumFixups;
941
942 return 0;
943}
944
945unsigned
946RISCVMCCodeEmitter::getYBNDSWImmOpValue(const MCInst &MI, unsigned OpNo,
947 SmallVectorImpl<MCFixup> &Fixups,
948 const MCSubtargetInfo &STI) const {
949 unsigned Imm = getImmOpValue(MI, OpNo, Fixups, STI);
950 assert(RISCV::isValidYBNDSWImm(Imm) && "Should have been checked before");
951 // YBNDSWI decodes to the requested length result as follows:
952 // If imm[8:0] == 0, result is 4096.
953 if (Imm == 4096)
954 return 0;
955 // If imm[8] == 0 and imm[7:0] != 0, result is imm[7:0] (1, 2, ..., 255).
956 if (Imm > 0 && Imm <= 255)
957 return Imm;
958 // If imm[8] == 1 and imm[7:5] == 0, result is
959 // `256 | (imm[3:0] << 4) | (imm[4] << 3)` (256, 264, ..., 504).
960 if (Imm >= 256 && Imm <= 504 && (Imm % 8) == 0) {
961 // Encode the multiples of 8 in this range in odd-even buckets, setting bit
962 // 4 of the immediate to 1 for odd multiples of 8.
963 unsigned MultipleOf8 = (Imm - 256) >> 3;
964 unsigned OddMultiple = MultipleOf8 & 1;
965 unsigned Bits3To0 = MultipleOf8 >> 1;
966 return 256 | (OddMultiple << 4) | Bits3To0;
967 }
968 // Otherwise, result is imm[7:0] << 4 (512, 528, ... 4080).
969 if (Imm >= 512 && Imm <= 4080 && (Imm % 16) == 0)
970 return 256 | (Imm >> 4);
971 llvm_unreachable("Invalid immediate for YBNDSWI");
972}
973
974unsigned RISCVMCCodeEmitter::getVMaskReg(const MCInst &MI, unsigned OpNo,
975 SmallVectorImpl<MCFixup> &Fixups,
976 const MCSubtargetInfo &STI) const {
977 MCOperand MO = MI.getOperand(OpNo);
978 assert(MO.isReg() && "Expected a register.");
979
980 switch (MO.getReg().id()) {
981 default:
982 llvm_unreachable("Invalid mask register.");
983 case RISCV::V0:
984 return 0;
985 case RISCV::NoRegister:
986 return 1;
987 }
988}
989
990unsigned RISCVMCCodeEmitter::getRlistOpValue(const MCInst &MI, unsigned OpNo,
991 SmallVectorImpl<MCFixup> &Fixups,
992 const MCSubtargetInfo &STI) const {
993 const MCOperand &MO = MI.getOperand(OpNo);
994 assert(MO.isImm() && "Rlist operand must be immediate");
995 auto Imm = MO.getImm();
996 assert(Imm >= 4 && "EABI is currently not implemented");
997 return Imm;
998}
999unsigned
1000RISCVMCCodeEmitter::getRlistS0OpValue(const MCInst &MI, unsigned OpNo,
1001 SmallVectorImpl<MCFixup> &Fixups,
1002 const MCSubtargetInfo &STI) const {
1003 const MCOperand &MO = MI.getOperand(OpNo);
1004 assert(MO.isImm() && "Rlist operand must be immediate");
1005 auto Imm = MO.getImm();
1006 assert(Imm >= 4 && "EABI is currently not implemented");
1007 assert(Imm != RISCVZC::RA && "Rlist operand must include s0");
1008 return Imm;
1009}
1010
1011#include "RISCVGenMCCodeEmitter.inc"
static void addFixup(SmallVectorImpl< MCFixup > &Fixups, uint32_t Offset, const MCExpr *Value, uint16_t Kind, bool PCRel=false)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
IRTranslator LLVM IR MI
#define QC_ACCESS_CASE(_Suffix)
static unsigned getInvertedBranchOp(unsigned BrOp)
static unsigned getImmOpValue(const MCOperand &MO, SmallVectorImpl< MCFixup > &Fixups, uint16_t Kind)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
MCCodeEmitter - Generic instruction encoding interface.
Context object for machine code objects.
Definition MCContext.h:84
const MCRegisterInfo * getRegisterInfo() const
Definition MCContext.h:411
const Triple & getTargetTriple() const
Definition MCContext.h:397
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:31
@ SymbolRef
References to labels and assigned expressions.
Definition MCExpr.h:40
@ Specifier
Expression with a relocation specifier.
Definition MCExpr.h:42
@ Binary
Binary expressions.
Definition MCExpr.h:38
ExprKind getKind() const
Definition MCExpr.h:82
static MCFixup create(uint32_t Offset, const MCExpr *Value, MCFixupKind Kind, bool PCRel=false)
Consider bit fields if we need more flags.
Definition MCFixup.h:90
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:187
void addOperand(const MCOperand Op)
Definition MCInst.h:214
unsigned getSize() const
Return the number of bytes in the encoding of this instruction, or zero if the encoding size cannot b...
Interface to description of machine instruction set.
Definition MCInstrInfo.h:27
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition MCInstrInfo.h:89
static MCOperand createExpr(const MCExpr *Val)
Definition MCInst.h:165
int64_t getImm() const
Definition MCInst.h:83
static MCOperand createImm(int64_t Val)
Definition MCInst.h:144
bool isImm() const
Definition MCInst.h:65
bool isReg() const
Definition MCInst.h:64
MCRegister getReg() const
Returns the register number.
Definition MCInst.h:72
const MCExpr * getExpr() const
Definition MCInst.h:117
bool isExpr() const
Definition MCInst.h:68
uint16_t getEncodingValue(MCRegister Reg) const
Returns the encoding for Reg.
constexpr unsigned id() const
Definition MCRegister.h:85
Generic base class for all target subtargets.
bool hasFeature(unsigned Feature) const
const Triple & getTargetTriple() const
const FeatureBitset & getFeatureBits() const
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void truncate(size_type N)
Like resize, but requires that N is less than size().
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition Triple.h:879
LLVM Value Representation.
Definition Value.h:75
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static unsigned getFormat(uint64_t TSFlags)
static MCRegister getTailExpandUseRegNo(const FeatureBitset &FeatureBits)
bool isValidYBNDSWImm(int64_t Imm)
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
void write(void *memory, value_type value, endianness endian)
Write a value to memory with a particular endianness.
Definition Endian.h:82
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
MCCodeEmitter * createRISCVMCCodeEmitter(const MCInstrInfo &MCII, MCContext &Ctx)
constexpr MCFixupKind FirstTargetFixupKind
Definition MCFixup.h:49
Op::Description Desc
static Lanai::Fixups FixupKind(const MCExpr *Expr)
static void addFixup(SmallVectorImpl< MCFixup > &Fixups, uint32_t Offset, const MCExpr *Value, uint16_t Kind)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N