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"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/RegisterScavenging.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/TargetRegistry.h"
26 
27 #define GET_INSTRINFO_CTOR_DTOR
28 #include "RISCVGenInstrInfo.inc"
29 
30 using namespace llvm;
31 
32 RISCVInstrInfo::RISCVInstrInfo()
33     : RISCVGenInstrInfo(RISCV::ADJCALLSTACKDOWN, RISCV::ADJCALLSTACKUP) {}
34 
35 void RISCVInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
36                                  MachineBasicBlock::iterator MBBI,
37                                  const DebugLoc &DL, unsigned DstReg,
38                                  unsigned SrcReg, bool KillSrc) const {
39   if (RISCV::GPRRegClass.contains(DstReg, SrcReg)) {
40     BuildMI(MBB, MBBI, DL, get(RISCV::ADDI), DstReg)
41         .addReg(SrcReg, getKillRegState(KillSrc))
42         .addImm(0);
43     return;
44   }
45 
46   // FPR->FPR copies
47   unsigned Opc;
48   if (RISCV::FPR32RegClass.contains(DstReg, SrcReg))
49     Opc = RISCV::FSGNJ_S;
50   else if (RISCV::FPR64RegClass.contains(DstReg, SrcReg))
51     Opc = RISCV::FSGNJ_D;
52   else
53     llvm_unreachable("Impossible reg-to-reg copy");
54 
55   BuildMI(MBB, MBBI, DL, get(Opc), DstReg)
56       .addReg(SrcReg, getKillRegState(KillSrc))
57       .addReg(SrcReg, getKillRegState(KillSrc));
58 }
59 
60 void RISCVInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
61                                          MachineBasicBlock::iterator I,
62                                          unsigned SrcReg, bool IsKill, int FI,
63                                          const TargetRegisterClass *RC,
64                                          const TargetRegisterInfo *TRI) const {
65   DebugLoc DL;
66   if (I != MBB.end())
67     DL = I->getDebugLoc();
68 
69   unsigned Opcode;
70 
71   if (RISCV::GPRRegClass.hasSubClassEq(RC))
72     Opcode = RISCV::SW;
73   else if (RISCV::FPR32RegClass.hasSubClassEq(RC))
74     Opcode = RISCV::FSW;
75   else if (RISCV::FPR64RegClass.hasSubClassEq(RC))
76     Opcode = RISCV::FSD;
77   else
78     llvm_unreachable("Can't store this register to stack slot");
79 
80   BuildMI(MBB, I, DL, get(Opcode))
81       .addReg(SrcReg, getKillRegState(IsKill))
82       .addFrameIndex(FI)
83       .addImm(0);
84 }
85 
86 void RISCVInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
87                                           MachineBasicBlock::iterator I,
88                                           unsigned DstReg, int FI,
89                                           const TargetRegisterClass *RC,
90                                           const TargetRegisterInfo *TRI) const {
91   DebugLoc DL;
92   if (I != MBB.end())
93     DL = I->getDebugLoc();
94 
95   unsigned Opcode;
96 
97   if (RISCV::GPRRegClass.hasSubClassEq(RC))
98     Opcode = RISCV::LW;
99   else if (RISCV::FPR32RegClass.hasSubClassEq(RC))
100     Opcode = RISCV::FLW;
101   else if (RISCV::FPR64RegClass.hasSubClassEq(RC))
102     Opcode = RISCV::FLD;
103   else
104     llvm_unreachable("Can't load this register from stack slot");
105 
106   BuildMI(MBB, I, DL, get(Opcode), DstReg).addFrameIndex(FI).addImm(0);
107 }
108 
109 void RISCVInstrInfo::movImm32(MachineBasicBlock &MBB,
110                               MachineBasicBlock::iterator MBBI,
111                               const DebugLoc &DL, unsigned DstReg, uint64_t Val,
112                               MachineInstr::MIFlag Flag) const {
113   assert(isInt<32>(Val) && "Can only materialize 32-bit constants");
114 
115   // TODO: If the value can be materialized using only one instruction, only
116   // insert a single instruction.
117 
118   uint64_t Hi20 = ((Val + 0x800) >> 12) & 0xfffff;
119   uint64_t Lo12 = SignExtend64<12>(Val);
120   BuildMI(MBB, MBBI, DL, get(RISCV::LUI), DstReg)
121       .addImm(Hi20)
122       .setMIFlag(Flag);
123   BuildMI(MBB, MBBI, DL, get(RISCV::ADDI), DstReg)
124       .addReg(DstReg, RegState::Kill)
125       .addImm(Lo12)
126       .setMIFlag(Flag);
127 }
128 
129 // The contents of values added to Cond are not examined outside of
130 // RISCVInstrInfo, giving us flexibility in what to push to it. For RISCV, we
131 // push BranchOpcode, Reg1, Reg2.
132 static void parseCondBranch(MachineInstr &LastInst, MachineBasicBlock *&Target,
133                             SmallVectorImpl<MachineOperand> &Cond) {
134   // Block ends with fall-through condbranch.
135   assert(LastInst.getDesc().isConditionalBranch() &&
136          "Unknown conditional branch");
137   Target = LastInst.getOperand(2).getMBB();
138   Cond.push_back(MachineOperand::CreateImm(LastInst.getOpcode()));
139   Cond.push_back(LastInst.getOperand(0));
140   Cond.push_back(LastInst.getOperand(1));
141 }
142 
143 static unsigned getOppositeBranchOpcode(int Opc) {
144   switch (Opc) {
145   default:
146     llvm_unreachable("Unrecognized conditional branch");
147   case RISCV::BEQ:
148     return RISCV::BNE;
149   case RISCV::BNE:
150     return RISCV::BEQ;
151   case RISCV::BLT:
152     return RISCV::BGE;
153   case RISCV::BGE:
154     return RISCV::BLT;
155   case RISCV::BLTU:
156     return RISCV::BGEU;
157   case RISCV::BGEU:
158     return RISCV::BLTU;
159   }
160 }
161 
162 bool RISCVInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
163                                    MachineBasicBlock *&TBB,
164                                    MachineBasicBlock *&FBB,
165                                    SmallVectorImpl<MachineOperand> &Cond,
166                                    bool AllowModify) const {
167   TBB = FBB = nullptr;
168   Cond.clear();
169 
170   // If the block has no terminators, it just falls into the block after it.
171   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
172   if (I == MBB.end() || !isUnpredicatedTerminator(*I))
173     return false;
174 
175   // Count the number of terminators and find the first unconditional or
176   // indirect branch.
177   MachineBasicBlock::iterator FirstUncondOrIndirectBr = MBB.end();
178   int NumTerminators = 0;
179   for (auto J = I.getReverse(); J != MBB.rend() && isUnpredicatedTerminator(*J);
180        J++) {
181     NumTerminators++;
182     if (J->getDesc().isUnconditionalBranch() ||
183         J->getDesc().isIndirectBranch()) {
184       FirstUncondOrIndirectBr = J.getReverse();
185     }
186   }
187 
188   // If AllowModify is true, we can erase any terminators after
189   // FirstUncondOrIndirectBR.
190   if (AllowModify && FirstUncondOrIndirectBr != MBB.end()) {
191     while (std::next(FirstUncondOrIndirectBr) != MBB.end()) {
192       std::next(FirstUncondOrIndirectBr)->eraseFromParent();
193       NumTerminators--;
194     }
195     I = FirstUncondOrIndirectBr;
196   }
197 
198   // We can't handle blocks that end in an indirect branch.
199   if (I->getDesc().isIndirectBranch())
200     return true;
201 
202   // We can't handle blocks with more than 2 terminators.
203   if (NumTerminators > 2)
204     return true;
205 
206   // Handle a single unconditional branch.
207   if (NumTerminators == 1 && I->getDesc().isUnconditionalBranch()) {
208     TBB = I->getOperand(0).getMBB();
209     return false;
210   }
211 
212   // Handle a single conditional branch.
213   if (NumTerminators == 1 && I->getDesc().isConditionalBranch()) {
214     parseCondBranch(*I, TBB, Cond);
215     return false;
216   }
217 
218   // Handle a conditional branch followed by an unconditional branch.
219   if (NumTerminators == 2 && std::prev(I)->getDesc().isConditionalBranch() &&
220       I->getDesc().isUnconditionalBranch()) {
221     parseCondBranch(*std::prev(I), TBB, Cond);
222     FBB = I->getOperand(0).getMBB();
223     return false;
224   }
225 
226   // Otherwise, we can't handle this.
227   return true;
228 }
229 
230 unsigned RISCVInstrInfo::removeBranch(MachineBasicBlock &MBB,
231                                       int *BytesRemoved) const {
232   if (BytesRemoved)
233     *BytesRemoved = 0;
234   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
235   if (I == MBB.end())
236     return 0;
237 
238   if (!I->getDesc().isUnconditionalBranch() &&
239       !I->getDesc().isConditionalBranch())
240     return 0;
241 
242   // Remove the branch.
243   I->eraseFromParent();
244   if (BytesRemoved)
245     *BytesRemoved += getInstSizeInBytes(*I);
246 
247   I = MBB.end();
248 
249   if (I == MBB.begin())
250     return 1;
251   --I;
252   if (!I->getDesc().isConditionalBranch())
253     return 1;
254 
255   // Remove the branch.
256   I->eraseFromParent();
257   if (BytesRemoved)
258     *BytesRemoved += getInstSizeInBytes(*I);
259   return 2;
260 }
261 
262 // Inserts a branch into the end of the specific MachineBasicBlock, returning
263 // the number of instructions inserted.
264 unsigned RISCVInstrInfo::insertBranch(
265     MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB,
266     ArrayRef<MachineOperand> Cond, const DebugLoc &DL, int *BytesAdded) const {
267   if (BytesAdded)
268     *BytesAdded = 0;
269 
270   // Shouldn't be a fall through.
271   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
272   assert((Cond.size() == 3 || Cond.size() == 0) &&
273          "RISCV branch conditions have two components!");
274 
275   // Unconditional branch.
276   if (Cond.empty()) {
277     MachineInstr &MI = *BuildMI(&MBB, DL, get(RISCV::PseudoBR)).addMBB(TBB);
278     if (BytesAdded)
279       *BytesAdded += getInstSizeInBytes(MI);
280     return 1;
281   }
282 
283   // Either a one or two-way conditional branch.
284   unsigned Opc = Cond[0].getImm();
285   MachineInstr &CondMI =
286       *BuildMI(&MBB, DL, get(Opc)).add(Cond[1]).add(Cond[2]).addMBB(TBB);
287   if (BytesAdded)
288     *BytesAdded += getInstSizeInBytes(CondMI);
289 
290   // One-way conditional branch.
291   if (!FBB)
292     return 1;
293 
294   // Two-way conditional branch.
295   MachineInstr &MI = *BuildMI(&MBB, DL, get(RISCV::PseudoBR)).addMBB(FBB);
296   if (BytesAdded)
297     *BytesAdded += getInstSizeInBytes(MI);
298   return 2;
299 }
300 
301 unsigned RISCVInstrInfo::insertIndirectBranch(MachineBasicBlock &MBB,
302                                               MachineBasicBlock &DestBB,
303                                               const DebugLoc &DL,
304                                               int64_t BrOffset,
305                                               RegScavenger *RS) const {
306   assert(RS && "RegScavenger required for long branching");
307   assert(MBB.empty() &&
308          "new block should be inserted for expanding unconditional branch");
309   assert(MBB.pred_size() == 1);
310 
311   MachineFunction *MF = MBB.getParent();
312   MachineRegisterInfo &MRI = MF->getRegInfo();
313   const auto &TM = static_cast<const RISCVTargetMachine &>(MF->getTarget());
314   const auto &STI = MF->getSubtarget<RISCVSubtarget>();
315 
316   if (TM.isPositionIndependent() || STI.is64Bit())
317     report_fatal_error("Unable to insert indirect branch");
318 
319   if (!isInt<32>(BrOffset))
320     report_fatal_error(
321         "Branch offsets outside of the signed 32-bit range not supported");
322 
323   // FIXME: A virtual register must be used initially, as the register
324   // scavenger won't work with empty blocks (SIInstrInfo::insertIndirectBranch
325   // uses the same workaround).
326   unsigned ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
327   auto II = MBB.end();
328 
329   MachineInstr &LuiMI = *BuildMI(MBB, II, DL, get(RISCV::LUI), ScratchReg)
330                              .addMBB(&DestBB, RISCVII::MO_HI);
331   BuildMI(MBB, II, DL, get(RISCV::PseudoBRIND))
332       .addReg(ScratchReg, RegState::Kill)
333       .addMBB(&DestBB, RISCVII::MO_LO);
334 
335   RS->enterBasicBlockEnd(MBB);
336   unsigned Scav = RS->scavengeRegisterBackwards(
337       RISCV::GPRRegClass, MachineBasicBlock::iterator(LuiMI), false, 0);
338   MRI.replaceRegWith(ScratchReg, Scav);
339   MRI.clearVirtRegs();
340   RS->setRegUsed(Scav);
341   return 8;
342 }
343 
344 bool RISCVInstrInfo::reverseBranchCondition(
345     SmallVectorImpl<MachineOperand> &Cond) const {
346   assert((Cond.size() == 3) && "Invalid branch condition!");
347   Cond[0].setImm(getOppositeBranchOpcode(Cond[0].getImm()));
348   return false;
349 }
350 
351 MachineBasicBlock *
352 RISCVInstrInfo::getBranchDestBlock(const MachineInstr &MI) const {
353   assert(MI.getDesc().isBranch() && "Unexpected opcode!");
354   // The branch target is always the last operand.
355   int NumOp = MI.getNumExplicitOperands();
356   return MI.getOperand(NumOp - 1).getMBB();
357 }
358 
359 bool RISCVInstrInfo::isBranchOffsetInRange(unsigned BranchOp,
360                                            int64_t BrOffset) const {
361   // Ideally we could determine the supported branch offset from the
362   // RISCVII::FormMask, but this can't be used for Pseudo instructions like
363   // PseudoBR.
364   switch (BranchOp) {
365   default:
366     llvm_unreachable("Unexpected opcode!");
367   case RISCV::BEQ:
368   case RISCV::BNE:
369   case RISCV::BLT:
370   case RISCV::BGE:
371   case RISCV::BLTU:
372   case RISCV::BGEU:
373     return isIntN(13, BrOffset);
374   case RISCV::JAL:
375   case RISCV::PseudoBR:
376     return isIntN(21, BrOffset);
377   }
378 }
379 
380 unsigned RISCVInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
381   unsigned Opcode = MI.getOpcode();
382 
383   switch (Opcode) {
384   default: { return get(Opcode).getSize(); }
385   case TargetOpcode::EH_LABEL:
386   case TargetOpcode::IMPLICIT_DEF:
387   case TargetOpcode::KILL:
388   case TargetOpcode::DBG_VALUE:
389     return 0;
390   case TargetOpcode::INLINEASM: {
391     const MachineFunction &MF = *MI.getParent()->getParent();
392     const auto &TM = static_cast<const RISCVTargetMachine &>(MF.getTarget());
393     return getInlineAsmLength(MI.getOperand(0).getSymbolName(),
394                               *TM.getMCAsmInfo());
395   }
396   }
397 }
398