ee62a6b30c9a7c2672641636de24e9b23f7ce8dc
[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 was developed by Owen Anderson and is distributed under
6 // the University of Illinois Open Source 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/BreakCriticalMachineEdge.h"
25 #include "llvm/CodeGen/LiveVariables.h"
26 #include "llvm/CodeGen/MachineDominators.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/SSARegMap.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/Compiler.h"
34 using namespace llvm;
35
36
37 namespace {
38   struct VISIBILITY_HIDDEN StrongPHIElimination : public MachineFunctionPass {
39     static char ID; // Pass identification, replacement for typeid
40     StrongPHIElimination() : MachineFunctionPass((intptr_t)&ID) {}
41
42     DenseMap<MachineBasicBlock*,
43              SmallVector<std::pair<unsigned, unsigned>, 2> > Waiting;
44
45     bool runOnMachineFunction(MachineFunction &Fn);
46     
47     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48       AU.addPreserved<LiveVariables>();
49       AU.addPreservedID(PHIEliminationID);
50       AU.addRequired<MachineDominatorTree>();
51       AU.addRequired<LiveVariables>();
52       AU.setPreservesAll();
53       MachineFunctionPass::getAnalysisUsage(AU);
54     }
55     
56     virtual void releaseMemory() {
57       preorder.clear();
58       maxpreorder.clear();
59       
60       waiting.clear();
61     }
62
63   private:
64     struct DomForestNode {
65     private:
66       std::vector<DomForestNode*> children;
67       unsigned reg;
68       
69       void addChild(DomForestNode* DFN) { children.push_back(DFN); }
70       
71     public:
72       typedef std::vector<DomForestNode*>::iterator iterator;
73       
74       DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
75         if (parent)
76           parent->addChild(this);
77       }
78       
79       ~DomForestNode() {
80         for (iterator I = begin(), E = end(); I != E; ++I)
81           delete *I;
82       }
83       
84       inline unsigned getReg() { return reg; }
85       
86       inline DomForestNode::iterator begin() { return children.begin(); }
87       inline DomForestNode::iterator end() { return children.end(); }
88     };
89     
90     DenseMap<MachineBasicBlock*, unsigned> preorder;
91     DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
92     
93     DenseMap<MachineBasicBlock*, std::vector<MachineInstr*> > waiting;
94     
95     
96     void computeDFS(MachineFunction& MF);
97     void processBlock(MachineBasicBlock* MBB);
98     
99     std::vector<DomForestNode*> computeDomForest(std::set<unsigned>& instrs);
100     void processPHIUnion(MachineInstr* Inst,
101                          std::set<unsigned>& PHIUnion,
102                          std::vector<StrongPHIElimination::DomForestNode*>& DF,
103                          std::vector<std::pair<unsigned, unsigned> >& locals);
104     void breakCriticalEdges(MachineFunction &Fn);
105     
106   };
107
108   char StrongPHIElimination::ID = 0;
109   RegisterPass<StrongPHIElimination> X("strong-phi-node-elimination",
110                   "Eliminate PHI nodes for register allocation, intelligently");
111 }
112
113 const PassInfo *llvm::StrongPHIEliminationID = X.getPassInfo();
114
115 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
116 /// of the given MachineFunction.  These numbers are then used in other parts
117 /// of the PHI elimination process.
118 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
119   SmallPtrSet<MachineDomTreeNode*, 8> frontier;
120   SmallPtrSet<MachineDomTreeNode*, 8> visited;
121   
122   unsigned time = 0;
123   
124   MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
125   
126   MachineDomTreeNode* node = DT.getRootNode();
127   
128   std::vector<MachineDomTreeNode*> worklist;
129   worklist.push_back(node);
130   
131   while (!worklist.empty()) {
132     MachineDomTreeNode* currNode = worklist.back();
133     
134     if (!frontier.count(currNode)) {
135       frontier.insert(currNode);
136       ++time;
137       preorder.insert(std::make_pair(currNode->getBlock(), time));
138     }
139     
140     bool inserted = false;
141     for (MachineDomTreeNode::iterator I = node->begin(), E = node->end();
142          I != E; ++I)
143       if (!frontier.count(*I) && !visited.count(*I)) {
144         worklist.push_back(*I);
145         inserted = true;
146         break;
147       }
148     
149     if (!inserted) {
150       frontier.erase(currNode);
151       visited.insert(currNode);
152       maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
153       
154       worklist.pop_back();
155     }
156   }
157 }
158
159 /// PreorderSorter - a helper class that is used to sort registers
160 /// according to the preorder number of their defining blocks
161 class PreorderSorter {
162 private:
163   DenseMap<MachineBasicBlock*, unsigned>& preorder;
164   LiveVariables& LV;
165   
166 public:
167   PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
168                 LiveVariables& L) : preorder(p), LV(L) { }
169   
170   bool operator()(unsigned A, unsigned B) {
171     if (A == B)
172       return false;
173     
174     MachineBasicBlock* ABlock = LV.getVarInfo(A).DefInst->getParent();
175     MachineBasicBlock* BBlock = LV.getVarInfo(A).DefInst->getParent();
176     
177     if (preorder[ABlock] < preorder[BBlock])
178       return true;
179     else if (preorder[ABlock] > preorder[BBlock])
180       return false;
181     
182     assert(0 && "Error sorting by dominance!");
183     return false;
184   }
185 };
186
187 /// computeDomForest - compute the subforest of the DomTree corresponding
188 /// to the defining blocks of the registers in question
189 std::vector<StrongPHIElimination::DomForestNode*>
190 StrongPHIElimination::computeDomForest(std::set<unsigned>& regs) {
191   LiveVariables& LV = getAnalysis<LiveVariables>();
192   
193   DomForestNode* VirtualRoot = new DomForestNode(0, 0);
194   maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
195   
196   std::vector<unsigned> worklist;
197   worklist.reserve(regs.size());
198   for (std::set<unsigned>::iterator I = regs.begin(), E = regs.end();
199        I != E; ++I)
200     worklist.push_back(*I);
201   
202   PreorderSorter PS(preorder, LV);
203   std::sort(worklist.begin(), worklist.end(), PS);
204   
205   DomForestNode* CurrentParent = VirtualRoot;
206   std::vector<DomForestNode*> stack;
207   stack.push_back(VirtualRoot);
208   
209   for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
210        I != E; ++I) {
211     unsigned pre = preorder[LV.getVarInfo(*I).DefInst->getParent()];
212     MachineBasicBlock* parentBlock =
213       LV.getVarInfo(CurrentParent->getReg()).DefInst->getParent();
214     
215     while (pre > maxpreorder[parentBlock]) {
216       stack.pop_back();
217       CurrentParent = stack.back();
218       
219       parentBlock = LV.getVarInfo(CurrentParent->getReg()).DefInst->getParent();
220     }
221     
222     DomForestNode* child = new DomForestNode(*I, CurrentParent);
223     stack.push_back(child);
224     CurrentParent = child;
225   }
226   
227   std::vector<DomForestNode*> ret;
228   ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
229   return ret;
230 }
231
232 /// isLiveIn - helper method that determines, from a VarInfo, if a register
233 /// is live into a block
234 bool isLiveIn(LiveVariables::VarInfo& V, MachineBasicBlock* MBB) {
235   if (V.AliveBlocks.test(MBB->getNumber()))
236     return true;
237   
238   if (V.DefInst->getParent() != MBB &&
239       V.UsedBlocks.test(MBB->getNumber()))
240     return true;
241   
242   return false;
243 }
244
245 /// isLiveOut - help method that determines, from a VarInfo, if a register is
246 /// live out of a block.
247 bool isLiveOut(LiveVariables::VarInfo& V, MachineBasicBlock* MBB) {
248   if (MBB == V.DefInst->getParent() ||
249       V.UsedBlocks.test(MBB->getNumber())) {
250     for (std::vector<MachineInstr*>::iterator I = V.Kills.begin(), 
251          E = V.Kills.end(); I != E; ++I)
252       if ((*I)->getParent() == MBB)
253         return false;
254     
255     return true;
256   }
257   
258   return false;
259 }
260
261 /// processBlock - Eliminate PHIs in the given block
262 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
263   LiveVariables& LV = getAnalysis<LiveVariables>();
264   
265   // Holds names that have been added to a set in any PHI within this block
266   // before the current one.
267   std::set<unsigned> ProcessedNames;
268   
269   MachineBasicBlock::iterator P = MBB->begin();
270   while (P->getOpcode() == TargetInstrInfo::PHI) {
271     LiveVariables::VarInfo& PHIInfo = LV.getVarInfo(P->getOperand(0).getReg());
272
273     unsigned DestReg = P->getOperand(0).getReg();
274
275     // Hold the names that are currently in the candidate set.
276     std::set<unsigned> PHIUnion;
277     std::set<MachineBasicBlock*> UnionedBlocks;
278   
279     for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
280       unsigned SrcReg = P->getOperand(i-1).getReg();
281       LiveVariables::VarInfo& SrcInfo = LV.getVarInfo(SrcReg);
282     
283       // Check for trivial interferences
284       if (isLiveIn(SrcInfo, P->getParent()) ||
285           isLiveOut(PHIInfo, SrcInfo.DefInst->getParent()) ||
286           ( PHIInfo.DefInst->getOpcode() == TargetInstrInfo::PHI &&
287             isLiveIn(PHIInfo, SrcInfo.DefInst->getParent()) ) ||
288           ProcessedNames.count(SrcReg) ||
289           UnionedBlocks.count(SrcInfo.DefInst->getParent())) {
290         
291         // add a copy from a_i to p in Waiting[From[a_i]]
292         MachineBasicBlock* From = P->getOperand(i).getMachineBasicBlock();
293         Waiting[From].push_back(std::make_pair(SrcReg, DestReg));
294       } else {
295         PHIUnion.insert(SrcReg);
296         UnionedBlocks.insert(SrcInfo.DefInst->getParent());
297       }
298     }
299     
300     std::vector<StrongPHIElimination::DomForestNode*> DF = 
301                                                      computeDomForest(PHIUnion);
302     
303     // Walk DomForest to resolve interferences
304     std::vector<std::pair<unsigned, unsigned> > localInterferences;
305     processPHIUnion(P, PHIUnion, DF, localInterferences);
306     
307     // FIXME: Check for local interferences
308     
309     ProcessedNames.insert(PHIUnion.begin(), PHIUnion.end());
310     ++P;
311   }
312 }
313
314 /// processPHIUnion - Take a set of candidate registers to be coallesced when
315 /// decomposing the PHI instruction.  Use the DominanceForest to remove the ones
316 /// that are known to interfere, and flag others that need to be checked for
317 /// local interferences.
318 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
319                                            std::set<unsigned>& PHIUnion,
320                         std::vector<StrongPHIElimination::DomForestNode*>& DF,
321                         std::vector<std::pair<unsigned, unsigned> >& locals) {
322   
323   std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
324   SmallPtrSet<DomForestNode*, 4> visited;
325   
326   LiveVariables& LV = getAnalysis<LiveVariables>();
327   unsigned DestReg = Inst->getOperand(0).getReg();
328   
329   // DF walk on the DomForest
330   while (!worklist.empty()) {
331     DomForestNode* DFNode = worklist.back();
332     
333     LiveVariables::VarInfo& Info = LV.getVarInfo(DFNode->getReg());
334     visited.insert(DFNode);
335     
336     bool inserted = false;
337     for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
338          CI != CE; ++CI) {
339       DomForestNode* child = *CI;   
340       LiveVariables::VarInfo& CInfo = LV.getVarInfo(child->getReg());
341         
342       if (isLiveOut(Info, CInfo.DefInst->getParent())) {
343         // Insert copies for parent
344         for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
345           if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
346             unsigned SrcReg = DFNode->getReg();
347             MachineBasicBlock* From = Inst->getOperand(i).getMBB();
348             
349             Waiting[From].push_back(std::make_pair(SrcReg, DestReg));
350             PHIUnion.erase(SrcReg);
351           }
352         }
353       } else if (isLiveIn(Info, CInfo.DefInst->getParent()) ||
354                  Info.DefInst->getParent() == CInfo.DefInst->getParent()) {
355         // Add (p, c) to possible local interferences
356         locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
357       }
358       
359       if (!visited.count(child)) {
360         worklist.push_back(child);
361         inserted = true;
362       }
363     }
364     
365     if (!inserted) worklist.pop_back();
366   }
367 }
368
369 /// breakCriticalEdges - Break critical edges coming into blocks with PHI
370 /// nodes, preserving dominator and livevariable info.
371 void StrongPHIElimination::breakCriticalEdges(MachineFunction &Fn) {
372   typedef std::pair<MachineBasicBlock*, MachineBasicBlock*> MBB_pair;
373   
374   MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
375   LiveVariables& LV = getAnalysis<LiveVariables>();
376   
377   // Find critical edges
378   std::vector<MBB_pair> criticals;
379   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
380     if (!I->empty() &&
381         I->begin()->getOpcode() == TargetInstrInfo::PHI &&
382         I->pred_size() > 1)
383       for (MachineBasicBlock::pred_iterator PI = I->pred_begin(),
384            PE = I->pred_end(); PI != PE; ++PI)
385         if ((*PI)->succ_size() > 1)
386           criticals.push_back(std::make_pair(*PI, I));
387   
388   for (std::vector<MBB_pair>::iterator I = criticals.begin(),
389        E = criticals.end(); I != E; ++I) {
390     // Split the edge
391     MachineBasicBlock* new_bb = SplitCriticalMachineEdge(I->first, I->second);
392     
393     // Update dominators
394     MDT.splitBlock(I->first);
395     
396     // Update livevariables
397     for (unsigned var = 1024; var < Fn.getSSARegMap()->getLastVirtReg(); ++var)
398       if (isLiveOut(LV.getVarInfo(var), I->first))
399         LV.getVarInfo(var).AliveBlocks.set(new_bb->getNumber());
400   }
401 }
402
403 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
404   breakCriticalEdges(Fn);
405   computeDFS(Fn);
406   
407   for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
408     if (!I->empty() &&
409         I->begin()->getOpcode() == TargetInstrInfo::PHI)
410       processBlock(I);
411   
412   return false;
413 }