LLVM 20.0.0git
OptimizePHIs.cpp
Go to the documentation of this file.
1//===- OptimizePHIs.cpp - Optimize machine instruction PHIs ---------------===//
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 optimizes machine instruction PHIs to take advantage of
10// opportunities created during DAG legalization.
11//
12//===----------------------------------------------------------------------===//
13
16#include "llvm/ADT/Statistic.h"
24#include "llvm/Pass.h"
25#include <cassert>
26
27using namespace llvm;
28
29#define DEBUG_TYPE "opt-phis"
30
31STATISTIC(NumPHICycles, "Number of PHI cycles replaced");
32STATISTIC(NumDeadPHICycles, "Number of dead PHI cycles");
33
34namespace {
35
36class OptimizePHIs {
37 MachineRegisterInfo *MRI = nullptr;
38 const TargetInstrInfo *TII = nullptr;
39
40public:
41 bool run(MachineFunction &Fn);
42
43private:
44 using InstrSet = SmallPtrSet<MachineInstr *, 16>;
45 using InstrSetIterator = SmallPtrSetIterator<MachineInstr *>;
46
47 bool IsSingleValuePHICycle(MachineInstr *MI, unsigned &SingleValReg,
48 InstrSet &PHIsInCycle);
49 bool IsDeadPHICycle(MachineInstr *MI, InstrSet &PHIsInCycle);
50 bool OptimizeBB(MachineBasicBlock &MBB);
51};
52
53class OptimizePHIsLegacy : public MachineFunctionPass {
54public:
55 static char ID;
56 OptimizePHIsLegacy() : MachineFunctionPass(ID) {
58 }
59
60 bool runOnMachineFunction(MachineFunction &MF) override {
61 if (skipFunction(MF.getFunction()))
62 return false;
63 OptimizePHIs OP;
64 return OP.run(MF);
65 }
66
67 void getAnalysisUsage(AnalysisUsage &AU) const override {
68 AU.setPreservesCFG();
70 }
71};
72} // end anonymous namespace
73
74char OptimizePHIsLegacy::ID = 0;
75
76char &llvm::OptimizePHIsLegacyID = OptimizePHIsLegacy::ID;
77
78INITIALIZE_PASS(OptimizePHIsLegacy, DEBUG_TYPE,
79 "Optimize machine instruction PHIs", false, false)
80
83 OptimizePHIs OP;
84 if (!OP.run(MF))
87 PA.preserveSet<CFGAnalyses>();
88 return PA;
89}
90
91bool OptimizePHIs::run(MachineFunction &Fn) {
92 MRI = &Fn.getRegInfo();
94
95 // Find dead PHI cycles and PHI cycles that can be replaced by a single
96 // value. InstCombine does these optimizations, but DAG legalization may
97 // introduce new opportunities, e.g., when i64 values are split up for
98 // 32-bit targets.
99 bool Changed = false;
100 for (MachineBasicBlock &MBB : Fn)
101 Changed |= OptimizeBB(MBB);
102
103 return Changed;
104}
105
106/// IsSingleValuePHICycle - Check if MI is a PHI where all the source operands
107/// are copies of SingleValReg, possibly via copies through other PHIs. If
108/// SingleValReg is zero on entry, it is set to the register with the single
109/// non-copy value. PHIsInCycle is a set used to keep track of the PHIs that
110/// have been scanned. PHIs may be grouped by cycle, several cycles or chains.
111bool OptimizePHIs::IsSingleValuePHICycle(MachineInstr *MI,
112 unsigned &SingleValReg,
113 InstrSet &PHIsInCycle) {
114 assert(MI->isPHI() && "IsSingleValuePHICycle expects a PHI instruction");
115 Register DstReg = MI->getOperand(0).getReg();
116
117 // See if we already saw this register.
118 if (!PHIsInCycle.insert(MI).second)
119 return true;
120
121 // Don't scan crazily complex things.
122 if (PHIsInCycle.size() == 16)
123 return false;
124
125 // Scan the PHI operands.
126 for (unsigned i = 1; i != MI->getNumOperands(); i += 2) {
127 Register SrcReg = MI->getOperand(i).getReg();
128 if (SrcReg == DstReg)
129 continue;
130 MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
131
132 // Skip over register-to-register moves.
133 if (SrcMI && SrcMI->isCopy() && !SrcMI->getOperand(0).getSubReg() &&
134 !SrcMI->getOperand(1).getSubReg() &&
135 SrcMI->getOperand(1).getReg().isVirtual()) {
136 SrcReg = SrcMI->getOperand(1).getReg();
137 SrcMI = MRI->getVRegDef(SrcReg);
138 }
139 if (!SrcMI)
140 return false;
141
142 if (SrcMI->isPHI()) {
143 if (!IsSingleValuePHICycle(SrcMI, SingleValReg, PHIsInCycle))
144 return false;
145 } else {
146 // Fail if there is more than one non-phi/non-move register.
147 if (SingleValReg != 0 && SingleValReg != SrcReg)
148 return false;
149 SingleValReg = SrcReg;
150 }
151 }
152 return true;
153}
154
155/// IsDeadPHICycle - Check if the register defined by a PHI is only used by
156/// other PHIs in a cycle.
157bool OptimizePHIs::IsDeadPHICycle(MachineInstr *MI, InstrSet &PHIsInCycle) {
158 assert(MI->isPHI() && "IsDeadPHICycle expects a PHI instruction");
159 Register DstReg = MI->getOperand(0).getReg();
160 assert(DstReg.isVirtual() && "PHI destination is not a virtual register");
161
162 // See if we already saw this register.
163 if (!PHIsInCycle.insert(MI).second)
164 return true;
165
166 // Don't scan crazily complex things.
167 if (PHIsInCycle.size() == 16)
168 return false;
169
170 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DstReg)) {
171 if (!UseMI.isPHI() || !IsDeadPHICycle(&UseMI, PHIsInCycle))
172 return false;
173 }
174
175 return true;
176}
177
178/// OptimizeBB - Remove dead PHI cycles and PHI cycles that can be replaced by
179/// a single value.
180bool OptimizePHIs::OptimizeBB(MachineBasicBlock &MBB) {
181 bool Changed = false;
183 MII = MBB.begin(), E = MBB.end(); MII != E; ) {
184 MachineInstr *MI = &*MII++;
185 if (!MI->isPHI())
186 break;
187
188 // Check for single-value PHI cycles.
189 unsigned SingleValReg = 0;
190 InstrSet PHIsInCycle;
191 if (IsSingleValuePHICycle(MI, SingleValReg, PHIsInCycle) &&
192 SingleValReg != 0) {
193 Register OldReg = MI->getOperand(0).getReg();
194 if (!MRI->constrainRegClass(SingleValReg, MRI->getRegClass(OldReg)))
195 continue;
196
197 MRI->replaceRegWith(OldReg, SingleValReg);
198 MI->eraseFromParent();
199
200 // The kill flags on OldReg and SingleValReg may no longer be correct.
201 MRI->clearKillFlags(SingleValReg);
202
203 ++NumPHICycles;
204 Changed = true;
205 continue;
206 }
207
208 // Check for dead PHI cycles.
209 PHIsInCycle.clear();
210 if (IsDeadPHICycle(MI, PHIsInCycle)) {
211 for (MachineInstr *PhiMI : PHIsInCycle) {
212 if (MII == PhiMI)
213 ++MII;
214 PhiMI->eraseFromParent();
215 }
216 ++NumDeadPHICycles;
217 Changed = true;
218 }
219 }
220 return Changed;
221}
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
MachineBasicBlock & MBB
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define DEBUG_TYPE
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
#define OP(OPC)
Definition: Instruction.h:45
This file defines the SmallPtrSet class.
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:166
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
Represent the analysis usage information of a pass.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:256
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:72
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
Definition: Pass.cpp:178
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.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
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.
Definition: MachineInstr.h:69
bool isCopy() const
bool isPHI() const
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:585
unsigned getSubReg() const
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:91
SmallPtrSetIterator - This implements a const_iterator for SmallPtrSet.
Definition: SmallPtrSet.h:312
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
TargetInstrInfo - Interface to description of machine instruction set.
virtual const TargetInstrInfo * getInstrInfo() const
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
char & OptimizePHIsLegacyID
OptimizePHIs - This pass optimizes machine instruction PHIs to take advantage of opportunities create...
void initializeOptimizePHIsLegacyPass(PassRegistry &)