LLVM  9.0.0svn
RISCVAsmBackend.cpp
Go to the documentation of this file.
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/MCAssembler.h"
13 #include "llvm/MC/MCContext.h"
14 #include "llvm/MC/MCDirectives.h"
16 #include "llvm/MC/MCExpr.h"
17 #include "llvm/MC/MCObjectWriter.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/MC/MCValue.h"
22 
23 using namespace llvm;
24 
25 // If linker relaxation is enabled, or the relax option had previously been
26 // enabled, always emit relocations even if the fixup can be resolved. This is
27 // necessary for correctness as offsets may change during relaxation.
29  const MCFixup &Fixup,
30  const MCValue &Target) {
31  bool ShouldForce = false;
32 
33  switch ((unsigned)Fixup.getKind()) {
34  default:
35  break;
39  return true;
42  // For pcrel_lo12, force a relocation if the target of the corresponding
43  // pcrel_hi20 is not in the same fragment.
44  const MCFixup *T = cast<RISCVMCExpr>(Fixup.getValue())->getPCRelHiFixup();
45  if (!T) {
46  Asm.getContext().reportError(Fixup.getLoc(),
47  "could not find corresponding %pcrel_hi");
48  return false;
49  }
50 
51  switch ((unsigned)T->getKind()) {
52  default:
53  llvm_unreachable("Unexpected fixup kind for pcrel_lo12");
54  break;
58  ShouldForce = true;
59  break;
61  ShouldForce = T->getValue()->findAssociatedFragment() !=
63  break;
64  }
65  break;
66  }
67 
68  return ShouldForce || STI.getFeatureBits()[RISCV::FeatureRelax] ||
69  ForceRelocs;
70 }
71 
73  bool Resolved,
74  uint64_t Value,
75  const MCRelaxableFragment *DF,
76  const MCAsmLayout &Layout,
77  const bool WasForced) const {
78  // Return true if the symbol is actually unresolved.
79  // Resolved could be always false when shouldForceRelocation return true.
80  // We use !WasForced to indicate that the symbol is unresolved and not forced
81  // by shouldForceRelocation.
82  if (!Resolved && !WasForced)
83  return true;
84 
85  int64_t Offset = int64_t(Value);
86  switch ((unsigned)Fixup.getKind()) {
87  default:
88  return false;
90  // For compressed branch instructions the immediate must be
91  // in the range [-256, 254].
92  return Offset > 254 || Offset < -256;
94  // For compressed jump instructions the immediate must be
95  // in the range [-2048, 2046].
96  return Offset > 2046 || Offset < -2048;
97  }
98 }
99 
101  const MCSubtargetInfo &STI,
102  MCInst &Res) const {
103  // TODO: replace this with call to auto generated uncompressinstr() function.
104  switch (Inst.getOpcode()) {
105  default:
106  llvm_unreachable("Opcode not expected!");
107  case RISCV::C_BEQZ:
108  // c.beqz $rs1, $imm -> beq $rs1, X0, $imm.
109  Res.setOpcode(RISCV::BEQ);
110  Res.addOperand(Inst.getOperand(0));
111  Res.addOperand(MCOperand::createReg(RISCV::X0));
112  Res.addOperand(Inst.getOperand(1));
113  break;
114  case RISCV::C_BNEZ:
115  // c.bnez $rs1, $imm -> bne $rs1, X0, $imm.
116  Res.setOpcode(RISCV::BNE);
117  Res.addOperand(Inst.getOperand(0));
118  Res.addOperand(MCOperand::createReg(RISCV::X0));
119  Res.addOperand(Inst.getOperand(1));
120  break;
121  case RISCV::C_J:
122  // c.j $imm -> jal X0, $imm.
123  Res.setOpcode(RISCV::JAL);
124  Res.addOperand(MCOperand::createReg(RISCV::X0));
125  Res.addOperand(Inst.getOperand(0));
126  break;
127  case RISCV::C_JAL:
128  // c.jal $imm -> jal X1, $imm.
129  Res.setOpcode(RISCV::JAL);
130  Res.addOperand(MCOperand::createReg(RISCV::X1));
131  Res.addOperand(Inst.getOperand(0));
132  break;
133  }
134 }
135 
136 // Given a compressed control flow instruction this function returns
137 // the expanded instruction.
138 unsigned RISCVAsmBackend::getRelaxedOpcode(unsigned Op) const {
139  switch (Op) {
140  default:
141  return Op;
142  case RISCV::C_BEQZ:
143  return RISCV::BEQ;
144  case RISCV::C_BNEZ:
145  return RISCV::BNE;
146  case RISCV::C_J:
147  case RISCV::C_JAL: // fall through.
148  return RISCV::JAL;
149  }
150 }
151 
153  const MCSubtargetInfo &STI) const {
154  return getRelaxedOpcode(Inst.getOpcode()) != Inst.getOpcode();
155 }
156 
157 bool RISCVAsmBackend::writeNopData(raw_ostream &OS, uint64_t Count) const {
158  bool HasStdExtC = STI.getFeatureBits()[RISCV::FeatureStdExtC];
159  unsigned MinNopLen = HasStdExtC ? 2 : 4;
160 
161  if ((Count % MinNopLen) != 0)
162  return false;
163 
164  // The canonical nop on RISC-V is addi x0, x0, 0.
165  for (; Count >= 4; Count -= 4)
166  OS.write("\x13\0\0\0", 4);
167 
168  // The canonical nop on RVC is c.nop.
169  if (Count && HasStdExtC)
170  OS.write("\x01\0", 2);
171 
172  return true;
173 }
174 
175 static uint64_t adjustFixupValue(const MCFixup &Fixup, uint64_t Value,
176  MCContext &Ctx) {
177  unsigned Kind = Fixup.getKind();
178  switch (Kind) {
179  default:
180  llvm_unreachable("Unknown fixup kind!");
184  llvm_unreachable("Relocation should be unconditionally forced\n");
185  case FK_Data_1:
186  case FK_Data_2:
187  case FK_Data_4:
188  case FK_Data_8:
189  return Value;
193  return Value & 0xfff;
197  return (((Value >> 5) & 0x7f) << 25) | ((Value & 0x1f) << 7);
201  // Add 1 if bit 11 is 1, to compensate for low 12 bits being negative.
202  return ((Value + 0x800) >> 12) & 0xfffff;
203  case RISCV::fixup_riscv_jal: {
204  if (!isInt<21>(Value))
205  Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
206  if (Value & 0x1)
207  Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
208  // Need to produce imm[19|10:1|11|19:12] from the 21-bit Value.
209  unsigned Sbit = (Value >> 20) & 0x1;
210  unsigned Hi8 = (Value >> 12) & 0xff;
211  unsigned Mid1 = (Value >> 11) & 0x1;
212  unsigned Lo10 = (Value >> 1) & 0x3ff;
213  // Inst{31} = Sbit;
214  // Inst{30-21} = Lo10;
215  // Inst{20} = Mid1;
216  // Inst{19-12} = Hi8;
217  Value = (Sbit << 19) | (Lo10 << 9) | (Mid1 << 8) | Hi8;
218  return Value;
219  }
221  if (!isInt<13>(Value))
222  Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
223  if (Value & 0x1)
224  Ctx.reportError(Fixup.getLoc(), "fixup value must be 2-byte aligned");
225  // Need to extract imm[12], imm[10:5], imm[4:1], imm[11] from the 13-bit
226  // Value.
227  unsigned Sbit = (Value >> 12) & 0x1;
228  unsigned Hi1 = (Value >> 11) & 0x1;
229  unsigned Mid6 = (Value >> 5) & 0x3f;
230  unsigned Lo4 = (Value >> 1) & 0xf;
231  // Inst{31} = Sbit;
232  // Inst{30-25} = Mid6;
233  // Inst{11-8} = Lo4;
234  // Inst{7} = Hi1;
235  Value = (Sbit << 31) | (Mid6 << 25) | (Lo4 << 8) | (Hi1 << 7);
236  return Value;
237  }
240  // Jalr will add UpperImm with the sign-extended 12-bit LowerImm,
241  // we need to add 0x800ULL before extract upper bits to reflect the
242  // effect of the sign extension.
243  uint64_t UpperImm = (Value + 0x800ULL) & 0xfffff000ULL;
244  uint64_t LowerImm = Value & 0xfffULL;
245  return UpperImm | ((LowerImm << 20) << 32);
246  }
248  // Need to produce offset[11|4|9:8|10|6|7|3:1|5] from the 11-bit Value.
249  unsigned Bit11 = (Value >> 11) & 0x1;
250  unsigned Bit4 = (Value >> 4) & 0x1;
251  unsigned Bit9_8 = (Value >> 8) & 0x3;
252  unsigned Bit10 = (Value >> 10) & 0x1;
253  unsigned Bit6 = (Value >> 6) & 0x1;
254  unsigned Bit7 = (Value >> 7) & 0x1;
255  unsigned Bit3_1 = (Value >> 1) & 0x7;
256  unsigned Bit5 = (Value >> 5) & 0x1;
257  Value = (Bit11 << 10) | (Bit4 << 9) | (Bit9_8 << 7) | (Bit10 << 6) |
258  (Bit6 << 5) | (Bit7 << 4) | (Bit3_1 << 1) | Bit5;
259  return Value;
260  }
262  // Need to produce offset[8|4:3], [reg 3 bit], offset[7:6|2:1|5]
263  unsigned Bit8 = (Value >> 8) & 0x1;
264  unsigned Bit7_6 = (Value >> 6) & 0x3;
265  unsigned Bit5 = (Value >> 5) & 0x1;
266  unsigned Bit4_3 = (Value >> 3) & 0x3;
267  unsigned Bit2_1 = (Value >> 1) & 0x3;
268  Value = (Bit8 << 12) | (Bit4_3 << 10) | (Bit7_6 << 5) | (Bit2_1 << 3) |
269  (Bit5 << 2);
270  return Value;
271  }
272 
273  }
274 }
275 
277  const MCValue &Target,
278  MutableArrayRef<char> Data, uint64_t Value,
279  bool IsResolved,
280  const MCSubtargetInfo *STI) const {
281  MCContext &Ctx = Asm.getContext();
283  if (!Value)
284  return; // Doesn't change encoding.
285  // Apply any target-specific value adjustments.
286  Value = adjustFixupValue(Fixup, Value, Ctx);
287 
288  // Shift the value into position.
289  Value <<= Info.TargetOffset;
290 
291  unsigned Offset = Fixup.getOffset();
292  unsigned NumBytes = alignTo(Info.TargetSize + Info.TargetOffset, 8) / 8;
293 
294  assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
295 
296  // For each byte of the fragment that the fixup touches, mask in the
297  // bits from the fixup value.
298  for (unsigned i = 0; i != NumBytes; ++i) {
299  Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
300  }
301 }
302 
303 // Linker relaxation may change code size. We have to insert Nops
304 // for .align directive when linker relaxation enabled. So then Linker
305 // could satisfy alignment by removing Nops.
306 // The function return the total Nops Size we need to insert.
308  const MCAlignFragment &AF, unsigned &Size) {
309  // Calculate Nops Size only when linker relaxation enabled.
310  if (!STI.getFeatureBits()[RISCV::FeatureRelax])
311  return false;
312 
313  bool HasStdExtC = STI.getFeatureBits()[RISCV::FeatureStdExtC];
314  unsigned MinNopLen = HasStdExtC ? 2 : 4;
315 
316  Size = AF.getAlignment() - MinNopLen;
317  return true;
318 }
319 
320 // We need to insert R_RISCV_ALIGN relocation type to indicate the
321 // position of Nops and the total bytes of the Nops have been inserted
322 // when linker relaxation enabled.
323 // The function insert fixup_riscv_align fixup which eventually will
324 // transfer to R_RISCV_ALIGN relocation type.
326  const MCAsmLayout &Layout,
327  MCAlignFragment &AF) {
328  // Insert the fixup only when linker relaxation enabled.
329  if (!STI.getFeatureBits()[RISCV::FeatureRelax])
330  return false;
331 
332  // Calculate total Nops we need to insert.
333  unsigned Count;
335  // No Nop need to insert, simply return.
336  if (Count == 0)
337  return false;
338 
339  MCContext &Ctx = Asm.getContext();
340  const MCExpr *Dummy = MCConstantExpr::create(0, Ctx);
341  // Create fixup_riscv_align fixup.
342  MCFixup Fixup =
344 
345  uint64_t FixedValue = 0;
346  MCValue NopBytes = MCValue::get(Count);
347 
348  Asm.getWriter().recordRelocation(Asm, Layout, &AF, Fixup, NopBytes,
349  FixedValue);
350 
351  return true;
352 }
353 
354 std::unique_ptr<MCObjectTargetWriter>
356  return createRISCVELFObjectWriter(OSABI, Is64Bit);
357 }
358 
360  const MCSubtargetInfo &STI,
361  const MCRegisterInfo &MRI,
362  const MCTargetOptions &Options) {
363  const Triple &TT = STI.getTargetTriple();
364  uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TT.getOS());
365  return new RISCVAsmBackend(STI, OSABI, TT.isArch64Bit(), Options);
366 }
std::unique_ptr< MCObjectTargetWriter > createRISCVELFObjectWriter(uint8_t OSABI, bool Is64Bit)
MCAsmBackend * createRISCVAsmBackend(const Target &T, const MCSubtargetInfo &STI, const MCRegisterInfo &MRI, const MCTargetOptions &Options)
This class represents lattice values for constants.
Definition: AllocatorList.h:23
This represents an "assembler immediate".
Definition: MCValue.h:39
OSType getOS() const
getOS - Get the parsed operating system type of this triple.
Definition: Triple.h:304
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:684
bool fixupNeedsRelaxationAdvanced(const MCFixup &Fixup, bool Resolved, uint64_t Value, const MCRelaxableFragment *DF, const MCAsmLayout &Layout, const bool WasForced) const override
Target specific predicate for whether a given fixup requires the associated instruction to be relaxed...
unsigned TargetOffset
The bit offset to write the relocation into.
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:74
const Triple & getTargetTriple() const
MCContext & getContext() const
Definition: MCAssembler.h:284
static MCOperand createReg(unsigned Reg)
Definition: MCInst.h:115
const FeatureBitset & getFeatureBits() const
Encapsulates the layout of an assembly file at a particular point in time.
Definition: MCAsmLayout.h:28
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
MCObjectWriter & getWriter() const
Definition: MCAssembler.h:296
bool shouldInsertExtraNopBytesForCodeAlign(const MCAlignFragment &AF, unsigned &Size) override
Hook to check if extra nop bytes must be inserted for alignment directive.
This file implements a class to represent arbitrary precision integral constant values and operations...
A four-byte fixup.
Definition: MCFixup.h:26
Context object for machine code objects.
Definition: MCContext.h:62
unsigned getRelaxedOpcode(unsigned Op) const
bool writeNopData(raw_ostream &OS, uint64_t Count) const override
Write an (optimal) nop sequence of Count bytes to the given output.
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...
Analysis containing CSE Info
Definition: CSEInfo.cpp:20
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...
A relaxable fragment holds on to its MCInst, since it may need to be relaxed during the assembler lay...
Definition: MCFragment.h:270
unsigned const MachineRegisterInfo * MRI
static uint64_t adjustFixupValue(const MCFixup &Fixup, uint64_t Value, MCContext &Ctx)
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:290
bool shouldInsertFixupForCodeAlign(MCAssembler &Asm, const MCAsmLayout &Layout, MCAlignFragment &AF) override
Hook which indicates if the target requires a fixup to be generated when handling an align directive ...
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:148
MCFixupKind
Extensible enumeration to represent the type of a fixup.
Definition: MCFixup.h:22
void reportError(SMLoc L, const Twine &Msg)
Definition: MCContext.cpp:652
uint32_t getOffset() const
Definition: MCFixup.h:125
std::unique_ptr< MCObjectTargetWriter > createObjectTargetWriter() const override
static MCFixup create(uint32_t Offset, const MCExpr *Value, MCFixupKind Kind, SMLoc Loc=SMLoc())
Definition: MCFixup.h:90
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
A one-byte fixup.
Definition: MCFixup.h:24
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:43
raw_ostream & write(unsigned char C)
PowerPC TLS Dynamic Call Fixup
SMLoc getLoc() const
Definition: MCFixup.h:166
void setOpcode(unsigned Op)
Definition: MCInst.h:170
const MCOperand & getOperand(unsigned i) const
Definition: MCInst.h:179
virtual void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment, const MCFixup &Fixup, MCValue Target, uint64_t &FixedValue)=0
Record a relocation entry.
unsigned TargetSize
The number of bits written by this fixup.
MCFragment * findAssociatedFragment() const
Find the "associated section" for this expression, which is currently defined as the absolute section...
Definition: MCExpr.cpp:868
Target - Wrapper for Target specific information.
unsigned getAlignment() const
Definition: MCFragment.h:317
bool isArch64Bit() const
Test whether the architecture is 64-bit.
Definition: Triple.cpp:1290
static MCValue get(const MCSymbolRefExpr *SymA, const MCSymbolRefExpr *SymB=nullptr, int64_t Val=0, uint32_t RefKind=0)
Definition: MCValue.h:62
Generic base class for all target subtargets.
A eight-byte fixup.
Definition: MCFixup.h:27
uint32_t Size
Definition: Profile.cpp:46
void relaxInstruction(const MCInst &Inst, const MCSubtargetInfo &STI, MCInst &Res) const override
Relax the instruction in the given fragment to the next wider instruction.
Target independent information on a fixup kind.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:72
Generic interface to target specific assembler backends.
Definition: MCAsmBackend.h:41
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
const MCExpr * getValue() const
Definition: MCFixup.h:128
void addOperand(const MCOperand &Op)
Definition: MCInst.h:183
bool shouldForceRelocation(const MCAssembler &Asm, const MCFixup &Fixup, const MCValue &Target) override
Hook to check if a relocation is needed for some target specific reason.
bool mayNeedRelaxation(const MCInst &Inst, const MCSubtargetInfo &STI) const override
Check whether the given instruction may need relaxation.
Represents a location in source code.
Definition: SMLoc.h:23
unsigned getOpcode() const
Definition: MCInst.h:171
const MCFixupKindInfo & getFixupKindInfo(MCFixupKind Kind) const override
Get information on a fixup kind.
RISCVAsmBackend(const MCSubtargetInfo &STI, uint8_t OSABI, bool Is64Bit, const MCTargetOptions &Options)
A two-byte fixup.
Definition: MCFixup.h:25
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx)
Definition: MCExpr.cpp:163
MCFixupKind getKind() const
Definition: MCFixup.h:123