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"
31 STATISTIC(NumCoalesces, "Number of copies coalesced");
32 STATISTIC(NumCSEs, "Number of common subexpression eliminated");
33 STATISTIC(NumPhysCSEs,
34 "Number of physreg referencing common subexpr eliminated");
35 STATISTIC(NumCrossBBCSEs,
36 "Number of cross-MBB physreg referencing CS eliminated");
37 STATISTIC(NumCommutes, "Number of copies coalesced after commuting");
40 class MachineCSE : public MachineFunctionPass {
41 const TargetInstrInfo *TII;
42 const TargetRegisterInfo *TRI;
44 MachineDominatorTree *DT;
45 MachineRegisterInfo *MRI;
47 static char ID; // Pass identification
48 MachineCSE() : MachineFunctionPass(ID), LookAheadLimit(5), CurrVN(0) {
49 initializeMachineCSEPass(*PassRegistry::getPassRegistry());
52 virtual bool runOnMachineFunction(MachineFunction &MF);
54 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56 MachineFunctionPass::getAnalysisUsage(AU);
57 AU.addRequired<AliasAnalysis>();
58 AU.addPreservedID(MachineLoopInfoID);
59 AU.addRequired<MachineDominatorTree>();
60 AU.addPreserved<MachineDominatorTree>();
63 virtual void releaseMemory() {
66 AllocatableRegs.clear();
71 const unsigned LookAheadLimit;
72 typedef RecyclingAllocator<BumpPtrAllocator,
73 ScopedHashTableVal<MachineInstr*, unsigned> > AllocatorTy;
74 typedef ScopedHashTable<MachineInstr*, unsigned,
75 MachineInstrExpressionTrait, AllocatorTy> ScopedHTType;
76 typedef ScopedHTType::ScopeTy ScopeType;
77 DenseMap<MachineBasicBlock*, ScopeType*> ScopeMap;
79 SmallVector<MachineInstr*, 64> Exps;
81 BitVector AllocatableRegs;
82 BitVector ReservedRegs;
84 bool PerformTrivialCoalescing(MachineInstr *MI, MachineBasicBlock *MBB);
85 bool isPhysDefTriviallyDead(unsigned Reg,
86 MachineBasicBlock::const_iterator I,
87 MachineBasicBlock::const_iterator E) const ;
88 bool hasLivePhysRegDefUses(const MachineInstr *MI,
89 const MachineBasicBlock *MBB,
90 SmallSet<unsigned,8> &PhysRefs,
91 SmallVector<unsigned,2> &PhysDefs) const;
92 bool PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
93 SmallSet<unsigned,8> &PhysRefs,
94 SmallVector<unsigned,2> &PhysDefs,
95 bool &NonLocal) const;
96 bool isCSECandidate(MachineInstr *MI);
97 bool isProfitableToCSE(unsigned CSReg, unsigned Reg,
98 MachineInstr *CSMI, MachineInstr *MI);
99 void EnterScope(MachineBasicBlock *MBB);
100 void ExitScope(MachineBasicBlock *MBB);
101 bool ProcessBlock(MachineBasicBlock *MBB);
102 void ExitScopeIfDone(MachineDomTreeNode *Node,
103 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
104 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
105 bool PerformCSE(MachineDomTreeNode *Node);
107 } // end anonymous namespace
109 char MachineCSE::ID = 0;
110 char &llvm::MachineCSEID = MachineCSE::ID;
111 INITIALIZE_PASS_BEGIN(MachineCSE, "machine-cse",
112 "Machine Common Subexpression Elimination", false, false)
113 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
114 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
115 INITIALIZE_PASS_END(MachineCSE, "machine-cse",
116 "Machine Common Subexpression Elimination", false, false)
118 bool MachineCSE::PerformTrivialCoalescing(MachineInstr *MI,
119 MachineBasicBlock *MBB) {
120 bool Changed = false;
121 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
122 MachineOperand &MO = MI->getOperand(i);
123 if (!MO.isReg() || !MO.isUse())
125 unsigned Reg = MO.getReg();
126 if (!TargetRegisterInfo::isVirtualRegister(Reg))
128 if (!MRI->hasOneNonDBGUse(Reg))
129 // Only coalesce single use copies. This ensure the copy will be
132 MachineInstr *DefMI = MRI->getVRegDef(Reg);
133 if (DefMI->getParent() != MBB)
135 if (!DefMI->isCopy())
137 unsigned SrcReg = DefMI->getOperand(1).getReg();
138 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
140 if (DefMI->getOperand(0).getSubReg() || DefMI->getOperand(1).getSubReg())
142 if (!MRI->constrainRegClass(SrcReg, MRI->getRegClass(Reg)))
144 DEBUG(dbgs() << "Coalescing: " << *DefMI);
145 DEBUG(dbgs() << "*** to: " << *MI);
147 MRI->clearKillFlags(SrcReg);
148 DefMI->eraseFromParent();
157 MachineCSE::isPhysDefTriviallyDead(unsigned Reg,
158 MachineBasicBlock::const_iterator I,
159 MachineBasicBlock::const_iterator E) const {
160 unsigned LookAheadLeft = LookAheadLimit;
161 while (LookAheadLeft) {
162 // Skip over dbg_value's.
163 while (I != E && I->isDebugValue())
167 // Reached end of block, register is obviously dead.
170 bool SeenDef = false;
171 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
172 const MachineOperand &MO = I->getOperand(i);
173 if (MO.isRegMask() && MO.clobbersPhysReg(Reg))
175 if (!MO.isReg() || !MO.getReg())
177 if (!TRI->regsOverlap(MO.getReg(), Reg))
185 // See a def of Reg (or an alias) before encountering any use, it's
195 /// hasLivePhysRegDefUses - Return true if the specified instruction read/write
196 /// physical registers (except for dead defs of physical registers). It also
197 /// returns the physical register def by reference if it's the only one and the
198 /// instruction does not uses a physical register.
199 bool MachineCSE::hasLivePhysRegDefUses(const MachineInstr *MI,
200 const MachineBasicBlock *MBB,
201 SmallSet<unsigned,8> &PhysRefs,
202 SmallVector<unsigned,2> &PhysDefs) const{
203 MachineBasicBlock::const_iterator I = MI; I = llvm::next(I);
204 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
205 const MachineOperand &MO = MI->getOperand(i);
208 unsigned Reg = MO.getReg();
211 if (TargetRegisterInfo::isVirtualRegister(Reg))
213 // If the def is dead, it's ok. But the def may not marked "dead". That's
214 // common since this pass is run before livevariables. We can scan
215 // forward a few instructions and check if it is obviously dead.
217 (MO.isDead() || isPhysDefTriviallyDead(Reg, I, MBB->end())))
219 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
220 PhysRefs.insert(*AI);
222 PhysDefs.push_back(Reg);
225 return !PhysRefs.empty();
228 bool MachineCSE::PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
229 SmallSet<unsigned,8> &PhysRefs,
230 SmallVector<unsigned,2> &PhysDefs,
231 bool &NonLocal) const {
232 // For now conservatively returns false if the common subexpression is
233 // not in the same basic block as the given instruction. The only exception
234 // is if the common subexpression is in the sole predecessor block.
235 const MachineBasicBlock *MBB = MI->getParent();
236 const MachineBasicBlock *CSMBB = CSMI->getParent();
238 bool CrossMBB = false;
240 if (MBB->pred_size() != 1 || *MBB->pred_begin() != CSMBB)
243 for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) {
244 if (AllocatableRegs.test(PhysDefs[i]) || ReservedRegs.test(PhysDefs[i]))
245 // Avoid extending live range of physical registers if they are
246 //allocatable or reserved.
251 MachineBasicBlock::const_iterator I = CSMI; I = llvm::next(I);
252 MachineBasicBlock::const_iterator E = MI;
253 MachineBasicBlock::const_iterator EE = CSMBB->end();
254 unsigned LookAheadLeft = LookAheadLimit;
255 while (LookAheadLeft) {
256 // Skip over dbg_value's.
257 while (I != E && I != EE && I->isDebugValue())
261 assert(CrossMBB && "Reaching end-of-MBB without finding MI?");
273 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
274 const MachineOperand &MO = I->getOperand(i);
275 // RegMasks go on instructions like calls that clobber lots of physregs.
276 // Don't attempt to CSE across such an instruction.
279 if (!MO.isReg() || !MO.isDef())
281 unsigned MOReg = MO.getReg();
282 if (TargetRegisterInfo::isVirtualRegister(MOReg))
284 if (PhysRefs.count(MOReg))
295 bool MachineCSE::isCSECandidate(MachineInstr *MI) {
296 if (MI->isLabel() || MI->isPHI() || MI->isImplicitDef() ||
297 MI->isKill() || MI->isInlineAsm() || MI->isDebugValue())
301 if (MI->isCopyLike())
304 // Ignore stuff that we obviously can't move.
305 if (MI->mayStore() || MI->isCall() || MI->isTerminator() ||
306 MI->hasUnmodeledSideEffects())
310 // Okay, this instruction does a load. As a refinement, we allow the target
311 // to decide whether the loaded value is actually a constant. If so, we can
312 // actually use it as a load.
313 if (!MI->isInvariantLoad(AA))
314 // FIXME: we should be able to hoist loads with no other side effects if
315 // there are no other instructions which can change memory in this loop.
316 // This is a trivial form of alias analysis.
322 /// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
323 /// common expression that defines Reg.
324 bool MachineCSE::isProfitableToCSE(unsigned CSReg, unsigned Reg,
325 MachineInstr *CSMI, MachineInstr *MI) {
326 // FIXME: Heuristics that works around the lack the live range splitting.
328 // Heuristics #1: Don't CSE "cheap" computation if the def is not local or in
329 // an immediate predecessor. We don't want to increase register pressure and
330 // end up causing other computation to be spilled.
331 if (MI->isAsCheapAsAMove()) {
332 MachineBasicBlock *CSBB = CSMI->getParent();
333 MachineBasicBlock *BB = MI->getParent();
334 if (CSBB != BB && !CSBB->isSuccessor(BB))
338 // Heuristics #2: If the expression doesn't not use a vr and the only use
339 // of the redundant computation are copies, do not cse.
340 bool HasVRegUse = false;
341 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
342 const MachineOperand &MO = MI->getOperand(i);
343 if (MO.isReg() && MO.isUse() &&
344 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
350 bool HasNonCopyUse = false;
351 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
352 E = MRI->use_nodbg_end(); I != E; ++I) {
353 MachineInstr *Use = &*I;
355 if (!Use->isCopyLike()) {
356 HasNonCopyUse = true;
364 // Heuristics #3: If the common subexpression is used by PHIs, do not reuse
365 // it unless the defined value is already used in the BB of the new use.
367 SmallPtrSet<MachineBasicBlock*, 4> CSBBs;
368 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(CSReg),
369 E = MRI->use_nodbg_end(); I != E; ++I) {
370 MachineInstr *Use = &*I;
371 HasPHI |= Use->isPHI();
372 CSBBs.insert(Use->getParent());
377 return CSBBs.count(MI->getParent());
380 void MachineCSE::EnterScope(MachineBasicBlock *MBB) {
381 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
382 ScopeType *Scope = new ScopeType(VNT);
383 ScopeMap[MBB] = Scope;
386 void MachineCSE::ExitScope(MachineBasicBlock *MBB) {
387 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
388 DenseMap<MachineBasicBlock*, ScopeType*>::iterator SI = ScopeMap.find(MBB);
389 assert(SI != ScopeMap.end());
394 bool MachineCSE::ProcessBlock(MachineBasicBlock *MBB) {
395 bool Changed = false;
397 SmallVector<std::pair<unsigned, unsigned>, 8> CSEPairs;
398 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
399 MachineInstr *MI = &*I;
402 if (!isCSECandidate(MI))
405 bool FoundCSE = VNT.count(MI);
407 // Look for trivial copy coalescing opportunities.
408 if (PerformTrivialCoalescing(MI, MBB)) {
411 // After coalescing MI itself may become a copy.
412 if (MI->isCopyLike())
414 FoundCSE = VNT.count(MI);
418 // Commute commutable instructions.
419 bool Commuted = false;
420 if (!FoundCSE && MI->isCommutable()) {
421 MachineInstr *NewMI = TII->commuteInstruction(MI);
424 FoundCSE = VNT.count(NewMI);
426 // New instruction. It doesn't need to be kept.
427 NewMI->eraseFromParent();
429 } else if (!FoundCSE)
430 // MI was changed but it didn't help, commute it back!
431 (void)TII->commuteInstruction(MI);
435 // If the instruction defines physical registers and the values *may* be
436 // used, then it's not safe to replace it with a common subexpression.
437 // It's also not safe if the instruction uses physical registers.
438 bool CrossMBBPhysDef = false;
439 SmallSet<unsigned,8> PhysRefs;
440 SmallVector<unsigned, 2> PhysDefs;
441 if (FoundCSE && hasLivePhysRegDefUses(MI, MBB, PhysRefs, PhysDefs)) {
444 // ... Unless the CS is local or is in the sole predecessor block
445 // and it also defines the physical register which is not clobbered
446 // in between and the physical register uses were not clobbered.
447 unsigned CSVN = VNT.lookup(MI);
448 MachineInstr *CSMI = Exps[CSVN];
449 if (PhysRegDefsReach(CSMI, MI, PhysRefs, PhysDefs, CrossMBBPhysDef))
454 VNT.insert(MI, CurrVN++);
459 // Found a common subexpression, eliminate it.
460 unsigned CSVN = VNT.lookup(MI);
461 MachineInstr *CSMI = Exps[CSVN];
462 DEBUG(dbgs() << "Examining: " << *MI);
463 DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
465 // Check if it's profitable to perform this CSE.
467 unsigned NumDefs = MI->getDesc().getNumDefs();
468 for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
469 MachineOperand &MO = MI->getOperand(i);
470 if (!MO.isReg() || !MO.isDef())
472 unsigned OldReg = MO.getReg();
473 unsigned NewReg = CSMI->getOperand(i).getReg();
474 if (OldReg == NewReg)
477 assert(TargetRegisterInfo::isVirtualRegister(OldReg) &&
478 TargetRegisterInfo::isVirtualRegister(NewReg) &&
479 "Do not CSE physical register defs!");
481 if (!isProfitableToCSE(NewReg, OldReg, CSMI, MI)) {
486 // Don't perform CSE if the result of the old instruction cannot exist
487 // within the register class of the new instruction.
488 const TargetRegisterClass *OldRC = MRI->getRegClass(OldReg);
489 if (!MRI->constrainRegClass(NewReg, OldRC)) {
494 CSEPairs.push_back(std::make_pair(OldReg, NewReg));
498 // Actually perform the elimination.
500 for (unsigned i = 0, e = CSEPairs.size(); i != e; ++i) {
501 MRI->replaceRegWith(CSEPairs[i].first, CSEPairs[i].second);
502 MRI->clearKillFlags(CSEPairs[i].second);
505 if (CrossMBBPhysDef) {
506 // Add physical register defs now coming in from a predecessor to MBB
508 while (!PhysDefs.empty()) {
509 unsigned LiveIn = PhysDefs.pop_back_val();
510 if (!MBB->isLiveIn(LiveIn))
511 MBB->addLiveIn(LiveIn);
516 MI->eraseFromParent();
518 if (!PhysRefs.empty())
524 DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
525 VNT.insert(MI, CurrVN++);
534 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
535 /// dominator tree node if its a leaf or all of its children are done. Walk
536 /// up the dominator tree to destroy ancestors which are now done.
538 MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node,
539 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
540 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
541 if (OpenChildren[Node])
545 ExitScope(Node->getBlock());
547 // Now traverse upwards to pop ancestors whose offsprings are all done.
548 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
549 unsigned Left = --OpenChildren[Parent];
552 ExitScope(Parent->getBlock());
557 bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) {
558 SmallVector<MachineDomTreeNode*, 32> Scopes;
559 SmallVector<MachineDomTreeNode*, 8> WorkList;
560 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
561 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
565 // Perform a DFS walk to determine the order of visit.
566 WorkList.push_back(Node);
568 Node = WorkList.pop_back_val();
569 Scopes.push_back(Node);
570 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
571 unsigned NumChildren = Children.size();
572 OpenChildren[Node] = NumChildren;
573 for (unsigned i = 0; i != NumChildren; ++i) {
574 MachineDomTreeNode *Child = Children[i];
575 ParentMap[Child] = Node;
576 WorkList.push_back(Child);
578 } while (!WorkList.empty());
581 bool Changed = false;
582 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
583 MachineDomTreeNode *Node = Scopes[i];
584 MachineBasicBlock *MBB = Node->getBlock();
586 Changed |= ProcessBlock(MBB);
587 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
588 ExitScopeIfDone(Node, OpenChildren, ParentMap);
594 bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
595 TII = MF.getTarget().getInstrInfo();
596 TRI = MF.getTarget().getRegisterInfo();
597 MRI = &MF.getRegInfo();
598 AA = &getAnalysis<AliasAnalysis>();
599 DT = &getAnalysis<MachineDominatorTree>();
600 AllocatableRegs = TRI->getAllocatableSet(MF);
601 ReservedRegs = TRI->getReservedRegs(MF);
602 return PerformCSE(DT->getRootNode());