1 //===-- MachineCSE.cpp - Machine Common Subexpression Elimination Pass ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs global common subexpression elimination on machine
11 // instructions using a scoped hash table based value numbering scheme. It
12 // must be run while the machine function is still in SSA form.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "machine-cse"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/CodeGen/MachineDominators.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/ADT/ScopedHashTable.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Support/Debug.h"
29 STATISTIC(NumCoalesces, "Number of copies coalesced");
30 STATISTIC(NumCSEs, "Number of common subexpression eliminated");
33 class MachineCSE : public MachineFunctionPass {
34 const TargetInstrInfo *TII;
35 const TargetRegisterInfo *TRI;
37 MachineDominatorTree *DT;
38 MachineRegisterInfo *MRI;
40 static char ID; // Pass identification
41 MachineCSE() : MachineFunctionPass(&ID), CurrVN(0) {}
43 virtual bool runOnMachineFunction(MachineFunction &MF);
45 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47 MachineFunctionPass::getAnalysisUsage(AU);
48 AU.addRequired<AliasAnalysis>();
49 AU.addRequired<MachineDominatorTree>();
50 AU.addPreserved<MachineDominatorTree>();
55 ScopedHashTable<MachineInstr*, unsigned, MachineInstrExpressionTrait> VNT;
56 SmallVector<MachineInstr*, 64> Exps;
58 bool PerformTrivialCoalescing(MachineInstr *MI, MachineBasicBlock *MBB);
59 bool isPhysDefTriviallyDead(unsigned Reg,
60 MachineBasicBlock::const_iterator I,
61 MachineBasicBlock::const_iterator E);
62 bool hasLivePhysRegDefUse(MachineInstr *MI, MachineBasicBlock *MBB);
63 bool isCSECandidate(MachineInstr *MI);
64 bool isProfitableToCSE(unsigned Reg, MachineInstr *MI);
65 bool ProcessBlock(MachineDomTreeNode *Node);
67 } // end anonymous namespace
69 char MachineCSE::ID = 0;
70 static RegisterPass<MachineCSE>
71 X("machine-cse", "Machine Common Subexpression Elimination");
73 FunctionPass *llvm::createMachineCSEPass() { return new MachineCSE(); }
75 bool MachineCSE::PerformTrivialCoalescing(MachineInstr *MI,
76 MachineBasicBlock *MBB) {
78 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
79 MachineOperand &MO = MI->getOperand(i);
80 if (!MO.isReg() || !MO.isUse())
82 unsigned Reg = MO.getReg();
83 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
85 if (!MRI->hasOneUse(Reg))
86 // Only coalesce single use copies. This ensure the copy will be
89 MachineInstr *DefMI = MRI->getVRegDef(Reg);
90 if (DefMI->getParent() != MBB)
92 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
93 if (TII->isMoveInstr(*DefMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
94 TargetRegisterInfo::isVirtualRegister(SrcReg) &&
95 !SrcSubIdx && !DstSubIdx) {
96 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
97 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
98 if (SRC == RC || RC->hasSubClass(SRC)) {
99 DEBUG(dbgs() << "Coalescing: " << *DefMI);
100 DEBUG(dbgs() << "*** to: " << *MI);
102 DefMI->eraseFromParent();
112 bool MachineCSE::isPhysDefTriviallyDead(unsigned Reg,
113 MachineBasicBlock::const_iterator I,
114 MachineBasicBlock::const_iterator E) {
115 unsigned LookAheadLeft = 5;
116 while (LookAheadLeft--) {
118 // Reached end of block, register is obviously dead.
121 if (I->isDebugValue())
123 bool SeenDef = false;
124 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
125 const MachineOperand &MO = I->getOperand(i);
126 if (!MO.isReg() || !MO.getReg())
128 if (!TRI->regsOverlap(MO.getReg(), Reg))
135 // See a def of Reg (or an alias) before encountering any use, it's
143 bool MachineCSE::hasLivePhysRegDefUse(MachineInstr *MI, MachineBasicBlock *MBB){
144 unsigned PhysDef = 0;
145 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
146 MachineOperand &MO = MI->getOperand(i);
149 unsigned Reg = MO.getReg();
152 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
154 // Can't touch anything to read a physical register.
157 // If the def is dead, it's ok.
159 // Ok, this is a physical register def that's not marked "dead". That's
160 // common since this pass is run before livevariables. We can scan
161 // forward a few instructions and check if it is obviously dead.
163 // Multiple physical register defs. These are rare, forget about it.
170 MachineBasicBlock::iterator I = MI; I = llvm::next(I);
171 if (!isPhysDefTriviallyDead(PhysDef, I, MBB->end()))
177 bool MachineCSE::isCSECandidate(MachineInstr *MI) {
178 if (MI->isLabel() || MI->isPHI() || MI->isImplicitDef() ||
179 MI->isKill() || MI->isInlineAsm())
182 // Ignore copies or instructions that read / write physical registers
183 // (except for dead defs of physical registers).
184 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
185 if (TII->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) ||
186 MI->isExtractSubreg() || MI->isInsertSubreg() || MI->isSubregToReg())
189 // Ignore stuff that we obviously can't move.
190 const TargetInstrDesc &TID = MI->getDesc();
191 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
192 TID.hasUnmodeledSideEffects())
196 // Okay, this instruction does a load. As a refinement, we allow the target
197 // to decide whether the loaded value is actually a constant. If so, we can
198 // actually use it as a load.
199 if (!MI->isInvariantLoad(AA))
200 // FIXME: we should be able to hoist loads with no other side effects if
201 // there are no other instructions which can change memory in this loop.
202 // This is a trivial form of alias analysis.
208 /// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
209 /// common expression that defines Reg.
210 bool MachineCSE::isProfitableToCSE(unsigned Reg, MachineInstr *MI) {
211 // FIXME: This "heuristic" works around the lack the live range splitting.
212 // If the common subexpression is used by PHIs, do not reuse it unless the
213 // defined value is already used in the BB of the new use.
215 SmallPtrSet<MachineBasicBlock*, 4> CSBBs;
216 for (MachineRegisterInfo::use_nodbg_iterator I =
217 MRI->use_nodbg_begin(Reg),
218 E = MRI->use_nodbg_end(); I != E; ++I) {
219 MachineInstr *Use = &*I;
220 HasPHI |= Use->isPHI();
221 CSBBs.insert(Use->getParent());
226 return CSBBs.count(MI->getParent());
229 bool MachineCSE::ProcessBlock(MachineDomTreeNode *Node) {
230 bool Changed = false;
232 SmallVector<std::pair<unsigned, unsigned>, 8> CSEPairs;
233 ScopedHashTableScope<MachineInstr*, unsigned,
234 MachineInstrExpressionTrait> VNTS(VNT);
235 MachineBasicBlock *MBB = Node->getBlock();
236 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
237 MachineInstr *MI = &*I;
240 if (!isCSECandidate(MI))
243 bool FoundCSE = VNT.count(MI);
245 // Look for trivial copy coalescing opportunities.
246 if (PerformTrivialCoalescing(MI, MBB))
247 FoundCSE = VNT.count(MI);
249 // FIXME: commute commutable instructions?
251 // If the instruction defines a physical register and the value *may* be
252 // used, then it's not safe to replace it with a common subexpression.
253 if (FoundCSE && hasLivePhysRegDefUse(MI, MBB))
257 VNT.insert(MI, CurrVN++);
262 // Found a common subexpression, eliminate it.
263 unsigned CSVN = VNT.lookup(MI);
264 MachineInstr *CSMI = Exps[CSVN];
265 DEBUG(dbgs() << "Examining: " << *MI);
266 DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
268 // Check if it's profitable to perform this CSE.
270 unsigned NumDefs = MI->getDesc().getNumDefs();
271 for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
272 MachineOperand &MO = MI->getOperand(i);
273 if (!MO.isReg() || !MO.isDef())
275 unsigned OldReg = MO.getReg();
276 unsigned NewReg = CSMI->getOperand(i).getReg();
277 if (OldReg == NewReg)
279 assert(TargetRegisterInfo::isVirtualRegister(OldReg) &&
280 TargetRegisterInfo::isVirtualRegister(NewReg) &&
281 "Do not CSE physical register defs!");
282 if (!isProfitableToCSE(NewReg, MI)) {
286 CSEPairs.push_back(std::make_pair(OldReg, NewReg));
290 // Actually perform the elimination.
292 for (unsigned i = 0, e = CSEPairs.size(); i != e; ++i)
293 MRI->replaceRegWith(CSEPairs[i].first, CSEPairs[i].second);
294 MI->eraseFromParent();
297 DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
298 VNT.insert(MI, CurrVN++);
304 // Recursively call ProcessBlock with childred.
305 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
306 for (unsigned i = 0, e = Children.size(); i != e; ++i)
307 Changed |= ProcessBlock(Children[i]);
312 bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
313 TII = MF.getTarget().getInstrInfo();
314 TRI = MF.getTarget().getRegisterInfo();
315 MRI = &MF.getRegInfo();
316 AA = &getAnalysis<AliasAnalysis>();
317 DT = &getAnalysis<MachineDominatorTree>();
318 return ProcessBlock(DT->getRootNode());