Move StrongPHIElimination after live interval analysis. This will make things happie...
[oota-llvm.git] / lib / CodeGen / StrongPHIElimination.cpp
1 //===- StrongPhiElimination.cpp - Eliminate PHI nodes by inserting copies -===//
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 eliminates machine instruction PHI nodes by inserting copy
11 // instructions, using an intelligent copy-folding technique based on
12 // dominator information.  This is technique is derived from:
13 // 
14 //    Budimlic, et al. Fast copy coalescing and live-range identification.
15 //    In Proceedings of the ACM SIGPLAN 2002 Conference on Programming Language
16 //    Design and Implementation (Berlin, Germany, June 17 - 19, 2002).
17 //    PLDI '02. ACM, New York, NY, 25-32.
18 //    DOI= http://doi.acm.org/10.1145/512529.512534
19 //
20 //===----------------------------------------------------------------------===//
21
22 #define DEBUG_TYPE "strongphielim"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/ADT/DepthFirstIterator.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/Compiler.h"
34 using namespace llvm;
35
36
37 namespace {
38   struct VISIBILITY_HIDDEN StrongPHIElimination : public MachineFunctionPass {
39     static char ID; // Pass identification, replacement for typeid
40     StrongPHIElimination() : MachineFunctionPass((intptr_t)&ID) {}
41
42     // Waiting stores, for each MBB, the set of copies that need to
43     // be inserted into that MBB
44     DenseMap<MachineBasicBlock*,
45              std::map<unsigned, unsigned> > Waiting;
46     
47     // Stacks holds the renaming stack for each register
48     std::map<unsigned, std::vector<unsigned> > Stacks;
49     
50     // Registers in UsedByAnother are PHI nodes that are themselves
51     // used as operands to another another PHI node
52     std::set<unsigned> UsedByAnother;
53     
54     // RenameSets are the sets of operands to a PHI (the defining instruction
55     // of the key) that can be renamed without copies
56     std::map<unsigned, std::set<unsigned> > RenameSets;
57
58     // Store the DFS-in number of each block
59     DenseMap<MachineBasicBlock*, unsigned> preorder;
60     
61     // Store the DFS-out number of each block
62     DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
63
64     bool runOnMachineFunction(MachineFunction &Fn);
65     
66     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67       AU.addRequired<MachineDominatorTree>();
68       AU.addRequired<LiveIntervals>();
69       
70       // TODO: Actually make this true.
71       AU.addPreserved<LiveIntervals>();
72       MachineFunctionPass::getAnalysisUsage(AU);
73     }
74     
75     virtual void releaseMemory() {
76       preorder.clear();
77       maxpreorder.clear();
78       
79       Waiting.clear();
80       Stacks.clear();
81       UsedByAnother.clear();
82       RenameSets.clear();
83     }
84
85   private:
86     
87     /// DomForestNode - Represents a node in the "dominator forest".  This is
88     /// a forest in which the nodes represent registers and the edges
89     /// represent a dominance relation in the block defining those registers.
90     struct DomForestNode {
91     private:
92       // Store references to our children
93       std::vector<DomForestNode*> children;
94       // The register we represent
95       unsigned reg;
96       
97       // Add another node as our child
98       void addChild(DomForestNode* DFN) { children.push_back(DFN); }
99       
100     public:
101       typedef std::vector<DomForestNode*>::iterator iterator;
102       
103       // Create a DomForestNode by providing the register it represents, and
104       // the node to be its parent.  The virtual root node has register 0
105       // and a null parent.
106       DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
107         if (parent)
108           parent->addChild(this);
109       }
110       
111       ~DomForestNode() {
112         for (iterator I = begin(), E = end(); I != E; ++I)
113           delete *I;
114       }
115       
116       /// getReg - Return the regiser that this node represents
117       inline unsigned getReg() { return reg; }
118       
119       // Provide iterator access to our children
120       inline DomForestNode::iterator begin() { return children.begin(); }
121       inline DomForestNode::iterator end() { return children.end(); }
122     };
123     
124     void computeDFS(MachineFunction& MF);
125     void processBlock(MachineBasicBlock* MBB);
126     
127     std::vector<DomForestNode*> computeDomForest(std::set<unsigned>& instrs,
128                                                  MachineRegisterInfo& MRI);
129     void processPHIUnion(MachineInstr* Inst,
130                          std::set<unsigned>& PHIUnion,
131                          std::vector<StrongPHIElimination::DomForestNode*>& DF,
132                          std::vector<std::pair<unsigned, unsigned> >& locals);
133     void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
134     void InsertCopies(MachineBasicBlock* MBB, std::set<MachineBasicBlock*>& v);
135   };
136
137   char StrongPHIElimination::ID = 0;
138   RegisterPass<StrongPHIElimination> X("strong-phi-node-elimination",
139                   "Eliminate PHI nodes for register allocation, intelligently");
140 }
141
142 const PassInfo *llvm::StrongPHIEliminationID = X.getPassInfo();
143
144 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
145 /// of the given MachineFunction.  These numbers are then used in other parts
146 /// of the PHI elimination process.
147 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
148   SmallPtrSet<MachineDomTreeNode*, 8> frontier;
149   SmallPtrSet<MachineDomTreeNode*, 8> visited;
150   
151   unsigned time = 0;
152   
153   MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
154   
155   MachineDomTreeNode* node = DT.getRootNode();
156   
157   std::vector<MachineDomTreeNode*> worklist;
158   worklist.push_back(node);
159   
160   while (!worklist.empty()) {
161     MachineDomTreeNode* currNode = worklist.back();
162     
163     if (!frontier.count(currNode)) {
164       frontier.insert(currNode);
165       ++time;
166       preorder.insert(std::make_pair(currNode->getBlock(), time));
167     }
168     
169     bool inserted = false;
170     for (MachineDomTreeNode::iterator I = node->begin(), E = node->end();
171          I != E; ++I)
172       if (!frontier.count(*I) && !visited.count(*I)) {
173         worklist.push_back(*I);
174         inserted = true;
175         break;
176       }
177     
178     if (!inserted) {
179       frontier.erase(currNode);
180       visited.insert(currNode);
181       maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
182       
183       worklist.pop_back();
184     }
185   }
186 }
187
188 /// PreorderSorter - a helper class that is used to sort registers
189 /// according to the preorder number of their defining blocks
190 class PreorderSorter {
191 private:
192   DenseMap<MachineBasicBlock*, unsigned>& preorder;
193   MachineRegisterInfo& MRI;
194   
195 public:
196   PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
197                 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
198   
199   bool operator()(unsigned A, unsigned B) {
200     if (A == B)
201       return false;
202     
203     MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
204     MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
205     
206     if (preorder[ABlock] < preorder[BBlock])
207       return true;
208     else if (preorder[ABlock] > preorder[BBlock])
209       return false;
210     
211     return false;
212   }
213 };
214
215 /// computeDomForest - compute the subforest of the DomTree corresponding
216 /// to the defining blocks of the registers in question
217 std::vector<StrongPHIElimination::DomForestNode*>
218 StrongPHIElimination::computeDomForest(std::set<unsigned>& regs, 
219                                        MachineRegisterInfo& MRI) {
220   // Begin by creating a virtual root node, since the actual results
221   // may well be a forest.  Assume this node has maximum DFS-out number.
222   DomForestNode* VirtualRoot = new DomForestNode(0, 0);
223   maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
224   
225   // Populate a worklist with the registers
226   std::vector<unsigned> worklist;
227   worklist.reserve(regs.size());
228   for (std::set<unsigned>::iterator I = regs.begin(), E = regs.end();
229        I != E; ++I)
230     worklist.push_back(*I);
231   
232   // Sort the registers by the DFS-in number of their defining block
233   PreorderSorter PS(preorder, MRI);
234   std::sort(worklist.begin(), worklist.end(), PS);
235   
236   // Create a "current parent" stack, and put the virtual root on top of it
237   DomForestNode* CurrentParent = VirtualRoot;
238   std::vector<DomForestNode*> stack;
239   stack.push_back(VirtualRoot);
240   
241   // Iterate over all the registers in the previously computed order
242   for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
243        I != E; ++I) {
244     unsigned pre = preorder[MRI.getVRegDef(*I)->getParent()];
245     MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
246                  MRI.getVRegDef(CurrentParent->getReg())->getParent() :
247                  0;
248     
249     // If the DFS-in number of the register is greater than the DFS-out number
250     // of the current parent, repeatedly pop the parent stack until it isn't.
251     while (pre > maxpreorder[parentBlock]) {
252       stack.pop_back();
253       CurrentParent = stack.back();
254       
255       parentBlock = CurrentParent->getReg() ?
256                    MRI.getVRegDef(CurrentParent->getReg())->getParent() :
257                    0;
258     }
259     
260     // Now that we've found the appropriate parent, create a DomForestNode for
261     // this register and attach it to the forest
262     DomForestNode* child = new DomForestNode(*I, CurrentParent);
263     
264     // Push this new node on the "current parent" stack
265     stack.push_back(child);
266     CurrentParent = child;
267   }
268   
269   // Return a vector containing the children of the virtual root node
270   std::vector<DomForestNode*> ret;
271   ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
272   return ret;
273 }
274
275 /// isLiveIn - helper method that determines, from a regno, if a register
276 /// is live into a block
277 static bool isLiveIn(unsigned r, MachineBasicBlock* MBB,
278                      LiveIntervals& LI) {
279   LiveInterval& I = LI.getOrCreateInterval(r);
280   unsigned idx = LI.getMBBStartIdx(MBB);
281   return I.liveBeforeAndAt(idx);
282 }
283
284 /// isLiveOut - help method that determines, from a regno, if a register is
285 /// live out of a block.
286 static bool isLiveOut(unsigned r, MachineBasicBlock* MBB,
287                       LiveIntervals& LI) {
288   for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
289        E = MBB->succ_end(); PI != E; ++PI) {
290     if (isLiveIn(r, *PI, LI))
291       return true;
292   }
293   
294   return false;
295 }
296
297 /// interferes - checks for local interferences by scanning a block.  The only
298 /// trick parameter is 'mode' which tells it the relationship of the two
299 /// registers. 0 - defined in the same block, 1 - first properly dominates
300 /// second, 2 - second properly dominates first 
301 static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
302                        LiveIntervals& LV, unsigned mode) {
303   MachineInstr* def = 0;
304   MachineInstr* kill = 0;
305   
306   // The code is still in SSA form at this point, so there is only one
307   // definition per VReg.  Thus we can safely use MRI->getVRegDef().
308   const MachineRegisterInfo* MRI = &scan->getParent()->getRegInfo();
309   
310   bool interference = false;
311   
312   // Wallk the block, checking for interferences
313   for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
314        MBI != MBE; ++MBI) {
315     MachineInstr* curr = MBI;
316     
317     // Same defining block...
318     if (mode == 0) {
319       if (curr == MRI->getVRegDef(a)) {
320         // If we find our first definition, save it
321         if (!def) {
322           def = curr;
323         // If there's already an unkilled definition, then 
324         // this is an interference
325         } else if (!kill) {
326           interference = true;
327           break;
328         // If there's a definition followed by a KillInst, then
329         // they can't interfere
330         } else {
331           interference = false;
332           break;
333         }
334       // Symmetric with the above
335       } else if (curr == MRI->getVRegDef(b)) {
336         if (!def) {
337           def = curr;
338         } else if (!kill) {
339           interference = true;
340           break;
341         } else {
342           interference = false;
343           break;
344         }
345       // Store KillInsts if they match up with the definition
346       } else if (curr->killsRegister(a)) {
347         if (def == MRI->getVRegDef(a)) {
348           kill = curr;
349         } else if (curr->killsRegister(b)) {
350           if (def == MRI->getVRegDef(b)) {
351             kill = curr;
352           }
353         }
354       }
355     // First properly dominates second...
356     } else if (mode == 1) {
357       if (curr == MRI->getVRegDef(b)) {
358         // Definition of second without kill of first is an interference
359         if (!kill) {
360           interference = true;
361           break;
362         // Definition after a kill is a non-interference
363         } else {
364           interference = false;
365           break;
366         }
367       // Save KillInsts of First
368       } else if (curr->killsRegister(a)) {
369         kill = curr;
370       }
371     // Symmetric with the above
372     } else if (mode == 2) {
373       if (curr == MRI->getVRegDef(a)) {
374         if (!kill) {
375           interference = true;
376           break;
377         } else {
378           interference = false;
379           break;
380         }
381       } else if (curr->killsRegister(b)) {
382         kill = curr;
383       }
384     }
385   }
386   
387   return interference;
388 }
389
390 /// processBlock - Determine how to break up PHIs in the current block.  Each
391 /// PHI is broken up by some combination of renaming its operands and inserting
392 /// copies.  This method is responsible for determining which operands receive
393 /// which treatment.
394 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
395   LiveIntervals& LI = getAnalysis<LiveIntervals>();
396   MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
397   
398   // Holds names that have been added to a set in any PHI within this block
399   // before the current one.
400   std::set<unsigned> ProcessedNames;
401   
402   // Iterate over all the PHI nodes in this block
403   MachineBasicBlock::iterator P = MBB->begin();
404   while (P != MBB->end() && P->getOpcode() == TargetInstrInfo::PHI) {
405     unsigned DestReg = P->getOperand(0).getReg();
406
407     // PHIUnion is the set of incoming registers to the PHI node that
408     // are going to be renames rather than having copies inserted.  This set
409     // is refinded over the course of this function.  UnionedBlocks is the set
410     // of corresponding MBBs.
411     std::set<unsigned> PHIUnion;
412     std::set<MachineBasicBlock*> UnionedBlocks;
413   
414     // Iterate over the operands of the PHI node
415     for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
416       unsigned SrcReg = P->getOperand(i-1).getReg();
417     
418       // Check for trivial interferences via liveness information, allowing us
419       // to avoid extra work later.  Any registers that interfere cannot both
420       // be in the renaming set, so choose one and add copies for it instead.
421       // The conditions are:
422       //   1) if the operand is live into the PHI node's block OR
423       //   2) if the PHI node is live out of the operand's defining block OR
424       //   3) if the operand is itself a PHI node and the original PHI is
425       //      live into the operand's defining block OR
426       //   4) if the operand is already being renamed for another PHI node
427       //      in this block OR
428       //   5) if any two operands are defined in the same block, insert copies
429       //      for one of them
430       if (isLiveIn(SrcReg, P->getParent(), LI) ||
431           isLiveOut(P->getOperand(0).getReg(),
432                     MRI.getVRegDef(SrcReg)->getParent(), LI) ||
433           ( MRI.getVRegDef(SrcReg)->getOpcode() == TargetInstrInfo::PHI &&
434             isLiveIn(P->getOperand(0).getReg(),
435                      MRI.getVRegDef(SrcReg)->getParent(), LI) ) ||
436           ProcessedNames.count(SrcReg) ||
437           UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
438         
439         // Add a copy for the selected register
440         MachineBasicBlock* From = P->getOperand(i).getMBB();
441         Waiting[From].insert(std::make_pair(SrcReg, DestReg));
442         UsedByAnother.insert(SrcReg);
443       } else {
444         // Otherwise, add it to the renaming set
445         PHIUnion.insert(SrcReg);
446         UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
447       }
448     }
449     
450     // Compute the dominator forest for the renaming set.  This is a forest
451     // where the nodes are the registers and the edges represent dominance 
452     // relations between the defining blocks of the registers
453     std::vector<StrongPHIElimination::DomForestNode*> DF = 
454                                                 computeDomForest(PHIUnion, MRI);
455     
456     // Walk DomForest to resolve interferences at an inter-block level.  This
457     // will remove registers from the renaming set (and insert copies for them)
458     // if interferences are found.
459     std::vector<std::pair<unsigned, unsigned> > localInterferences;
460     processPHIUnion(P, PHIUnion, DF, localInterferences);
461     
462     // The dominator forest walk may have returned some register pairs whose
463     // interference cannot be determines from dominator analysis.  We now 
464     // examine these pairs for local interferences.
465     for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
466         localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
467       std::pair<unsigned, unsigned> p = *I;
468       
469       MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
470       
471       // Determine the block we need to scan and the relationship between
472       // the two registers
473       MachineBasicBlock* scan = 0;
474       unsigned mode = 0;
475       if (MRI.getVRegDef(p.first)->getParent() ==
476           MRI.getVRegDef(p.second)->getParent()) {
477         scan = MRI.getVRegDef(p.first)->getParent();
478         mode = 0; // Same block
479       } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
480                                MRI.getVRegDef(p.second)->getParent())) {
481         scan = MRI.getVRegDef(p.second)->getParent();
482         mode = 1; // First dominates second
483       } else {
484         scan = MRI.getVRegDef(p.first)->getParent();
485         mode = 2; // Second dominates first
486       }
487       
488       // If there's an interference, we need to insert  copies
489       if (interferes(p.first, p.second, scan, LI, mode)) {
490         // Insert copies for First
491         for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
492           if (P->getOperand(i-1).getReg() == p.first) {
493             unsigned SrcReg = p.first;
494             MachineBasicBlock* From = P->getOperand(i).getMBB();
495             
496             Waiting[From].insert(std::make_pair(SrcReg,
497                                                 P->getOperand(0).getReg()));
498             UsedByAnother.insert(SrcReg);
499             
500             PHIUnion.erase(SrcReg);
501           }
502         }
503       }
504     }
505     
506     // Add the renaming set for this PHI node to our overal renaming information
507     RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
508     
509     // Remember which registers are already renamed, so that we don't try to 
510     // rename them for another PHI node in this block
511     ProcessedNames.insert(PHIUnion.begin(), PHIUnion.end());
512     
513     ++P;
514   }
515 }
516
517 /// processPHIUnion - Take a set of candidate registers to be coalesced when
518 /// decomposing the PHI instruction.  Use the DominanceForest to remove the ones
519 /// that are known to interfere, and flag others that need to be checked for
520 /// local interferences.
521 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
522                                            std::set<unsigned>& PHIUnion,
523                         std::vector<StrongPHIElimination::DomForestNode*>& DF,
524                         std::vector<std::pair<unsigned, unsigned> >& locals) {
525   
526   std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
527   SmallPtrSet<DomForestNode*, 4> visited;
528   
529   // Code is still in SSA form, so we can use MRI::getVRegDef()
530   MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
531   
532   LiveIntervals& LI = getAnalysis<LiveIntervals>();
533   unsigned DestReg = Inst->getOperand(0).getReg();
534   
535   // DF walk on the DomForest
536   while (!worklist.empty()) {
537     DomForestNode* DFNode = worklist.back();
538     
539     visited.insert(DFNode);
540     
541     bool inserted = false;
542     for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
543          CI != CE; ++CI) {
544       DomForestNode* child = *CI;   
545       
546       // If the current node is live-out of the defining block of one of its
547       // children, insert a copy for it.  NOTE: The paper actually calls for
548       // a more elaborate heuristic for determining whether to insert copies
549       // for the child or the parent.  In the interest of simplicity, we're
550       // just always choosing the parent.
551       if (isLiveOut(DFNode->getReg(),
552           MRI.getVRegDef(child->getReg())->getParent(), LI)) {
553         // Insert copies for parent
554         for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
555           if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
556             unsigned SrcReg = DFNode->getReg();
557             MachineBasicBlock* From = Inst->getOperand(i).getMBB();
558             
559             Waiting[From].insert(std::make_pair(SrcReg, DestReg));
560             UsedByAnother.insert(SrcReg);
561             
562             PHIUnion.erase(SrcReg);
563           }
564         }
565       
566       // If a node is live-in to the defining block of one of its children, but
567       // not live-out, then we need to scan that block for local interferences.
568       } else if (isLiveIn(DFNode->getReg(),
569                           MRI.getVRegDef(child->getReg())->getParent(), LI) ||
570                  MRI.getVRegDef(DFNode->getReg())->getParent() ==
571                                  MRI.getVRegDef(child->getReg())->getParent()) {
572         // Add (p, c) to possible local interferences
573         locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
574       }
575       
576       if (!visited.count(child)) {
577         worklist.push_back(child);
578         inserted = true;
579       }
580     }
581     
582     if (!inserted) worklist.pop_back();
583   }
584 }
585
586 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
587 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
588 /// problems.
589 ///
590 /// Based on "Practical Improvements to the Construction and Destruction
591 /// of Static Single Assignment Form" by Briggs, et al.
592 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
593                                           std::set<unsigned>& pushed) {
594   // FIXME: This function needs to update LiveVariables
595   std::map<unsigned, unsigned>& copy_set= Waiting[MBB];
596   
597   std::map<unsigned, unsigned> worklist;
598   std::map<unsigned, unsigned> map;
599   
600   // Setup worklist of initial copies
601   for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
602        E = copy_set.end(); I != E; ) {
603     map.insert(std::make_pair(I->first, I->first));
604     map.insert(std::make_pair(I->second, I->second));
605          
606     if (!UsedByAnother.count(I->first)) {
607       worklist.insert(*I);
608       
609       // Avoid iterator invalidation
610       unsigned first = I->first;
611       ++I;
612       copy_set.erase(first);
613     } else {
614       ++I;
615     }
616   }
617   
618   LiveIntervals& LI = getAnalysis<LiveIntervals>();
619   MachineFunction* MF = MBB->getParent();
620   MachineRegisterInfo& MRI = MF->getRegInfo();
621   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
622   
623   // Iterate over the worklist, inserting copies
624   while (!worklist.empty() || !copy_set.empty()) {
625     while (!worklist.empty()) {
626       std::pair<unsigned, unsigned> curr = *worklist.begin();
627       worklist.erase(curr.first);
628       
629       const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
630       
631       if (isLiveOut(curr.second, MBB, LI)) {
632         // Create a temporary
633         unsigned t = MF->getRegInfo().createVirtualRegister(RC);
634         
635         // Insert copy from curr.second to a temporary at
636         // the Phi defining curr.second
637         MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
638         TII->copyRegToReg(*PI->getParent(), PI, t,
639                           curr.second, RC, RC);
640         
641         // Push temporary on Stacks
642         Stacks[curr.second].push_back(t);
643         
644         // Insert curr.second in pushed
645         pushed.insert(curr.second);
646       }
647       
648       // Insert copy from map[curr.first] to curr.second
649       TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), curr.second,
650                         map[curr.first], RC, RC);
651       map[curr.first] = curr.second;
652       
653       // If curr.first is a destination in copy_set...
654       for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
655            E = copy_set.end(); I != E; )
656         if (curr.first == I->second) {
657           std::pair<unsigned, unsigned> temp = *I;
658           
659           // Avoid iterator invalidation
660           ++I;
661           copy_set.erase(temp.first);
662           worklist.insert(temp);
663           
664           break;
665         } else {
666           ++I;
667         }
668     }
669     
670     if (!copy_set.empty()) {
671       std::pair<unsigned, unsigned> curr = *copy_set.begin();
672       copy_set.erase(curr.first);
673       
674       const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
675       
676       // Insert a copy from dest to a new temporary t at the end of b
677       unsigned t = MF->getRegInfo().createVirtualRegister(RC);
678       TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), t,
679                         curr.second, RC, RC);
680       map[curr.second] = t;
681       
682       worklist.insert(curr);
683     }
684   }
685 }
686
687 /// InsertCopies - insert copies into MBB and all of its successors
688 void StrongPHIElimination::InsertCopies(MachineBasicBlock* MBB,
689                                         std::set<MachineBasicBlock*>& visited) {
690   visited.insert(MBB);
691   
692   std::set<unsigned> pushed;
693   
694   // Rewrite register uses from Stacks
695   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
696       I != E; ++I)
697     for (unsigned i = 0; i < I->getNumOperands(); ++i)
698       if (I->getOperand(i).isRegister() &&
699           Stacks[I->getOperand(i).getReg()].size()) {
700         I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
701       }
702   
703   // Schedule the copies for this block
704   ScheduleCopies(MBB, pushed);
705   
706   // Recur to our successors
707   for (GraphTraits<MachineBasicBlock*>::ChildIteratorType I = 
708        GraphTraits<MachineBasicBlock*>::child_begin(MBB), E =
709        GraphTraits<MachineBasicBlock*>::child_end(MBB); I != E; ++I)
710     if (!visited.count(*I))
711       InsertCopies(*I, visited);
712   
713   // As we exit this block, pop the names we pushed while processing it
714   for (std::set<unsigned>::iterator I = pushed.begin(), 
715        E = pushed.end(); I != E; ++I)
716     Stacks[*I].pop_back();
717 }
718
719 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
720   // Compute DFS numbers of each block
721   computeDFS(Fn);
722   
723   // Determine which phi node operands need copies
724   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
725     if (!I->empty() &&
726         I->begin()->getOpcode() == TargetInstrInfo::PHI)
727       processBlock(I);
728   
729   // Insert copies
730   // FIXME: This process should probably preserve LiveVariables
731   std::set<MachineBasicBlock*> visited;
732   InsertCopies(Fn.begin(), visited);
733   
734   // Perform renaming
735   typedef std::map<unsigned, std::set<unsigned> > RenameSetType;
736   for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
737        I != E; ++I)
738     for (std::set<unsigned>::iterator SI = I->second.begin(),
739          SE = I->second.end(); SI != SE; ++SI)
740       Fn.getRegInfo().replaceRegWith(*SI, I->first);
741   
742   // FIXME: Insert last-minute copies
743   
744   // Remove PHIs
745   std::vector<MachineInstr*> phis;
746   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
747     for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
748          BI != BE; ++BI)
749       if (BI->getOpcode() == TargetInstrInfo::PHI)
750         phis.push_back(BI);
751   }
752   
753   for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
754        I != E; ++I)
755     (*I)->eraseFromParent();
756   
757   return false;
758 }