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;
36 MachineRegisterInfo *MRI;
37 MachineDominatorTree *DT;
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 ProcessBlock(MachineDomTreeNode *Node);
66 } // end anonymous namespace
68 char MachineCSE::ID = 0;
69 static RegisterPass<MachineCSE>
70 X("machine-cse", "Machine Common Subexpression Elimination");
72 FunctionPass *llvm::createMachineCSEPass() { return new MachineCSE(); }
74 bool MachineCSE::PerformTrivialCoalescing(MachineInstr *MI,
75 MachineBasicBlock *MBB) {
77 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
78 MachineOperand &MO = MI->getOperand(i);
79 if (!MO.isReg() || !MO.isUse())
81 unsigned Reg = MO.getReg();
82 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
84 if (!MRI->hasOneUse(Reg))
85 // Only coalesce single use copies. This ensure the copy will be
88 MachineInstr *DefMI = MRI->getVRegDef(Reg);
89 if (DefMI->getParent() != MBB)
91 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
92 if (TII->isMoveInstr(*DefMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
93 TargetRegisterInfo::isVirtualRegister(SrcReg) &&
94 MRI->getRegClass(SrcReg) == MRI->getRegClass(Reg) &&
95 !SrcSubIdx && !DstSubIdx) {
96 DEBUG(dbgs() << "Coalescing: " << *DefMI);
97 DEBUG(dbgs() << "*** to: " << *MI);
99 DefMI->eraseFromParent();
108 bool MachineCSE::isPhysDefTriviallyDead(unsigned Reg,
109 MachineBasicBlock::const_iterator I,
110 MachineBasicBlock::const_iterator E) {
111 unsigned LookAheadLeft = 5;
112 while (LookAheadLeft--) {
114 // Reached end of block, register is obviously dead.
117 if (I->isDebugValue())
119 bool SeenDef = false;
120 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
121 const MachineOperand &MO = I->getOperand(i);
122 if (!MO.isReg() || !MO.getReg())
124 if (!TRI->regsOverlap(MO.getReg(), Reg))
131 // See a def of Reg (or an alias) before encountering any use, it's
139 bool MachineCSE::hasLivePhysRegDefUse(MachineInstr *MI, MachineBasicBlock *MBB){
140 unsigned PhysDef = 0;
141 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
142 MachineOperand &MO = MI->getOperand(i);
145 unsigned Reg = MO.getReg();
148 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
150 // Can't touch anything to read a physical register.
153 // If the def is dead, it's ok.
155 // Ok, this is a physical register def that's not marked "dead". That's
156 // common since this pass is run before livevariables. We can scan
157 // forward a few instructions and check if it is obviously dead.
159 // Multiple physical register defs. These are rare, forget about it.
166 MachineBasicBlock::iterator I = MI; I = llvm::next(I);
167 if (!isPhysDefTriviallyDead(PhysDef, I, MBB->end()))
173 bool MachineCSE::isCSECandidate(MachineInstr *MI) {
174 // Ignore copies or instructions that read / write physical registers
175 // (except for dead defs of physical registers).
176 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
177 if (TII->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) ||
178 MI->isExtractSubreg() || MI->isInsertSubreg() || MI->isSubregToReg())
181 // Ignore stuff that we obviously can't move.
182 const TargetInstrDesc &TID = MI->getDesc();
183 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
184 TID.hasUnmodeledSideEffects())
188 // Okay, this instruction does a load. As a refinement, we allow the target
189 // to decide whether the loaded value is actually a constant. If so, we can
190 // actually use it as a load.
191 if (!MI->isInvariantLoad(AA))
192 // FIXME: we should be able to hoist loads with no other side effects if
193 // there are no other instructions which can change memory in this loop.
194 // This is a trivial form of alias analysis.
200 bool MachineCSE::ProcessBlock(MachineDomTreeNode *Node) {
201 bool Changed = false;
203 ScopedHashTableScope<MachineInstr*, unsigned,
204 MachineInstrExpressionTrait> VNTS(VNT);
205 MachineBasicBlock *MBB = Node->getBlock();
206 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
207 MachineInstr *MI = &*I;
210 if (!isCSECandidate(MI))
213 bool FoundCSE = VNT.count(MI);
215 // Look for trivial copy coalescing opportunities.
216 if (PerformTrivialCoalescing(MI, MBB))
217 FoundCSE = VNT.count(MI);
219 // FIXME: commute commutable instructions?
221 // If the instruction defines a physical register and the value *may* be
222 // used, then it's not safe to replace it with a common subexpression.
223 if (FoundCSE && hasLivePhysRegDefUse(MI, MBB))
227 VNT.insert(MI, CurrVN++);
232 // Found a common subexpression, eliminate it.
233 unsigned CSVN = VNT.lookup(MI);
234 MachineInstr *CSMI = Exps[CSVN];
235 DEBUG(dbgs() << "Examining: " << *MI);
236 DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
237 unsigned NumDefs = MI->getDesc().getNumDefs();
238 for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
239 MachineOperand &MO = MI->getOperand(i);
240 if (!MO.isReg() || !MO.isDef())
242 unsigned OldReg = MO.getReg();
243 unsigned NewReg = CSMI->getOperand(i).getReg();
244 if (OldReg == NewReg)
246 assert(TargetRegisterInfo::isVirtualRegister(OldReg) &&
247 TargetRegisterInfo::isVirtualRegister(NewReg) &&
248 "Do not CSE physical register defs!");
249 MRI->replaceRegWith(OldReg, NewReg);
252 MI->eraseFromParent();
256 // Recursively call ProcessBlock with childred.
257 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
258 for (unsigned i = 0, e = Children.size(); i != e; ++i)
259 Changed |= ProcessBlock(Children[i]);
264 bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
265 TII = MF.getTarget().getInstrInfo();
266 TRI = MF.getTarget().getRegisterInfo();
267 MRI = &MF.getRegInfo();
268 DT = &getAnalysis<MachineDominatorTree>();
269 AA = &getAnalysis<AliasAnalysis>();
270 return ProcessBlock(DT->getRootNode());