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/STLExtras.h"
17 #include "Support/StatisticReporter.h"
20 Statistic<> NumRemoved ("indvars\t\t- Number of aux indvars removed");
21 Statistic<> NumInserted("indvars\t\t- Number of cannonical indvars added");
24 // InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
27 static Instruction *InsertCast(Value *Val, const Type *Ty,
28 BasicBlock::iterator It) {
29 Instruction *Cast = new CastInst(Val, Ty);
30 if (Val->hasName()) Cast->setName(Val->getName()+"-casted");
31 It->getParent()->getInstList().insert(It, Cast);
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.
43 BasicBlock *Header = Loop->getBlocks().front();
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...
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 nonphi instruction...
55 // If there are no phi nodes in this basic block, there can't be indvars...
56 if (IndVars.empty()) return Changed;
58 // Loop over the induction variables, looking for a cannonical induction
59 // variable, and checking to make sure they are not all unknown induction
62 bool FoundIndVars = false;
63 InductionVariable *Cannonical = 0;
64 for (unsigned i = 0; i < IndVars.size(); ++i) {
65 if (IndVars[i].InductionType == InductionVariable::Cannonical &&
66 !isa<PointerType>(IndVars[i].Phi->getType()))
67 Cannonical = &IndVars[i];
68 if (IndVars[i].InductionType != InductionVariable::Unknown)
72 // No induction variables, bail early... don't add a cannonnical indvar
73 if (!FoundIndVars) return Changed;
75 // Okay, we want to convert other induction variables to use a cannonical
76 // indvar. If we don't have one, add one now...
78 // Create the PHI node for the new induction variable
79 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar");
81 // Insert the phi node at the end of the other phi nodes...
82 AfterPHIIt = ++Header->getInstList().insert(AfterPHIIt, PN);
84 // Create the increment instruction to add one to the counter...
85 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
86 ConstantUInt::get(Type::UIntTy,1),
89 // Insert the add instruction after all of the PHI nodes...
90 Header->getInstList().insert(AfterPHIIt, Add);
92 // Figure out which block is incoming and which is the backedge for the loop
93 BasicBlock *Incoming, *BackEdgeBlock;
94 pred_iterator PI = pred_begin(Header);
95 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
96 if (Loop->contains(*PI)) { // First pred is back edge...
97 BackEdgeBlock = *PI++;
101 BackEdgeBlock = *PI++;
103 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
105 // Add incoming values for the PHI node...
106 PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming);
107 PN->addIncoming(Add, BackEdgeBlock);
109 // Analyze the new induction variable...
110 IndVars.push_back(InductionVariable(PN, Loops));
111 assert(IndVars.back().InductionType == InductionVariable::Cannonical &&
112 "Just inserted cannonical indvar that is not cannonical!");
113 Cannonical = &IndVars.back();
118 DEBUG(std::cerr << "Induction variables:\n");
120 // Get the current loop iteration count, which is always the value of the
121 // cannonical phi node...
123 PHINode *IterCount = Cannonical->Phi;
125 // Loop through and replace all of the auxillary induction variables with
126 // references to the primary induction variable...
128 for (unsigned i = 0; i < IndVars.size(); ++i) {
129 InductionVariable *IV = &IndVars[i];
131 DEBUG(IV->print(std::cerr));
133 // Don't do math with pointers...
134 const Type *IVTy = IV->Phi->getType();
135 if (isa<PointerType>(IVTy)) IVTy = Type::ULongTy;
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)) {
143 // If the types are not compatible, insert a cast now...
144 if (Val->getType() != IVTy)
145 Val = InsertCast(Val, IVTy, AfterPHIIt);
146 if (IV->Step->getType() != IVTy)
147 IV->Step = InsertCast(IV->Step, IVTy, AfterPHIIt);
149 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step,
150 IV->Phi->getName()+"-scale");
151 // Insert the phi node at the end of the other phi nodes...
152 Header->getInstList().insert(AfterPHIIt, Val);
156 if (IV->Start != Constant::getNullValue(IV->Start->getType())) {
157 // If the types are not compatible, insert a cast now...
158 if (Val->getType() != IVTy)
159 Val = InsertCast(Val, IVTy, AfterPHIIt);
160 if (IV->Start->getType() != IVTy)
161 IV->Start = InsertCast(IV->Start, IVTy, AfterPHIIt);
163 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start,
164 IV->Phi->getName()+"-offset");
166 // Insert the phi node at the end of the other phi nodes...
167 Header->getInstList().insert(AfterPHIIt, Val);
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(), AfterPHIIt);
174 // Replace all uses of the old PHI node with the new computed value...
175 IV->Phi->replaceAllUsesWith(Val);
177 // Move the PHI name to it's new equivalent value...
178 std::string OldName = IV->Phi->getName();
179 IV->Phi->setName("");
180 Val->setName(OldName);
182 // Delete the old, now unused, phi node...
183 Header->getInstList().erase(IV->Phi);
193 struct InductionVariableSimplify : public FunctionPass {
194 virtual bool runOnFunction(Function &) {
195 LoopInfo &LI = getAnalysis<LoopInfo>();
197 // Induction Variables live in the header nodes of loops
198 return reduce_apply_bool(LI.getTopLevelLoops().begin(),
199 LI.getTopLevelLoops().end(),
200 std::bind1st(std::ptr_fun(TransformLoop), &LI));
203 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
204 AU.addRequired<LoopInfo>();
208 RegisterOpt<InductionVariableSimplify> X("indvars",
209 "Cannonicalize Induction Variables");
212 Pass *createIndVarSimplifyPass() {
213 return new InductionVariableSimplify();