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/IndVarSimplify.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"
20 #include "llvm/Analysis/Writer.h"
23 // InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
26 static Instruction *InsertCast(Instruction *Val, const Type *Ty,
27 BasicBlock::iterator It) {
28 Instruction *Cast = new CastInst(Val, Ty);
29 if (Val->hasName()) Cast->setName(Val->getName()+"-casted");
30 Val->getParent()->getInstList().insert(It, Cast);
34 static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
35 // Transform all subloops before this loop...
36 bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
37 Loop->getSubLoops().end(),
38 std::bind1st(std::ptr_fun(TransformLoop), Loops));
39 // Get the header node for this loop. All of the phi nodes that could be
40 // induction variables must live in this basic block.
41 BasicBlock *Header = (BasicBlock*)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 for (BasicBlock::iterator I = Header->begin();
49 PHINode *PN = dyn_cast<PHINode>(*I); ++I)
50 IndVars.push_back(InductionVariable(PN, Loops));
52 // If there are no phi nodes in this basic block, there can't be indvars...
53 if (IndVars.empty()) return Changed;
55 // Loop over the induction variables, looking for a cannonical induction
56 // variable, and checking to make sure they are not all unknown induction
59 bool FoundIndVars = false;
60 InductionVariable *Cannonical = 0;
61 for (unsigned i = 0; i < IndVars.size(); ++i) {
62 if (IndVars[i].InductionType == InductionVariable::Cannonical)
63 Cannonical = &IndVars[i];
64 if (IndVars[i].InductionType != InductionVariable::Unknown)
68 // No induction variables, bail early... don't add a cannonnical indvar
69 if (!FoundIndVars) return Changed;
71 // Okay, we want to convert other induction variables to use a cannonical
72 // indvar. If we don't have one, add one now...
74 // Create the PHI node for the new induction variable
75 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar");
77 // Insert the phi node at the end of the other phi nodes...
78 Header->getInstList().insert(Header->begin()+IndVars.size(), PN);
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),
85 // Insert the add instruction after all of the PHI nodes...
86 Header->getInstList().insert(Header->begin()+(IndVars.size()+1), Add);
88 // Figure out which block is incoming and which is the backedge for the loop
89 BasicBlock *Incoming, *BackEdgeBlock;
90 pred_iterator PI = pred_begin(Header);
91 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
92 if (Loop->contains(*PI)) { // First pred is back edge...
93 BackEdgeBlock = *PI++;
97 BackEdgeBlock = *PI++;
99 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
101 // Add incoming values for the PHI node...
102 PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming);
103 PN->addIncoming(Add, BackEdgeBlock);
105 // Analyze the new induction variable...
106 IndVars.push_back(InductionVariable(PN, Loops));
107 assert(IndVars.back().InductionType == InductionVariable::Cannonical &&
108 "Just inserted cannonical indvar that is not cannonical!");
109 Cannonical = &IndVars.back();
114 cerr << "Induction variables:\n";
117 // Get the current loop iteration count, which is always the value of the
118 // cannonical phi node...
120 PHINode *IterCount = Cannonical->Phi;
122 // Loop through and replace all of the auxillary induction variables with
123 // references to the primary induction variable...
125 unsigned InsertPos = IndVars.size();
126 for (unsigned i = 0; i < IndVars.size(); ++i) {
127 InductionVariable *IV = &IndVars[i];
131 // Don't modify the cannonical indvar or unrecognized indvars...
132 if (IV != Cannonical && IV->InductionType != InductionVariable::Unknown) {
133 Instruction *Val = IterCount;
134 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
135 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
136 std::string Name; // Create a scale by the step value...
137 if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-scale";
139 // If the types are not compatible, insert a cast now...
140 if (Val->getType() != IV->Step->getType())
141 Val = InsertCast(Val, IV->Step->getType(),
142 Header->begin()+InsertPos++);
144 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step, Name);
145 // Insert the phi node at the end of the other phi nodes...
146 Header->getInstList().insert(Header->begin()+InsertPos++, Val);
149 if (!isa<Constant>(IV->Start) || // If the start != 0
150 !cast<Constant>(IV->Start)->isNullValue()) {
151 std::string Name; // Create a offset by the start value...
152 if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-offset";
154 // If the types are not compatible, insert a cast now...
155 if (Val->getType() != IV->Start->getType())
156 Val = InsertCast(Val, IV->Start->getType(),
157 Header->begin()+InsertPos++);
159 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start, Name);
160 // Insert the phi node at the end of the other phi nodes...
161 Header->getInstList().insert(Header->begin()+InsertPos++, Val);
164 // If the PHI node has a different type than val is, insert a cast now...
165 if (Val->getType() != IV->Phi->getType())
166 Val = InsertCast(Val, IV->Phi->getType(),
167 Header->begin()+InsertPos++);
169 // Replace all uses of the old PHI node with the new computed value...
170 IV->Phi->replaceAllUsesWith(Val);
172 // Move the PHI name to it's new equivalent value...
173 std::string OldName = IV->Phi->getName();
174 IV->Phi->setName("");
175 Val->setName(OldName);
177 // Delete the old, now unused, phi node...
178 Header->getInstList().remove(IV->Phi);
180 InsertPos--; // Deleted an instr, decrement insert position
188 static bool doit(Function *M, LoopInfo &Loops) {
189 // Induction Variables live in the header nodes of the loops of the function
190 return reduce_apply_bool(Loops.getTopLevelLoops().begin(),
191 Loops.getTopLevelLoops().end(),
192 std::bind1st(std::ptr_fun(TransformLoop), &Loops));
197 struct InductionVariableSimplify : public FunctionPass {
198 const char *getPassName() const {
199 return "Induction Variable Cannonicalize";
202 virtual bool runOnFunction(Function *F) {
203 return doit(F, getAnalysis<LoopInfo>());
206 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
207 AU.addRequired(LoopInfo::ID);
213 Pass *createIndVarSimplifyPass() {
214 return new InductionVariableSimplify();