blob: 7b1eb5d7327535c79f240beb8a012f530ef900ac [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
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +00008#include "llvm/Transforms/Scalar.h"
Chris Lattner476e6df2001-12-03 17:28:42 +00009#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 Lattnerca142372002-04-28 19:55:58 +000014#include "llvm/Constants.h"
Chris Lattner83d485b2002-02-12 22:39:50 +000015#include "llvm/Support/CFG.h"
Chris Lattner476e6df2001-12-03 17:28:42 +000016#include "Support/STLExtras.h"
Chris Lattner0b18c1d2002-05-10 15:38:35 +000017#include "Support/StatisticReporter.h"
18
19static Statistic<> NumRemoved ("indvars\t\t- Number of aux indvars removed");
20static Statistic<> NumInserted("indvars\t\t- Number of cannonical indvars added");
Chris Lattner476e6df2001-12-03 17:28:42 +000021
Chris Lattner91daaab2001-12-04 04:32:29 +000022#if 0
23#define DEBUG
24#include "llvm/Analysis/Writer.h"
25#endif
26
27// InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
28// name...
29//
30static Instruction *InsertCast(Instruction *Val, const Type *Ty,
31 BasicBlock::iterator It) {
32 Instruction *Cast = new CastInst(Val, Ty);
33 if (Val->hasName()) Cast->setName(Val->getName()+"-casted");
34 Val->getParent()->getInstList().insert(It, Cast);
35 return Cast;
36}
37
Chris Lattner78dd56f2002-04-28 16:21:30 +000038static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
Chris Lattner476e6df2001-12-03 17:28:42 +000039 // Transform all subloops before this loop...
40 bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
41 Loop->getSubLoops().end(),
Chris Lattner7f74a562002-01-20 22:54:45 +000042 std::bind1st(std::ptr_fun(TransformLoop), Loops));
Chris Lattner476e6df2001-12-03 17:28:42 +000043 // Get the header node for this loop. All of the phi nodes that could be
44 // induction variables must live in this basic block.
Chris Lattner0b18c1d2002-05-10 15:38:35 +000045 //
46 BasicBlock *Header = Loop->getBlocks().front();
Chris Lattner476e6df2001-12-03 17:28:42 +000047
48 // Loop over all of the PHI nodes in the basic block, calculating the
49 // induction variables that they represent... stuffing the induction variable
50 // info into a vector...
51 //
Chris Lattner7f74a562002-01-20 22:54:45 +000052 std::vector<InductionVariable> IndVars; // Induction variables for block
Chris Lattner476e6df2001-12-03 17:28:42 +000053 for (BasicBlock::iterator I = Header->begin();
54 PHINode *PN = dyn_cast<PHINode>(*I); ++I)
55 IndVars.push_back(InductionVariable(PN, Loops));
56
Chris Lattner91daaab2001-12-04 04:32:29 +000057 // If there are no phi nodes in this basic block, there can't be indvars...
Chris Lattner476e6df2001-12-03 17:28:42 +000058 if (IndVars.empty()) return Changed;
59
60 // Loop over the induction variables, looking for a cannonical induction
61 // variable, and checking to make sure they are not all unknown induction
62 // variables.
63 //
64 bool FoundIndVars = false;
65 InductionVariable *Cannonical = 0;
66 for (unsigned i = 0; i < IndVars.size(); ++i) {
67 if (IndVars[i].InductionType == InductionVariable::Cannonical)
68 Cannonical = &IndVars[i];
69 if (IndVars[i].InductionType != InductionVariable::Unknown)
70 FoundIndVars = true;
71 }
72
73 // No induction variables, bail early... don't add a cannonnical indvar
74 if (!FoundIndVars) return Changed;
75
76 // Okay, we want to convert other induction variables to use a cannonical
77 // indvar. If we don't have one, add one now...
78 if (!Cannonical) {
Chris Lattner91daaab2001-12-04 04:32:29 +000079 // Create the PHI node for the new induction variable
80 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar");
Chris Lattner476e6df2001-12-03 17:28:42 +000081
Chris Lattner91daaab2001-12-04 04:32:29 +000082 // Insert the phi node at the end of the other phi nodes...
83 Header->getInstList().insert(Header->begin()+IndVars.size(), PN);
84
85 // Create the increment instruction to add one to the counter...
86 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
87 ConstantUInt::get(Type::UIntTy,1),
88 "add1-indvar");
89
90 // Insert the add instruction after all of the PHI nodes...
91 Header->getInstList().insert(Header->begin()+(IndVars.size()+1), Add);
92
93 // Figure out which block is incoming and which is the backedge for the loop
94 BasicBlock *Incoming, *BackEdgeBlock;
Chris Lattner83d485b2002-02-12 22:39:50 +000095 pred_iterator PI = pred_begin(Header);
96 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner91daaab2001-12-04 04:32:29 +000097 if (Loop->contains(*PI)) { // First pred is back edge...
98 BackEdgeBlock = *PI++;
99 Incoming = *PI++;
100 } else {
101 Incoming = *PI++;
102 BackEdgeBlock = *PI++;
103 }
Chris Lattner83d485b2002-02-12 22:39:50 +0000104 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner91daaab2001-12-04 04:32:29 +0000105
106 // Add incoming values for the PHI node...
Chris Lattner2716b5e2002-04-27 02:25:14 +0000107 PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming);
Chris Lattner91daaab2001-12-04 04:32:29 +0000108 PN->addIncoming(Add, BackEdgeBlock);
109
110 // Analyze the new induction variable...
111 IndVars.push_back(InductionVariable(PN, Loops));
112 assert(IndVars.back().InductionType == InductionVariable::Cannonical &&
113 "Just inserted cannonical indvar that is not cannonical!");
114 Cannonical = &IndVars.back();
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000115 ++NumInserted;
Chris Lattner67439402001-12-05 19:41:33 +0000116 Changed = true;
Chris Lattner91daaab2001-12-04 04:32:29 +0000117 }
118
119#ifdef DEBUG
120 cerr << "Induction variables:\n";
121#endif
122
123 // Get the current loop iteration count, which is always the value of the
124 // cannonical phi node...
125 //
126 PHINode *IterCount = Cannonical->Phi;
127
128 // Loop through and replace all of the auxillary induction variables with
129 // references to the primary induction variable...
130 //
131 unsigned InsertPos = IndVars.size();
132 for (unsigned i = 0; i < IndVars.size(); ++i) {
133 InductionVariable *IV = &IndVars[i];
134#ifdef DEBUG
135 cerr << IndVars[i];
136#endif
Chris Lattnerd23d7522001-12-04 08:13:06 +0000137 // Don't modify the cannonical indvar or unrecognized indvars...
138 if (IV != Cannonical && IV->InductionType != InductionVariable::Unknown) {
Chris Lattner91daaab2001-12-04 04:32:29 +0000139 Instruction *Val = IterCount;
140 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
141 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
Chris Lattner7f74a562002-01-20 22:54:45 +0000142 std::string Name; // Create a scale by the step value...
Chris Lattner91daaab2001-12-04 04:32:29 +0000143 if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-scale";
144
145 // If the types are not compatible, insert a cast now...
146 if (Val->getType() != IV->Step->getType())
147 Val = InsertCast(Val, IV->Step->getType(),
148 Header->begin()+InsertPos++);
149
150 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step, Name);
151 // Insert the phi node at the end of the other phi nodes...
152 Header->getInstList().insert(Header->begin()+InsertPos++, Val);
153 }
154
155 if (!isa<Constant>(IV->Start) || // If the start != 0
156 !cast<Constant>(IV->Start)->isNullValue()) {
Chris Lattner7f74a562002-01-20 22:54:45 +0000157 std::string Name; // Create a offset by the start value...
Chris Lattner91daaab2001-12-04 04:32:29 +0000158 if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-offset";
159
160 // If the types are not compatible, insert a cast now...
161 if (Val->getType() != IV->Start->getType())
162 Val = InsertCast(Val, IV->Start->getType(),
163 Header->begin()+InsertPos++);
164
165 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start, Name);
166 // Insert the phi node at the end of the other phi nodes...
167 Header->getInstList().insert(Header->begin()+InsertPos++, Val);
168 }
169
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(),
173 Header->begin()+InsertPos++);
174
175 // Replace all uses of the old PHI node with the new computed value...
176 IV->Phi->replaceAllUsesWith(Val);
177
178 // Move the PHI name to it's new equivalent value...
Chris Lattner7f74a562002-01-20 22:54:45 +0000179 std::string OldName = IV->Phi->getName();
Chris Lattner91daaab2001-12-04 04:32:29 +0000180 IV->Phi->setName("");
181 Val->setName(OldName);
182
183 // Delete the old, now unused, phi node...
184 Header->getInstList().remove(IV->Phi);
185 delete IV->Phi;
186 InsertPos--; // Deleted an instr, decrement insert position
Chris Lattner67439402001-12-05 19:41:33 +0000187 Changed = true;
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000188 ++NumRemoved;
Chris Lattner91daaab2001-12-04 04:32:29 +0000189 }
Chris Lattner476e6df2001-12-03 17:28:42 +0000190 }
191
192 return Changed;
193}
194
Chris Lattner04805fa2002-02-26 21:46:54 +0000195namespace {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000196 struct InductionVariableSimplify : public FunctionPass {
Chris Lattner37104aa2002-04-29 14:57:45 +0000197 const char *getPassName() const {
198 return "Induction Variable Cannonicalize";
199 }
200
Chris Lattnerc8e66542002-04-27 06:56:12 +0000201 virtual bool runOnFunction(Function *F) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000202 LoopInfo &LI = getAnalysis<LoopInfo>();
203
204 // Induction Variables live in the header nodes of loops
205 return reduce_apply_bool(LI.getTopLevelLoops().begin(),
206 LI.getTopLevelLoops().end(),
207 std::bind1st(std::ptr_fun(TransformLoop), &LI));
Chris Lattner04805fa2002-02-26 21:46:54 +0000208 }
209
Chris Lattnerc8e66542002-04-27 06:56:12 +0000210 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner78dd56f2002-04-28 16:21:30 +0000211 AU.addRequired(LoopInfo::ID);
Chris Lattnerf12cc842002-04-28 21:27:06 +0000212 AU.preservesCFG();
Chris Lattner04805fa2002-02-26 21:46:54 +0000213 }
214 };
Chris Lattnerd5d56782002-01-31 00:45:11 +0000215}
216
Chris Lattner04805fa2002-02-26 21:46:54 +0000217Pass *createIndVarSimplifyPass() {
218 return new InductionVariableSimplify();
Chris Lattnerd5d56782002-01-31 00:45:11 +0000219}
Chris Lattner04805fa2002-02-26 21:46:54 +0000220