• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- MachineCSE.cpp - Machine Common Subexpression Elimination Pass ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15 
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"
29 using namespace llvm;
30 
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");
38 
39 namespace {
40   class MachineCSE : public MachineFunctionPass {
41     const TargetInstrInfo *TII;
42     const TargetRegisterInfo *TRI;
43     AliasAnalysis *AA;
44     MachineDominatorTree *DT;
45     MachineRegisterInfo *MRI;
46   public:
47     static char ID; // Pass identification
MachineCSE()48     MachineCSE() : MachineFunctionPass(ID), LookAheadLimit(5), CurrVN(0) {
49       initializeMachineCSEPass(*PassRegistry::getPassRegistry());
50     }
51 
52     virtual bool runOnMachineFunction(MachineFunction &MF);
53 
getAnalysisUsage(AnalysisUsage & AU) const54     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55       AU.setPreservesCFG();
56       MachineFunctionPass::getAnalysisUsage(AU);
57       AU.addRequired<AliasAnalysis>();
58       AU.addPreservedID(MachineLoopInfoID);
59       AU.addRequired<MachineDominatorTree>();
60       AU.addPreserved<MachineDominatorTree>();
61     }
62 
releaseMemory()63     virtual void releaseMemory() {
64       ScopeMap.clear();
65       Exps.clear();
66       AllocatableRegs.clear();
67       ReservedRegs.clear();
68     }
69 
70   private:
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;
78     ScopedHTType VNT;
79     SmallVector<MachineInstr*, 64> Exps;
80     unsigned CurrVN;
81     BitVector AllocatableRegs;
82     BitVector ReservedRegs;
83 
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);
106   };
107 } // end anonymous namespace
108 
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)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)113 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
114 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
115 INITIALIZE_PASS_END(MachineCSE, "machine-cse",
116                 "Machine Common Subexpression Elimination", false, false)
117 
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())
124       continue;
125     unsigned Reg = MO.getReg();
126     if (!TargetRegisterInfo::isVirtualRegister(Reg))
127       continue;
128     if (!MRI->hasOneNonDBGUse(Reg))
129       // Only coalesce single use copies. This ensure the copy will be
130       // deleted.
131       continue;
132     MachineInstr *DefMI = MRI->getVRegDef(Reg);
133     if (DefMI->getParent() != MBB)
134       continue;
135     if (!DefMI->isCopy())
136       continue;
137     unsigned SrcReg = DefMI->getOperand(1).getReg();
138     if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
139       continue;
140     if (DefMI->getOperand(0).getSubReg() || DefMI->getOperand(1).getSubReg())
141       continue;
142     if (!MRI->constrainRegClass(SrcReg, MRI->getRegClass(Reg)))
143       continue;
144     DEBUG(dbgs() << "Coalescing: " << *DefMI);
145     DEBUG(dbgs() << "***     to: " << *MI);
146     MO.setReg(SrcReg);
147     MRI->clearKillFlags(SrcReg);
148     DefMI->eraseFromParent();
149     ++NumCoalesces;
150     Changed = true;
151   }
152 
153   return Changed;
154 }
155 
156 bool
isPhysDefTriviallyDead(unsigned Reg,MachineBasicBlock::const_iterator I,MachineBasicBlock::const_iterator E) const157 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())
164       ++I;
165 
166     if (I == E)
167       // Reached end of block, register is obviously dead.
168       return true;
169 
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))
174         SeenDef = true;
175       if (!MO.isReg() || !MO.getReg())
176         continue;
177       if (!TRI->regsOverlap(MO.getReg(), Reg))
178         continue;
179       if (MO.isUse())
180         // Found a use!
181         return false;
182       SeenDef = true;
183     }
184     if (SeenDef)
185       // See a def of Reg (or an alias) before encountering any use, it's
186       // trivially dead.
187       return true;
188 
189     --LookAheadLeft;
190     ++I;
191   }
192   return false;
193 }
194 
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.
hasLivePhysRegDefUses(const MachineInstr * MI,const MachineBasicBlock * MBB,SmallSet<unsigned,8> & PhysRefs,SmallVector<unsigned,2> & PhysDefs) const199 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);
206     if (!MO.isReg())
207       continue;
208     unsigned Reg = MO.getReg();
209     if (!Reg)
210       continue;
211     if (TargetRegisterInfo::isVirtualRegister(Reg))
212       continue;
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.
216     if (MO.isDef() &&
217         (MO.isDead() || isPhysDefTriviallyDead(Reg, I, MBB->end())))
218       continue;
219     PhysRefs.insert(Reg);
220     if (MO.isDef())
221       PhysDefs.push_back(Reg);
222     for (const uint16_t *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias)
223       PhysRefs.insert(*Alias);
224   }
225 
226   return !PhysRefs.empty();
227 }
228 
PhysRegDefsReach(MachineInstr * CSMI,MachineInstr * MI,SmallSet<unsigned,8> & PhysRefs,SmallVector<unsigned,2> & PhysDefs,bool & NonLocal) const229 bool MachineCSE::PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
230                                   SmallSet<unsigned,8> &PhysRefs,
231                                   SmallVector<unsigned,2> &PhysDefs,
232                                   bool &NonLocal) const {
233   // For now conservatively returns false if the common subexpression is
234   // not in the same basic block as the given instruction. The only exception
235   // is if the common subexpression is in the sole predecessor block.
236   const MachineBasicBlock *MBB = MI->getParent();
237   const MachineBasicBlock *CSMBB = CSMI->getParent();
238 
239   bool CrossMBB = false;
240   if (CSMBB != MBB) {
241     if (MBB->pred_size() != 1 || *MBB->pred_begin() != CSMBB)
242       return false;
243 
244     for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) {
245       if (AllocatableRegs.test(PhysDefs[i]) || ReservedRegs.test(PhysDefs[i]))
246         // Avoid extending live range of physical registers if they are
247         //allocatable or reserved.
248         return false;
249     }
250     CrossMBB = true;
251   }
252   MachineBasicBlock::const_iterator I = CSMI; I = llvm::next(I);
253   MachineBasicBlock::const_iterator E = MI;
254   MachineBasicBlock::const_iterator EE = CSMBB->end();
255   unsigned LookAheadLeft = LookAheadLimit;
256   while (LookAheadLeft) {
257     // Skip over dbg_value's.
258     while (I != E && I != EE && I->isDebugValue())
259       ++I;
260 
261     if (I == EE) {
262       assert(CrossMBB && "Reaching end-of-MBB without finding MI?");
263       (void)CrossMBB;
264       CrossMBB = false;
265       NonLocal = true;
266       I = MBB->begin();
267       EE = MBB->end();
268       continue;
269     }
270 
271     if (I == E)
272       return true;
273 
274     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
275       const MachineOperand &MO = I->getOperand(i);
276       // RegMasks go on instructions like calls that clobber lots of physregs.
277       // Don't attempt to CSE across such an instruction.
278       if (MO.isRegMask())
279         return false;
280       if (!MO.isReg() || !MO.isDef())
281         continue;
282       unsigned MOReg = MO.getReg();
283       if (TargetRegisterInfo::isVirtualRegister(MOReg))
284         continue;
285       if (PhysRefs.count(MOReg))
286         return false;
287     }
288 
289     --LookAheadLeft;
290     ++I;
291   }
292 
293   return false;
294 }
295 
isCSECandidate(MachineInstr * MI)296 bool MachineCSE::isCSECandidate(MachineInstr *MI) {
297   if (MI->isLabel() || MI->isPHI() || MI->isImplicitDef() ||
298       MI->isKill() || MI->isInlineAsm() || MI->isDebugValue())
299     return false;
300 
301   // Ignore copies.
302   if (MI->isCopyLike())
303     return false;
304 
305   // Ignore stuff that we obviously can't move.
306   if (MI->mayStore() || MI->isCall() || MI->isTerminator() ||
307       MI->hasUnmodeledSideEffects())
308     return false;
309 
310   if (MI->mayLoad()) {
311     // Okay, this instruction does a load. As a refinement, we allow the target
312     // to decide whether the loaded value is actually a constant. If so, we can
313     // actually use it as a load.
314     if (!MI->isInvariantLoad(AA))
315       // FIXME: we should be able to hoist loads with no other side effects if
316       // there are no other instructions which can change memory in this loop.
317       // This is a trivial form of alias analysis.
318       return false;
319   }
320   return true;
321 }
322 
323 /// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
324 /// common expression that defines Reg.
isProfitableToCSE(unsigned CSReg,unsigned Reg,MachineInstr * CSMI,MachineInstr * MI)325 bool MachineCSE::isProfitableToCSE(unsigned CSReg, unsigned Reg,
326                                    MachineInstr *CSMI, MachineInstr *MI) {
327   // FIXME: Heuristics that works around the lack the live range splitting.
328 
329   // Heuristics #1: Don't CSE "cheap" computation if the def is not local or in
330   // an immediate predecessor. We don't want to increase register pressure and
331   // end up causing other computation to be spilled.
332   if (MI->isAsCheapAsAMove()) {
333     MachineBasicBlock *CSBB = CSMI->getParent();
334     MachineBasicBlock *BB = MI->getParent();
335     if (CSBB != BB && !CSBB->isSuccessor(BB))
336       return false;
337   }
338 
339   // Heuristics #2: If the expression doesn't not use a vr and the only use
340   // of the redundant computation are copies, do not cse.
341   bool HasVRegUse = false;
342   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
343     const MachineOperand &MO = MI->getOperand(i);
344     if (MO.isReg() && MO.isUse() &&
345         TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
346       HasVRegUse = true;
347       break;
348     }
349   }
350   if (!HasVRegUse) {
351     bool HasNonCopyUse = false;
352     for (MachineRegisterInfo::use_nodbg_iterator I =  MRI->use_nodbg_begin(Reg),
353            E = MRI->use_nodbg_end(); I != E; ++I) {
354       MachineInstr *Use = &*I;
355       // Ignore copies.
356       if (!Use->isCopyLike()) {
357         HasNonCopyUse = true;
358         break;
359       }
360     }
361     if (!HasNonCopyUse)
362       return false;
363   }
364 
365   // Heuristics #3: If the common subexpression is used by PHIs, do not reuse
366   // it unless the defined value is already used in the BB of the new use.
367   bool HasPHI = false;
368   SmallPtrSet<MachineBasicBlock*, 4> CSBBs;
369   for (MachineRegisterInfo::use_nodbg_iterator I =  MRI->use_nodbg_begin(CSReg),
370        E = MRI->use_nodbg_end(); I != E; ++I) {
371     MachineInstr *Use = &*I;
372     HasPHI |= Use->isPHI();
373     CSBBs.insert(Use->getParent());
374   }
375 
376   if (!HasPHI)
377     return true;
378   return CSBBs.count(MI->getParent());
379 }
380 
EnterScope(MachineBasicBlock * MBB)381 void MachineCSE::EnterScope(MachineBasicBlock *MBB) {
382   DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
383   ScopeType *Scope = new ScopeType(VNT);
384   ScopeMap[MBB] = Scope;
385 }
386 
ExitScope(MachineBasicBlock * MBB)387 void MachineCSE::ExitScope(MachineBasicBlock *MBB) {
388   DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
389   DenseMap<MachineBasicBlock*, ScopeType*>::iterator SI = ScopeMap.find(MBB);
390   assert(SI != ScopeMap.end());
391   ScopeMap.erase(SI);
392   delete SI->second;
393 }
394 
ProcessBlock(MachineBasicBlock * MBB)395 bool MachineCSE::ProcessBlock(MachineBasicBlock *MBB) {
396   bool Changed = false;
397 
398   SmallVector<std::pair<unsigned, unsigned>, 8> CSEPairs;
399   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
400     MachineInstr *MI = &*I;
401     ++I;
402 
403     if (!isCSECandidate(MI))
404       continue;
405 
406     bool FoundCSE = VNT.count(MI);
407     if (!FoundCSE) {
408       // Look for trivial copy coalescing opportunities.
409       if (PerformTrivialCoalescing(MI, MBB)) {
410         Changed = true;
411 
412         // After coalescing MI itself may become a copy.
413         if (MI->isCopyLike())
414           continue;
415         FoundCSE = VNT.count(MI);
416       }
417     }
418 
419     // Commute commutable instructions.
420     bool Commuted = false;
421     if (!FoundCSE && MI->isCommutable()) {
422       MachineInstr *NewMI = TII->commuteInstruction(MI);
423       if (NewMI) {
424         Commuted = true;
425         FoundCSE = VNT.count(NewMI);
426         if (NewMI != MI) {
427           // New instruction. It doesn't need to be kept.
428           NewMI->eraseFromParent();
429           Changed = true;
430         } else if (!FoundCSE)
431           // MI was changed but it didn't help, commute it back!
432           (void)TII->commuteInstruction(MI);
433       }
434     }
435 
436     // If the instruction defines physical registers and the values *may* be
437     // used, then it's not safe to replace it with a common subexpression.
438     // It's also not safe if the instruction uses physical registers.
439     bool CrossMBBPhysDef = false;
440     SmallSet<unsigned,8> PhysRefs;
441     SmallVector<unsigned, 2> PhysDefs;
442     if (FoundCSE && hasLivePhysRegDefUses(MI, MBB, PhysRefs, PhysDefs)) {
443       FoundCSE = false;
444 
445       // ... Unless the CS is local or is in the sole predecessor block
446       // and it also defines the physical register which is not clobbered
447       // in between and the physical register uses were not clobbered.
448       unsigned CSVN = VNT.lookup(MI);
449       MachineInstr *CSMI = Exps[CSVN];
450       if (PhysRegDefsReach(CSMI, MI, PhysRefs, PhysDefs, CrossMBBPhysDef))
451         FoundCSE = true;
452     }
453 
454     if (!FoundCSE) {
455       VNT.insert(MI, CurrVN++);
456       Exps.push_back(MI);
457       continue;
458     }
459 
460     // Found a common subexpression, eliminate it.
461     unsigned CSVN = VNT.lookup(MI);
462     MachineInstr *CSMI = Exps[CSVN];
463     DEBUG(dbgs() << "Examining: " << *MI);
464     DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
465 
466     // Check if it's profitable to perform this CSE.
467     bool DoCSE = true;
468     unsigned NumDefs = MI->getDesc().getNumDefs();
469     for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
470       MachineOperand &MO = MI->getOperand(i);
471       if (!MO.isReg() || !MO.isDef())
472         continue;
473       unsigned OldReg = MO.getReg();
474       unsigned NewReg = CSMI->getOperand(i).getReg();
475       if (OldReg == NewReg)
476         continue;
477 
478       assert(TargetRegisterInfo::isVirtualRegister(OldReg) &&
479              TargetRegisterInfo::isVirtualRegister(NewReg) &&
480              "Do not CSE physical register defs!");
481 
482       if (!isProfitableToCSE(NewReg, OldReg, CSMI, MI)) {
483         DoCSE = false;
484         break;
485       }
486 
487       // Don't perform CSE if the result of the old instruction cannot exist
488       // within the register class of the new instruction.
489       const TargetRegisterClass *OldRC = MRI->getRegClass(OldReg);
490       if (!MRI->constrainRegClass(NewReg, OldRC)) {
491         DoCSE = false;
492         break;
493       }
494 
495       CSEPairs.push_back(std::make_pair(OldReg, NewReg));
496       --NumDefs;
497     }
498 
499     // Actually perform the elimination.
500     if (DoCSE) {
501       for (unsigned i = 0, e = CSEPairs.size(); i != e; ++i) {
502         MRI->replaceRegWith(CSEPairs[i].first, CSEPairs[i].second);
503         MRI->clearKillFlags(CSEPairs[i].second);
504       }
505 
506       if (CrossMBBPhysDef) {
507         // Add physical register defs now coming in from a predecessor to MBB
508         // livein list.
509         while (!PhysDefs.empty()) {
510           unsigned LiveIn = PhysDefs.pop_back_val();
511           if (!MBB->isLiveIn(LiveIn))
512             MBB->addLiveIn(LiveIn);
513         }
514         ++NumCrossBBCSEs;
515       }
516 
517       MI->eraseFromParent();
518       ++NumCSEs;
519       if (!PhysRefs.empty())
520         ++NumPhysCSEs;
521       if (Commuted)
522         ++NumCommutes;
523       Changed = true;
524     } else {
525       DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
526       VNT.insert(MI, CurrVN++);
527       Exps.push_back(MI);
528     }
529     CSEPairs.clear();
530   }
531 
532   return Changed;
533 }
534 
535 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
536 /// dominator tree node if its a leaf or all of its children are done. Walk
537 /// up the dominator tree to destroy ancestors which are now done.
538 void
ExitScopeIfDone(MachineDomTreeNode * Node,DenseMap<MachineDomTreeNode *,unsigned> & OpenChildren,DenseMap<MachineDomTreeNode *,MachineDomTreeNode * > & ParentMap)539 MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node,
540                 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
541                 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
542   if (OpenChildren[Node])
543     return;
544 
545   // Pop scope.
546   ExitScope(Node->getBlock());
547 
548   // Now traverse upwards to pop ancestors whose offsprings are all done.
549   while (MachineDomTreeNode *Parent = ParentMap[Node]) {
550     unsigned Left = --OpenChildren[Parent];
551     if (Left != 0)
552       break;
553     ExitScope(Parent->getBlock());
554     Node = Parent;
555   }
556 }
557 
PerformCSE(MachineDomTreeNode * Node)558 bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) {
559   SmallVector<MachineDomTreeNode*, 32> Scopes;
560   SmallVector<MachineDomTreeNode*, 8> WorkList;
561   DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
562   DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
563 
564   CurrVN = 0;
565 
566   // Perform a DFS walk to determine the order of visit.
567   WorkList.push_back(Node);
568   do {
569     Node = WorkList.pop_back_val();
570     Scopes.push_back(Node);
571     const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
572     unsigned NumChildren = Children.size();
573     OpenChildren[Node] = NumChildren;
574     for (unsigned i = 0; i != NumChildren; ++i) {
575       MachineDomTreeNode *Child = Children[i];
576       ParentMap[Child] = Node;
577       WorkList.push_back(Child);
578     }
579   } while (!WorkList.empty());
580 
581   // Now perform CSE.
582   bool Changed = false;
583   for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
584     MachineDomTreeNode *Node = Scopes[i];
585     MachineBasicBlock *MBB = Node->getBlock();
586     EnterScope(MBB);
587     Changed |= ProcessBlock(MBB);
588     // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
589     ExitScopeIfDone(Node, OpenChildren, ParentMap);
590   }
591 
592   return Changed;
593 }
594 
runOnMachineFunction(MachineFunction & MF)595 bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
596   TII = MF.getTarget().getInstrInfo();
597   TRI = MF.getTarget().getRegisterInfo();
598   MRI = &MF.getRegInfo();
599   AA = &getAnalysis<AliasAnalysis>();
600   DT = &getAnalysis<MachineDominatorTree>();
601   AllocatableRegs = TRI->getAllocatableSet(MF);
602   ReservedRegs = TRI->getReservedRegs(MF);
603   return PerformCSE(DT->getRootNode());
604 }
605