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