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