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