LLVM  9.0.0svn
RISCVMCCodeEmitter.cpp
Go to the documentation of this file.
1 //===-- RISCVMCCodeEmitter.cpp - Convert RISCV 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 
16 #include "Utils/RISCVBaseInfo.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCCodeEmitter.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCInstBuilder.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCRegisterInfo.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/Support/Casting.h"
30 
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "mccodeemitter"
34 
35 STATISTIC(MCNumEmitted, "Number of MC instructions emitted");
36 STATISTIC(MCNumFixups, "Number of MC fixups created");
37 
38 namespace {
39 class RISCVMCCodeEmitter : public MCCodeEmitter {
40  RISCVMCCodeEmitter(const RISCVMCCodeEmitter &) = delete;
41  void operator=(const RISCVMCCodeEmitter &) = delete;
42  MCContext &Ctx;
43  MCInstrInfo const &MCII;
44 
45 public:
46  RISCVMCCodeEmitter(MCContext &ctx, MCInstrInfo const &MCII)
47  : Ctx(ctx), MCII(MCII) {}
48 
49  ~RISCVMCCodeEmitter() override {}
50 
51  void encodeInstruction(const MCInst &MI, raw_ostream &OS,
53  const MCSubtargetInfo &STI) const override;
54 
55  void expandFunctionCall(const MCInst &MI, raw_ostream &OS,
57  const MCSubtargetInfo &STI) const;
58 
59  void expandAddTPRel(const MCInst &MI, raw_ostream &OS,
61  const MCSubtargetInfo &STI) const;
62 
63  /// TableGen'erated function for getting the binary encoding for an
64  /// instruction.
65  uint64_t getBinaryCodeForInstr(const MCInst &MI,
67  const MCSubtargetInfo &STI) const;
68 
69  /// Return binary encoding of operand. If the machine operand requires
70  /// relocation, record the relocation and return zero.
71  unsigned getMachineOpValue(const MCInst &MI, const MCOperand &MO,
73  const MCSubtargetInfo &STI) const;
74 
75  unsigned getImmOpValueAsr1(const MCInst &MI, unsigned OpNo,
77  const MCSubtargetInfo &STI) const;
78 
79  unsigned getImmOpValue(const MCInst &MI, unsigned OpNo,
81  const MCSubtargetInfo &STI) const;
82 };
83 } // end anonymous namespace
84 
86  const MCRegisterInfo &MRI,
87  MCContext &Ctx) {
88  return new RISCVMCCodeEmitter(Ctx, MCII);
89 }
90 
91 // Expand PseudoCALL and PseudoTAIL to AUIPC and JALR with relocation types.
92 // We expand PseudoCALL and PseudoTAIL while encoding, meaning AUIPC and JALR
93 // won't go through RISCV MC to MC compressed instruction transformation. This
94 // is acceptable because AUIPC has no 16-bit form and C_JALR have no immediate
95 // operand field. We let linker relaxation deal with it. When linker
96 // relaxation enabled, AUIPC and JALR have chance relax to JAL. If C extension
97 // is enabled, JAL has chance relax to C_JAL.
98 void RISCVMCCodeEmitter::expandFunctionCall(const MCInst &MI, raw_ostream &OS,
100  const MCSubtargetInfo &STI) const {
101  MCInst TmpInst;
102  MCOperand Func = MI.getOperand(0);
103  unsigned Ra = (MI.getOpcode() == RISCV::PseudoTAIL) ? RISCV::X6 : RISCV::X1;
104  uint32_t Binary;
105 
106  assert(Func.isExpr() && "Expected expression");
107 
108  const MCExpr *CallExpr = Func.getExpr();
109 
110  // Emit AUIPC Ra, Func with R_RISCV_CALL relocation type.
111  TmpInst = MCInstBuilder(RISCV::AUIPC)
112  .addReg(Ra)
113  .addOperand(MCOperand::createExpr(CallExpr));
114  Binary = getBinaryCodeForInstr(TmpInst, Fixups, STI);
116 
117  if (MI.getOpcode() == RISCV::PseudoTAIL)
118  // Emit JALR X0, X6, 0
119  TmpInst = MCInstBuilder(RISCV::JALR).addReg(RISCV::X0).addReg(Ra).addImm(0);
120  else
121  // Emit JALR X1, X1, 0
122  TmpInst = MCInstBuilder(RISCV::JALR).addReg(Ra).addReg(Ra).addImm(0);
123  Binary = getBinaryCodeForInstr(TmpInst, Fixups, STI);
125 }
126 
127 // Expand PseudoAddTPRel to a simple ADD with the correct relocation.
128 void RISCVMCCodeEmitter::expandAddTPRel(const MCInst &MI, raw_ostream &OS,
129  SmallVectorImpl<MCFixup> &Fixups,
130  const MCSubtargetInfo &STI) const {
131  MCOperand DestReg = MI.getOperand(0);
132  MCOperand SrcReg = MI.getOperand(1);
133  MCOperand TPReg = MI.getOperand(2);
134  assert(TPReg.isReg() && TPReg.getReg() == RISCV::X4 &&
135  "Expected thread pointer as second input to TP-relative add");
136 
137  MCOperand SrcSymbol = MI.getOperand(3);
138  assert(SrcSymbol.isExpr() &&
139  "Expected expression as third input to TP-relative add");
140 
141  const RISCVMCExpr *Expr = dyn_cast<RISCVMCExpr>(SrcSymbol.getExpr());
142  assert(Expr && Expr->getKind() == RISCVMCExpr::VK_RISCV_TPREL_ADD &&
143  "Expected tprel_add relocation on TP-relative symbol");
144 
145  // Emit the correct tprel_add relocation for the symbol.
146  Fixups.push_back(MCFixup::create(
148 
149  // Emit fixup_riscv_relax for tprel_add where the relax feature is enabled.
150  if (STI.getFeatureBits()[RISCV::FeatureRelax]) {
152  Fixups.push_back(MCFixup::create(
153  0, Dummy, MCFixupKind(RISCV::fixup_riscv_relax), MI.getLoc()));
154  }
155 
156  // Emit a normal ADD instruction with the given operands.
157  MCInst TmpInst = MCInstBuilder(RISCV::ADD)
158  .addOperand(DestReg)
159  .addOperand(SrcReg)
160  .addOperand(TPReg);
161  uint32_t Binary = getBinaryCodeForInstr(TmpInst, Fixups, STI);
163 }
164 
165 void RISCVMCCodeEmitter::encodeInstruction(const MCInst &MI, raw_ostream &OS,
166  SmallVectorImpl<MCFixup> &Fixups,
167  const MCSubtargetInfo &STI) const {
168  const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
169  // Get byte count of instruction.
170  unsigned Size = Desc.getSize();
171 
172  if (MI.getOpcode() == RISCV::PseudoCALL ||
173  MI.getOpcode() == RISCV::PseudoTAIL) {
174  expandFunctionCall(MI, OS, Fixups, STI);
175  MCNumEmitted += 2;
176  return;
177  }
178 
179  if (MI.getOpcode() == RISCV::PseudoAddTPRel) {
180  expandAddTPRel(MI, OS, Fixups, STI);
181  MCNumEmitted += 1;
182  return;
183  }
184 
185  switch (Size) {
186  default:
187  llvm_unreachable("Unhandled encodeInstruction length!");
188  case 2: {
189  uint16_t Bits = getBinaryCodeForInstr(MI, Fixups, STI);
190  support::endian::write<uint16_t>(OS, Bits, support::little);
191  break;
192  }
193  case 4: {
194  uint32_t Bits = getBinaryCodeForInstr(MI, Fixups, STI);
196  break;
197  }
198  }
199 
200  ++MCNumEmitted; // Keep track of the # of mi's emitted.
201 }
202 
203 unsigned
204 RISCVMCCodeEmitter::getMachineOpValue(const MCInst &MI, const MCOperand &MO,
205  SmallVectorImpl<MCFixup> &Fixups,
206  const MCSubtargetInfo &STI) const {
207 
208  if (MO.isReg())
209  return Ctx.getRegisterInfo()->getEncodingValue(MO.getReg());
210 
211  if (MO.isImm())
212  return static_cast<unsigned>(MO.getImm());
213 
214  llvm_unreachable("Unhandled expression!");
215  return 0;
216 }
217 
218 unsigned
219 RISCVMCCodeEmitter::getImmOpValueAsr1(const MCInst &MI, unsigned OpNo,
220  SmallVectorImpl<MCFixup> &Fixups,
221  const MCSubtargetInfo &STI) const {
222  const MCOperand &MO = MI.getOperand(OpNo);
223 
224  if (MO.isImm()) {
225  unsigned Res = MO.getImm();
226  assert((Res & 1) == 0 && "LSB is non-zero");
227  return Res >> 1;
228  }
229 
230  return getImmOpValue(MI, OpNo, Fixups, STI);
231 }
232 
233 unsigned RISCVMCCodeEmitter::getImmOpValue(const MCInst &MI, unsigned OpNo,
234  SmallVectorImpl<MCFixup> &Fixups,
235  const MCSubtargetInfo &STI) const {
236  bool EnableRelax = STI.getFeatureBits()[RISCV::FeatureRelax];
237  const MCOperand &MO = MI.getOperand(OpNo);
238 
239  MCInstrDesc const &Desc = MCII.get(MI.getOpcode());
240  unsigned MIFrm = Desc.TSFlags & RISCVII::InstFormatMask;
241 
242  // If the destination is an immediate, there is nothing to do.
243  if (MO.isImm())
244  return MO.getImm();
245 
246  assert(MO.isExpr() &&
247  "getImmOpValue expects only expressions or immediates");
248  const MCExpr *Expr = MO.getExpr();
249  MCExpr::ExprKind Kind = Expr->getKind();
251  bool RelaxCandidate = false;
252  if (Kind == MCExpr::Target) {
253  const RISCVMCExpr *RVExpr = cast<RISCVMCExpr>(Expr);
254 
255  switch (RVExpr->getKind()) {
258  llvm_unreachable("Unhandled fixup kind!");
260  // tprel_add is only used to indicate that a relocation should be emitted
261  // for an add instruction used in TP-relative addressing. It should not be
262  // expanded as if representing an actual instruction operand and so to
263  // encounter it here is an error.
265  "VK_RISCV_TPREL_ADD should not represent an instruction operand");
267  if (MIFrm == RISCVII::InstFormatI)
268  FixupKind = RISCV::fixup_riscv_lo12_i;
269  else if (MIFrm == RISCVII::InstFormatS)
270  FixupKind = RISCV::fixup_riscv_lo12_s;
271  else
272  llvm_unreachable("VK_RISCV_LO used with unexpected instruction format");
273  RelaxCandidate = true;
274  break;
276  FixupKind = RISCV::fixup_riscv_hi20;
277  RelaxCandidate = true;
278  break;
280  if (MIFrm == RISCVII::InstFormatI)
282  else if (MIFrm == RISCVII::InstFormatS)
284  else
286  "VK_RISCV_PCREL_LO used with unexpected instruction format");
287  RelaxCandidate = true;
288  break;
290  FixupKind = RISCV::fixup_riscv_pcrel_hi20;
291  RelaxCandidate = true;
292  break;
294  FixupKind = RISCV::fixup_riscv_got_hi20;
295  break;
297  if (MIFrm == RISCVII::InstFormatI)
299  else if (MIFrm == RISCVII::InstFormatS)
301  else
303  "VK_RISCV_TPREL_LO used with unexpected instruction format");
304  RelaxCandidate = true;
305  break;
307  FixupKind = RISCV::fixup_riscv_tprel_hi20;
308  RelaxCandidate = true;
309  break;
311  FixupKind = RISCV::fixup_riscv_call;
312  RelaxCandidate = true;
313  break;
315  FixupKind = RISCV::fixup_riscv_call_plt;
316  RelaxCandidate = true;
317  break;
318  }
319  } else if (Kind == MCExpr::SymbolRef &&
320  cast<MCSymbolRefExpr>(Expr)->getKind() == MCSymbolRefExpr::VK_None) {
321  if (Desc.getOpcode() == RISCV::JAL) {
322  FixupKind = RISCV::fixup_riscv_jal;
323  } else if (MIFrm == RISCVII::InstFormatB) {
324  FixupKind = RISCV::fixup_riscv_branch;
325  } else if (MIFrm == RISCVII::InstFormatCJ) {
326  FixupKind = RISCV::fixup_riscv_rvc_jump;
327  } else if (MIFrm == RISCVII::InstFormatCB) {
328  FixupKind = RISCV::fixup_riscv_rvc_branch;
329  }
330  }
331 
332  assert(FixupKind != RISCV::fixup_riscv_invalid && "Unhandled expression!");
333 
334  Fixups.push_back(
335  MCFixup::create(0, Expr, MCFixupKind(FixupKind), MI.getLoc()));
336  ++MCNumFixups;
337 
338  // Ensure an R_RISCV_RELAX relocation will be emitted if linker relaxation is
339  // enabled and the current fixup will result in a relocation that may be
340  // relaxed.
341  if (EnableRelax && RelaxCandidate) {
343  Fixups.push_back(
345  MI.getLoc()));
346  ++MCNumFixups;
347  }
348 
349  return 0;
350 }
351 
352 #include "RISCVGenMCCodeEmitter.inc"
bool isImm() const
Definition: MCInst.h:58
This class represents lattice values for constants.
Definition: AllocatorList.h:23
static MCOperand createExpr(const MCExpr *Val)
Definition: MCInst.h:136
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:163
bool isReg() const
Definition: MCInst.h:57
VariantKind getKind() const
Definition: RISCVMCExpr.h:56
STATISTIC(NumFunctions, "Total number of functions")
static Lanai::Fixups FixupKind(const MCExpr *Expr)
const FeatureBitset & getFeatureBits() const
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:41
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
MCCodeEmitter * createRISCVMCCodeEmitter(const MCInstrInfo &MCII, const MCRegisterInfo &MRI, MCContext &Ctx)
unsigned getReg() const
Returns the register number.
Definition: MCInst.h:64
Context object for machine code objects.
Definition: MCContext.h:62
Simple integer binary arithmetic operators.
Definition: ISDOpcodes.h:200
const MCExpr * getExpr() const
Definition: MCInst.h:95
MCInstBuilder & addOperand(const MCOperand &Op)
Add an operand.
Definition: MCInstBuilder.h:61
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:158
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
void write(void *memory, value_type value, endianness endian)
Write a value to memory with a particular endianness.
Definition: Endian.h:99
int64_t getImm() const
Definition: MCInst.h:75
MCInstBuilder & addReg(unsigned Reg)
Add a new register operand.
Definition: MCInstBuilder.h:31
unsigned const MachineRegisterInfo * MRI
MCCodeEmitter - Generic instruction encoding interface.
Definition: MCCodeEmitter.h:21
Interface to description of machine instruction set.
Definition: MCInstrInfo.h:23
MCFixupKind
Extensible enumeration to represent the type of a fixup.
Definition: MCFixup.h:22
bool isExpr() const
Definition: MCInst.h:60
MCInstBuilder & addImm(int64_t Val)
Add a new integer immediate operand.
Definition: MCInstBuilder.h:37
static MCFixup create(uint32_t Offset, const MCExpr *Value, MCFixupKind Kind, SMLoc Loc=SMLoc())
Definition: MCFixup.h:89
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const MCOperand & getOperand(unsigned i) const
Definition: MCInst.h:179
SMLoc getLoc() const
Definition: MCInst.h:177
Generic base class for all target subtargets.
References to labels and assigned expressions.
Definition: MCExpr.h:40
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
uint32_t Size
Definition: Profile.cpp:46
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getOpcode() const
Return the opcode number for this descriptor.
Definition: MCInstrDesc.h:203
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
IRTranslator LLVM IR MI
Target specific expression.
Definition: MCExpr.h:42
unsigned getOpcode() const
Definition: MCInst.h:171
Instances of this class represent operands of the MCInst class.
Definition: MCInst.h:34
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx)
Definition: MCExpr.cpp:163
unsigned getSize() const
Return the number of bytes in the encoding of this instruction, or zero if the encoding size cannot b...
Definition: MCInstrDesc.h:580