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");
34 static cl::opt<bool> CSEPhysDef("machine-cse-phys-defs",
35 cl::init(false), cl::Hidden);
38 class MachineCSE : public MachineFunctionPass {
39 const TargetInstrInfo *TII;
40 const TargetRegisterInfo *TRI;
42 MachineDominatorTree *DT;
43 MachineRegisterInfo *MRI;
45 static char ID; // Pass identification
46 MachineCSE() : MachineFunctionPass(&ID), LookAheadLimit(5), CurrVN(0) {}
48 virtual bool runOnMachineFunction(MachineFunction &MF);
50 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
52 MachineFunctionPass::getAnalysisUsage(AU);
53 AU.addRequired<AliasAnalysis>();
54 AU.addRequired<MachineDominatorTree>();
55 AU.addPreserved<MachineDominatorTree>();
59 const unsigned LookAheadLimit;
60 typedef ScopedHashTableScope<MachineInstr*, unsigned,
61 MachineInstrExpressionTrait> ScopeType;
62 DenseMap<MachineBasicBlock*, ScopeType*> ScopeMap;
63 ScopedHashTable<MachineInstr*, unsigned, MachineInstrExpressionTrait> VNT;
64 SmallVector<MachineInstr*, 64> Exps;
67 bool PerformTrivialCoalescing(MachineInstr *MI, MachineBasicBlock *MBB);
68 bool isPhysDefTriviallyDead(unsigned Reg,
69 MachineBasicBlock::const_iterator I,
70 MachineBasicBlock::const_iterator E) const ;
71 bool hasLivePhysRegDefUse(const MachineInstr *MI,
72 const MachineBasicBlock *MBB,
73 unsigned &PhysDef) const;
74 bool PhysRegDefReaches(MachineInstr *CSMI, MachineInstr *MI,
75 unsigned PhysDef) const;
76 bool isCSECandidate(MachineInstr *MI);
77 bool isProfitableToCSE(unsigned CSReg, unsigned Reg,
78 MachineInstr *CSMI, MachineInstr *MI);
79 void EnterScope(MachineBasicBlock *MBB);
80 void ExitScope(MachineBasicBlock *MBB);
81 bool ProcessBlock(MachineBasicBlock *MBB);
82 void ExitScopeIfDone(MachineDomTreeNode *Node,
83 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
84 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
85 bool PerformCSE(MachineDomTreeNode *Node);
87 } // end anonymous namespace
89 char MachineCSE::ID = 0;
90 static RegisterPass<MachineCSE>
91 X("machine-cse", "Machine Common Subexpression Elimination");
93 FunctionPass *llvm::createMachineCSEPass() { return new MachineCSE(); }
95 bool MachineCSE::PerformTrivialCoalescing(MachineInstr *MI,
96 MachineBasicBlock *MBB) {
98 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
99 MachineOperand &MO = MI->getOperand(i);
100 if (!MO.isReg() || !MO.isUse())
102 unsigned Reg = MO.getReg();
103 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
105 if (!MRI->hasOneUse(Reg))
106 // Only coalesce single use copies. This ensure the copy will be
109 MachineInstr *DefMI = MRI->getVRegDef(Reg);
110 if (DefMI->getParent() != MBB)
112 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
113 if (TII->isMoveInstr(*DefMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
114 TargetRegisterInfo::isVirtualRegister(SrcReg) &&
115 !SrcSubIdx && !DstSubIdx) {
116 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
117 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
118 const TargetRegisterClass *NewRC = getCommonSubClass(RC, SRC);
121 DEBUG(dbgs() << "Coalescing: " << *DefMI);
122 DEBUG(dbgs() << "*** to: " << *MI);
124 MRI->clearKillFlags(SrcReg);
126 MRI->setRegClass(SrcReg, NewRC);
127 DefMI->eraseFromParent();
137 MachineCSE::isPhysDefTriviallyDead(unsigned Reg,
138 MachineBasicBlock::const_iterator I,
139 MachineBasicBlock::const_iterator E) const {
140 unsigned LookAheadLeft = LookAheadLimit;
141 while (LookAheadLeft) {
142 // Skip over dbg_value's.
143 while (I != E && I->isDebugValue())
147 // Reached end of block, register is obviously dead.
150 bool SeenDef = false;
151 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
152 const MachineOperand &MO = I->getOperand(i);
153 if (!MO.isReg() || !MO.getReg())
155 if (!TRI->regsOverlap(MO.getReg(), Reg))
163 // See a def of Reg (or an alias) before encountering any use, it's
173 /// hasLivePhysRegDefUse - Return true if the specified instruction read / write
174 /// physical registers (except for dead defs of physical registers). It also
175 /// returns the physical register def by reference if it's the only one.
176 bool MachineCSE::hasLivePhysRegDefUse(const MachineInstr *MI,
177 const MachineBasicBlock *MBB,
178 unsigned &PhysDef) const {
180 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
181 const MachineOperand &MO = MI->getOperand(i);
184 unsigned Reg = MO.getReg();
187 if (TargetRegisterInfo::isVirtualRegister(Reg))
190 // Can't touch anything to read a physical register.
193 // If the def is dead, it's ok.
195 // Ok, this is a physical register def that's not marked "dead". That's
196 // common since this pass is run before livevariables. We can scan
197 // forward a few instructions and check if it is obviously dead.
199 // Multiple physical register defs. These are rare, forget about it.
207 MachineBasicBlock::const_iterator I = MI; I = llvm::next(I);
208 if (!isPhysDefTriviallyDead(PhysDef, I, MBB->end()))
214 bool MachineCSE::PhysRegDefReaches(MachineInstr *CSMI, MachineInstr *MI,
215 unsigned PhysDef) const {
216 // For now conservatively returns false if the common subexpression is
217 // not in the same basic block as the given instruction.
218 MachineBasicBlock *MBB = MI->getParent();
219 if (CSMI->getParent() != MBB)
221 MachineBasicBlock::const_iterator I = CSMI; I = llvm::next(I);
222 MachineBasicBlock::const_iterator E = MI;
223 unsigned LookAheadLeft = LookAheadLimit;
224 while (LookAheadLeft) {
225 // Skip over dbg_value's.
226 while (I != E && I->isDebugValue())
231 if (I->modifiesRegister(PhysDef, TRI))
241 static bool isCopy(const MachineInstr *MI, const TargetInstrInfo *TII) {
242 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
243 return TII->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) ||
244 MI->isExtractSubreg() || MI->isInsertSubreg() || MI->isSubregToReg();
247 bool MachineCSE::isCSECandidate(MachineInstr *MI) {
248 if (MI->isLabel() || MI->isPHI() || MI->isImplicitDef() ||
249 MI->isKill() || MI->isInlineAsm() || MI->isDebugValue())
256 // Ignore stuff that we obviously can't move.
257 const TargetInstrDesc &TID = MI->getDesc();
258 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
259 TID.hasUnmodeledSideEffects())
263 // Okay, this instruction does a load. As a refinement, we allow the target
264 // to decide whether the loaded value is actually a constant. If so, we can
265 // actually use it as a load.
266 if (!MI->isInvariantLoad(AA))
267 // FIXME: we should be able to hoist loads with no other side effects if
268 // there are no other instructions which can change memory in this loop.
269 // This is a trivial form of alias analysis.
275 /// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
276 /// common expression that defines Reg.
277 bool MachineCSE::isProfitableToCSE(unsigned CSReg, unsigned Reg,
278 MachineInstr *CSMI, MachineInstr *MI) {
279 // FIXME: Heuristics that works around the lack the live range splitting.
281 // Heuristics #1: Don't cse "cheap" computating if the def is not local or in an
282 // immediate predecessor. We don't want to increase register pressure and end up
283 // causing other computation to be spilled.
284 if (MI->getDesc().isAsCheapAsAMove()) {
285 MachineBasicBlock *CSBB = CSMI->getParent();
286 MachineBasicBlock *BB = MI->getParent();
288 find(CSBB->succ_begin(), CSBB->succ_end(), BB) == CSBB->succ_end())
292 // Heuristics #2: If the expression doesn't not use a vr and the only use
293 // of the redundant computation are copies, do not cse.
294 bool HasVRegUse = false;
295 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
296 const MachineOperand &MO = MI->getOperand(i);
297 if (MO.isReg() && MO.isUse() && MO.getReg() &&
298 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
304 bool HasNonCopyUse = false;
305 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
306 E = MRI->use_nodbg_end(); I != E; ++I) {
307 MachineInstr *Use = &*I;
309 if (!isCopy(Use, TII)) {
310 HasNonCopyUse = true;
318 // Heuristics #3: If the common subexpression is used by PHIs, do not reuse
319 // it unless the defined value is already used in the BB of the new use.
321 SmallPtrSet<MachineBasicBlock*, 4> CSBBs;
322 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(CSReg),
323 E = MRI->use_nodbg_end(); I != E; ++I) {
324 MachineInstr *Use = &*I;
325 HasPHI |= Use->isPHI();
326 CSBBs.insert(Use->getParent());
331 return CSBBs.count(MI->getParent());
334 void MachineCSE::EnterScope(MachineBasicBlock *MBB) {
335 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
336 ScopeType *Scope = new ScopeType(VNT);
337 ScopeMap[MBB] = Scope;
340 void MachineCSE::ExitScope(MachineBasicBlock *MBB) {
341 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
342 DenseMap<MachineBasicBlock*, ScopeType*>::iterator SI = ScopeMap.find(MBB);
343 assert(SI != ScopeMap.end());
348 bool MachineCSE::ProcessBlock(MachineBasicBlock *MBB) {
349 bool Changed = false;
351 SmallVector<std::pair<unsigned, unsigned>, 8> CSEPairs;
352 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
353 MachineInstr *MI = &*I;
356 if (!isCSECandidate(MI))
359 bool FoundCSE = VNT.count(MI);
361 // Look for trivial copy coalescing opportunities.
362 if (PerformTrivialCoalescing(MI, MBB)) {
363 // After coalescing MI itself may become a copy.
366 FoundCSE = VNT.count(MI);
369 // FIXME: commute commutable instructions?
371 // If the instruction defines a physical register and the value *may* be
372 // used, then it's not safe to replace it with a common subexpression.
373 unsigned PhysDef = 0;
374 if (FoundCSE && hasLivePhysRegDefUse(MI, MBB, PhysDef)) {
377 // ... Unless the CS is local and it also defines the physical register
378 // which is not clobbered in between.
379 if (PhysDef && CSEPhysDef) {
380 unsigned CSVN = VNT.lookup(MI);
381 MachineInstr *CSMI = Exps[CSVN];
382 if (PhysRegDefReaches(CSMI, MI, PhysDef))
388 VNT.insert(MI, CurrVN++);
393 // Found a common subexpression, eliminate it.
394 unsigned CSVN = VNT.lookup(MI);
395 MachineInstr *CSMI = Exps[CSVN];
396 DEBUG(dbgs() << "Examining: " << *MI);
397 DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
399 // Check if it's profitable to perform this CSE.
401 unsigned NumDefs = MI->getDesc().getNumDefs();
402 for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
403 MachineOperand &MO = MI->getOperand(i);
404 if (!MO.isReg() || !MO.isDef())
406 unsigned OldReg = MO.getReg();
407 unsigned NewReg = CSMI->getOperand(i).getReg();
408 if (OldReg == NewReg)
410 assert(TargetRegisterInfo::isVirtualRegister(OldReg) &&
411 TargetRegisterInfo::isVirtualRegister(NewReg) &&
412 "Do not CSE physical register defs!");
413 if (!isProfitableToCSE(NewReg, OldReg, CSMI, MI)) {
417 CSEPairs.push_back(std::make_pair(OldReg, NewReg));
421 // Actually perform the elimination.
423 for (unsigned i = 0, e = CSEPairs.size(); i != e; ++i) {
424 MRI->replaceRegWith(CSEPairs[i].first, CSEPairs[i].second);
425 MRI->clearKillFlags(CSEPairs[i].second);
427 MI->eraseFromParent();
430 DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
431 VNT.insert(MI, CurrVN++);
440 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
441 /// dominator tree node if its a leaf or all of its children are done. Walk
442 /// up the dominator tree to destroy ancestors which are now done.
444 MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node,
445 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
446 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
447 if (OpenChildren[Node])
451 ExitScope(Node->getBlock());
453 // Now traverse upwards to pop ancestors whose offsprings are all done.
454 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
455 unsigned Left = --OpenChildren[Parent];
458 ExitScope(Parent->getBlock());
463 bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) {
464 SmallVector<MachineDomTreeNode*, 32> Scopes;
465 SmallVector<MachineDomTreeNode*, 8> WorkList;
466 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
467 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
469 // Perform a DFS walk to determine the order of visit.
470 WorkList.push_back(Node);
472 Node = WorkList.pop_back_val();
473 Scopes.push_back(Node);
474 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
475 unsigned NumChildren = Children.size();
476 OpenChildren[Node] = NumChildren;
477 for (unsigned i = 0; i != NumChildren; ++i) {
478 MachineDomTreeNode *Child = Children[i];
479 ParentMap[Child] = Node;
480 WorkList.push_back(Child);
482 } while (!WorkList.empty());
485 bool Changed = false;
486 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
487 MachineDomTreeNode *Node = Scopes[i];
488 MachineBasicBlock *MBB = Node->getBlock();
490 Changed |= ProcessBlock(MBB);
491 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
492 ExitScopeIfDone(Node, OpenChildren, ParentMap);
498 bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
499 TII = MF.getTarget().getInstrInfo();
500 TRI = MF.getTarget().getRegisterInfo();
501 MRI = &MF.getRegInfo();
502 AA = &getAnalysis<AliasAnalysis>();
503 DT = &getAnalysis<MachineDominatorTree>();
504 return PerformCSE(DT->getRootNode());