1 //===-- RISCVInstrInfo.cpp - RISCV Instruction Information ------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file contains the RISCV implementation of the TargetInstrInfo class.
11 //===----------------------------------------------------------------------===//
13 #include "RISCVInstrInfo.h"
15 #include "RISCVSubtarget.h"
16 #include "RISCVTargetMachine.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/RegisterScavenging.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/TargetRegistry.h"
26 #define GET_INSTRINFO_CTOR_DTOR
27 #include "RISCVGenInstrInfo.inc"
31 RISCVInstrInfo::RISCVInstrInfo()
32 : RISCVGenInstrInfo(RISCV::ADJCALLSTACKDOWN
, RISCV::ADJCALLSTACKUP
) {}
34 unsigned RISCVInstrInfo::isLoadFromStackSlot(const MachineInstr
&MI
,
35 int &FrameIndex
) const {
36 switch (MI
.getOpcode()) {
51 if (MI
.getOperand(1).isFI() && MI
.getOperand(2).isImm() &&
52 MI
.getOperand(2).getImm() == 0) {
53 FrameIndex
= MI
.getOperand(1).getIndex();
54 return MI
.getOperand(0).getReg();
60 unsigned RISCVInstrInfo::isStoreToStackSlot(const MachineInstr
&MI
,
61 int &FrameIndex
) const {
62 switch (MI
.getOpcode()) {
74 if (MI
.getOperand(0).isFI() && MI
.getOperand(1).isImm() &&
75 MI
.getOperand(1).getImm() == 0) {
76 FrameIndex
= MI
.getOperand(0).getIndex();
77 return MI
.getOperand(2).getReg();
83 void RISCVInstrInfo::copyPhysReg(MachineBasicBlock
&MBB
,
84 MachineBasicBlock::iterator MBBI
,
85 const DebugLoc
&DL
, unsigned DstReg
,
86 unsigned SrcReg
, bool KillSrc
) const {
87 if (RISCV::GPRRegClass
.contains(DstReg
, SrcReg
)) {
88 BuildMI(MBB
, MBBI
, DL
, get(RISCV::ADDI
), DstReg
)
89 .addReg(SrcReg
, getKillRegState(KillSrc
))
96 if (RISCV::FPR32RegClass
.contains(DstReg
, SrcReg
))
98 else if (RISCV::FPR64RegClass
.contains(DstReg
, SrcReg
))
101 llvm_unreachable("Impossible reg-to-reg copy");
103 BuildMI(MBB
, MBBI
, DL
, get(Opc
), DstReg
)
104 .addReg(SrcReg
, getKillRegState(KillSrc
))
105 .addReg(SrcReg
, getKillRegState(KillSrc
));
108 void RISCVInstrInfo::storeRegToStackSlot(MachineBasicBlock
&MBB
,
109 MachineBasicBlock::iterator I
,
110 unsigned SrcReg
, bool IsKill
, int FI
,
111 const TargetRegisterClass
*RC
,
112 const TargetRegisterInfo
*TRI
) const {
115 DL
= I
->getDebugLoc();
119 if (RISCV::GPRRegClass
.hasSubClassEq(RC
))
120 Opcode
= TRI
->getRegSizeInBits(RISCV::GPRRegClass
) == 32 ?
121 RISCV::SW
: RISCV::SD
;
122 else if (RISCV::FPR32RegClass
.hasSubClassEq(RC
))
124 else if (RISCV::FPR64RegClass
.hasSubClassEq(RC
))
127 llvm_unreachable("Can't store this register to stack slot");
129 BuildMI(MBB
, I
, DL
, get(Opcode
))
130 .addReg(SrcReg
, getKillRegState(IsKill
))
135 void RISCVInstrInfo::loadRegFromStackSlot(MachineBasicBlock
&MBB
,
136 MachineBasicBlock::iterator I
,
137 unsigned DstReg
, int FI
,
138 const TargetRegisterClass
*RC
,
139 const TargetRegisterInfo
*TRI
) const {
142 DL
= I
->getDebugLoc();
146 if (RISCV::GPRRegClass
.hasSubClassEq(RC
))
147 Opcode
= TRI
->getRegSizeInBits(RISCV::GPRRegClass
) == 32 ?
148 RISCV::LW
: RISCV::LD
;
149 else if (RISCV::FPR32RegClass
.hasSubClassEq(RC
))
151 else if (RISCV::FPR64RegClass
.hasSubClassEq(RC
))
154 llvm_unreachable("Can't load this register from stack slot");
156 BuildMI(MBB
, I
, DL
, get(Opcode
), DstReg
).addFrameIndex(FI
).addImm(0);
159 void RISCVInstrInfo::movImm32(MachineBasicBlock
&MBB
,
160 MachineBasicBlock::iterator MBBI
,
161 const DebugLoc
&DL
, Register DstReg
, uint64_t Val
,
162 MachineInstr::MIFlag Flag
) const {
163 assert(isInt
<32>(Val
) && "Can only materialize 32-bit constants");
165 // TODO: If the value can be materialized using only one instruction, only
166 // insert a single instruction.
168 uint64_t Hi20
= ((Val
+ 0x800) >> 12) & 0xfffff;
169 uint64_t Lo12
= SignExtend64
<12>(Val
);
170 BuildMI(MBB
, MBBI
, DL
, get(RISCV::LUI
), DstReg
)
173 BuildMI(MBB
, MBBI
, DL
, get(RISCV::ADDI
), DstReg
)
174 .addReg(DstReg
, RegState::Kill
)
179 // The contents of values added to Cond are not examined outside of
180 // RISCVInstrInfo, giving us flexibility in what to push to it. For RISCV, we
181 // push BranchOpcode, Reg1, Reg2.
182 static void parseCondBranch(MachineInstr
&LastInst
, MachineBasicBlock
*&Target
,
183 SmallVectorImpl
<MachineOperand
> &Cond
) {
184 // Block ends with fall-through condbranch.
185 assert(LastInst
.getDesc().isConditionalBranch() &&
186 "Unknown conditional branch");
187 Target
= LastInst
.getOperand(2).getMBB();
188 Cond
.push_back(MachineOperand::CreateImm(LastInst
.getOpcode()));
189 Cond
.push_back(LastInst
.getOperand(0));
190 Cond
.push_back(LastInst
.getOperand(1));
193 static unsigned getOppositeBranchOpcode(int Opc
) {
196 llvm_unreachable("Unrecognized conditional branch");
212 bool RISCVInstrInfo::analyzeBranch(MachineBasicBlock
&MBB
,
213 MachineBasicBlock
*&TBB
,
214 MachineBasicBlock
*&FBB
,
215 SmallVectorImpl
<MachineOperand
> &Cond
,
216 bool AllowModify
) const {
220 // If the block has no terminators, it just falls into the block after it.
221 MachineBasicBlock::iterator I
= MBB
.getLastNonDebugInstr();
222 if (I
== MBB
.end() || !isUnpredicatedTerminator(*I
))
225 // Count the number of terminators and find the first unconditional or
227 MachineBasicBlock::iterator FirstUncondOrIndirectBr
= MBB
.end();
228 int NumTerminators
= 0;
229 for (auto J
= I
.getReverse(); J
!= MBB
.rend() && isUnpredicatedTerminator(*J
);
232 if (J
->getDesc().isUnconditionalBranch() ||
233 J
->getDesc().isIndirectBranch()) {
234 FirstUncondOrIndirectBr
= J
.getReverse();
238 // If AllowModify is true, we can erase any terminators after
239 // FirstUncondOrIndirectBR.
240 if (AllowModify
&& FirstUncondOrIndirectBr
!= MBB
.end()) {
241 while (std::next(FirstUncondOrIndirectBr
) != MBB
.end()) {
242 std::next(FirstUncondOrIndirectBr
)->eraseFromParent();
245 I
= FirstUncondOrIndirectBr
;
248 // We can't handle blocks that end in an indirect branch.
249 if (I
->getDesc().isIndirectBranch())
252 // We can't handle blocks with more than 2 terminators.
253 if (NumTerminators
> 2)
256 // Handle a single unconditional branch.
257 if (NumTerminators
== 1 && I
->getDesc().isUnconditionalBranch()) {
258 TBB
= I
->getOperand(0).getMBB();
262 // Handle a single conditional branch.
263 if (NumTerminators
== 1 && I
->getDesc().isConditionalBranch()) {
264 parseCondBranch(*I
, TBB
, Cond
);
268 // Handle a conditional branch followed by an unconditional branch.
269 if (NumTerminators
== 2 && std::prev(I
)->getDesc().isConditionalBranch() &&
270 I
->getDesc().isUnconditionalBranch()) {
271 parseCondBranch(*std::prev(I
), TBB
, Cond
);
272 FBB
= I
->getOperand(0).getMBB();
276 // Otherwise, we can't handle this.
280 unsigned RISCVInstrInfo::removeBranch(MachineBasicBlock
&MBB
,
281 int *BytesRemoved
) const {
284 MachineBasicBlock::iterator I
= MBB
.getLastNonDebugInstr();
288 if (!I
->getDesc().isUnconditionalBranch() &&
289 !I
->getDesc().isConditionalBranch())
292 // Remove the branch.
294 *BytesRemoved
+= getInstSizeInBytes(*I
);
295 I
->eraseFromParent();
299 if (I
== MBB
.begin())
302 if (!I
->getDesc().isConditionalBranch())
305 // Remove the branch.
307 *BytesRemoved
+= getInstSizeInBytes(*I
);
308 I
->eraseFromParent();
312 // Inserts a branch into the end of the specific MachineBasicBlock, returning
313 // the number of instructions inserted.
314 unsigned RISCVInstrInfo::insertBranch(
315 MachineBasicBlock
&MBB
, MachineBasicBlock
*TBB
, MachineBasicBlock
*FBB
,
316 ArrayRef
<MachineOperand
> Cond
, const DebugLoc
&DL
, int *BytesAdded
) const {
320 // Shouldn't be a fall through.
321 assert(TBB
&& "InsertBranch must not be told to insert a fallthrough");
322 assert((Cond
.size() == 3 || Cond
.size() == 0) &&
323 "RISCV branch conditions have two components!");
325 // Unconditional branch.
327 MachineInstr
&MI
= *BuildMI(&MBB
, DL
, get(RISCV::PseudoBR
)).addMBB(TBB
);
329 *BytesAdded
+= getInstSizeInBytes(MI
);
333 // Either a one or two-way conditional branch.
334 unsigned Opc
= Cond
[0].getImm();
335 MachineInstr
&CondMI
=
336 *BuildMI(&MBB
, DL
, get(Opc
)).add(Cond
[1]).add(Cond
[2]).addMBB(TBB
);
338 *BytesAdded
+= getInstSizeInBytes(CondMI
);
340 // One-way conditional branch.
344 // Two-way conditional branch.
345 MachineInstr
&MI
= *BuildMI(&MBB
, DL
, get(RISCV::PseudoBR
)).addMBB(FBB
);
347 *BytesAdded
+= getInstSizeInBytes(MI
);
351 unsigned RISCVInstrInfo::insertIndirectBranch(MachineBasicBlock
&MBB
,
352 MachineBasicBlock
&DestBB
,
355 RegScavenger
*RS
) const {
356 assert(RS
&& "RegScavenger required for long branching");
357 assert(MBB
.empty() &&
358 "new block should be inserted for expanding unconditional branch");
359 assert(MBB
.pred_size() == 1);
361 MachineFunction
*MF
= MBB
.getParent();
362 MachineRegisterInfo
&MRI
= MF
->getRegInfo();
363 const auto &TM
= static_cast<const RISCVTargetMachine
&>(MF
->getTarget());
365 if (TM
.isPositionIndependent())
366 report_fatal_error("Unable to insert indirect branch");
368 if (!isInt
<32>(BrOffset
))
370 "Branch offsets outside of the signed 32-bit range not supported");
372 // FIXME: A virtual register must be used initially, as the register
373 // scavenger won't work with empty blocks (SIInstrInfo::insertIndirectBranch
374 // uses the same workaround).
375 Register ScratchReg
= MRI
.createVirtualRegister(&RISCV::GPRRegClass
);
378 MachineInstr
&LuiMI
= *BuildMI(MBB
, II
, DL
, get(RISCV::LUI
), ScratchReg
)
379 .addMBB(&DestBB
, RISCVII::MO_HI
);
380 BuildMI(MBB
, II
, DL
, get(RISCV::PseudoBRIND
))
381 .addReg(ScratchReg
, RegState::Kill
)
382 .addMBB(&DestBB
, RISCVII::MO_LO
);
384 RS
->enterBasicBlockEnd(MBB
);
385 unsigned Scav
= RS
->scavengeRegisterBackwards(RISCV::GPRRegClass
,
386 LuiMI
.getIterator(), false, 0);
387 MRI
.replaceRegWith(ScratchReg
, Scav
);
389 RS
->setRegUsed(Scav
);
393 bool RISCVInstrInfo::reverseBranchCondition(
394 SmallVectorImpl
<MachineOperand
> &Cond
) const {
395 assert((Cond
.size() == 3) && "Invalid branch condition!");
396 Cond
[0].setImm(getOppositeBranchOpcode(Cond
[0].getImm()));
401 RISCVInstrInfo::getBranchDestBlock(const MachineInstr
&MI
) const {
402 assert(MI
.getDesc().isBranch() && "Unexpected opcode!");
403 // The branch target is always the last operand.
404 int NumOp
= MI
.getNumExplicitOperands();
405 return MI
.getOperand(NumOp
- 1).getMBB();
408 bool RISCVInstrInfo::isBranchOffsetInRange(unsigned BranchOp
,
409 int64_t BrOffset
) const {
410 // Ideally we could determine the supported branch offset from the
411 // RISCVII::FormMask, but this can't be used for Pseudo instructions like
415 llvm_unreachable("Unexpected opcode!");
422 return isIntN(13, BrOffset
);
424 case RISCV::PseudoBR
:
425 return isIntN(21, BrOffset
);
429 unsigned RISCVInstrInfo::getInstSizeInBytes(const MachineInstr
&MI
) const {
430 unsigned Opcode
= MI
.getOpcode();
433 default: { return get(Opcode
).getSize(); }
434 case TargetOpcode::EH_LABEL
:
435 case TargetOpcode::IMPLICIT_DEF
:
436 case TargetOpcode::KILL
:
437 case TargetOpcode::DBG_VALUE
:
439 case RISCV::PseudoCALLReg
:
440 case RISCV::PseudoCALL
:
441 case RISCV::PseudoTAIL
:
442 case RISCV::PseudoLLA
:
443 case RISCV::PseudoLA
:
444 case RISCV::PseudoLA_TLS_IE
:
445 case RISCV::PseudoLA_TLS_GD
:
447 case TargetOpcode::INLINEASM
:
448 case TargetOpcode::INLINEASM_BR
: {
449 const MachineFunction
&MF
= *MI
.getParent()->getParent();
450 const auto &TM
= static_cast<const RISCVTargetMachine
&>(MF
.getTarget());
451 return getInlineAsmLength(MI
.getOperand(0).getSymbolName(),
457 bool RISCVInstrInfo::isAsCheapAsAMove(const MachineInstr
&MI
) const {
458 const unsigned Opcode
= MI
.getOpcode();
465 return (MI
.getOperand(1).isReg() && MI
.getOperand(1).getReg() == RISCV::X0
);
467 return MI
.isAsCheapAsAMove();