1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
3 // InductionVariableSimplify - Transform induction variables in a program
4 // to all use a single cannonical induction variable per loop.
6 //===----------------------------------------------------------------------===//
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/Debug.h"
17 #include "Support/Statistic.h"
18 #include "Support/STLExtras.h"
21 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
22 Statistic<> NumInserted("indvars", "Number of cannonical indvars added");
25 // InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
28 static Instruction *InsertCast(Value *Val, const Type *Ty,
29 Instruction *InsertBefore) {
30 return new CastInst(Val, Ty, Val->getName()+"-casted", InsertBefore);
33 static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
34 // Transform all subloops before this loop...
35 bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
36 Loop->getSubLoops().end(),
37 std::bind1st(std::ptr_fun(TransformLoop), Loops));
38 // Get the header node for this loop. All of the phi nodes that could be
39 // induction variables must live in this basic block.
41 BasicBlock *Header = Loop->getBlocks().front();
43 // Loop over all of the PHI nodes in the basic block, calculating the
44 // induction variables that they represent... stuffing the induction variable
45 // info into a vector...
47 std::vector<InductionVariable> IndVars; // Induction variables for block
48 BasicBlock::iterator AfterPHIIt = Header->begin();
49 for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt)
50 IndVars.push_back(InductionVariable(PN, Loops));
51 // AfterPHIIt now points to first nonphi instruction...
53 // If there are no phi nodes in this basic block, there can't be indvars...
54 if (IndVars.empty()) return Changed;
56 // Loop over the induction variables, looking for a cannonical induction
57 // variable, and checking to make sure they are not all unknown induction
60 bool FoundIndVars = false;
61 InductionVariable *Cannonical = 0;
62 for (unsigned i = 0; i < IndVars.size(); ++i) {
63 if (IndVars[i].InductionType == InductionVariable::Cannonical &&
64 !isa<PointerType>(IndVars[i].Phi->getType()))
65 Cannonical = &IndVars[i];
66 if (IndVars[i].InductionType != InductionVariable::Unknown)
70 // No induction variables, bail early... don't add a cannonnical indvar
71 if (!FoundIndVars) return Changed;
73 // Okay, we want to convert other induction variables to use a cannonical
74 // indvar. If we don't have one, add one now...
76 // Create the PHI node for the new induction variable, and insert the phi
77 // node at the end of the other phi nodes...
78 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar", AfterPHIIt);
80 // Create the increment instruction to add one to the counter...
81 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
82 ConstantUInt::get(Type::UIntTy,1),
83 "add1-indvar", AfterPHIIt);
85 // Figure out which block is incoming and which is the backedge for the loop
86 BasicBlock *Incoming, *BackEdgeBlock;
87 pred_iterator PI = pred_begin(Header);
88 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
89 if (Loop->contains(*PI)) { // First pred is back edge...
90 BackEdgeBlock = *PI++;
94 BackEdgeBlock = *PI++;
96 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
98 // Add incoming values for the PHI node...
99 PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming);
100 PN->addIncoming(Add, BackEdgeBlock);
102 // Analyze the new induction variable...
103 IndVars.push_back(InductionVariable(PN, Loops));
104 assert(IndVars.back().InductionType == InductionVariable::Cannonical &&
105 "Just inserted cannonical indvar that is not cannonical!");
106 Cannonical = &IndVars.back();
111 DEBUG(std::cerr << "Induction variables:\n");
113 // Get the current loop iteration count, which is always the value of the
114 // cannonical phi node...
116 PHINode *IterCount = Cannonical->Phi;
118 // Loop through and replace all of the auxillary induction variables with
119 // references to the primary induction variable...
121 for (unsigned i = 0; i < IndVars.size(); ++i) {
122 InductionVariable *IV = &IndVars[i];
124 DEBUG(IV->print(std::cerr));
126 // Don't do math with pointers...
127 const Type *IVTy = IV->Phi->getType();
128 if (isa<PointerType>(IVTy)) IVTy = Type::ULongTy;
130 // Don't modify the cannonical indvar or unrecognized indvars...
131 if (IV != Cannonical && IV->InductionType != InductionVariable::Unknown) {
132 Instruction *Val = IterCount;
133 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
134 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
136 // If the types are not compatible, insert a cast now...
137 if (Val->getType() != IVTy)
138 Val = InsertCast(Val, IVTy, AfterPHIIt);
139 if (IV->Step->getType() != IVTy)
140 IV->Step = InsertCast(IV->Step, IVTy, AfterPHIIt);
142 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step,
143 IV->Phi->getName()+"-scale", AfterPHIIt);
147 if (IV->Start != Constant::getNullValue(IV->Start->getType())) {
148 // If the types are not compatible, insert a cast now...
149 if (Val->getType() != IVTy)
150 Val = InsertCast(Val, IVTy, AfterPHIIt);
151 if (IV->Start->getType() != IVTy)
152 IV->Start = InsertCast(IV->Start, IVTy, AfterPHIIt);
154 // Insert the instruction after the phi nodes...
155 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start,
156 IV->Phi->getName()+"-offset", AfterPHIIt);
159 // If the PHI node has a different type than val is, insert a cast now...
160 if (Val->getType() != IV->Phi->getType())
161 Val = InsertCast(Val, IV->Phi->getType(), AfterPHIIt);
163 // Replace all uses of the old PHI node with the new computed value...
164 IV->Phi->replaceAllUsesWith(Val);
166 // Move the PHI name to it's new equivalent value...
167 std::string OldName = IV->Phi->getName();
168 IV->Phi->setName("");
169 Val->setName(OldName);
171 // Delete the old, now unused, phi node...
172 Header->getInstList().erase(IV->Phi);
182 struct InductionVariableSimplify : public FunctionPass {
183 virtual bool runOnFunction(Function &) {
184 LoopInfo &LI = getAnalysis<LoopInfo>();
186 // Induction Variables live in the header nodes of loops
187 return reduce_apply_bool(LI.getTopLevelLoops().begin(),
188 LI.getTopLevelLoops().end(),
189 std::bind1st(std::ptr_fun(TransformLoop), &LI));
192 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
193 AU.addRequired<LoopInfo>();
194 AU.setPreservesCFG();
197 RegisterOpt<InductionVariableSimplify> X("indvars",
198 "Cannonicalize Induction Variables");
201 Pass *createIndVarSimplifyPass() {
202 return new InductionVariableSimplify();