Make LCSSA insert proper Phi nodes throughout the rest of the CFG by computing
[oota-llvm.git] / lib / Transforms / Utils / LCSSA.cpp
1 //===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Owen Anderson and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass transforms loops by placing phi nodes at the end of the loops for
11 // all values that are live across the loop boundary.  For example, it turns
12 // the left into the right code:
13 // 
14 // for (...)                for (...)
15 //   if (c)                   if(c)
16 //     X1 = ...                 X1 = ...
17 //   else                     else
18 //     X2 = ...                 X2 = ...
19 //   X3 = phi(X1, X2)         X3 = phi(X1, X2)
20 // ... = X3 + 4              X4 = phi(X3)
21 //                           ... = X4 + 4
22 //
23 // This is still valid LLVM; the extra phi nodes are purely redundant, and will
24 // be trivially eliminated by InstCombine.  The major benefit of this 
25 // transformation is that it makes many other loop optimizations, such as 
26 // LoopUnswitching, simpler.
27 //
28 //===----------------------------------------------------------------------===//
29
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Function.h"
33 #include "llvm/Instructions.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Analysis/Dominators.h"
36 #include "llvm/Analysis/LoopInfo.h"
37 #include "llvm/Support/CFG.h"
38 #include <algorithm>
39 #include <map>
40 #include <vector>
41
42 using namespace llvm;
43
44 namespace {
45   static Statistic<> NumLCSSA("lcssa", "Number of live out of a loop");
46   
47   class LCSSA : public FunctionPass {
48   public:
49     
50   
51     LoopInfo *LI;  // Loop information
52     DominatorTree *DT;       // Dominator Tree for the current Loop...
53     DominanceFrontier *DF;   // Current Dominance Frontier
54     
55     virtual bool runOnFunction(Function &F);
56     bool visitSubloop(Loop* L);
57     
58     /// This transformation requires natural loop information & requires that
59     /// loop preheaders be inserted into the CFG.  It maintains both of these,
60     /// as well as the CFG.  It also requires dominator information.
61     ///
62     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
63       AU.setPreservesCFG();
64       AU.addRequiredID(LoopSimplifyID);
65       AU.addPreservedID(LoopSimplifyID);
66       AU.addRequired<LoopInfo>();
67       AU.addPreserved<LoopInfo>();
68       AU.addRequired<DominatorTree>();
69       AU.addRequired<DominanceFrontier>();
70     }
71   private:
72     std::set<Instruction*> getLoopValuesUsedOutsideLoop(Loop *L,
73                                            std::vector<BasicBlock*> LoopBlocks);
74   };
75   
76   RegisterOpt<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass");
77 }
78
79 FunctionPass *llvm::createLCSSAPass() { return new LCSSA(); }
80
81 bool LCSSA::runOnFunction(Function &F) {
82   bool changed = false;
83   LI = &getAnalysis<LoopInfo>();
84   DF = &getAnalysis<DominanceFrontier>();
85   DT = &getAnalysis<DominatorTree>();
86     
87   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
88     changed |= visitSubloop(*I);
89   }
90       
91   return changed;
92 }
93
94 bool LCSSA::visitSubloop(Loop* L) {
95   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
96     visitSubloop(*I);
97   
98   // Speed up queries by creating a sorted list of blocks
99   std::vector<BasicBlock*> LoopBlocks(L->block_begin(), L->block_end());
100   std::sort(LoopBlocks.begin(), LoopBlocks.end());
101   
102   std::set<Instruction*> AffectedValues = getLoopValuesUsedOutsideLoop(L,
103                                            LoopBlocks);
104   
105   std::vector<BasicBlock*> exitBlocks;
106   L->getExitBlocks(exitBlocks);
107   
108   // Phi nodes that need to be IDF-processed
109   std::vector<PHINode*> workList;
110   
111   // Iterate over all affected values for this loop and insert Phi nodes
112   // for them in the appropriate exit blocks
113   for (std::set<Instruction*>::iterator I = AffectedValues.begin(),
114        E = AffectedValues.end(); I != E; ++I) {
115     ++NumLCSSA; // We are applying the transformation
116     for (std::vector<BasicBlock*>::iterator BBI = exitBlocks.begin(),
117          BBE = exitBlocks.end(); BBI != BBE; ++BBI) {
118       PHINode *phi = new PHINode((*I)->getType(), "lcssa");
119       (*BBI)->getInstList().insert((*BBI)->front(), phi);
120       workList.push_back(phi);
121     
122       // Since LoopSimplify has been run, we know that all of these predecessors
123       // are in the loop, so just hook them up in the obvious manner.
124       for (pred_iterator PI = pred_begin(*BBI), PE = pred_end(*BBI); PI != PE;
125            ++PI)
126         phi->addIncoming(*I, *PI);
127     }
128   }
129   
130   // Calculate the IDF of these LCSSA Phi nodes, inserting new Phi's where
131   // necessary.  Keep track of these new Phi's in DFPhis.
132   std::map<BasicBlock*, PHINode*> DFPhis;
133   for (std::vector<PHINode*>::iterator I = workList.begin(),
134        E = workList.end(); I != E; ++I) {
135     
136     // Get the current Phi's DF, and insert Phi nodes.  Add these new
137     // nodes to our worklist.
138     DominanceFrontier::const_iterator it = DF->find((*I)->getParent());
139     if (it != DF->end()) {
140       const DominanceFrontier::DomSetType &S = it->second;
141       for (DominanceFrontier::DomSetType::const_iterator P = S.begin(),
142              PE = S.end(); P != PE; ++P) {
143         if (DFPhis[*P] == 0) {
144           // Still doesn't have operands...
145           PHINode *phi = new PHINode((*I)->getType(), "lcssa");
146           (*P)->getInstList().insert((*P)->front(), phi);
147           DFPhis[*P] = phi;
148           
149           workList.push_back(phi);
150         }
151       }
152     }
153     
154     // Get the predecessor blocks of the current Phi, and use them to hook up
155     // the operands of the current Phi to any members of DFPhis that dominate
156     // it.  This is a nop for the Phis inserted directly in the exit blocks,
157     // since they are not dominated by any members of DFPhis.
158     for (pred_iterator PI = pred_begin((*I)->getParent()),
159          E = pred_end((*I)->getParent()); PI != E; ++PI)
160       for (std::map<BasicBlock*, PHINode*>::iterator MI = DFPhis.begin(),
161            ME = DFPhis.end(); MI != ME; ++MI)
162         if (DT->getNode((*MI).first)->dominates(DT->getNode(*PI))) {
163           (*I)->addIncoming((*MI).second, *PI);
164           
165           // Since dominate() is not cheap, don't do it more than we have to.
166           break;
167         }
168   }
169   
170   // FIXME: Should update all uses.
171   
172   return true; // FIXME: Should be more intelligent in our return value.
173 }
174
175 /// getLoopValuesUsedOutsideLoop - Return any values defined in the loop that
176 /// are used by instructions outside of it.
177 std::set<Instruction*> LCSSA::getLoopValuesUsedOutsideLoop(Loop *L, 
178                                          std::vector<BasicBlock*> LoopBlocks) {
179
180   std::set<Instruction*> AffectedValues;  
181   for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
182        BB != E; ++BB) {
183     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
184       for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
185            ++UI) {
186         BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
187         if (!std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), UserBB))
188           AffectedValues.insert(I);
189       }
190   }
191   return AffectedValues;
192 }