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