Fix bug: test/Regression/Transforms/InstCombine/2002-05-14-TouchDeletedInst.ll
[oota-llvm.git] / lib / Transforms / Scalar / IndVarSimplify.cpp
1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
2 //
3 // InductionVariableSimplify - Transform induction variables in a program
4 //   to all use a single cannonical induction variable per loop.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/Transforms/Scalar.h"
9 #include "llvm/Analysis/InductionVariable.h"
10 #include "llvm/Analysis/LoopInfo.h"
11 #include "llvm/iPHINode.h"
12 #include "llvm/iOther.h"
13 #include "llvm/Type.h"
14 #include "llvm/Constants.h"
15 #include "llvm/Support/CFG.h"
16 #include "Support/STLExtras.h"
17 #include "Support/StatisticReporter.h"
18
19 static Statistic<> NumRemoved ("indvars\t\t- Number of aux indvars removed");
20 static Statistic<> NumInserted("indvars\t\t- Number of cannonical indvars added");
21
22 #if 0
23 #define DEBUG
24 #include "llvm/Analysis/Writer.h"
25 #endif
26
27 // InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
28 // name...
29 //
30 static Instruction *InsertCast(Instruction *Val, const Type *Ty,
31                                BasicBlock::iterator It) {
32   Instruction *Cast = new CastInst(Val, Ty);
33   if (Val->hasName()) Cast->setName(Val->getName()+"-casted");
34   Val->getParent()->getInstList().insert(It, Cast);
35   return Cast;
36 }
37
38 static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
39   // Transform all subloops before this loop...
40   bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
41                                    Loop->getSubLoops().end(),
42                               std::bind1st(std::ptr_fun(TransformLoop), Loops));
43   // Get the header node for this loop.  All of the phi nodes that could be
44   // induction variables must live in this basic block.
45   //
46   BasicBlock *Header = Loop->getBlocks().front();
47   
48   // Loop over all of the PHI nodes in the basic block, calculating the
49   // induction variables that they represent... stuffing the induction variable
50   // info into a vector...
51   //
52   std::vector<InductionVariable> IndVars;    // Induction variables for block
53   for (BasicBlock::iterator I = Header->begin(); 
54        PHINode *PN = dyn_cast<PHINode>(*I); ++I)
55     IndVars.push_back(InductionVariable(PN, Loops));
56
57   // If there are no phi nodes in this basic block, there can't be indvars...
58   if (IndVars.empty()) return Changed;
59   
60   // Loop over the induction variables, looking for a cannonical induction
61   // variable, and checking to make sure they are not all unknown induction
62   // variables.
63   //
64   bool FoundIndVars = false;
65   InductionVariable *Cannonical = 0;
66   for (unsigned i = 0; i < IndVars.size(); ++i) {
67     if (IndVars[i].InductionType == InductionVariable::Cannonical)
68       Cannonical = &IndVars[i];
69     if (IndVars[i].InductionType != InductionVariable::Unknown)
70       FoundIndVars = true;
71   }
72
73   // No induction variables, bail early... don't add a cannonnical indvar
74   if (!FoundIndVars) return Changed;
75
76   // Okay, we want to convert other induction variables to use a cannonical
77   // indvar.  If we don't have one, add one now...
78   if (!Cannonical) {
79     // Create the PHI node for the new induction variable
80     PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar");
81
82     // Insert the phi node at the end of the other phi nodes...
83     Header->getInstList().insert(Header->begin()+IndVars.size(), PN);
84
85     // Create the increment instruction to add one to the counter...
86     Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
87                                               ConstantUInt::get(Type::UIntTy,1),
88                                               "add1-indvar");
89
90     // Insert the add instruction after all of the PHI nodes...
91     Header->getInstList().insert(Header->begin()+(IndVars.size()+1), Add);
92
93     // Figure out which block is incoming and which is the backedge for the loop
94     BasicBlock *Incoming, *BackEdgeBlock;
95     pred_iterator PI = pred_begin(Header);
96     assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
97     if (Loop->contains(*PI)) {  // First pred is back edge...
98       BackEdgeBlock = *PI++;
99       Incoming      = *PI++;
100     } else {
101       Incoming      = *PI++;
102       BackEdgeBlock = *PI++;
103     }
104     assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
105     
106     // Add incoming values for the PHI node...
107     PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming);
108     PN->addIncoming(Add, BackEdgeBlock);
109
110     // Analyze the new induction variable...
111     IndVars.push_back(InductionVariable(PN, Loops));
112     assert(IndVars.back().InductionType == InductionVariable::Cannonical &&
113            "Just inserted cannonical indvar that is not cannonical!");
114     Cannonical = &IndVars.back();
115     ++NumInserted;
116     Changed = true;
117   }
118
119 #ifdef DEBUG
120   cerr << "Induction variables:\n";
121 #endif
122
123   // Get the current loop iteration count, which is always the value of the
124   // cannonical phi node...
125   //
126   PHINode *IterCount = Cannonical->Phi;
127
128   // Loop through and replace all of the auxillary induction variables with
129   // references to the primary induction variable...
130   //
131   unsigned InsertPos = IndVars.size();
132   for (unsigned i = 0; i < IndVars.size(); ++i) {
133     InductionVariable *IV = &IndVars[i];
134 #ifdef DEBUG
135     cerr << IndVars[i];
136 #endif
137     // Don't modify the cannonical indvar or unrecognized indvars...
138     if (IV != Cannonical && IV->InductionType != InductionVariable::Unknown) {
139       Instruction *Val = IterCount;
140       if (!isa<ConstantInt>(IV->Step) ||   // If the step != 1
141           !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
142         std::string Name;   // Create a scale by the step value...
143         if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-scale";
144
145         // If the types are not compatible, insert a cast now...
146         if (Val->getType() != IV->Step->getType())
147           Val = InsertCast(Val, IV->Step->getType(),
148                            Header->begin()+InsertPos++);
149
150         Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step, Name);
151         // Insert the phi node at the end of the other phi nodes...
152         Header->getInstList().insert(Header->begin()+InsertPos++, Val);
153       }
154
155       if (!isa<Constant>(IV->Start) ||   // If the start != 0
156           !cast<Constant>(IV->Start)->isNullValue()) {
157         std::string Name;   // Create a offset by the start value...
158         if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-offset";
159
160         // If the types are not compatible, insert a cast now...
161         if (Val->getType() != IV->Start->getType())
162           Val = InsertCast(Val, IV->Start->getType(),
163                            Header->begin()+InsertPos++);
164
165         Val = BinaryOperator::create(Instruction::Add, Val, IV->Start, Name);
166         // Insert the phi node at the end of the other phi nodes...
167         Header->getInstList().insert(Header->begin()+InsertPos++, Val);
168       }
169
170       // If the PHI node has a different type than val is, insert a cast now...
171       if (Val->getType() != IV->Phi->getType())
172           Val = InsertCast(Val, IV->Phi->getType(),
173                            Header->begin()+InsertPos++);
174       
175       // Replace all uses of the old PHI node with the new computed value...
176       IV->Phi->replaceAllUsesWith(Val);
177
178       // Move the PHI name to it's new equivalent value...
179       std::string OldName = IV->Phi->getName();
180       IV->Phi->setName("");
181       Val->setName(OldName);
182
183       // Delete the old, now unused, phi node...
184       Header->getInstList().remove(IV->Phi);
185       delete IV->Phi;
186       InsertPos--;            // Deleted an instr, decrement insert position
187       Changed = true;
188       ++NumRemoved;
189     }
190   }
191
192   return Changed;
193 }
194
195 namespace {
196   struct InductionVariableSimplify : public FunctionPass {
197     const char *getPassName() const {
198       return "Induction Variable Cannonicalize";
199     }
200
201     virtual bool runOnFunction(Function *F) {
202       LoopInfo &LI = getAnalysis<LoopInfo>();
203
204       // Induction Variables live in the header nodes of loops
205       return reduce_apply_bool(LI.getTopLevelLoops().begin(),
206                                LI.getTopLevelLoops().end(),
207                                std::bind1st(std::ptr_fun(TransformLoop), &LI));
208     }
209     
210     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
211       AU.addRequired(LoopInfo::ID);
212       AU.preservesCFG();
213     }
214   };
215 }
216
217 Pass *createIndVarSimplifyPass() {
218   return new InductionVariableSimplify();
219 }
220