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/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/RecyclingAllocator.h"
32 STATISTIC(NumCoalesces, "Number of copies coalesced");
33 STATISTIC(NumCSEs, "Number of common subexpression eliminated");
34 STATISTIC(NumPhysCSEs,
35 "Number of physreg referencing common subexpr eliminated");
36 STATISTIC(NumCommutes, "Number of copies coalesced after commuting");
39 class MachineCSE : public MachineFunctionPass {
40 const TargetInstrInfo *TII;
41 const TargetRegisterInfo *TRI;
43 MachineDominatorTree *DT;
44 MachineRegisterInfo *MRI;
46 static char ID; // Pass identification
47 MachineCSE() : MachineFunctionPass(ID), LookAheadLimit(5), CurrVN(0) {
48 initializeMachineCSEPass(*PassRegistry::getPassRegistry());
51 virtual bool runOnMachineFunction(MachineFunction &MF);
53 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55 MachineFunctionPass::getAnalysisUsage(AU);
56 AU.addRequired<AliasAnalysis>();
57 AU.addPreservedID(MachineLoopInfoID);
58 AU.addRequired<MachineDominatorTree>();
59 AU.addPreserved<MachineDominatorTree>();
62 virtual void releaseMemory() {
68 const unsigned LookAheadLimit;
69 typedef RecyclingAllocator<BumpPtrAllocator,
70 ScopedHashTableVal<MachineInstr*, unsigned> > AllocatorTy;
71 typedef ScopedHashTable<MachineInstr*, unsigned,
72 MachineInstrExpressionTrait, AllocatorTy> ScopedHTType;
73 typedef ScopedHTType::ScopeTy ScopeType;
74 DenseMap<MachineBasicBlock*, ScopeType*> ScopeMap;
76 SmallVector<MachineInstr*, 64> Exps;
79 bool PerformTrivialCoalescing(MachineInstr *MI, MachineBasicBlock *MBB);
80 bool isPhysDefTriviallyDead(unsigned Reg,
81 MachineBasicBlock::const_iterator I,
82 MachineBasicBlock::const_iterator E) const ;
83 bool hasLivePhysRegDefUses(const MachineInstr *MI,
84 const MachineBasicBlock *MBB,
85 SmallSet<unsigned,8> &PhysRefs,
86 SmallVector<unsigned,8> &PhysDefs) const;
87 bool PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
88 SmallSet<unsigned,8> &PhysRefs) const;
89 bool isCSECandidate(MachineInstr *MI);
90 bool isProfitableToCSE(unsigned CSReg, unsigned Reg,
91 MachineInstr *CSMI, MachineInstr *MI);
92 void EnterScope(MachineBasicBlock *MBB);
93 void ExitScope(MachineBasicBlock *MBB);
94 bool ProcessBlock(MachineBasicBlock *MBB);
95 void ExitScopeIfDone(MachineDomTreeNode *Node,
96 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
97 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
98 bool PerformCSE(MachineDomTreeNode *Node);
100 } // end anonymous namespace
102 char MachineCSE::ID = 0;
103 INITIALIZE_PASS_BEGIN(MachineCSE, "machine-cse",
104 "Machine Common Subexpression Elimination", false, false)
105 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
106 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
107 INITIALIZE_PASS_END(MachineCSE, "machine-cse",
108 "Machine Common Subexpression Elimination", false, false)
110 FunctionPass *llvm::createMachineCSEPass() { return new MachineCSE(); }
112 bool MachineCSE::PerformTrivialCoalescing(MachineInstr *MI,
113 MachineBasicBlock *MBB) {
114 bool Changed = false;
115 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
116 MachineOperand &MO = MI->getOperand(i);
117 if (!MO.isReg() || !MO.isUse())
119 unsigned Reg = MO.getReg();
120 if (!TargetRegisterInfo::isVirtualRegister(Reg))
122 if (!MRI->hasOneNonDBGUse(Reg))
123 // Only coalesce single use copies. This ensure the copy will be
126 MachineInstr *DefMI = MRI->getVRegDef(Reg);
127 if (DefMI->getParent() != MBB)
129 if (!DefMI->isCopy())
131 unsigned SrcReg = DefMI->getOperand(1).getReg();
132 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
134 if (DefMI->getOperand(0).getSubReg() || DefMI->getOperand(1).getSubReg())
136 if (!MRI->constrainRegClass(SrcReg, MRI->getRegClass(Reg)))
138 DEBUG(dbgs() << "Coalescing: " << *DefMI);
139 DEBUG(dbgs() << "*** to: " << *MI);
141 MRI->clearKillFlags(SrcReg);
142 DefMI->eraseFromParent();
151 MachineCSE::isPhysDefTriviallyDead(unsigned Reg,
152 MachineBasicBlock::const_iterator I,
153 MachineBasicBlock::const_iterator E) const {
154 unsigned LookAheadLeft = LookAheadLimit;
155 while (LookAheadLeft) {
156 // Skip over dbg_value's.
157 while (I != E && I->isDebugValue())
161 // Reached end of block, register is obviously dead.
164 bool SeenDef = false;
165 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
166 const MachineOperand &MO = I->getOperand(i);
167 if (!MO.isReg() || !MO.getReg())
169 if (!TRI->regsOverlap(MO.getReg(), Reg))
177 // See a def of Reg (or an alias) before encountering any use, it's
187 /// hasLivePhysRegDefUses - Return true if the specified instruction read/write
188 /// physical registers (except for dead defs of physical registers). It also
189 /// returns the physical register def by reference if it's the only one and the
190 /// instruction does not uses a physical register.
191 bool MachineCSE::hasLivePhysRegDefUses(const MachineInstr *MI,
192 const MachineBasicBlock *MBB,
193 SmallSet<unsigned,8> &PhysRefs,
194 SmallVector<unsigned,8> &PhysDefs) const{
195 MachineBasicBlock::const_iterator I = MI; I = llvm::next(I);
196 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
197 const MachineOperand &MO = MI->getOperand(i);
200 unsigned Reg = MO.getReg();
203 if (TargetRegisterInfo::isVirtualRegister(Reg))
205 // If the def is dead, it's ok. But the def may 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 (MO.isDead() || isPhysDefTriviallyDead(Reg, I, MBB->end())))
211 PhysDefs.push_back(Reg);
212 PhysRefs.insert(Reg);
213 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias)
214 PhysRefs.insert(*Alias);
217 return !PhysRefs.empty();
220 bool MachineCSE::PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
221 SmallSet<unsigned,8> &PhysRefs) const {
222 // Look backward from MI to find CSMI.
223 unsigned LookAheadLeft = LookAheadLimit;
224 MachineBasicBlock::const_reverse_iterator I(MI);
225 MachineBasicBlock::const_reverse_iterator E(MI->getParent()->rend());
226 while (LookAheadLeft) {
227 while (LookAheadLeft && I != E) {
228 // Skip over dbg_value's.
229 while (I != E && I->isDebugValue())
235 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
236 const MachineOperand &MO = I->getOperand(i);
237 if (!MO.isReg() || !MO.isDef())
239 unsigned MOReg = MO.getReg();
240 if (TargetRegisterInfo::isVirtualRegister(MOReg))
242 if (PhysRefs.count(MOReg))
249 // Go back another BB; for now, only go back at most one BB.
250 MachineBasicBlock *CSBB = CSMI->getParent();
251 MachineBasicBlock *BB = MI->getParent();
252 if (!CSBB->isSuccessor(BB) || BB->pred_size() != 1)
261 bool MachineCSE::isCSECandidate(MachineInstr *MI) {
262 if (MI->isLabel() || MI->isPHI() || MI->isImplicitDef() ||
263 MI->isKill() || MI->isInlineAsm() || MI->isDebugValue())
267 if (MI->isCopyLike())
270 // Ignore stuff that we obviously can't move.
271 const TargetInstrDesc &TID = MI->getDesc();
272 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
273 MI->hasUnmodeledSideEffects())
277 // Okay, this instruction does a load. As a refinement, we allow the target
278 // to decide whether the loaded value is actually a constant. If so, we can
279 // actually use it as a load.
280 if (!MI->isInvariantLoad(AA))
281 // FIXME: we should be able to hoist loads with no other side effects if
282 // there are no other instructions which can change memory in this loop.
283 // This is a trivial form of alias analysis.
289 /// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
290 /// common expression that defines Reg.
291 bool MachineCSE::isProfitableToCSE(unsigned CSReg, unsigned Reg,
292 MachineInstr *CSMI, MachineInstr *MI) {
293 // FIXME: Heuristics that works around the lack the live range splitting.
295 // Heuristics #1: Don't CSE "cheap" computation if the def is not local or in
296 // an immediate predecessor. We don't want to increase register pressure and
297 // end up causing other computation to be spilled.
298 if (MI->getDesc().isAsCheapAsAMove()) {
299 MachineBasicBlock *CSBB = CSMI->getParent();
300 MachineBasicBlock *BB = MI->getParent();
301 if (CSBB != BB && !CSBB->isSuccessor(BB))
305 // Heuristics #2: If the expression doesn't not use a vr and the only use
306 // of the redundant computation are copies, do not cse.
307 bool HasVRegUse = false;
308 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
309 const MachineOperand &MO = MI->getOperand(i);
310 if (MO.isReg() && MO.isUse() &&
311 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
317 bool HasNonCopyUse = false;
318 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
319 E = MRI->use_nodbg_end(); I != E; ++I) {
320 MachineInstr *Use = &*I;
322 if (!Use->isCopyLike()) {
323 HasNonCopyUse = true;
331 // Heuristics #3: If the common subexpression is used by PHIs, do not reuse
332 // it unless the defined value is already used in the BB of the new use.
334 SmallPtrSet<MachineBasicBlock*, 4> CSBBs;
335 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(CSReg),
336 E = MRI->use_nodbg_end(); I != E; ++I) {
337 MachineInstr *Use = &*I;
338 HasPHI |= Use->isPHI();
339 CSBBs.insert(Use->getParent());
344 return CSBBs.count(MI->getParent());
347 void MachineCSE::EnterScope(MachineBasicBlock *MBB) {
348 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
349 ScopeType *Scope = new ScopeType(VNT);
350 ScopeMap[MBB] = Scope;
353 void MachineCSE::ExitScope(MachineBasicBlock *MBB) {
354 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
355 DenseMap<MachineBasicBlock*, ScopeType*>::iterator SI = ScopeMap.find(MBB);
356 assert(SI != ScopeMap.end());
361 bool MachineCSE::ProcessBlock(MachineBasicBlock *MBB) {
362 bool Changed = false;
364 SmallVector<std::pair<unsigned, unsigned>, 8> CSEPairs;
365 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
366 MachineInstr *MI = &*I;
369 if (!isCSECandidate(MI))
372 bool FoundCSE = VNT.count(MI);
374 // Look for trivial copy coalescing opportunities.
375 if (PerformTrivialCoalescing(MI, MBB)) {
378 // After coalescing MI itself may become a copy.
379 if (MI->isCopyLike())
381 FoundCSE = VNT.count(MI);
385 // Commute commutable instructions.
386 bool Commuted = false;
387 if (!FoundCSE && MI->getDesc().isCommutable()) {
388 MachineInstr *NewMI = TII->commuteInstruction(MI);
391 FoundCSE = VNT.count(NewMI);
393 // New instruction. It doesn't need to be kept.
394 NewMI->eraseFromParent();
396 } else if (!FoundCSE)
397 // MI was changed but it didn't help, commute it back!
398 (void)TII->commuteInstruction(MI);
402 // If the instruction defines physical registers and the values *may* be
403 // used, then it's not safe to replace it with a common subexpression.
404 // It's also not safe if the instruction uses physical registers.
405 SmallSet<unsigned,8> PhysRefs;
406 SmallVector<unsigned,8> DirectPhysRefs;
407 if (FoundCSE && hasLivePhysRegDefUses(MI, MBB, PhysRefs, DirectPhysRefs)) {
410 // ... Unless the CS is local and it also defines the physical register
411 // which is not clobbered in between and the physical register uses
412 // were not clobbered.
413 unsigned CSVN = VNT.lookup(MI);
414 MachineInstr *CSMI = Exps[CSVN];
415 if (PhysRegDefsReach(CSMI, MI, PhysRefs))
420 VNT.insert(MI, CurrVN++);
425 // Found a common subexpression, eliminate it.
426 unsigned CSVN = VNT.lookup(MI);
427 MachineInstr *CSMI = Exps[CSVN];
428 DEBUG(dbgs() << "Examining: " << *MI);
429 DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
431 // Check if it's profitable to perform this CSE.
433 unsigned NumDefs = MI->getDesc().getNumDefs();
434 for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
435 MachineOperand &MO = MI->getOperand(i);
436 if (!MO.isReg() || !MO.isDef())
438 unsigned OldReg = MO.getReg();
439 unsigned NewReg = CSMI->getOperand(i).getReg();
440 if (OldReg == NewReg)
442 assert(TargetRegisterInfo::isVirtualRegister(OldReg) &&
443 TargetRegisterInfo::isVirtualRegister(NewReg) &&
444 "Do not CSE physical register defs!");
445 if (!isProfitableToCSE(NewReg, OldReg, CSMI, MI)) {
449 CSEPairs.push_back(std::make_pair(OldReg, NewReg));
453 // Actually perform the elimination.
455 for (unsigned i = 0, e = CSEPairs.size(); i != e; ++i) {
456 MRI->replaceRegWith(CSEPairs[i].first, CSEPairs[i].second);
457 MRI->clearKillFlags(CSEPairs[i].second);
459 MI->eraseFromParent();
460 if (!DirectPhysRefs.empty() && CSMI->getParent() != MBB) {
461 assert(CSMI->getParent()->isSuccessor(MBB));
462 SmallVector<unsigned,8>::iterator PI = DirectPhysRefs.begin(),
463 PE = DirectPhysRefs.end();
464 for (; PI != PE; ++PI)
468 if (!PhysRefs.empty())
474 DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
475 VNT.insert(MI, CurrVN++);
484 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
485 /// dominator tree node if its a leaf or all of its children are done. Walk
486 /// up the dominator tree to destroy ancestors which are now done.
488 MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node,
489 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
490 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
491 if (OpenChildren[Node])
495 ExitScope(Node->getBlock());
497 // Now traverse upwards to pop ancestors whose offsprings are all done.
498 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
499 unsigned Left = --OpenChildren[Parent];
502 ExitScope(Parent->getBlock());
507 bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) {
508 SmallVector<MachineDomTreeNode*, 32> Scopes;
509 SmallVector<MachineDomTreeNode*, 8> WorkList;
510 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
511 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
515 // Perform a DFS walk to determine the order of visit.
516 WorkList.push_back(Node);
518 Node = WorkList.pop_back_val();
519 Scopes.push_back(Node);
520 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
521 unsigned NumChildren = Children.size();
522 OpenChildren[Node] = NumChildren;
523 for (unsigned i = 0; i != NumChildren; ++i) {
524 MachineDomTreeNode *Child = Children[i];
525 ParentMap[Child] = Node;
526 WorkList.push_back(Child);
528 } while (!WorkList.empty());
531 bool Changed = false;
532 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
533 MachineDomTreeNode *Node = Scopes[i];
534 MachineBasicBlock *MBB = Node->getBlock();
536 Changed |= ProcessBlock(MBB);
537 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
538 ExitScopeIfDone(Node, OpenChildren, ParentMap);
544 bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
545 TII = MF.getTarget().getInstrInfo();
546 TRI = MF.getTarget().getRegisterInfo();
547 MRI = &MF.getRegInfo();
548 AA = &getAnalysis<AliasAnalysis>();
549 DT = &getAnalysis<MachineDominatorTree>();
550 return PerformCSE(DT->getRootNode());