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
14#include "llvm/CodeGen/OptimizePHIs.h"
15#include "llvm/ADT/SmallPtrSet.h"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/CodeGen/MachineBasicBlock.h"
18#include "llvm/CodeGen/MachineFunctionPass.h"
19#include "llvm/CodeGen/MachineInstr.h"
20#include "llvm/CodeGen/MachineOperand.h"
21#include "llvm/CodeGen/MachineRegisterInfo.h"
22#include "llvm/CodeGen/TargetSubtargetInfo.h"
23#include "llvm/InitializePasses.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, Register &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) {}
57
58 bool runOnMachineFunction(MachineFunction &MF) override {
59 if (skipFunction(F: MF.getFunction()))
60 return false;
61 OptimizePHIs OP;
62 return OP.run(Fn&: MF);
63 }
64
65 void getAnalysisUsage(AnalysisUsage &AU) const override {
66 AU.setPreservesCFG();
67 MachineFunctionPass::getAnalysisUsage(AU);
68 }
69};
70} // end anonymous namespace
71
72char OptimizePHIsLegacy::ID = 0;
73
74char &llvm::OptimizePHIsLegacyID = OptimizePHIsLegacy::ID;
75
76INITIALIZE_PASS(OptimizePHIsLegacy, DEBUG_TYPE,
77 "Optimize machine instruction PHIs", false, false)
78
79PreservedAnalyses OptimizePHIsPass::run(MachineFunction &MF,
80 MachineFunctionAnalysisManager &MFAM) {
81 OptimizePHIs OP;
82 if (!OP.run(Fn&: MF))
83 return PreservedAnalyses::all();
84 auto PA = getMachineFunctionPassPreservedAnalyses();
85 PA.preserveSet<CFGAnalyses>();
86 return PA;
87}
88
89bool OptimizePHIs::run(MachineFunction &Fn) {
90 MRI = &Fn.getRegInfo();
91 TII = Fn.getSubtarget().getInstrInfo();
92
93 // Find dead PHI cycles and PHI cycles that can be replaced by a single
94 // value. InstCombine does these optimizations, but DAG legalization may
95 // introduce new opportunities, e.g., when i64 values are split up for
96 // 32-bit targets.
97 bool Changed = false;
98 for (MachineBasicBlock &MBB : Fn)
99 Changed |= OptimizeBB(MBB);
100
101 return Changed;
102}
103
104/// IsSingleValuePHICycle - Check if MI is a PHI where all the source operands
105/// are copies of SingleValReg, possibly via copies through other PHIs. If
106/// SingleValReg is zero on entry, it is set to the register with the single
107/// non-copy value. PHIsInCycle is a set used to keep track of the PHIs that
108/// have been scanned. PHIs may be grouped by cycle, several cycles or chains.
109bool OptimizePHIs::IsSingleValuePHICycle(MachineInstr *MI,
110 Register &SingleValReg,
111 InstrSet &PHIsInCycle) {
112 assert(MI->isPHI() && "IsSingleValuePHICycle expects a PHI instruction");
113 Register DstReg = MI->getOperand(i: 0).getReg();
114
115 // See if we already saw this register.
116 if (!PHIsInCycle.insert(Ptr: MI).second)
117 return true;
118
119 // Don't scan crazily complex things.
120 if (PHIsInCycle.size() == 16)
121 return false;
122
123 // Scan the PHI operands.
124 for (unsigned i = 1; i != MI->getNumOperands(); i += 2) {
125 Register SrcReg = MI->getOperand(i).getReg();
126 if (SrcReg == DstReg)
127 continue;
128 MachineInstr *SrcMI = MRI->getVRegDef(Reg: SrcReg);
129
130 // Skip over register-to-register moves.
131 if (SrcMI && SrcMI->isCopy() && !SrcMI->getOperand(i: 0).getSubReg() &&
132 !SrcMI->getOperand(i: 1).getSubReg() &&
133 SrcMI->getOperand(i: 1).getReg().isVirtual()) {
134 SrcReg = SrcMI->getOperand(i: 1).getReg();
135 SrcMI = MRI->getVRegDef(Reg: SrcReg);
136 }
137 if (!SrcMI)
138 return false;
139
140 if (SrcMI->isPHI()) {
141 if (!IsSingleValuePHICycle(MI: SrcMI, SingleValReg, PHIsInCycle))
142 return false;
143 } else {
144 // Fail if there is more than one non-phi/non-move register.
145 if (SingleValReg && SingleValReg != SrcReg)
146 return false;
147 SingleValReg = SrcReg;
148 }
149 }
150 return true;
151}
152
153/// IsDeadPHICycle - Check if the register defined by a PHI is only used by
154/// other PHIs in a cycle.
155bool OptimizePHIs::IsDeadPHICycle(MachineInstr *MI, InstrSet &PHIsInCycle) {
156 assert(MI->isPHI() && "IsDeadPHICycle expects a PHI instruction");
157 Register DstReg = MI->getOperand(i: 0).getReg();
158 assert(DstReg.isVirtual() && "PHI destination is not a virtual register");
159
160 // See if we already saw this register.
161 if (!PHIsInCycle.insert(Ptr: MI).second)
162 return true;
163
164 // Don't scan crazily complex things.
165 if (PHIsInCycle.size() == 16)
166 return false;
167
168 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg: DstReg)) {
169 if (!UseMI.isPHI() || !IsDeadPHICycle(MI: &UseMI, PHIsInCycle))
170 return false;
171 }
172
173 return true;
174}
175
176/// OptimizeBB - Remove dead PHI cycles and PHI cycles that can be replaced by
177/// a single value.
178bool OptimizePHIs::OptimizeBB(MachineBasicBlock &MBB) {
179 bool Changed = false;
180 for (MachineBasicBlock::iterator
181 MII = MBB.begin(), E = MBB.end(); MII != E; ) {
182 MachineInstr *MI = &*MII++;
183 if (!MI->isPHI())
184 break;
185
186 // Check for single-value PHI cycles.
187 Register SingleValReg;
188 InstrSet PHIsInCycle;
189 if (IsSingleValuePHICycle(MI, SingleValReg, PHIsInCycle) && SingleValReg) {
190 Register OldReg = MI->getOperand(i: 0).getReg();
191 if (!MRI->constrainRegClass(Reg: SingleValReg, RC: MRI->getRegClass(Reg: OldReg)))
192 continue;
193
194 MRI->replaceRegWith(FromReg: OldReg, ToReg: SingleValReg);
195 MI->eraseFromParent();
196
197 // The kill flags on OldReg and SingleValReg may no longer be correct.
198 MRI->clearKillFlags(Reg: SingleValReg);
199
200 ++NumPHICycles;
201 Changed = true;
202 continue;
203 }
204
205 // Check for dead PHI cycles.
206 PHIsInCycle.clear();
207 if (IsDeadPHICycle(MI, PHIsInCycle)) {
208 for (MachineInstr *PhiMI : PHIsInCycle) {
209 if (MII == PhiMI)
210 ++MII;
211 PhiMI->eraseFromParent();
212 }
213 ++NumDeadPHICycles;
214 Changed = true;
215 }
216 }
217 return Changed;
218}
219