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/DenseMap.h"
24 #include "llvm/ADT/ScopedHashTable.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
31 STATISTIC(NumCoalesces, "Number of copies coalesced");
32 STATISTIC(NumCSEs, "Number of common subexpression eliminated");
33 STATISTIC(NumPhysCSEs, "Number of phyreg defining common subexpr eliminated");
36 class MachineCSE : public MachineFunctionPass {
37 const TargetInstrInfo *TII;
38 const TargetRegisterInfo *TRI;
40 MachineDominatorTree *DT;
41 MachineRegisterInfo *MRI;
43 static char ID; // Pass identification
44 MachineCSE() : MachineFunctionPass(ID), LookAheadLimit(5), CurrVN(0) {
45 initializeMachineCSEPass(*PassRegistry::getPassRegistry());
48 virtual bool runOnMachineFunction(MachineFunction &MF);
50 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
52 MachineFunctionPass::getAnalysisUsage(AU);
53 AU.addRequired<AliasAnalysis>();
54 AU.addPreservedID(MachineLoopInfoID);
55 AU.addRequired<MachineDominatorTree>();
56 AU.addPreserved<MachineDominatorTree>();
59 virtual void releaseMemory() {
65 const unsigned LookAheadLimit;
66 typedef ScopedHashTableScope<MachineInstr*, unsigned,
67 MachineInstrExpressionTrait> ScopeType;
68 DenseMap<MachineBasicBlock*, ScopeType*> ScopeMap;
69 ScopedHashTable<MachineInstr*, unsigned, MachineInstrExpressionTrait> VNT;
70 SmallVector<MachineInstr*, 64> Exps;
73 bool PerformTrivialCoalescing(MachineInstr *MI, MachineBasicBlock *MBB);
74 bool isPhysDefTriviallyDead(unsigned Reg,
75 MachineBasicBlock::const_iterator I,
76 MachineBasicBlock::const_iterator E) const ;
77 bool hasLivePhysRegDefUse(const MachineInstr *MI,
78 const MachineBasicBlock *MBB,
79 unsigned &PhysDef) const;
80 bool PhysRegDefReaches(MachineInstr *CSMI, MachineInstr *MI,
81 unsigned PhysDef) const;
82 bool isCSECandidate(MachineInstr *MI);
83 bool isProfitableToCSE(unsigned CSReg, unsigned Reg,
84 MachineInstr *CSMI, MachineInstr *MI);
85 void EnterScope(MachineBasicBlock *MBB);
86 void ExitScope(MachineBasicBlock *MBB);
87 bool ProcessBlock(MachineBasicBlock *MBB);
88 void ExitScopeIfDone(MachineDomTreeNode *Node,
89 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
90 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
91 bool PerformCSE(MachineDomTreeNode *Node);
93 } // end anonymous namespace
95 char MachineCSE::ID = 0;
96 INITIALIZE_PASS_BEGIN(MachineCSE, "machine-cse",
97 "Machine Common Subexpression Elimination", false, false)
98 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
99 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
100 INITIALIZE_PASS_END(MachineCSE, "machine-cse",
101 "Machine Common Subexpression Elimination", false, false)
103 FunctionPass *llvm::createMachineCSEPass() { return new MachineCSE(); }
105 bool MachineCSE::PerformTrivialCoalescing(MachineInstr *MI,
106 MachineBasicBlock *MBB) {
107 bool Changed = false;
108 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
109 MachineOperand &MO = MI->getOperand(i);
110 if (!MO.isReg() || !MO.isUse())
112 unsigned Reg = MO.getReg();
113 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
115 if (!MRI->hasOneNonDBGUse(Reg))
116 // Only coalesce single use copies. This ensure the copy will be
119 MachineInstr *DefMI = MRI->getVRegDef(Reg);
120 if (DefMI->getParent() != MBB)
122 if (!DefMI->isCopy())
124 unsigned SrcReg = DefMI->getOperand(1).getReg();
125 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
127 if (DefMI->getOperand(0).getSubReg() || DefMI->getOperand(1).getSubReg())
129 if (!MRI->constrainRegClass(SrcReg, MRI->getRegClass(Reg)))
131 DEBUG(dbgs() << "Coalescing: " << *DefMI);
132 DEBUG(dbgs() << "*** to: " << *MI);
134 MRI->clearKillFlags(SrcReg);
135 DefMI->eraseFromParent();
144 MachineCSE::isPhysDefTriviallyDead(unsigned Reg,
145 MachineBasicBlock::const_iterator I,
146 MachineBasicBlock::const_iterator E) const {
147 unsigned LookAheadLeft = LookAheadLimit;
148 while (LookAheadLeft) {
149 // Skip over dbg_value's.
150 while (I != E && I->isDebugValue())
154 // Reached end of block, register is obviously dead.
157 bool SeenDef = false;
158 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
159 const MachineOperand &MO = I->getOperand(i);
160 if (!MO.isReg() || !MO.getReg())
162 if (!TRI->regsOverlap(MO.getReg(), Reg))
170 // See a def of Reg (or an alias) before encountering any use, it's
180 /// hasLivePhysRegDefUse - Return true if the specified instruction read / write
181 /// physical registers (except for dead defs of physical registers). It also
182 /// returns the physical register def by reference if it's the only one and the
183 /// instruction does not uses a physical register.
184 bool MachineCSE::hasLivePhysRegDefUse(const MachineInstr *MI,
185 const MachineBasicBlock *MBB,
186 unsigned &PhysDef) const {
188 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
189 const MachineOperand &MO = MI->getOperand(i);
192 unsigned Reg = MO.getReg();
195 if (TargetRegisterInfo::isVirtualRegister(Reg))
198 // Can't touch anything to read a physical register.
203 // If the def is dead, it's ok.
205 // Ok, this is a physical register def that's not marked "dead". That's
206 // common since this pass is run before livevariables. We can scan
207 // forward a few instructions and check if it is obviously dead.
209 // Multiple physical register defs. These are rare, forget about it.
217 MachineBasicBlock::const_iterator I = MI; I = llvm::next(I);
218 if (!isPhysDefTriviallyDead(PhysDef, I, MBB->end()))
224 bool MachineCSE::PhysRegDefReaches(MachineInstr *CSMI, MachineInstr *MI,
225 unsigned PhysDef) const {
226 // For now conservatively returns false if the common subexpression is
227 // not in the same basic block as the given instruction.
228 MachineBasicBlock *MBB = MI->getParent();
229 if (CSMI->getParent() != MBB)
231 MachineBasicBlock::const_iterator I = CSMI; I = llvm::next(I);
232 MachineBasicBlock::const_iterator E = MI;
233 unsigned LookAheadLeft = LookAheadLimit;
234 while (LookAheadLeft) {
235 // Skip over dbg_value's.
236 while (I != E && I->isDebugValue())
241 if (I->modifiesRegister(PhysDef, TRI))
251 bool MachineCSE::isCSECandidate(MachineInstr *MI) {
252 if (MI->isLabel() || MI->isPHI() || MI->isImplicitDef() ||
253 MI->isKill() || MI->isInlineAsm() || MI->isDebugValue())
257 if (MI->isCopyLike())
260 // Ignore stuff that we obviously can't move.
261 const TargetInstrDesc &TID = MI->getDesc();
262 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
263 TID.hasUnmodeledSideEffects())
267 // Okay, this instruction does a load. As a refinement, we allow the target
268 // to decide whether the loaded value is actually a constant. If so, we can
269 // actually use it as a load.
270 if (!MI->isInvariantLoad(AA))
271 // FIXME: we should be able to hoist loads with no other side effects if
272 // there are no other instructions which can change memory in this loop.
273 // This is a trivial form of alias analysis.
279 /// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
280 /// common expression that defines Reg.
281 bool MachineCSE::isProfitableToCSE(unsigned CSReg, unsigned Reg,
282 MachineInstr *CSMI, MachineInstr *MI) {
283 // FIXME: Heuristics that works around the lack the live range splitting.
285 // Heuristics #1: Don't cse "cheap" computating if the def is not local or in an
286 // immediate predecessor. We don't want to increase register pressure and end up
287 // causing other computation to be spilled.
288 if (MI->getDesc().isAsCheapAsAMove()) {
289 MachineBasicBlock *CSBB = CSMI->getParent();
290 MachineBasicBlock *BB = MI->getParent();
292 find(CSBB->succ_begin(), CSBB->succ_end(), BB) == CSBB->succ_end())
296 // Heuristics #2: If the expression doesn't not use a vr and the only use
297 // of the redundant computation are copies, do not cse.
298 bool HasVRegUse = false;
299 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
300 const MachineOperand &MO = MI->getOperand(i);
301 if (MO.isReg() && MO.isUse() && MO.getReg() &&
302 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
308 bool HasNonCopyUse = false;
309 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
310 E = MRI->use_nodbg_end(); I != E; ++I) {
311 MachineInstr *Use = &*I;
313 if (!Use->isCopyLike()) {
314 HasNonCopyUse = true;
322 // Heuristics #3: If the common subexpression is used by PHIs, do not reuse
323 // it unless the defined value is already used in the BB of the new use.
325 SmallPtrSet<MachineBasicBlock*, 4> CSBBs;
326 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(CSReg),
327 E = MRI->use_nodbg_end(); I != E; ++I) {
328 MachineInstr *Use = &*I;
329 HasPHI |= Use->isPHI();
330 CSBBs.insert(Use->getParent());
335 return CSBBs.count(MI->getParent());
338 void MachineCSE::EnterScope(MachineBasicBlock *MBB) {
339 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
340 ScopeType *Scope = new ScopeType(VNT);
341 ScopeMap[MBB] = Scope;
344 void MachineCSE::ExitScope(MachineBasicBlock *MBB) {
345 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
346 DenseMap<MachineBasicBlock*, ScopeType*>::iterator SI = ScopeMap.find(MBB);
347 assert(SI != ScopeMap.end());
352 bool MachineCSE::ProcessBlock(MachineBasicBlock *MBB) {
353 bool Changed = false;
355 SmallVector<std::pair<unsigned, unsigned>, 8> CSEPairs;
356 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
357 MachineInstr *MI = &*I;
360 if (!isCSECandidate(MI))
363 bool DefPhys = false;
364 bool FoundCSE = VNT.count(MI);
366 // Look for trivial copy coalescing opportunities.
367 if (PerformTrivialCoalescing(MI, MBB)) {
368 // After coalescing MI itself may become a copy.
369 if (MI->isCopyLike())
371 FoundCSE = VNT.count(MI);
374 // FIXME: commute commutable instructions?
376 // If the instruction defines a physical register and the value *may* be
377 // used, then it's not safe to replace it with a common subexpression.
378 unsigned PhysDef = 0;
379 if (FoundCSE && hasLivePhysRegDefUse(MI, MBB, PhysDef)) {
382 // ... Unless the CS is local and it also defines the physical register
383 // which is not clobbered in between.
385 unsigned CSVN = VNT.lookup(MI);
386 MachineInstr *CSMI = Exps[CSVN];
387 if (PhysRegDefReaches(CSMI, MI, PhysDef)) {
395 VNT.insert(MI, CurrVN++);
400 // Found a common subexpression, eliminate it.
401 unsigned CSVN = VNT.lookup(MI);
402 MachineInstr *CSMI = Exps[CSVN];
403 DEBUG(dbgs() << "Examining: " << *MI);
404 DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
406 // Check if it's profitable to perform this CSE.
408 unsigned NumDefs = MI->getDesc().getNumDefs();
409 for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
410 MachineOperand &MO = MI->getOperand(i);
411 if (!MO.isReg() || !MO.isDef())
413 unsigned OldReg = MO.getReg();
414 unsigned NewReg = CSMI->getOperand(i).getReg();
415 if (OldReg == NewReg)
417 assert(TargetRegisterInfo::isVirtualRegister(OldReg) &&
418 TargetRegisterInfo::isVirtualRegister(NewReg) &&
419 "Do not CSE physical register defs!");
420 if (!isProfitableToCSE(NewReg, OldReg, CSMI, MI)) {
424 CSEPairs.push_back(std::make_pair(OldReg, NewReg));
428 // Actually perform the elimination.
430 for (unsigned i = 0, e = CSEPairs.size(); i != e; ++i) {
431 MRI->replaceRegWith(CSEPairs[i].first, CSEPairs[i].second);
432 MRI->clearKillFlags(CSEPairs[i].second);
434 MI->eraseFromParent();
439 DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
440 VNT.insert(MI, CurrVN++);
449 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
450 /// dominator tree node if its a leaf or all of its children are done. Walk
451 /// up the dominator tree to destroy ancestors which are now done.
453 MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node,
454 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
455 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
456 if (OpenChildren[Node])
460 ExitScope(Node->getBlock());
462 // Now traverse upwards to pop ancestors whose offsprings are all done.
463 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
464 unsigned Left = --OpenChildren[Parent];
467 ExitScope(Parent->getBlock());
472 bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) {
473 SmallVector<MachineDomTreeNode*, 32> Scopes;
474 SmallVector<MachineDomTreeNode*, 8> WorkList;
475 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
476 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
480 // Perform a DFS walk to determine the order of visit.
481 WorkList.push_back(Node);
483 Node = WorkList.pop_back_val();
484 Scopes.push_back(Node);
485 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
486 unsigned NumChildren = Children.size();
487 OpenChildren[Node] = NumChildren;
488 for (unsigned i = 0; i != NumChildren; ++i) {
489 MachineDomTreeNode *Child = Children[i];
490 ParentMap[Child] = Node;
491 WorkList.push_back(Child);
493 } while (!WorkList.empty());
496 bool Changed = false;
497 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
498 MachineDomTreeNode *Node = Scopes[i];
499 MachineBasicBlock *MBB = Node->getBlock();
501 Changed |= ProcessBlock(MBB);
502 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
503 ExitScopeIfDone(Node, OpenChildren, ParentMap);
509 bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
510 TII = MF.getTarget().getInstrInfo();
511 TRI = MF.getTarget().getRegisterInfo();
512 MRI = &MF.getRegInfo();
513 AA = &getAnalysis<AliasAnalysis>();
514 DT = &getAnalysis<MachineDominatorTree>();
515 return PerformCSE(DT->getRootNode());