1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
15 //===----------------------------------------------------------------------===//
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"
30 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
31 Statistic<> NumInserted("indvars", "Number of canonical indvars added");
34 // InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
37 static Instruction *InsertCast(Value *Val, const Type *Ty,
38 Instruction *InsertBefore) {
39 return new CastInst(Val, Ty, Val->getName()+"-casted", InsertBefore);
42 static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
43 // Transform all subloops before this loop...
44 bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
45 Loop->getSubLoops().end(),
46 std::bind1st(std::ptr_fun(TransformLoop), Loops));
47 // Get the header node for this loop. All of the phi nodes that could be
48 // induction variables must live in this basic block.
50 BasicBlock *Header = Loop->getHeader();
52 // Loop over all of the PHI nodes in the basic block, calculating the
53 // induction variables that they represent... stuffing the induction variable
54 // info into a vector...
56 std::vector<InductionVariable> IndVars; // Induction variables for block
57 BasicBlock::iterator AfterPHIIt = Header->begin();
58 for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt)
59 IndVars.push_back(InductionVariable(PN, Loops));
60 // AfterPHIIt now points to first non-phi instruction...
62 // If there are no phi nodes in this basic block, there can't be indvars...
63 if (IndVars.empty()) return Changed;
65 // Loop over the induction variables, looking for a canonical induction
66 // variable, and checking to make sure they are not all unknown induction
69 bool FoundIndVars = false;
70 InductionVariable *Canonical = 0;
71 for (unsigned i = 0; i < IndVars.size(); ++i) {
72 if (IndVars[i].InductionType == InductionVariable::Canonical &&
73 !isa<PointerType>(IndVars[i].Phi->getType()))
74 Canonical = &IndVars[i];
75 if (IndVars[i].InductionType != InductionVariable::Unknown)
79 // No induction variables, bail early... don't add a canonical indvar
80 if (!FoundIndVars) return Changed;
82 // Okay, we want to convert other induction variables to use a canonical
83 // indvar. If we don't have one, add one now...
85 // Create the PHI node for the new induction variable, and insert the phi
86 // node at the start of the PHI nodes...
87 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar", Header->begin());
89 // Create the increment instruction to add one to the counter...
90 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
91 ConstantUInt::get(Type::UIntTy,1),
92 "add1-indvar", AfterPHIIt);
94 // Figure out which block is incoming and which is the backedge for the loop
95 BasicBlock *Incoming, *BackEdgeBlock;
96 pred_iterator PI = pred_begin(Header);
97 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
98 if (Loop->contains(*PI)) { // First pred is back edge...
99 BackEdgeBlock = *PI++;
103 BackEdgeBlock = *PI++;
105 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
107 // Add incoming values for the PHI node...
108 PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming);
109 PN->addIncoming(Add, BackEdgeBlock);
111 // Analyze the new induction variable...
112 IndVars.push_back(InductionVariable(PN, Loops));
113 assert(IndVars.back().InductionType == InductionVariable::Canonical &&
114 "Just inserted canonical indvar that is not canonical!");
115 Canonical = &IndVars.back();
119 // If we have a canonical induction variable, make sure that it is the first
120 // one in the basic block.
121 if (&Header->front() != Canonical->Phi)
122 Header->getInstList().splice(Header->begin(), Header->getInstList(),
126 DEBUG(std::cerr << "Induction variables:\n");
128 // Get the current loop iteration count, which is always the value of the
129 // canonical phi node...
131 PHINode *IterCount = Canonical->Phi;
133 // Loop through and replace all of the auxiliary induction variables with
134 // references to the canonical induction variable...
136 for (unsigned i = 0; i < IndVars.size(); ++i) {
137 InductionVariable *IV = &IndVars[i];
139 DEBUG(IV->print(std::cerr));
141 // Don't do math with pointers...
142 const Type *IVTy = IV->Phi->getType();
143 if (isa<PointerType>(IVTy)) IVTy = Type::ULongTy;
145 // Don't modify the canonical indvar or unrecognized indvars...
146 if (IV != Canonical && IV->InductionType != InductionVariable::Unknown) {
147 Instruction *Val = IterCount;
148 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
149 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
151 // If the types are not compatible, insert a cast now...
152 if (Val->getType() != IVTy)
153 Val = InsertCast(Val, IVTy, AfterPHIIt);
154 if (IV->Step->getType() != IVTy)
155 IV->Step = InsertCast(IV->Step, IVTy, AfterPHIIt);
157 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step,
158 IV->Phi->getName()+"-scale", AfterPHIIt);
162 if (IV->Start != Constant::getNullValue(IV->Start->getType())) {
163 // If the types are not compatible, insert a cast now...
164 if (Val->getType() != IVTy)
165 Val = InsertCast(Val, IVTy, AfterPHIIt);
166 if (IV->Start->getType() != IVTy)
167 IV->Start = InsertCast(IV->Start, IVTy, AfterPHIIt);
169 // Insert the instruction after the phi nodes...
170 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start,
171 IV->Phi->getName()+"-offset", AfterPHIIt);
174 // If the PHI node has a different type than val is, insert a cast now...
175 if (Val->getType() != IV->Phi->getType())
176 Val = InsertCast(Val, IV->Phi->getType(), AfterPHIIt);
178 // Replace all uses of the old PHI node with the new computed value...
179 IV->Phi->replaceAllUsesWith(Val);
181 // Move the PHI name to it's new equivalent value...
182 std::string OldName = IV->Phi->getName();
183 IV->Phi->setName("");
184 Val->setName(OldName);
186 // Delete the old, now unused, phi node...
187 Header->getInstList().erase(IV->Phi);
197 struct InductionVariableSimplify : public FunctionPass {
198 virtual bool runOnFunction(Function &) {
199 LoopInfo &LI = getAnalysis<LoopInfo>();
201 // Induction Variables live in the header nodes of loops
202 return reduce_apply_bool(LI.getTopLevelLoops().begin(),
203 LI.getTopLevelLoops().end(),
204 std::bind1st(std::ptr_fun(TransformLoop), &LI));
207 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
208 AU.addRequired<LoopInfo>();
209 AU.addRequiredID(LoopSimplifyID);
210 AU.setPreservesCFG();
213 RegisterOpt<InductionVariableSimplify> X("indvars",
214 "Canonicalize Induction Variables");
217 Pass *createIndVarSimplifyPass() {
218 return new InductionVariableSimplify();