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/RegisterClassInfo.h"
23#include "llvm/CodeGen/TargetSubtargetInfo.h"
24#include "llvm/InitializePasses.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
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 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
68 MachineFunctionPass::getAnalysisUsage(AU);
69 }
70};
71} // end anonymous namespace
72
73char OptimizePHIsLegacy::ID = 0;
74
75char &llvm::OptimizePHIsLegacyID = OptimizePHIsLegacy::ID;
76
77INITIALIZE_PASS(OptimizePHIsLegacy, DEBUG_TYPE,
78 "Optimize machine instruction PHIs", false, false)
79
80PreservedAnalyses OptimizePHIsPass::run(MachineFunction &MF,
81 MachineFunctionAnalysisManager &MFAM) {
82 OptimizePHIs OP;
83 if (!OP.run(Fn&: MF))
84 return PreservedAnalyses::all();
85 auto PA = getMachineFunctionPassPreservedAnalyses();
86 PA.preserveSet<CFGAnalyses>();
87 PA.preserve<MachineRegisterClassAnalysis>();
88 return PA;
89}
90
91bool OptimizePHIs::run(MachineFunction &Fn) {
92 MRI = &Fn.getRegInfo();
93 TII = Fn.getSubtarget().getInstrInfo();
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 Register &SingleValReg,
113 InstrSet &PHIsInCycle) {
114 assert(MI->isPHI() && "IsSingleValuePHICycle expects a PHI instruction");
115 Register DstReg = MI->getOperand(i: 0).getReg();
116
117 // See if we already saw this register.
118 if (!PHIsInCycle.insert(Ptr: 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(Reg: SrcReg);
131
132 // Skip over register-to-register moves.
133 if (SrcMI && SrcMI->isCopy() && !SrcMI->getOperand(i: 0).getSubReg() &&
134 !SrcMI->getOperand(i: 1).getSubReg() &&
135 SrcMI->getOperand(i: 1).getReg().isVirtual()) {
136 SrcReg = SrcMI->getOperand(i: 1).getReg();
137 SrcMI = MRI->getVRegDef(Reg: SrcReg);
138 }
139 if (!SrcMI)
140 return false;
141
142 if (SrcMI->isPHI()) {
143 if (!IsSingleValuePHICycle(MI: SrcMI, SingleValReg, PHIsInCycle))
144 return false;
145 } else {
146 // Fail if there is more than one non-phi/non-move register.
147 if (SingleValReg && 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(i: 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(Ptr: 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(Reg: DstReg)) {
171 if (!UseMI.isPHI() || !IsDeadPHICycle(MI: &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;
182 for (MachineBasicBlock::iterator
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 Register SingleValReg;
190 InstrSet PHIsInCycle;
191 if (IsSingleValuePHICycle(MI, SingleValReg, PHIsInCycle) && SingleValReg) {
192 Register OldReg = MI->getOperand(i: 0).getReg();
193 if (!MRI->constrainRegClass(Reg: SingleValReg, RC: MRI->getRegClass(Reg: OldReg)))
194 continue;
195
196 MRI->replaceRegWith(FromReg: OldReg, ToReg: SingleValReg);
197 MI->eraseFromParent();
198
199 ++NumPHICycles;
200 Changed = true;
201 continue;
202 }
203
204 // Check for dead PHI cycles.
205 PHIsInCycle.clear();
206 if (IsDeadPHICycle(MI, PHIsInCycle)) {
207 for (MachineInstr *PhiMI : PHIsInCycle) {
208 if (MII == PhiMI)
209 ++MII;
210 PhiMI->eraseFromParent();
211 }
212 ++NumDeadPHICycles;
213 Changed = true;
214 }
215 }
216 return Changed;
217}
218