LLVM 24.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"
25#include "llvm/Pass.h"
26#include <cassert>
27
28using namespace llvm;
29
30#define DEBUG_TYPE "opt-phis"
31
32STATISTIC(NumPHICycles, "Number of PHI cycles replaced");
33STATISTIC(NumDeadPHICycles, "Number of dead PHI cycles");
34
35namespace {
36
37class OptimizePHIs {
38 MachineRegisterInfo *MRI = nullptr;
39 const TargetInstrInfo *TII = nullptr;
40
41public:
42 bool run(MachineFunction &Fn);
43
44private:
45 using InstrSet = SmallPtrSet<MachineInstr *, 16>;
46 using InstrSetIterator = SmallPtrSetIterator<MachineInstr *>;
47
48 bool IsSingleValuePHICycle(MachineInstr *MI, Register &SingleValReg,
49 InstrSet &PHIsInCycle);
50 bool IsDeadPHICycle(MachineInstr *MI, InstrSet &PHIsInCycle);
51 bool OptimizeBB(MachineBasicBlock &MBB);
52};
53
54class OptimizePHIsLegacy : public MachineFunctionPass {
55public:
56 static char ID;
57 OptimizePHIsLegacy() : MachineFunctionPass(ID) {}
58
59 bool runOnMachineFunction(MachineFunction &MF) override {
60 if (skipFunction(MF.getFunction()))
61 return false;
62 OptimizePHIs OP;
63 return OP.run(MF);
64 }
65
66 void getAnalysisUsage(AnalysisUsage &AU) const override {
67 AU.setPreservesCFG();
68 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
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 PA.preserve<MachineRegisterClassAnalysis>();
89 return PA;
90}
91
92bool OptimizePHIs::run(MachineFunction &Fn) {
93 MRI = &Fn.getRegInfo();
95
96 // Find dead PHI cycles and PHI cycles that can be replaced by a single
97 // value. InstCombine does these optimizations, but DAG legalization may
98 // introduce new opportunities, e.g., when i64 values are split up for
99 // 32-bit targets.
100 bool Changed = false;
101 for (MachineBasicBlock &MBB : Fn)
102 Changed |= OptimizeBB(MBB);
103
104 return Changed;
105}
106
107/// IsSingleValuePHICycle - Check if MI is a PHI where all the source operands
108/// are copies of SingleValReg, possibly via copies through other PHIs. If
109/// SingleValReg is zero on entry, it is set to the register with the single
110/// non-copy value. PHIsInCycle is a set used to keep track of the PHIs that
111/// have been scanned. PHIs may be grouped by cycle, several cycles or chains.
112bool OptimizePHIs::IsSingleValuePHICycle(MachineInstr *MI,
113 Register &SingleValReg,
114 InstrSet &PHIsInCycle) {
115 assert(MI->isPHI() && "IsSingleValuePHICycle expects a PHI instruction");
116 Register DstReg = MI->getOperand(0).getReg();
117
118 // See if we already saw this register.
119 if (!PHIsInCycle.insert(MI).second)
120 return true;
121
122 // Don't scan crazily complex things.
123 if (PHIsInCycle.size() == 16)
124 return false;
125
126 // Scan the PHI operands.
127 for (unsigned i = 1; i != MI->getNumOperands(); i += 2) {
128 Register SrcReg = MI->getOperand(i).getReg();
129 if (SrcReg == DstReg)
130 continue;
131 MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
132
133 // Skip over register-to-register moves.
134 if (SrcMI && SrcMI->isCopy() && !SrcMI->getOperand(0).getSubReg() &&
135 !SrcMI->getOperand(1).getSubReg() &&
136 SrcMI->getOperand(1).getReg().isVirtual()) {
137 SrcReg = SrcMI->getOperand(1).getReg();
138 SrcMI = MRI->getVRegDef(SrcReg);
139 }
140 if (!SrcMI)
141 return false;
142
143 if (SrcMI->isPHI()) {
144 if (!IsSingleValuePHICycle(SrcMI, SingleValReg, PHIsInCycle))
145 return false;
146 } else {
147 // Fail if there is more than one non-phi/non-move register.
148 if (SingleValReg && SingleValReg != SrcReg)
149 return false;
150 SingleValReg = SrcReg;
151 }
152 }
153 return true;
154}
155
156/// IsDeadPHICycle - Check if the register defined by a PHI is only used by
157/// other PHIs in a cycle.
158bool OptimizePHIs::IsDeadPHICycle(MachineInstr *MI, InstrSet &PHIsInCycle) {
159 assert(MI->isPHI() && "IsDeadPHICycle expects a PHI instruction");
160 Register DstReg = MI->getOperand(0).getReg();
161 assert(DstReg.isVirtual() && "PHI destination is not a virtual register");
162
163 // See if we already saw this register.
164 if (!PHIsInCycle.insert(MI).second)
165 return true;
166
167 // Don't scan crazily complex things.
168 if (PHIsInCycle.size() == 16)
169 return false;
170
171 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DstReg)) {
172 if (!UseMI.isPHI() || !IsDeadPHICycle(&UseMI, PHIsInCycle))
173 return false;
174 }
175
176 return true;
177}
178
179/// OptimizeBB - Remove dead PHI cycles and PHI cycles that can be replaced by
180/// a single value.
181bool OptimizePHIs::OptimizeBB(MachineBasicBlock &MBB) {
182 bool Changed = false;
184 MII = MBB.begin(), E = MBB.end(); MII != E; ) {
185 MachineInstr *MI = &*MII++;
186 if (!MI->isPHI())
187 break;
188
189 // Check for single-value PHI cycles.
190 Register SingleValReg;
191 InstrSet PHIsInCycle;
192 if (IsSingleValuePHICycle(MI, SingleValReg, PHIsInCycle) && SingleValReg) {
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}
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
#define OP(OPC)
Definition Instruction.h:46
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:171
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:275
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
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.
bool isCopy() const
const MachineOperand & getOperand(unsigned i) const
unsigned getSubReg() const
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI void clearKillFlags(Register Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
LLVM_ABI MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
SmallPtrSetIterator - This implements a const_iterator for SmallPtrSet.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
TargetInstrInfo - Interface to description of machine instruction set.
virtual const TargetInstrInfo * getInstrInfo() const
Changed
This is an optimization pass for GlobalISel generic memory operations.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI char & OptimizePHIsLegacyID
OptimizePHIs - This pass optimizes machine instruction PHIs to take advantage of opportunities create...