More cleanups. Also, add a special case for updating PHI nodes, and
[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 <cassert>
40 #include <map>
41 #include <vector>
42
43 using namespace llvm;
44
45 namespace {
46   static Statistic<> NumLCSSA("lcssa",
47                               "Number of live out of a loop variables");
48   
49   class LCSSA : public FunctionPass {
50   public:
51     
52   
53     LoopInfo *LI;  // Loop information
54     DominatorTree *DT;       // Dominator Tree for the current Loop...
55     DominanceFrontier *DF;   // Current Dominance Frontier
56     
57     virtual bool runOnFunction(Function &F);
58     bool visitSubloop(Loop* L);
59     void processInstruction(Instruction* Instr,
60                             const std::vector<BasicBlock*>& LoopBlocks,
61                             const std::vector<BasicBlock*>& exitBlocks);
62     
63     /// This transformation requires natural loop information & requires that
64     /// loop preheaders be inserted into the CFG.  It maintains both of these,
65     /// as well as the CFG.  It also requires dominator information.
66     ///
67     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68       AU.setPreservesCFG();
69       AU.addRequiredID(LoopSimplifyID);
70       AU.addPreservedID(LoopSimplifyID);
71       AU.addRequired<LoopInfo>();
72       AU.addPreserved<LoopInfo>();
73       AU.addRequired<DominatorTree>();
74       AU.addRequired<DominanceFrontier>();
75     }
76   private:
77     std::set<Instruction*> getLoopValuesUsedOutsideLoop(Loop *L,
78                                     const std::vector<BasicBlock*>& LoopBlocks);
79     Instruction *getValueDominatingBlock(BasicBlock *BB,
80                                    std::map<BasicBlock*, Instruction*> PotDoms);
81   };
82   
83   RegisterOpt<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass");
84 }
85
86 FunctionPass *llvm::createLCSSAPass() { return new LCSSA(); }
87
88 bool LCSSA::runOnFunction(Function &F) {
89   bool changed = false;
90   LI = &getAnalysis<LoopInfo>();
91   DF = &getAnalysis<DominanceFrontier>();
92   DT = &getAnalysis<DominatorTree>();
93     
94   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
95     changed |= visitSubloop(*I);
96   }
97       
98   return changed;
99 }
100
101 bool LCSSA::visitSubloop(Loop* L) {
102   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
103     visitSubloop(*I);
104   
105   // Speed up queries by creating a sorted list of blocks
106   std::vector<BasicBlock*> LoopBlocks(L->block_begin(), L->block_end());
107   std::sort(LoopBlocks.begin(), LoopBlocks.end());
108   
109   std::set<Instruction*> AffectedValues = getLoopValuesUsedOutsideLoop(L,
110                                            LoopBlocks);
111   
112   // If no values are affected, we can save a lot of work, since we know that
113   // nothing will be changed.
114   if (AffectedValues.empty())
115     return false;
116   
117   std::vector<BasicBlock*> exitBlocks;
118   L->getExitBlocks(exitBlocks);
119   
120   
121   // Iterate over all affected values for this loop and insert Phi nodes
122   // for them in the appropriate exit blocks
123   
124   for (std::set<Instruction*>::iterator I = AffectedValues.begin(),
125        E = AffectedValues.end(); I != E; ++I) {
126     processInstruction(*I, LoopBlocks, exitBlocks);
127   }
128   
129   return true; // FIXME: Should be more intelligent in our return value.
130 }
131
132 /// processInstruction - 
133 void LCSSA::processInstruction(Instruction* Instr,
134                                const std::vector<BasicBlock*>& LoopBlocks,
135                                const std::vector<BasicBlock*>& exitBlocks)
136 {
137   ++NumLCSSA; // We are applying the transformation
138   
139   std::map<BasicBlock*, Instruction*> Phis;
140   Phis[Instr->getParent()] = Instr;
141   
142   // Phi nodes that need to be IDF-processed
143   std::vector<PHINode*> workList;
144   
145   for (std::vector<BasicBlock*>::const_iterator BBI = exitBlocks.begin(),
146       BBE = exitBlocks.end(); BBI != BBE; ++BBI)
147     if (DT->getNode(Instr->getParent())->dominates(DT->getNode(*BBI))) {
148       PHINode *phi = new PHINode(Instr->getType(), "lcssa", (*BBI)->begin());
149       workList.push_back(phi);
150       Phis[*BBI] = phi;
151     }
152   
153   // Calculate the IDF of these LCSSA Phi nodes, inserting new Phi's where
154   // necessary.  Keep track of these new Phi's in Phis.
155   while (!workList.empty()) {
156     PHINode *CurPHI = workList.back();
157     workList.pop_back();
158     
159     // Get the current Phi's DF, and insert Phi nodes.  Add these new
160     // nodes to our worklist.
161     DominanceFrontier::const_iterator it = DF->find(CurPHI->getParent());
162     if (it != DF->end()) {
163       const DominanceFrontier::DomSetType &S = it->second;
164       for (DominanceFrontier::DomSetType::const_iterator P = S.begin(),
165            PE = S.end(); P != PE; ++P) {
166         if (Phis[*P] == 0) {
167           // Still doesn't have operands...
168           PHINode *phi = new PHINode(Instr->getType(), "lcssa", (*P)->begin());
169           Phis[*P] = phi;
170           
171           workList.push_back(phi);
172         }
173       }
174     }
175     
176     // Get the predecessor blocks of the current Phi, and use them to hook up
177     // the operands of the current Phi to any members of DFPhis that dominate
178     // it.  This is a nop for the Phis inserted directly in the exit blocks,
179     // since they are not dominated by any members of DFPhis.
180     for (pred_iterator PI = pred_begin(CurPHI->getParent()),
181          E = pred_end(CurPHI->getParent()); PI != E; ++PI)
182       CurPHI->addIncoming(getValueDominatingBlock(*PI, Phis),
183                           *PI);
184   }
185   
186   // Find all uses of the affected value, and replace them with the
187   // appropriate Phi.
188   std::vector<Instruction*> Uses;
189   for (Instruction::use_iterator UI = Instr->use_begin(), UE = Instr->use_end();
190        UI != UE; ++UI) {
191     Instruction* use = cast<Instruction>(*UI);
192     // Don't need to update uses within the loop body
193     if (!std::binary_search(LoopBlocks.begin(), LoopBlocks.end(),
194         use->getParent()) &&
195         !(std::binary_search(exitBlocks.begin(), exitBlocks.end(),
196         use->getParent()) && isa<PHINode>(use)))
197       Uses.push_back(use);
198   }
199   
200   // Deliberately remove the initial instruction from Phis set.
201   Phis.erase(Instr->getParent());
202   
203   for (std::vector<Instruction*>::iterator II = Uses.begin(), IE = Uses.end();
204        II != IE; ++II) {
205     if (PHINode* phi = dyn_cast<PHINode>(*II)) {
206       for (unsigned int i = 0; i < phi->getNumIncomingValues(); ++i) {
207         // FIXME: Replace a Phi entry if and only if the corresponding 
208         // predecessor is dominated.
209         Instruction* dominator = 
210                         getValueDominatingBlock(phi->getIncomingBlock(i), Phis);
211         
212         if (phi->getIncomingValue(i) == Instr)
213           phi->setIncomingValue(i, dominator);
214       }
215     } else {
216        (*II)->replaceUsesOfWith(Instr,
217                                 getValueDominatingBlock((*II)->getParent(),
218                                 Phis));
219     }
220   }
221 }
222
223 /// getLoopValuesUsedOutsideLoop - Return any values defined in the loop that
224 /// are used by instructions outside of it.
225 std::set<Instruction*> LCSSA::getLoopValuesUsedOutsideLoop(Loop *L, 
226                                    const std::vector<BasicBlock*>& LoopBlocks) {
227   
228   // FIXME: For large loops, we may be able to avoid a lot of use-scanning
229   // by using dominance information.  In particular, if a block does not
230   // dominate any of the loop exits, then none of the values defined in the
231   // block could be used outside the loop.
232   
233   std::set<Instruction*> AffectedValues;  
234   for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
235        BB != E; ++BB) {
236     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
237       for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
238            ++UI) {
239         BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
240         if (!std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), UserBB)) {
241           AffectedValues.insert(I);
242           break;
243         }
244       }
245   }
246   return AffectedValues;
247 }
248
249 Instruction *LCSSA::getValueDominatingBlock(BasicBlock *BB,
250                                   std::map<BasicBlock*, Instruction*> PotDoms) {
251   DominatorTree::Node* bbNode = DT->getNode(BB);
252   while (bbNode != 0) {
253     std::map<BasicBlock*, Instruction*>::iterator I =
254                                                PotDoms.find(bbNode->getBlock());
255     if (I != PotDoms.end()) {
256       return (*I).second;
257     }
258     bbNode = bbNode->getIDom();
259   }
260   
261   assert(0 && "No dominating value found.");
262   
263   return 0;
264 }