LLVM  8.0.1
RISCVInstrInfo.cpp
Go to the documentation of this file.
1 //===-- RISCVInstrInfo.cpp - RISCV Instruction Information ------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the RISCV implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVInstrInfo.h"
15 #include "RISCV.h"
16 #include "RISCVSubtarget.h"
17 #include "RISCVTargetMachine.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
26 
27 #define GET_INSTRINFO_CTOR_DTOR
28 #include "RISCVGenInstrInfo.inc"
29 
30 using namespace llvm;
31 
33  : RISCVGenInstrInfo(RISCV::ADJCALLSTACKDOWN, RISCV::ADJCALLSTACKUP) {}
34 
36  int &FrameIndex) const {
37  switch (MI.getOpcode()) {
38  default:
39  return 0;
40  case RISCV::LB:
41  case RISCV::LBU:
42  case RISCV::LH:
43  case RISCV::LHU:
44  case RISCV::LW:
45  case RISCV::FLW:
46  case RISCV::LWU:
47  case RISCV::LD:
48  case RISCV::FLD:
49  break;
50  }
51 
52  if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() &&
53  MI.getOperand(2).getImm() == 0) {
54  FrameIndex = MI.getOperand(1).getIndex();
55  return MI.getOperand(0).getReg();
56  }
57 
58  return 0;
59 }
60 
62  int &FrameIndex) const {
63  switch (MI.getOpcode()) {
64  default:
65  return 0;
66  case RISCV::SB:
67  case RISCV::SH:
68  case RISCV::SW:
69  case RISCV::FSW:
70  case RISCV::SD:
71  case RISCV::FSD:
72  break;
73  }
74 
75  if (MI.getOperand(0).isFI() && MI.getOperand(1).isImm() &&
76  MI.getOperand(1).getImm() == 0) {
77  FrameIndex = MI.getOperand(0).getIndex();
78  return MI.getOperand(2).getReg();
79  }
80 
81  return 0;
82 }
83 
86  const DebugLoc &DL, unsigned DstReg,
87  unsigned SrcReg, bool KillSrc) const {
88  if (RISCV::GPRRegClass.contains(DstReg, SrcReg)) {
89  BuildMI(MBB, MBBI, DL, get(RISCV::ADDI), DstReg)
90  .addReg(SrcReg, getKillRegState(KillSrc))
91  .addImm(0);
92  return;
93  }
94 
95  // FPR->FPR copies
96  unsigned Opc;
97  if (RISCV::FPR32RegClass.contains(DstReg, SrcReg))
98  Opc = RISCV::FSGNJ_S;
99  else if (RISCV::FPR64RegClass.contains(DstReg, SrcReg))
100  Opc = RISCV::FSGNJ_D;
101  else
102  llvm_unreachable("Impossible reg-to-reg copy");
103 
104  BuildMI(MBB, MBBI, DL, get(Opc), DstReg)
105  .addReg(SrcReg, getKillRegState(KillSrc))
106  .addReg(SrcReg, getKillRegState(KillSrc));
107 }
108 
111  unsigned SrcReg, bool IsKill, int FI,
112  const TargetRegisterClass *RC,
113  const TargetRegisterInfo *TRI) const {
114  DebugLoc DL;
115  if (I != MBB.end())
116  DL = I->getDebugLoc();
117 
118  unsigned Opcode;
119 
120  if (RISCV::GPRRegClass.hasSubClassEq(RC))
121  Opcode = TRI->getRegSizeInBits(RISCV::GPRRegClass) == 32 ?
122  RISCV::SW : RISCV::SD;
123  else if (RISCV::FPR32RegClass.hasSubClassEq(RC))
124  Opcode = RISCV::FSW;
125  else if (RISCV::FPR64RegClass.hasSubClassEq(RC))
126  Opcode = RISCV::FSD;
127  else
128  llvm_unreachable("Can't store this register to stack slot");
129 
130  BuildMI(MBB, I, DL, get(Opcode))
131  .addReg(SrcReg, getKillRegState(IsKill))
132  .addFrameIndex(FI)
133  .addImm(0);
134 }
135 
138  unsigned DstReg, int FI,
139  const TargetRegisterClass *RC,
140  const TargetRegisterInfo *TRI) const {
141  DebugLoc DL;
142  if (I != MBB.end())
143  DL = I->getDebugLoc();
144 
145  unsigned Opcode;
146 
147  if (RISCV::GPRRegClass.hasSubClassEq(RC))
148  Opcode = TRI->getRegSizeInBits(RISCV::GPRRegClass) == 32 ?
149  RISCV::LW : RISCV::LD;
150  else if (RISCV::FPR32RegClass.hasSubClassEq(RC))
151  Opcode = RISCV::FLW;
152  else if (RISCV::FPR64RegClass.hasSubClassEq(RC))
153  Opcode = RISCV::FLD;
154  else
155  llvm_unreachable("Can't load this register from stack slot");
156 
157  BuildMI(MBB, I, DL, get(Opcode), DstReg).addFrameIndex(FI).addImm(0);
158 }
159 
162  const DebugLoc &DL, unsigned DstReg, uint64_t Val,
163  MachineInstr::MIFlag Flag) const {
164  assert(isInt<32>(Val) && "Can only materialize 32-bit constants");
165 
166  // TODO: If the value can be materialized using only one instruction, only
167  // insert a single instruction.
168 
169  uint64_t Hi20 = ((Val + 0x800) >> 12) & 0xfffff;
170  uint64_t Lo12 = SignExtend64<12>(Val);
171  BuildMI(MBB, MBBI, DL, get(RISCV::LUI), DstReg)
172  .addImm(Hi20)
173  .setMIFlag(Flag);
174  BuildMI(MBB, MBBI, DL, get(RISCV::ADDI), DstReg)
175  .addReg(DstReg, RegState::Kill)
176  .addImm(Lo12)
177  .setMIFlag(Flag);
178 }
179 
180 // The contents of values added to Cond are not examined outside of
181 // RISCVInstrInfo, giving us flexibility in what to push to it. For RISCV, we
182 // push BranchOpcode, Reg1, Reg2.
185  // Block ends with fall-through condbranch.
186  assert(LastInst.getDesc().isConditionalBranch() &&
187  "Unknown conditional branch");
188  Target = LastInst.getOperand(2).getMBB();
190  Cond.push_back(LastInst.getOperand(0));
191  Cond.push_back(LastInst.getOperand(1));
192 }
193 
194 static unsigned getOppositeBranchOpcode(int Opc) {
195  switch (Opc) {
196  default:
197  llvm_unreachable("Unrecognized conditional branch");
198  case RISCV::BEQ:
199  return RISCV::BNE;
200  case RISCV::BNE:
201  return RISCV::BEQ;
202  case RISCV::BLT:
203  return RISCV::BGE;
204  case RISCV::BGE:
205  return RISCV::BLT;
206  case RISCV::BLTU:
207  return RISCV::BGEU;
208  case RISCV::BGEU:
209  return RISCV::BLTU;
210  }
211 }
212 
214  MachineBasicBlock *&TBB,
215  MachineBasicBlock *&FBB,
217  bool AllowModify) const {
218  TBB = FBB = nullptr;
219  Cond.clear();
220 
221  // If the block has no terminators, it just falls into the block after it.
223  if (I == MBB.end() || !isUnpredicatedTerminator(*I))
224  return false;
225 
226  // Count the number of terminators and find the first unconditional or
227  // indirect branch.
228  MachineBasicBlock::iterator FirstUncondOrIndirectBr = MBB.end();
229  int NumTerminators = 0;
230  for (auto J = I.getReverse(); J != MBB.rend() && isUnpredicatedTerminator(*J);
231  J++) {
232  NumTerminators++;
233  if (J->getDesc().isUnconditionalBranch() ||
234  J->getDesc().isIndirectBranch()) {
235  FirstUncondOrIndirectBr = J.getReverse();
236  }
237  }
238 
239  // If AllowModify is true, we can erase any terminators after
240  // FirstUncondOrIndirectBR.
241  if (AllowModify && FirstUncondOrIndirectBr != MBB.end()) {
242  while (std::next(FirstUncondOrIndirectBr) != MBB.end()) {
243  std::next(FirstUncondOrIndirectBr)->eraseFromParent();
244  NumTerminators--;
245  }
246  I = FirstUncondOrIndirectBr;
247  }
248 
249  // We can't handle blocks that end in an indirect branch.
250  if (I->getDesc().isIndirectBranch())
251  return true;
252 
253  // We can't handle blocks with more than 2 terminators.
254  if (NumTerminators > 2)
255  return true;
256 
257  // Handle a single unconditional branch.
258  if (NumTerminators == 1 && I->getDesc().isUnconditionalBranch()) {
259  TBB = I->getOperand(0).getMBB();
260  return false;
261  }
262 
263  // Handle a single conditional branch.
264  if (NumTerminators == 1 && I->getDesc().isConditionalBranch()) {
265  parseCondBranch(*I, TBB, Cond);
266  return false;
267  }
268 
269  // Handle a conditional branch followed by an unconditional branch.
270  if (NumTerminators == 2 && std::prev(I)->getDesc().isConditionalBranch() &&
271  I->getDesc().isUnconditionalBranch()) {
272  parseCondBranch(*std::prev(I), TBB, Cond);
273  FBB = I->getOperand(0).getMBB();
274  return false;
275  }
276 
277  // Otherwise, we can't handle this.
278  return true;
279 }
280 
282  int *BytesRemoved) const {
283  if (BytesRemoved)
284  *BytesRemoved = 0;
286  if (I == MBB.end())
287  return 0;
288 
289  if (!I->getDesc().isUnconditionalBranch() &&
290  !I->getDesc().isConditionalBranch())
291  return 0;
292 
293  // Remove the branch.
294  I->eraseFromParent();
295  if (BytesRemoved)
296  *BytesRemoved += getInstSizeInBytes(*I);
297 
298  I = MBB.end();
299 
300  if (I == MBB.begin())
301  return 1;
302  --I;
303  if (!I->getDesc().isConditionalBranch())
304  return 1;
305 
306  // Remove the branch.
307  I->eraseFromParent();
308  if (BytesRemoved)
309  *BytesRemoved += getInstSizeInBytes(*I);
310  return 2;
311 }
312 
313 // Inserts a branch into the end of the specific MachineBasicBlock, returning
314 // the number of instructions inserted.
317  ArrayRef<MachineOperand> Cond, const DebugLoc &DL, int *BytesAdded) const {
318  if (BytesAdded)
319  *BytesAdded = 0;
320 
321  // Shouldn't be a fall through.
322  assert(TBB && "InsertBranch must not be told to insert a fallthrough");
323  assert((Cond.size() == 3 || Cond.size() == 0) &&
324  "RISCV branch conditions have two components!");
325 
326  // Unconditional branch.
327  if (Cond.empty()) {
328  MachineInstr &MI = *BuildMI(&MBB, DL, get(RISCV::PseudoBR)).addMBB(TBB);
329  if (BytesAdded)
330  *BytesAdded += getInstSizeInBytes(MI);
331  return 1;
332  }
333 
334  // Either a one or two-way conditional branch.
335  unsigned Opc = Cond[0].getImm();
336  MachineInstr &CondMI =
337  *BuildMI(&MBB, DL, get(Opc)).add(Cond[1]).add(Cond[2]).addMBB(TBB);
338  if (BytesAdded)
339  *BytesAdded += getInstSizeInBytes(CondMI);
340 
341  // One-way conditional branch.
342  if (!FBB)
343  return 1;
344 
345  // Two-way conditional branch.
346  MachineInstr &MI = *BuildMI(&MBB, DL, get(RISCV::PseudoBR)).addMBB(FBB);
347  if (BytesAdded)
348  *BytesAdded += getInstSizeInBytes(MI);
349  return 2;
350 }
351 
353  MachineBasicBlock &DestBB,
354  const DebugLoc &DL,
355  int64_t BrOffset,
356  RegScavenger *RS) const {
357  assert(RS && "RegScavenger required for long branching");
358  assert(MBB.empty() &&
359  "new block should be inserted for expanding unconditional branch");
360  assert(MBB.pred_size() == 1);
361 
362  MachineFunction *MF = MBB.getParent();
363  MachineRegisterInfo &MRI = MF->getRegInfo();
364  const auto &TM = static_cast<const RISCVTargetMachine &>(MF->getTarget());
365 
366  if (TM.isPositionIndependent())
367  report_fatal_error("Unable to insert indirect branch");
368 
369  if (!isInt<32>(BrOffset))
371  "Branch offsets outside of the signed 32-bit range not supported");
372 
373  // FIXME: A virtual register must be used initially, as the register
374  // scavenger won't work with empty blocks (SIInstrInfo::insertIndirectBranch
375  // uses the same workaround).
376  unsigned ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
377  auto II = MBB.end();
378 
379  MachineInstr &LuiMI = *BuildMI(MBB, II, DL, get(RISCV::LUI), ScratchReg)
380  .addMBB(&DestBB, RISCVII::MO_HI);
381  BuildMI(MBB, II, DL, get(RISCV::PseudoBRIND))
382  .addReg(ScratchReg, RegState::Kill)
383  .addMBB(&DestBB, RISCVII::MO_LO);
384 
385  RS->enterBasicBlockEnd(MBB);
386  unsigned Scav = RS->scavengeRegisterBackwards(
387  RISCV::GPRRegClass, MachineBasicBlock::iterator(LuiMI), false, 0);
388  MRI.replaceRegWith(ScratchReg, Scav);
389  MRI.clearVirtRegs();
390  RS->setRegUsed(Scav);
391  return 8;
392 }
393 
395  SmallVectorImpl<MachineOperand> &Cond) const {
396  assert((Cond.size() == 3) && "Invalid branch condition!");
397  Cond[0].setImm(getOppositeBranchOpcode(Cond[0].getImm()));
398  return false;
399 }
400 
403  assert(MI.getDesc().isBranch() && "Unexpected opcode!");
404  // The branch target is always the last operand.
405  int NumOp = MI.getNumExplicitOperands();
406  return MI.getOperand(NumOp - 1).getMBB();
407 }
408 
410  int64_t BrOffset) const {
411  // Ideally we could determine the supported branch offset from the
412  // RISCVII::FormMask, but this can't be used for Pseudo instructions like
413  // PseudoBR.
414  switch (BranchOp) {
415  default:
416  llvm_unreachable("Unexpected opcode!");
417  case RISCV::BEQ:
418  case RISCV::BNE:
419  case RISCV::BLT:
420  case RISCV::BGE:
421  case RISCV::BLTU:
422  case RISCV::BGEU:
423  return isIntN(13, BrOffset);
424  case RISCV::JAL:
425  case RISCV::PseudoBR:
426  return isIntN(21, BrOffset);
427  }
428 }
429 
431  unsigned Opcode = MI.getOpcode();
432 
433  switch (Opcode) {
434  default: { return get(Opcode).getSize(); }
436  case TargetOpcode::IMPLICIT_DEF:
437  case TargetOpcode::KILL:
438  case TargetOpcode::DBG_VALUE:
439  return 0;
440  case RISCV::PseudoCALL:
441  case RISCV::PseudoTAIL:
442  return 8;
444  const MachineFunction &MF = *MI.getParent()->getParent();
445  const auto &TM = static_cast<const RISCVTargetMachine &>(MF.getTarget());
446  return getInlineAsmLength(MI.getOperand(0).getSymbolName(),
447  *TM.getMCAsmInfo());
448  }
449  }
450 }
const MachineInstrBuilder & add(const MachineOperand &MO) const
MachineBasicBlock * getMBB() const
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
This class represents lattice values for constants.
Definition: AllocatorList.h:24
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
unsigned getReg() const
getReg - Returns the register number.
unsigned const TargetRegisterInfo * TRI
A debug info location.
Definition: DebugLoc.h:34
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
void clearVirtRegs()
clearVirtRegs - Remove all virtual registers (after physreg assignment).
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &dl, int *BytesAdded=nullptr) const override
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
return AArch64::GPR64RegClass contains(Reg)
bool isBranch() const
Returns true if this is a conditional, unconditional, or indirect branch.
Definition: MCInstrDesc.h:277
void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, unsigned SrcReg, bool IsKill, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const override
unsigned scavengeRegisterBackwards(const TargetRegisterClass &RC, MachineBasicBlock::iterator To, bool RestoreAfter, int SPAdj)
Make a register of the specific register class available from the current position backwards to the p...
unsigned isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex) const override
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:409
const char * getSymbolName() const
INLINEASM - Represents an inline asm block.
Definition: ISDOpcodes.h:667
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:406
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
reverse_iterator getReverse() const
Get a reverse iterator to the same node.
void movImm32(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, unsigned DstReg, uint64_t Val, MachineInstr::MIFlag Flag=MachineInstr::NoFlags) const
iterator getLastNonDebugInstr()
Returns an iterator to the last non-debug instruction in the basic block, or end().
reverse_iterator rend()
unsigned getKillRegState(bool B)
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:118
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
This file declares the machine register scavenger class.
unsigned const MachineRegisterInfo * MRI
This instruction implements an extending load to FP stack slots.
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
bool isConditionalBranch() const
Return true if this is a branch which may fall through to the next instruction or may transfer contro...
Definition: MCInstrDesc.h:287
void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, unsigned DstReg, unsigned SrcReg, bool KillSrc) const override
MCInstrDesc const & getDesc(MCInstrInfo const &MCII, MCInst const &MCI)
const MachineInstrBuilder & addFrameIndex(int Idx) const
bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:398
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
size_t size() const
Definition: SmallVector.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned getNumExplicitOperands() const
Returns the number of non-implicit operands.
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
Definition: ISDOpcodes.h:672
unsigned isLoadFromStackSlot(const MachineInstr &MI, int &FrameIndex) const override
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
constexpr bool isInt< 32 >(int64_t x)
Definition: MathExtras.h:309
static unsigned getOppositeBranchOpcode(int Opc)
unsigned getInstSizeInBytes(const MachineInstr &MI) const override
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
void enterBasicBlockEnd(MachineBasicBlock &MBB)
Start tracking liveness from the end of basic block MBB.
int64_t getImm() const
unsigned pred_size() const
Target - Wrapper for Target specific information.
void replaceRegWith(unsigned FromReg, unsigned ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:254
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Representation of each machine instruction.
Definition: MachineInstr.h:64
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
unsigned insertIndirectBranch(MachineBasicBlock &MBB, MachineBasicBlock &NewDestBB, const DebugLoc &DL, int64_t BrOffset, RegScavenger *RS=nullptr) const override
MachineBasicBlock * getBranchDestBlock(const MachineInstr &MI) const override
static MachineOperand CreateImm(int64_t Val)
#define I(x, y, z)
Definition: MD5.cpp:58
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
bool isBranchOffsetInRange(unsigned BranchOpc, int64_t BrOffset) const override
static void parseCondBranch(MachineInstr &LastInst, MachineBasicBlock *&Target, SmallVectorImpl< MachineOperand > &Cond)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void setRegUsed(unsigned Reg, LaneBitmask LaneMask=LaneBitmask::getAll())
Tell the scavenger a register is used.
IRTranslator LLVM IR MI
unsigned getRegSizeInBits(const TargetRegisterClass &RC) const
Return the size in bits of a register from class RC.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned char TargetFlags=0) const
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:414
unsigned createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, unsigned DstReg, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const override
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144