LLVM 24.0.0git
RISCVRedundantCopyElimination.cpp
Go to the documentation of this file.
1//=- RISCVRedundantCopyElimination.cpp - Remove useless copy for RISC-V -----=//
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 pass removes unnecessary zero copies in BBs that are targets of
10// beqz/bnez instructions. For instance, the copy instruction in the code below
11// can be removed because the beqz jumps to BB#2 when a0 is zero.
12// BB#1:
13// beqz %a0, <BB#2>
14// BB#2:
15// %a0 = COPY %x0
16//
17// This pass also recognizes Xqcibi branch-immediate forms when compared
18// against non-zero immediates.
19//
20// This pass should be run after register allocation and is based on the
21// earliest versions of AArch64RedundantCopyElimination.
22//
23// The pass also handles register-register branches when one operand is
24// materialized as a non-zero immediate in the predecessor block.
25//
26//===----------------------------------------------------------------------===//
27
28#include "RISCV.h"
29#include "RISCVInstrInfo.h"
30#include "llvm/ADT/Statistic.h"
38#include "llvm/IR/Analysis.h"
39#include "llvm/Support/Debug.h"
40#include <optional>
41
42using namespace llvm;
43
44#define DEBUG_TYPE "riscv-redundant-copy-elimination"
45
46STATISTIC(NumCopiesRemoved, "Number of copies removed.");
47
48namespace {
49class RISCVRedundantCopyEliminationLegacy : public MachineFunctionPass {
50public:
51 static char ID;
52 RISCVRedundantCopyEliminationLegacy() : MachineFunctionPass(ID) {}
53
54 bool runOnMachineFunction(MachineFunction &MF) override;
55 MachineFunctionProperties getRequiredProperties() const override {
56 return MachineFunctionProperties().setNoVRegs();
57 }
58
59 StringRef getPassName() const override {
60 return "RISC-V Redundant Copy Elimination";
61 }
62
63 void getAnalysisUsage(AnalysisUsage &AU) const override {
64 AU.setPreservesCFG();
65 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
67 }
68};
69
70} // end anonymous namespace
71
72char RISCVRedundantCopyEliminationLegacy::ID = 0;
73
74INITIALIZE_PASS(RISCVRedundantCopyEliminationLegacy, "riscv-copyelim",
75 "RISC-V Redundant Copy Elimination", false, false)
76
77static bool
78guaranteesZeroRegInBlock(MachineBasicBlock &MBB,
81 assert(Cond.size() == 3 && "Unexpected number of operands");
82 assert(TBB != nullptr && "Expected branch target basic block");
83 auto Opc = Cond[0].getImm();
84 if (Opc == RISCV::BEQ && Cond[2].isReg() && Cond[2].getReg() == RISCV::X0 &&
85 TBB == &MBB)
86 return true;
87 if (Opc == RISCV::BNE && Cond[2].isReg() && Cond[2].getReg() == RISCV::X0 &&
88 TBB != &MBB)
89 return true;
90 return false;
91}
92
93static bool
97 assert(Cond.size() == 3 && "Unexpected number of operands");
98 assert(TBB != nullptr && "Expected branch target basic block");
99 auto Opc = Cond[0].getImm();
100 if ((Opc == RISCV::QC_BEQI || Opc == RISCV::QC_E_BEQI ||
101 Opc == RISCV::NDS_BEQC || Opc == RISCV::BEQI) &&
102 Cond[2].isImm() && Cond[2].getImm() != 0 && TBB == &MBB)
103 return true;
104 if ((Opc == RISCV::QC_BNEI || Opc == RISCV::QC_E_BNEI ||
105 Opc == RISCV::NDS_BNEC || Opc == RISCV::BNEI) &&
106 Cond[2].isImm() && Cond[2].getImm() != 0 && TBB != &MBB)
107 return true;
108 return false;
109}
110
111// Match copy from x0, "addi rd, x0, imm", or "qc.li rd, imm", returning the
112// defined register and the known value. Reg is invalid if MI isn't a match.
114 if (MI.isCopy() && MI.getOperand(0).isReg() && MI.getOperand(1).isReg() &&
115 MI.getOperand(1).getReg() == RISCV::X0)
116 return RegImmPair(MI.getOperand(0).getReg(), 0);
117 if (MI.getOpcode() == RISCV::ADDI && MI.getOperand(0).isReg() &&
118 MI.getOperand(1).isReg() && MI.getOperand(1).getReg() == RISCV::X0 &&
119 MI.getOperand(2).isImm())
120 return RegImmPair(MI.getOperand(0).getReg(), MI.getOperand(2).getImm());
121 if (MI.getOpcode() == RISCV::QC_LI && MI.getOperand(0).isReg() &&
122 MI.getOperand(1).isImm())
123 return RegImmPair(MI.getOperand(0).getReg(), MI.getOperand(1).getImm());
124 return RegImmPair(Register(), 0);
125}
126
127static std::optional<int64_t>
129 const TargetRegisterInfo *TRI) {
130 // A write to X0 is discarded, so it cannot establish a nonzero value.
131 if (Reg == RISCV::X0)
132 return std::nullopt;
133
134 for (auto I = MBB.getFirstTerminator(); I != MBB.begin();) {
135 MachineInstr &MI = *--I;
136 if (!MI.modifiesRegister(Reg, TRI))
137 continue;
138 // The last modification must define Reg itself to a known value.
140 if (Match.Reg == Reg)
141 return Match.Imm;
142 return std::nullopt;
143 }
144 return std::nullopt;
145}
146
149 const TargetRegisterInfo *TRI,
150 const TargetInstrInfo *TII) {
151 // Check if the current basic block has a single predecessor.
152 if (MBB.pred_size() != 1)
153 return false;
154
155 // Check if the predecessor has two successors, implying the block ends in a
156 // conditional branch.
157 MachineBasicBlock *PredMBB = *MBB.pred_begin();
158 if (PredMBB->succ_size() != 2)
159 return false;
160
161 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
163 if (TII->analyzeBranch(*PredMBB, TBB, FBB, Cond, /*AllowModify*/ false) ||
164 Cond.empty())
165 return false;
166
167 Register TargetReg = Cond[1].getReg();
168
169 if (!TargetReg)
170 return false;
171
172 bool IsZeroCopy = guaranteesZeroRegInBlock(MBB, Cond, TBB);
173 bool IsImmCopy = !IsZeroCopy && guaranteesRegEqualsImmInBlock(MBB, Cond, TBB);
174 int64_t CompareImm = IsImmCopy ? Cond[2].getImm() : 0;
175 if (!IsZeroCopy && !IsImmCopy && Cond.size() == 3 &&
176 (Cond[0].getImm() == RISCV::BEQ || Cond[0].getImm() == RISCV::BNE) &&
177 Cond[2].isReg()) {
178 // One branch operand may have been materialized with ADDI or QC_LI.
179 // The other operand is known to have the same value on the equality edge,
180 // irrespective of the operand order.
181 std::optional<int64_t> Imm =
183 if (Imm && *Imm != 0) {
184 TargetReg = Cond[1].getReg();
185 CompareImm = *Imm;
186 IsImmCopy = true;
187 } else {
189 if (Imm && *Imm != 0) {
190 TargetReg = Cond[2].getReg();
191 CompareImm = *Imm;
192 IsImmCopy = true;
193 }
194 }
195 // For BEQ, equality is guaranteed on the taken edge. For BNE, it is
196 // guaranteed on the fallthrough edge.
197 IsImmCopy &= (Cond[0].getImm() == RISCV::BEQ) == (TBB == &MBB);
198 }
199
200 if (!IsZeroCopy && !IsImmCopy)
201 return false;
202
203 bool Changed = false;
204 MachineBasicBlock::iterator LastChange = MBB.begin();
205 // Remove redundant Copy instructions unless TargetReg is modified.
206 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;) {
207 MachineInstr *MI = &*I;
208 ++I;
209 // Compare with non-zero immediate or a known register value:
210 // remove redundant copy, addi rd,x0,imm, or qc.li rd,imm as applicable.
212 if (Match.Reg && TargetReg == Match.Reg && Match.Imm == CompareImm &&
213 !MRI->isReserved(Match.Reg)) {
214 LLVM_DEBUG(dbgs() << "Remove redundant Copy: ");
215 LLVM_DEBUG(MI->print(dbgs()));
216
217 MI->eraseFromParent();
218 Changed = true;
219 LastChange = I;
220 ++NumCopiesRemoved;
221 continue;
222 }
223
224 if (MI->modifiesRegister(TargetReg, TRI))
225 break;
226 }
227
228 if (!Changed)
229 return false;
230
232 assert((CondBr->getOpcode() == RISCV::BEQ ||
233 CondBr->getOpcode() == RISCV::BNE ||
234 CondBr->getOpcode() == RISCV::BEQI ||
235 CondBr->getOpcode() == RISCV::BNEI ||
236 CondBr->getOpcode() == RISCV::QC_BEQI ||
237 CondBr->getOpcode() == RISCV::QC_BNEI ||
238 CondBr->getOpcode() == RISCV::QC_E_BEQI ||
239 CondBr->getOpcode() == RISCV::QC_E_BNEI ||
240 CondBr->getOpcode() == RISCV::NDS_BEQC ||
241 CondBr->getOpcode() == RISCV::NDS_BNEC) &&
242 "Unexpected opcode");
243 assert((CondBr->getOperand(0).getReg() == TargetReg ||
244 CondBr->getOperand(1).getReg() == TargetReg) &&
245 "Unexpected register");
246
247 // Otherwise, we have to fixup the use-def chain, starting with the
248 // BEQ(I)/BNE(I). Conservatively mark as much as we can live.
249 CondBr->clearRegisterKills(TargetReg, TRI);
250
251 // Add newly used reg to the block's live-in list if it isn't there already.
252 if (!MBB.isLiveIn(TargetReg))
253 MBB.addLiveIn(TargetReg);
254
255 // Clear any kills of TargetReg between CondBr and the last removed COPY.
256 for (MachineInstr &MMI : make_range(MBB.begin(), LastChange))
257 MMI.clearRegisterKills(TargetReg, TRI);
258
259 return true;
260}
261
265 const MachineRegisterInfo *MRI = &MF.getRegInfo();
266
267 bool Changed = false;
268 for (MachineBasicBlock &MBB : MF)
270
271 return Changed;
272}
273
275 return new RISCVRedundantCopyEliminationLegacy();
276}
277
278bool RISCVRedundantCopyEliminationLegacy::runOnMachineFunction(
279 MachineFunction &MF) {
280 if (skipFunction(MF.getFunction()))
281 return false;
283}
284
285PreservedAnalyses
288 MFPropsModifier _(*this, MF);
290 if (!Changed)
291 return PreservedAnalyses::all();
294 .preserve<MachineRegisterClassAnalysis>();
295}
aarch64 promote const
uint64_t Imm
MachineBasicBlock & MBB
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static bool isReg(const MCInst &MI, unsigned OpNo)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
SmallVector< MachineOperand, 4 > Cond
MachineRegisterInfo & MRI
static bool guaranteesRegEqualsImmInBlock(MachineBasicBlock &MBB, const SmallVectorImpl< MachineOperand > &Cond, MachineBasicBlock *TBB)
static bool runRedundantCopyElimination(MachineFunction &MF)
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
assert(TBB !=nullptr &&"Expected branch target basic block")
static bool optimizeBlockForRedundantCopies(MachineBasicBlock &MBB, const MachineRegisterInfo *MRI, const TargetRegisterInfo *TRI, const TargetInstrInfo *TII)
static RegImmPair matchRegKnownVal(const MachineInstr &MI)
static std::optional< int64_t > getRegImmediateBeforeTerminator(MachineBasicBlock &MBB, Register Reg, const TargetRegisterInfo *TRI)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
An RAII based helper class to modify MachineFunctionProperties when running pass.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Wrapper class representing virtual and physical registers.
Definition Register.h:20
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
Pass manager infrastructure for declaring and invalidating analyses.
This is an optimization pass for GlobalISel generic memory operations.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
FunctionPass * createRISCVRedundantCopyEliminationLegacyPass()
Used to describe a register and immediate addition.