blob: 692fcacb7e3b2723334d9245d4e685c0c79a021b [file] [log] [blame]
Chris Lattner476e6df2001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
2//
3// InductionVariableSimplify - Transform induction variables in a program
4// to all use a single cannonical induction variable per loop.
5//
6//===----------------------------------------------------------------------===//
7
8#include "llvm/Transforms/Scalar/IndVarSimplify.h"
9#include "llvm/Analysis/InductionVariable.h"
10#include "llvm/Analysis/LoopInfo.h"
Chris Lattner476e6df2001-12-03 17:28:42 +000011#include "llvm/iPHINode.h"
Chris Lattner91daaab2001-12-04 04:32:29 +000012#include "llvm/iOther.h"
13#include "llvm/Type.h"
Chris Lattner60a65912002-02-12 21:07:25 +000014#include "llvm/BasicBlock.h"
Chris Lattner91daaab2001-12-04 04:32:29 +000015#include "llvm/ConstantVals.h"
Chris Lattner83d485b2002-02-12 22:39:50 +000016#include "llvm/Support/CFG.h"
Chris Lattner476e6df2001-12-03 17:28:42 +000017#include "Support/STLExtras.h"
18
Chris Lattner91daaab2001-12-04 04:32:29 +000019#if 0
20#define DEBUG
21#include "llvm/Analysis/Writer.h"
22#endif
23
24// InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
25// name...
26//
27static Instruction *InsertCast(Instruction *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 Val->getParent()->getInstList().insert(It, Cast);
32 return Cast;
33}
34
Chris Lattner476e6df2001-12-03 17:28:42 +000035static bool TransformLoop(cfg::LoopInfo *Loops, cfg::Loop *Loop) {
36 // Transform all subloops before this loop...
37 bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
38 Loop->getSubLoops().end(),
Chris Lattner7f74a562002-01-20 22:54:45 +000039 std::bind1st(std::ptr_fun(TransformLoop), Loops));
Chris Lattner476e6df2001-12-03 17:28:42 +000040 // Get the header node for this loop. All of the phi nodes that could be
41 // induction variables must live in this basic block.
42 BasicBlock *Header = (BasicBlock*)Loop->getBlocks().front();
43
44 // Loop over all of the PHI nodes in the basic block, calculating the
45 // induction variables that they represent... stuffing the induction variable
46 // info into a vector...
47 //
Chris Lattner7f74a562002-01-20 22:54:45 +000048 std::vector<InductionVariable> IndVars; // Induction variables for block
Chris Lattner476e6df2001-12-03 17:28:42 +000049 for (BasicBlock::iterator I = Header->begin();
50 PHINode *PN = dyn_cast<PHINode>(*I); ++I)
51 IndVars.push_back(InductionVariable(PN, Loops));
52
Chris Lattner91daaab2001-12-04 04:32:29 +000053 // If there are no phi nodes in this basic block, there can't be indvars...
Chris Lattner476e6df2001-12-03 17:28:42 +000054 if (IndVars.empty()) return Changed;
55
56 // Loop over the induction variables, looking for a cannonical induction
57 // variable, and checking to make sure they are not all unknown induction
58 // variables.
59 //
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 Cannonical = &IndVars[i];
65 if (IndVars[i].InductionType != InductionVariable::Unknown)
66 FoundIndVars = true;
67 }
68
69 // No induction variables, bail early... don't add a cannonnical indvar
70 if (!FoundIndVars) return Changed;
71
72 // Okay, we want to convert other induction variables to use a cannonical
73 // indvar. If we don't have one, add one now...
74 if (!Cannonical) {
Chris Lattner91daaab2001-12-04 04:32:29 +000075 // Create the PHI node for the new induction variable
76 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar");
Chris Lattner476e6df2001-12-03 17:28:42 +000077
Chris Lattner91daaab2001-12-04 04:32:29 +000078 // Insert the phi node at the end of the other phi nodes...
79 Header->getInstList().insert(Header->begin()+IndVars.size(), PN);
80
81 // Create the increment instruction to add one to the counter...
82 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
83 ConstantUInt::get(Type::UIntTy,1),
84 "add1-indvar");
85
86 // Insert the add instruction after all of the PHI nodes...
87 Header->getInstList().insert(Header->begin()+(IndVars.size()+1), Add);
88
89 // Figure out which block is incoming and which is the backedge for the loop
90 BasicBlock *Incoming, *BackEdgeBlock;
Chris Lattner83d485b2002-02-12 22:39:50 +000091 pred_iterator PI = pred_begin(Header);
92 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner91daaab2001-12-04 04:32:29 +000093 if (Loop->contains(*PI)) { // First pred is back edge...
94 BackEdgeBlock = *PI++;
95 Incoming = *PI++;
96 } else {
97 Incoming = *PI++;
98 BackEdgeBlock = *PI++;
99 }
Chris Lattner83d485b2002-02-12 22:39:50 +0000100 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner91daaab2001-12-04 04:32:29 +0000101
102 // Add incoming values for the PHI node...
103 PN->addIncoming(Constant::getNullConstant(Type::UIntTy), Incoming);
104 PN->addIncoming(Add, BackEdgeBlock);
105
106 // Analyze the new induction variable...
107 IndVars.push_back(InductionVariable(PN, Loops));
108 assert(IndVars.back().InductionType == InductionVariable::Cannonical &&
109 "Just inserted cannonical indvar that is not cannonical!");
110 Cannonical = &IndVars.back();
Chris Lattner67439402001-12-05 19:41:33 +0000111 Changed = true;
Chris Lattner91daaab2001-12-04 04:32:29 +0000112 }
113
114#ifdef DEBUG
115 cerr << "Induction variables:\n";
116#endif
117
118 // Get the current loop iteration count, which is always the value of the
119 // cannonical phi node...
120 //
121 PHINode *IterCount = Cannonical->Phi;
122
123 // Loop through and replace all of the auxillary induction variables with
124 // references to the primary induction variable...
125 //
126 unsigned InsertPos = IndVars.size();
127 for (unsigned i = 0; i < IndVars.size(); ++i) {
128 InductionVariable *IV = &IndVars[i];
129#ifdef DEBUG
130 cerr << IndVars[i];
131#endif
Chris Lattnerd23d7522001-12-04 08:13:06 +0000132 // Don't modify the cannonical indvar or unrecognized indvars...
133 if (IV != Cannonical && IV->InductionType != InductionVariable::Unknown) {
Chris Lattner91daaab2001-12-04 04:32:29 +0000134 Instruction *Val = IterCount;
135 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
136 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
Chris Lattner7f74a562002-01-20 22:54:45 +0000137 std::string Name; // Create a scale by the step value...
Chris Lattner91daaab2001-12-04 04:32:29 +0000138 if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-scale";
139
140 // If the types are not compatible, insert a cast now...
141 if (Val->getType() != IV->Step->getType())
142 Val = InsertCast(Val, IV->Step->getType(),
143 Header->begin()+InsertPos++);
144
145 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step, Name);
146 // Insert the phi node at the end of the other phi nodes...
147 Header->getInstList().insert(Header->begin()+InsertPos++, Val);
148 }
149
150 if (!isa<Constant>(IV->Start) || // If the start != 0
151 !cast<Constant>(IV->Start)->isNullValue()) {
Chris Lattner7f74a562002-01-20 22:54:45 +0000152 std::string Name; // Create a offset by the start value...
Chris Lattner91daaab2001-12-04 04:32:29 +0000153 if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-offset";
154
155 // If the types are not compatible, insert a cast now...
156 if (Val->getType() != IV->Start->getType())
157 Val = InsertCast(Val, IV->Start->getType(),
158 Header->begin()+InsertPos++);
159
160 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start, Name);
161 // Insert the phi node at the end of the other phi nodes...
162 Header->getInstList().insert(Header->begin()+InsertPos++, Val);
163 }
164
165 // If the PHI node has a different type than val is, insert a cast now...
166 if (Val->getType() != IV->Phi->getType())
167 Val = InsertCast(Val, IV->Phi->getType(),
168 Header->begin()+InsertPos++);
169
170 // Replace all uses of the old PHI node with the new computed value...
171 IV->Phi->replaceAllUsesWith(Val);
172
173 // Move the PHI name to it's new equivalent value...
Chris Lattner7f74a562002-01-20 22:54:45 +0000174 std::string OldName = IV->Phi->getName();
Chris Lattner91daaab2001-12-04 04:32:29 +0000175 IV->Phi->setName("");
176 Val->setName(OldName);
177
178 // Delete the old, now unused, phi node...
179 Header->getInstList().remove(IV->Phi);
180 delete IV->Phi;
181 InsertPos--; // Deleted an instr, decrement insert position
Chris Lattner67439402001-12-05 19:41:33 +0000182 Changed = true;
Chris Lattner91daaab2001-12-04 04:32:29 +0000183 }
Chris Lattner476e6df2001-12-03 17:28:42 +0000184 }
185
186 return Changed;
187}
188
Chris Lattnerd5d56782002-01-31 00:45:11 +0000189bool InductionVariableSimplify::doit(Method *M, cfg::LoopInfo &Loops) {
Chris Lattner476e6df2001-12-03 17:28:42 +0000190 // Induction Variables live in the header nodes of the loops of the method...
191 return reduce_apply_bool(Loops.getTopLevelLoops().begin(),
192 Loops.getTopLevelLoops().end(),
193 std::bind1st(std::ptr_fun(TransformLoop), &Loops));
194}
Chris Lattnerd5d56782002-01-31 00:45:11 +0000195
196bool InductionVariableSimplify::runOnMethod(Method *M) {
197 return doit(M, getAnalysis<cfg::LoopInfo>());
198}
199
200void InductionVariableSimplify::getAnalysisUsageInfo(Pass::AnalysisSet &Req,
201 Pass::AnalysisSet &Dest,
202 Pass::AnalysisSet &Prov) {
203 Req.push_back(cfg::LoopInfo::ID);
204}