Preserve the register coallescer, and update live intervals more correctly by trigger...
[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/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/RegisterCoalescer.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/ADT/DepthFirstIterator.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Support/Compiler.h"
36 using namespace llvm;
37
38 namespace {
39   struct VISIBILITY_HIDDEN StrongPHIElimination : public MachineFunctionPass {
40     static char ID; // Pass identification, replacement for typeid
41     StrongPHIElimination() : MachineFunctionPass((intptr_t)&ID) {}
42
43     // Waiting stores, for each MBB, the set of copies that need to
44     // be inserted into that MBB
45     DenseMap<MachineBasicBlock*,
46              std::map<unsigned, unsigned> > Waiting;
47     
48     // Stacks holds the renaming stack for each register
49     std::map<unsigned, std::vector<unsigned> > Stacks;
50     
51     // Registers in UsedByAnother are PHI nodes that are themselves
52     // used as operands to another another PHI node
53     std::set<unsigned> UsedByAnother;
54     
55     // RenameSets are the sets of operands (and their VNInfo IDs) to a PHI
56     // (the defining instruction of the key) that can be renamed without copies.
57     std::map<unsigned, std::map<unsigned, unsigned> > RenameSets;
58     
59     // PhiValueNumber holds the ID numbers of the VNs for each phi that we're
60     // eliminating, indexed by the register defined by that phi.
61     std::map<unsigned, unsigned> PhiValueNumber;
62
63     // Store the DFS-in number of each block
64     DenseMap<MachineBasicBlock*, unsigned> preorder;
65     
66     // Store the DFS-out number of each block
67     DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
68
69     bool runOnMachineFunction(MachineFunction &Fn);
70     
71     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
72       AU.addRequired<MachineDominatorTree>();
73       AU.addRequired<LiveIntervals>();
74       
75       // TODO: Actually make this true.
76       AU.addPreserved<LiveIntervals>();
77       AU.addPreserved<RegisterCoalescer>();
78       MachineFunctionPass::getAnalysisUsage(AU);
79     }
80     
81     virtual void releaseMemory() {
82       preorder.clear();
83       maxpreorder.clear();
84       
85       Waiting.clear();
86       Stacks.clear();
87       UsedByAnother.clear();
88       RenameSets.clear();
89     }
90
91   private:
92     
93     /// DomForestNode - Represents a node in the "dominator forest".  This is
94     /// a forest in which the nodes represent registers and the edges
95     /// represent a dominance relation in the block defining those registers.
96     struct DomForestNode {
97     private:
98       // Store references to our children
99       std::vector<DomForestNode*> children;
100       // The register we represent
101       unsigned reg;
102       
103       // Add another node as our child
104       void addChild(DomForestNode* DFN) { children.push_back(DFN); }
105       
106     public:
107       typedef std::vector<DomForestNode*>::iterator iterator;
108       
109       // Create a DomForestNode by providing the register it represents, and
110       // the node to be its parent.  The virtual root node has register 0
111       // and a null parent.
112       DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
113         if (parent)
114           parent->addChild(this);
115       }
116       
117       ~DomForestNode() {
118         for (iterator I = begin(), E = end(); I != E; ++I)
119           delete *I;
120       }
121       
122       /// getReg - Return the regiser that this node represents
123       inline unsigned getReg() { return reg; }
124       
125       // Provide iterator access to our children
126       inline DomForestNode::iterator begin() { return children.begin(); }
127       inline DomForestNode::iterator end() { return children.end(); }
128     };
129     
130     void computeDFS(MachineFunction& MF);
131     void processBlock(MachineBasicBlock* MBB);
132     
133     std::vector<DomForestNode*> computeDomForest(std::map<unsigned, unsigned>& instrs,
134                                                  MachineRegisterInfo& MRI);
135     void processPHIUnion(MachineInstr* Inst,
136                          std::map<unsigned, unsigned>& PHIUnion,
137                          std::vector<StrongPHIElimination::DomForestNode*>& DF,
138                          std::vector<std::pair<unsigned, unsigned> >& locals);
139     void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
140     void InsertCopies(MachineBasicBlock* MBB,
141                       SmallPtrSet<MachineBasicBlock*, 16>& v);
142     void mergeLiveIntervals(unsigned primary, unsigned secondary, unsigned VN);
143   };
144 }
145
146 char StrongPHIElimination::ID = 0;
147 static RegisterPass<StrongPHIElimination>
148 X("strong-phi-node-elimination",
149   "Eliminate PHI nodes for register allocation, intelligently");
150
151 const PassInfo *const llvm::StrongPHIEliminationID = &X;
152
153 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
154 /// of the given MachineFunction.  These numbers are then used in other parts
155 /// of the PHI elimination process.
156 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
157   SmallPtrSet<MachineDomTreeNode*, 8> frontier;
158   SmallPtrSet<MachineDomTreeNode*, 8> visited;
159   
160   unsigned time = 0;
161   
162   MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
163   
164   MachineDomTreeNode* node = DT.getRootNode();
165   
166   std::vector<MachineDomTreeNode*> worklist;
167   worklist.push_back(node);
168   
169   while (!worklist.empty()) {
170     MachineDomTreeNode* currNode = worklist.back();
171     
172     if (!frontier.count(currNode)) {
173       frontier.insert(currNode);
174       ++time;
175       preorder.insert(std::make_pair(currNode->getBlock(), time));
176     }
177     
178     bool inserted = false;
179     for (MachineDomTreeNode::iterator I = currNode->begin(), E = currNode->end();
180          I != E; ++I)
181       if (!frontier.count(*I) && !visited.count(*I)) {
182         worklist.push_back(*I);
183         inserted = true;
184         break;
185       }
186     
187     if (!inserted) {
188       frontier.erase(currNode);
189       visited.insert(currNode);
190       maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
191       
192       worklist.pop_back();
193     }
194   }
195 }
196
197 namespace {
198
199 /// PreorderSorter - a helper class that is used to sort registers
200 /// according to the preorder number of their defining blocks
201 class PreorderSorter {
202 private:
203   DenseMap<MachineBasicBlock*, unsigned>& preorder;
204   MachineRegisterInfo& MRI;
205   
206 public:
207   PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
208                 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
209   
210   bool operator()(unsigned A, unsigned B) {
211     if (A == B)
212       return false;
213     
214     MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
215     MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
216     
217     if (preorder[ABlock] < preorder[BBlock])
218       return true;
219     else if (preorder[ABlock] > preorder[BBlock])
220       return false;
221     
222     return false;
223   }
224 };
225
226 }
227
228 /// computeDomForest - compute the subforest of the DomTree corresponding
229 /// to the defining blocks of the registers in question
230 std::vector<StrongPHIElimination::DomForestNode*>
231 StrongPHIElimination::computeDomForest(std::map<unsigned, unsigned>& regs, 
232                                        MachineRegisterInfo& MRI) {
233   // Begin by creating a virtual root node, since the actual results
234   // may well be a forest.  Assume this node has maximum DFS-out number.
235   DomForestNode* VirtualRoot = new DomForestNode(0, 0);
236   maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
237   
238   // Populate a worklist with the registers
239   std::vector<unsigned> worklist;
240   worklist.reserve(regs.size());
241   for (std::map<unsigned, unsigned>::iterator I = regs.begin(), E = regs.end();
242        I != E; ++I)
243     worklist.push_back(I->first);
244   
245   // Sort the registers by the DFS-in number of their defining block
246   PreorderSorter PS(preorder, MRI);
247   std::sort(worklist.begin(), worklist.end(), PS);
248   
249   // Create a "current parent" stack, and put the virtual root on top of it
250   DomForestNode* CurrentParent = VirtualRoot;
251   std::vector<DomForestNode*> stack;
252   stack.push_back(VirtualRoot);
253   
254   // Iterate over all the registers in the previously computed order
255   for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
256        I != E; ++I) {
257     unsigned pre = preorder[MRI.getVRegDef(*I)->getParent()];
258     MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
259                  MRI.getVRegDef(CurrentParent->getReg())->getParent() :
260                  0;
261     
262     // If the DFS-in number of the register is greater than the DFS-out number
263     // of the current parent, repeatedly pop the parent stack until it isn't.
264     while (pre > maxpreorder[parentBlock]) {
265       stack.pop_back();
266       CurrentParent = stack.back();
267       
268       parentBlock = CurrentParent->getReg() ?
269                    MRI.getVRegDef(CurrentParent->getReg())->getParent() :
270                    0;
271     }
272     
273     // Now that we've found the appropriate parent, create a DomForestNode for
274     // this register and attach it to the forest
275     DomForestNode* child = new DomForestNode(*I, CurrentParent);
276     
277     // Push this new node on the "current parent" stack
278     stack.push_back(child);
279     CurrentParent = child;
280   }
281   
282   // Return a vector containing the children of the virtual root node
283   std::vector<DomForestNode*> ret;
284   ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
285   return ret;
286 }
287
288 /// isLiveIn - helper method that determines, from a regno, if a register
289 /// is live into a block
290 static bool isLiveIn(unsigned r, MachineBasicBlock* MBB,
291                      LiveIntervals& LI) {
292   LiveInterval& I = LI.getOrCreateInterval(r);
293   unsigned idx = LI.getMBBStartIdx(MBB);
294   return I.liveBeforeAndAt(idx);
295 }
296
297 /// isLiveOut - help method that determines, from a regno, if a register is
298 /// live out of a block.
299 static bool isLiveOut(unsigned r, MachineBasicBlock* MBB,
300                       LiveIntervals& LI) {
301   for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
302        E = MBB->succ_end(); PI != E; ++PI) {
303     if (isLiveIn(r, *PI, LI))
304       return true;
305   }
306   
307   return false;
308 }
309
310 /// interferes - checks for local interferences by scanning a block.  The only
311 /// trick parameter is 'mode' which tells it the relationship of the two
312 /// registers. 0 - defined in the same block, 1 - first properly dominates
313 /// second, 2 - second properly dominates first 
314 static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
315                        LiveIntervals& LV, unsigned mode) {
316   MachineInstr* def = 0;
317   MachineInstr* kill = 0;
318   
319   // The code is still in SSA form at this point, so there is only one
320   // definition per VReg.  Thus we can safely use MRI->getVRegDef().
321   const MachineRegisterInfo* MRI = &scan->getParent()->getRegInfo();
322   
323   bool interference = false;
324   
325   // Wallk the block, checking for interferences
326   for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
327        MBI != MBE; ++MBI) {
328     MachineInstr* curr = MBI;
329     
330     // Same defining block...
331     if (mode == 0) {
332       if (curr == MRI->getVRegDef(a)) {
333         // If we find our first definition, save it
334         if (!def) {
335           def = curr;
336         // If there's already an unkilled definition, then 
337         // this is an interference
338         } else if (!kill) {
339           interference = true;
340           break;
341         // If there's a definition followed by a KillInst, then
342         // they can't interfere
343         } else {
344           interference = false;
345           break;
346         }
347       // Symmetric with the above
348       } else if (curr == MRI->getVRegDef(b)) {
349         if (!def) {
350           def = curr;
351         } else if (!kill) {
352           interference = true;
353           break;
354         } else {
355           interference = false;
356           break;
357         }
358       // Store KillInsts if they match up with the definition
359       } else if (curr->killsRegister(a)) {
360         if (def == MRI->getVRegDef(a)) {
361           kill = curr;
362         } else if (curr->killsRegister(b)) {
363           if (def == MRI->getVRegDef(b)) {
364             kill = curr;
365           }
366         }
367       }
368     // First properly dominates second...
369     } else if (mode == 1) {
370       if (curr == MRI->getVRegDef(b)) {
371         // Definition of second without kill of first is an interference
372         if (!kill) {
373           interference = true;
374           break;
375         // Definition after a kill is a non-interference
376         } else {
377           interference = false;
378           break;
379         }
380       // Save KillInsts of First
381       } else if (curr->killsRegister(a)) {
382         kill = curr;
383       }
384     // Symmetric with the above
385     } else if (mode == 2) {
386       if (curr == MRI->getVRegDef(a)) {
387         if (!kill) {
388           interference = true;
389           break;
390         } else {
391           interference = false;
392           break;
393         }
394       } else if (curr->killsRegister(b)) {
395         kill = curr;
396       }
397     }
398   }
399   
400   return interference;
401 }
402
403 /// processBlock - Determine how to break up PHIs in the current block.  Each
404 /// PHI is broken up by some combination of renaming its operands and inserting
405 /// copies.  This method is responsible for determining which operands receive
406 /// which treatment.
407 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
408   LiveIntervals& LI = getAnalysis<LiveIntervals>();
409   MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
410   
411   // Holds names that have been added to a set in any PHI within this block
412   // before the current one.
413   std::set<unsigned> ProcessedNames;
414   
415   // Iterate over all the PHI nodes in this block
416   MachineBasicBlock::iterator P = MBB->begin();
417   while (P != MBB->end() && P->getOpcode() == TargetInstrInfo::PHI) {
418     unsigned DestReg = P->getOperand(0).getReg();
419
420     // Don't both doing PHI elimination for dead PHI's.
421     if (P->registerDefIsDead(DestReg)) {
422       ++P;
423       continue;
424     }
425
426     LiveInterval& PI = LI.getOrCreateInterval(DestReg);
427     unsigned pIdx = LI.getDefIndex(LI.getInstructionIndex(P));
428     VNInfo* PVN = PI.getLiveRangeContaining(pIdx)->valno;
429     PhiValueNumber.insert(std::make_pair(DestReg, PVN->id));
430
431     // PHIUnion is the set of incoming registers to the PHI node that
432     // are going to be renames rather than having copies inserted.  This set
433     // is refinded over the course of this function.  UnionedBlocks is the set
434     // of corresponding MBBs.
435     std::map<unsigned, unsigned> PHIUnion;
436     SmallPtrSet<MachineBasicBlock*, 8> UnionedBlocks;
437   
438     // Iterate over the operands of the PHI node
439     for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
440       unsigned SrcReg = P->getOperand(i-1).getReg();
441     
442       // Check for trivial interferences via liveness information, allowing us
443       // to avoid extra work later.  Any registers that interfere cannot both
444       // be in the renaming set, so choose one and add copies for it instead.
445       // The conditions are:
446       //   1) if the operand is live into the PHI node's block OR
447       //   2) if the PHI node is live out of the operand's defining block OR
448       //   3) if the operand is itself a PHI node and the original PHI is
449       //      live into the operand's defining block OR
450       //   4) if the operand is already being renamed for another PHI node
451       //      in this block OR
452       //   5) if any two operands are defined in the same block, insert copies
453       //      for one of them
454       if (isLiveIn(SrcReg, P->getParent(), LI) ||
455           isLiveOut(P->getOperand(0).getReg(),
456                     MRI.getVRegDef(SrcReg)->getParent(), LI) ||
457           ( MRI.getVRegDef(SrcReg)->getOpcode() == TargetInstrInfo::PHI &&
458             isLiveIn(P->getOperand(0).getReg(),
459                      MRI.getVRegDef(SrcReg)->getParent(), LI) ) ||
460           ProcessedNames.count(SrcReg) ||
461           UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
462         
463         // Add a copy for the selected register
464         MachineBasicBlock* From = P->getOperand(i).getMBB();
465         Waiting[From].insert(std::make_pair(SrcReg, DestReg));
466         UsedByAnother.insert(SrcReg);
467       } else {
468         // Otherwise, add it to the renaming set
469         LiveInterval& I = LI.getOrCreateInterval(SrcReg);
470         unsigned idx = LI.getMBBEndIdx(P->getOperand(i).getMBB());
471         VNInfo* VN = I.getLiveRangeContaining(idx)->valno;
472         
473         assert(VN && "No VNInfo for register?");
474         
475         PHIUnion.insert(std::make_pair(SrcReg, VN->id));
476         UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
477       }
478     }
479     
480     // Compute the dominator forest for the renaming set.  This is a forest
481     // where the nodes are the registers and the edges represent dominance 
482     // relations between the defining blocks of the registers
483     std::vector<StrongPHIElimination::DomForestNode*> DF = 
484                                                 computeDomForest(PHIUnion, MRI);
485     
486     // Walk DomForest to resolve interferences at an inter-block level.  This
487     // will remove registers from the renaming set (and insert copies for them)
488     // if interferences are found.
489     std::vector<std::pair<unsigned, unsigned> > localInterferences;
490     processPHIUnion(P, PHIUnion, DF, localInterferences);
491     
492     // If one of the inputs is defined in the same block as the current PHI
493     // then we need to check for a local interference between that input and
494     // the PHI.
495     for (std::map<unsigned, unsigned>::iterator I = PHIUnion.begin(),
496          E = PHIUnion.end(); I != E; ++I)
497       if (MRI.getVRegDef(I->first)->getParent() == P->getParent())
498         localInterferences.push_back(std::make_pair(I->first,
499                                                     P->getOperand(0).getReg()));
500     
501     // The dominator forest walk may have returned some register pairs whose
502     // interference cannot be determined from dominator analysis.  We now 
503     // examine these pairs for local interferences.
504     for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
505         localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
506       std::pair<unsigned, unsigned> p = *I;
507       
508       MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
509       
510       // Determine the block we need to scan and the relationship between
511       // the two registers
512       MachineBasicBlock* scan = 0;
513       unsigned mode = 0;
514       if (MRI.getVRegDef(p.first)->getParent() ==
515           MRI.getVRegDef(p.second)->getParent()) {
516         scan = MRI.getVRegDef(p.first)->getParent();
517         mode = 0; // Same block
518       } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
519                                MRI.getVRegDef(p.second)->getParent())) {
520         scan = MRI.getVRegDef(p.second)->getParent();
521         mode = 1; // First dominates second
522       } else {
523         scan = MRI.getVRegDef(p.first)->getParent();
524         mode = 2; // Second dominates first
525       }
526       
527       // If there's an interference, we need to insert  copies
528       if (interferes(p.first, p.second, scan, LI, mode)) {
529         // Insert copies for First
530         for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
531           if (P->getOperand(i-1).getReg() == p.first) {
532             unsigned SrcReg = p.first;
533             MachineBasicBlock* From = P->getOperand(i).getMBB();
534             
535             Waiting[From].insert(std::make_pair(SrcReg,
536                                                 P->getOperand(0).getReg()));
537             UsedByAnother.insert(SrcReg);
538             
539             PHIUnion.erase(SrcReg);
540           }
541         }
542       }
543     }
544     
545     // Add the renaming set for this PHI node to our overall renaming information
546     RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
547     
548     // Remember which registers are already renamed, so that we don't try to 
549     // rename them for another PHI node in this block
550     for (std::map<unsigned, unsigned>::iterator I = PHIUnion.begin(),
551          E = PHIUnion.end(); I != E; ++I)
552       ProcessedNames.insert(I->first);
553     
554     ++P;
555   }
556 }
557
558 /// processPHIUnion - Take a set of candidate registers to be coalesced when
559 /// decomposing the PHI instruction.  Use the DominanceForest to remove the ones
560 /// that are known to interfere, and flag others that need to be checked for
561 /// local interferences.
562 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
563                                         std::map<unsigned, unsigned>& PHIUnion,
564                         std::vector<StrongPHIElimination::DomForestNode*>& DF,
565                         std::vector<std::pair<unsigned, unsigned> >& locals) {
566   
567   std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
568   SmallPtrSet<DomForestNode*, 4> visited;
569   
570   // Code is still in SSA form, so we can use MRI::getVRegDef()
571   MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
572   
573   LiveIntervals& LI = getAnalysis<LiveIntervals>();
574   unsigned DestReg = Inst->getOperand(0).getReg();
575   
576   // DF walk on the DomForest
577   while (!worklist.empty()) {
578     DomForestNode* DFNode = worklist.back();
579     
580     visited.insert(DFNode);
581     
582     bool inserted = false;
583     for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
584          CI != CE; ++CI) {
585       DomForestNode* child = *CI;   
586       
587       // If the current node is live-out of the defining block of one of its
588       // children, insert a copy for it.  NOTE: The paper actually calls for
589       // a more elaborate heuristic for determining whether to insert copies
590       // for the child or the parent.  In the interest of simplicity, we're
591       // just always choosing the parent.
592       if (isLiveOut(DFNode->getReg(),
593           MRI.getVRegDef(child->getReg())->getParent(), LI)) {
594         // Insert copies for parent
595         for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
596           if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
597             unsigned SrcReg = DFNode->getReg();
598             MachineBasicBlock* From = Inst->getOperand(i).getMBB();
599             
600             Waiting[From].insert(std::make_pair(SrcReg, DestReg));
601             UsedByAnother.insert(SrcReg);
602             
603             PHIUnion.erase(SrcReg);
604           }
605         }
606       
607       // If a node is live-in to the defining block of one of its children, but
608       // not live-out, then we need to scan that block for local interferences.
609       } else if (isLiveIn(DFNode->getReg(),
610                           MRI.getVRegDef(child->getReg())->getParent(), LI) ||
611                  MRI.getVRegDef(DFNode->getReg())->getParent() ==
612                                  MRI.getVRegDef(child->getReg())->getParent()) {
613         // Add (p, c) to possible local interferences
614         locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
615       }
616       
617       if (!visited.count(child)) {
618         worklist.push_back(child);
619         inserted = true;
620       }
621     }
622     
623     if (!inserted) worklist.pop_back();
624   }
625 }
626
627 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
628 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
629 /// problems.
630 ///
631 /// Based on "Practical Improvements to the Construction and Destruction
632 /// of Static Single Assignment Form" by Briggs, et al.
633 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
634                                           std::set<unsigned>& pushed) {
635   // FIXME: This function needs to update LiveVariables
636   std::map<unsigned, unsigned>& copy_set= Waiting[MBB];
637   
638   std::map<unsigned, unsigned> worklist;
639   std::map<unsigned, unsigned> map;
640   
641   // Setup worklist of initial copies
642   for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
643        E = copy_set.end(); I != E; ) {
644     map.insert(std::make_pair(I->first, I->first));
645     map.insert(std::make_pair(I->second, I->second));
646          
647     if (!UsedByAnother.count(I->second)) {
648       worklist.insert(*I);
649       
650       // Avoid iterator invalidation
651       unsigned first = I->first;
652       ++I;
653       copy_set.erase(first);
654     } else {
655       ++I;
656     }
657   }
658   
659   LiveIntervals& LI = getAnalysis<LiveIntervals>();
660   MachineFunction* MF = MBB->getParent();
661   MachineRegisterInfo& MRI = MF->getRegInfo();
662   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
663   
664   // Iterate over the worklist, inserting copies
665   while (!worklist.empty() || !copy_set.empty()) {
666     while (!worklist.empty()) {
667       std::pair<unsigned, unsigned> curr = *worklist.begin();
668       worklist.erase(curr.first);
669       
670       const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
671       
672       if (isLiveOut(curr.second, MBB, LI)) {
673         // Create a temporary
674         unsigned t = MF->getRegInfo().createVirtualRegister(RC);
675         
676         // Insert copy from curr.second to a temporary at
677         // the Phi defining curr.second
678         MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
679         TII->copyRegToReg(*PI->getParent(), PI, t,
680                           curr.second, RC, RC);
681         
682         // Push temporary on Stacks
683         Stacks[curr.second].push_back(t);
684         
685         // Insert curr.second in pushed
686         pushed.insert(curr.second);
687       }
688       
689       // Insert copy from map[curr.first] to curr.second
690       TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), curr.second,
691                         map[curr.first], RC, RC);
692       map[curr.first] = curr.second;
693       
694       // If curr.first is a destination in copy_set...
695       for (std::map<unsigned, unsigned>::iterator I = copy_set.begin(),
696            E = copy_set.end(); I != E; )
697         if (curr.first == I->second) {
698           std::pair<unsigned, unsigned> temp = *I;
699           
700           // Avoid iterator invalidation
701           ++I;
702           copy_set.erase(temp.first);
703           worklist.insert(temp);
704           
705           break;
706         } else {
707           ++I;
708         }
709     }
710     
711     if (!copy_set.empty()) {
712       std::pair<unsigned, unsigned> curr = *copy_set.begin();
713       copy_set.erase(curr.first);
714       
715       const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
716       
717       // Insert a copy from dest to a new temporary t at the end of b
718       unsigned t = MF->getRegInfo().createVirtualRegister(RC);
719       TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), t,
720                         curr.second, RC, RC);
721       map[curr.second] = t;
722       
723       worklist.insert(curr);
724     }
725   }
726 }
727
728 /// InsertCopies - insert copies into MBB and all of its successors
729 void StrongPHIElimination::InsertCopies(MachineBasicBlock* MBB,
730                                  SmallPtrSet<MachineBasicBlock*, 16>& visited) {
731   visited.insert(MBB);
732   
733   std::set<unsigned> pushed;
734   
735   // Rewrite register uses from Stacks
736   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
737       I != E; ++I)
738     for (unsigned i = 0; i < I->getNumOperands(); ++i)
739       if (I->getOperand(i).isRegister() &&
740           Stacks[I->getOperand(i).getReg()].size()) {
741         I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
742       }
743   
744   // Schedule the copies for this block
745   ScheduleCopies(MBB, pushed);
746   
747   // Recur to our successors
748   for (GraphTraits<MachineBasicBlock*>::ChildIteratorType I = 
749        GraphTraits<MachineBasicBlock*>::child_begin(MBB), E =
750        GraphTraits<MachineBasicBlock*>::child_end(MBB); I != E; ++I)
751     if (!visited.count(*I))
752       InsertCopies(*I, visited);
753   
754   // As we exit this block, pop the names we pushed while processing it
755   for (std::set<unsigned>::iterator I = pushed.begin(), 
756        E = pushed.end(); I != E; ++I)
757     Stacks[*I].pop_back();
758 }
759
760 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
761 /// compute what the resultant value numbers for each value in the input two
762 /// ranges will be.  This is complicated by copies between the two which can
763 /// and will commonly cause multiple value numbers to be merged into one.
764 ///
765 /// VN is the value number that we're trying to resolve.  InstDefiningValue
766 /// keeps track of the new InstDefiningValue assignment for the result
767 /// LiveInterval.  ThisFromOther/OtherFromThis are sets that keep track of
768 /// whether a value in this or other is a copy from the opposite set.
769 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
770 /// already been assigned.
771 ///
772 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
773 /// contains the value number the copy is from.
774 ///
775 static unsigned ComputeUltimateVN(VNInfo *VNI,
776                                   SmallVector<VNInfo*, 16> &NewVNInfo,
777                                   DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
778                                   DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
779                                   SmallVector<int, 16> &ThisValNoAssignments,
780                                   SmallVector<int, 16> &OtherValNoAssignments) {
781   unsigned VN = VNI->id;
782
783   // If the VN has already been computed, just return it.
784   if (ThisValNoAssignments[VN] >= 0)
785     return ThisValNoAssignments[VN];
786 //  assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
787
788   // If this val is not a copy from the other val, then it must be a new value
789   // number in the destination.
790   DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
791   if (I == ThisFromOther.end()) {
792     NewVNInfo.push_back(VNI);
793     return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
794   }
795   VNInfo *OtherValNo = I->second;
796
797   // Otherwise, this *is* a copy from the RHS.  If the other side has already
798   // been computed, return it.
799   if (OtherValNoAssignments[OtherValNo->id] >= 0)
800     return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
801   
802   // Mark this value number as currently being computed, then ask what the
803   // ultimate value # of the other value is.
804   ThisValNoAssignments[VN] = -2;
805   unsigned UltimateVN =
806     ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
807                       OtherValNoAssignments, ThisValNoAssignments);
808   return ThisValNoAssignments[VN] = UltimateVN;
809 }
810
811 void StrongPHIElimination::mergeLiveIntervals(unsigned primary,
812                                               unsigned secondary,
813                                               unsigned secondaryVN) {
814   
815   LiveIntervals& LI = getAnalysis<LiveIntervals>();
816   LiveInterval& LHS = LI.getOrCreateInterval(primary);
817   LiveInterval& RHS = LI.getOrCreateInterval(secondary);
818   
819   // Compute the final value assignment, assuming that the live ranges can be
820   // coalesced.
821   SmallVector<int, 16> LHSValNoAssignments;
822   SmallVector<int, 16> RHSValNoAssignments;
823   SmallVector<VNInfo*, 16> NewVNInfo;
824   
825   LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
826   RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
827   NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
828   
829   for (LiveInterval::vni_iterator I = LHS.vni_begin(), E = LHS.vni_end();
830        I != E; ++I) {
831     VNInfo *VNI = *I;
832     unsigned VN = VNI->id;
833     if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U) 
834       continue;
835     
836     NewVNInfo.push_back(VNI);
837     LHSValNoAssignments[VN] = NewVNInfo.size()-1;
838   }
839   
840   for (LiveInterval::vni_iterator I = RHS.vni_begin(), E = RHS.vni_end();
841        I != E; ++I) {
842     VNInfo *VNI = *I;
843     unsigned VN = VNI->id;
844     if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
845       continue;
846       
847     NewVNInfo.push_back(VNI);
848     RHSValNoAssignments[VN] = NewVNInfo.size()-1;
849   }
850
851   // If we get here, we know that we can coalesce the live ranges.  Ask the
852   // intervals to coalesce themselves now.
853
854   LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
855   LI.removeInterval(secondary);
856   
857   // The valno that was previously the input to the PHI node
858   // now has a PHIKill.
859   LHS.getValNumInfo(RHSValNoAssignments[secondaryVN])->hasPHIKill = true;
860 }
861
862 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
863   LiveIntervals& LI = getAnalysis<LiveIntervals>();
864   
865   // Compute DFS numbers of each block
866   computeDFS(Fn);
867   
868   // Determine which phi node operands need copies
869   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
870     if (!I->empty() &&
871         I->begin()->getOpcode() == TargetInstrInfo::PHI)
872       processBlock(I);
873   
874   // Insert copies
875   // FIXME: This process should probably preserve LiveVariables
876   SmallPtrSet<MachineBasicBlock*, 16> visited;
877   InsertCopies(Fn.begin(), visited);
878   
879   // Perform renaming
880   typedef std::map<unsigned, std::map<unsigned, unsigned> > RenameSetType;
881   for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
882        I != E; ++I)
883     for (std::map<unsigned, unsigned>::iterator SI = I->second.begin(),
884          SE = I->second.end(); SI != SE; ++SI) {
885       mergeLiveIntervals(I->first, SI->first, SI->second);
886       Fn.getRegInfo().replaceRegWith(SI->first, I->first);
887     }
888   
889   // FIXME: Insert last-minute copies
890   
891   // Remove PHIs
892   std::vector<MachineInstr*> phis;
893   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
894     for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
895          BI != BE; ++BI)
896       if (BI->getOpcode() == TargetInstrInfo::PHI)
897         phis.push_back(BI);
898   }
899   
900   for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
901        I != E; ) {
902     MachineInstr* PInstr = *(I++);
903     
904     // If this is a dead PHI node, then remove it from LiveIntervals.
905     unsigned DestReg = PInstr->getOperand(0).getReg();
906     LiveInterval& PI = LI.getInterval(DestReg);
907     if (PInstr->registerDefIsDead(DestReg)) {
908       if (PI.containsOneValue()) {
909         LI.removeInterval(DestReg);
910       } else {
911         unsigned idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
912         PI.removeRange(*PI.getLiveRangeContaining(idx), true);
913       }
914     } else {
915       // If the PHI is not dead, then the valno defined by the PHI
916       // now has an unknown def.
917       unsigned idx = LI.getDefIndex(LI.getInstructionIndex(PInstr));
918       PI.getLiveRangeContaining(idx)->valno->def = ~0U;
919     }
920     
921     LI.RemoveMachineInstrFromMaps(PInstr);
922     PInstr->eraseFromParent();
923   }
924   
925   LI.computeNumbering();
926   
927   return true;
928 }