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