blob: ceb057d34592bf0094844a71597cd40ede3f897a [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
23// InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
24// name...
25//
26static 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);
31 return Cast;
32}
33
Chris Lattner78dd56f2002-04-28 16:21:30 +000034static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
Chris Lattner476e6df2001-12-03 17:28:42 +000035 // Transform all subloops before this loop...
36 bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
37 Loop->getSubLoops().end(),
Chris Lattner7f74a562002-01-20 22:54:45 +000038 std::bind1st(std::ptr_fun(TransformLoop), Loops));
Chris Lattner476e6df2001-12-03 17:28:42 +000039 // Get the header node for this loop. All of the phi nodes that could be
40 // induction variables must live in this basic block.
Chris Lattner0b18c1d2002-05-10 15:38:35 +000041 //
42 BasicBlock *Header = Loop->getBlocks().front();
Chris Lattner476e6df2001-12-03 17:28:42 +000043
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 Lattner113f4f42002-06-25 16:13:24 +000049 BasicBlock::iterator AfterPHIIt = Header->begin();
50 for (; PHINode *PN = dyn_cast<PHINode>(&*AfterPHIIt); ++AfterPHIIt)
Chris Lattner476e6df2001-12-03 17:28:42 +000051 IndVars.push_back(InductionVariable(PN, Loops));
Chris Lattner113f4f42002-06-25 16:13:24 +000052 // AfterPHIIt now points to first nonphi instruction...
Chris Lattner476e6df2001-12-03 17:28:42 +000053
Chris Lattner91daaab2001-12-04 04:32:29 +000054 // If there are no phi nodes in this basic block, there can't be indvars...
Chris Lattner476e6df2001-12-03 17:28:42 +000055 if (IndVars.empty()) return Changed;
56
57 // Loop over the induction variables, looking for a cannonical induction
58 // variable, and checking to make sure they are not all unknown induction
59 // variables.
60 //
61 bool FoundIndVars = false;
62 InductionVariable *Cannonical = 0;
63 for (unsigned i = 0; i < IndVars.size(); ++i) {
64 if (IndVars[i].InductionType == InductionVariable::Cannonical)
65 Cannonical = &IndVars[i];
66 if (IndVars[i].InductionType != InductionVariable::Unknown)
67 FoundIndVars = true;
68 }
69
70 // No induction variables, bail early... don't add a cannonnical indvar
71 if (!FoundIndVars) return Changed;
72
73 // Okay, we want to convert other induction variables to use a cannonical
74 // indvar. If we don't have one, add one now...
75 if (!Cannonical) {
Chris Lattner91daaab2001-12-04 04:32:29 +000076 // Create the PHI node for the new induction variable
77 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar");
Chris Lattner476e6df2001-12-03 17:28:42 +000078
Chris Lattner91daaab2001-12-04 04:32:29 +000079 // Insert the phi node at the end of the other phi nodes...
Chris Lattner113f4f42002-06-25 16:13:24 +000080 AfterPHIIt = ++Header->getInstList().insert(AfterPHIIt, PN);
Chris Lattner91daaab2001-12-04 04:32:29 +000081
82 // Create the increment instruction to add one to the counter...
83 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
84 ConstantUInt::get(Type::UIntTy,1),
85 "add1-indvar");
86
87 // Insert the add instruction after all of the PHI nodes...
Chris Lattner113f4f42002-06-25 16:13:24 +000088 Header->getInstList().insert(AfterPHIIt, Add);
Chris Lattner91daaab2001-12-04 04:32:29 +000089
90 // Figure out which block is incoming and which is the backedge for the loop
91 BasicBlock *Incoming, *BackEdgeBlock;
Chris Lattner83d485b2002-02-12 22:39:50 +000092 pred_iterator PI = pred_begin(Header);
93 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner91daaab2001-12-04 04:32:29 +000094 if (Loop->contains(*PI)) { // First pred is back edge...
95 BackEdgeBlock = *PI++;
96 Incoming = *PI++;
97 } else {
98 Incoming = *PI++;
99 BackEdgeBlock = *PI++;
100 }
Chris Lattner83d485b2002-02-12 22:39:50 +0000101 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner91daaab2001-12-04 04:32:29 +0000102
103 // Add incoming values for the PHI node...
Chris Lattner2716b5e2002-04-27 02:25:14 +0000104 PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming);
Chris Lattner91daaab2001-12-04 04:32:29 +0000105 PN->addIncoming(Add, BackEdgeBlock);
106
107 // Analyze the new induction variable...
108 IndVars.push_back(InductionVariable(PN, Loops));
109 assert(IndVars.back().InductionType == InductionVariable::Cannonical &&
110 "Just inserted cannonical indvar that is not cannonical!");
111 Cannonical = &IndVars.back();
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000112 ++NumInserted;
Chris Lattner67439402001-12-05 19:41:33 +0000113 Changed = true;
Chris Lattner91daaab2001-12-04 04:32:29 +0000114 }
115
Anand Shukla2bc64192002-06-25 21:07:58 +0000116 DEBUG(std::cerr << "Induction variables:\n");
Chris Lattner91daaab2001-12-04 04:32:29 +0000117
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 //
Chris Lattner91daaab2001-12-04 04:32:29 +0000126 for (unsigned i = 0; i < IndVars.size(); ++i) {
127 InductionVariable *IV = &IndVars[i];
Chris Lattner71cbd422002-05-22 17:17:27 +0000128
Chris Lattner26750072002-07-27 01:12:17 +0000129 DEBUG(IV->print(std::cerr));
Chris Lattner71cbd422002-05-22 17:17:27 +0000130
Chris Lattnerd23d7522001-12-04 08:13:06 +0000131 // Don't modify the cannonical indvar or unrecognized indvars...
132 if (IV != Cannonical && IV->InductionType != InductionVariable::Unknown) {
Chris Lattner91daaab2001-12-04 04:32:29 +0000133 Instruction *Val = IterCount;
134 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
135 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
Chris Lattner7f74a562002-01-20 22:54:45 +0000136 std::string Name; // Create a scale by the step value...
Chris Lattner91daaab2001-12-04 04:32:29 +0000137 if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-scale";
138
139 // If the types are not compatible, insert a cast now...
140 if (Val->getType() != IV->Step->getType())
Chris Lattner113f4f42002-06-25 16:13:24 +0000141 Val = InsertCast(Val, IV->Step->getType(), AfterPHIIt);
Chris Lattner91daaab2001-12-04 04:32:29 +0000142
143 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step, Name);
144 // Insert the phi node at the end of the other phi nodes...
Chris Lattner113f4f42002-06-25 16:13:24 +0000145 Header->getInstList().insert(AfterPHIIt, Val);
Chris Lattner91daaab2001-12-04 04:32:29 +0000146 }
147
148 if (!isa<Constant>(IV->Start) || // If the start != 0
149 !cast<Constant>(IV->Start)->isNullValue()) {
Chris Lattner7f74a562002-01-20 22:54:45 +0000150 std::string Name; // Create a offset by the start value...
Chris Lattner91daaab2001-12-04 04:32:29 +0000151 if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-offset";
152
153 // If the types are not compatible, insert a cast now...
154 if (Val->getType() != IV->Start->getType())
Chris Lattner113f4f42002-06-25 16:13:24 +0000155 Val = InsertCast(Val, IV->Start->getType(), AfterPHIIt);
Chris Lattner91daaab2001-12-04 04:32:29 +0000156
157 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start, Name);
158 // Insert the phi node at the end of the other phi nodes...
Chris Lattner113f4f42002-06-25 16:13:24 +0000159 Header->getInstList().insert(AfterPHIIt, Val);
Chris Lattner91daaab2001-12-04 04:32:29 +0000160 }
161
162 // If the PHI node has a different type than val is, insert a cast now...
163 if (Val->getType() != IV->Phi->getType())
Chris Lattner113f4f42002-06-25 16:13:24 +0000164 Val = InsertCast(Val, IV->Phi->getType(), AfterPHIIt);
Chris Lattner91daaab2001-12-04 04:32:29 +0000165
166 // Replace all uses of the old PHI node with the new computed value...
167 IV->Phi->replaceAllUsesWith(Val);
168
169 // Move the PHI name to it's new equivalent value...
Chris Lattner7f74a562002-01-20 22:54:45 +0000170 std::string OldName = IV->Phi->getName();
Chris Lattner91daaab2001-12-04 04:32:29 +0000171 IV->Phi->setName("");
172 Val->setName(OldName);
173
174 // Delete the old, now unused, phi node...
Chris Lattner113f4f42002-06-25 16:13:24 +0000175 Header->getInstList().erase(IV->Phi);
Chris Lattner67439402001-12-05 19:41:33 +0000176 Changed = true;
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000177 ++NumRemoved;
Chris Lattner91daaab2001-12-04 04:32:29 +0000178 }
Chris Lattner476e6df2001-12-03 17:28:42 +0000179 }
180
181 return Changed;
182}
183
Chris Lattner04805fa2002-02-26 21:46:54 +0000184namespace {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000185 struct InductionVariableSimplify : public FunctionPass {
Chris Lattner113f4f42002-06-25 16:13:24 +0000186 virtual bool runOnFunction(Function &) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000187 LoopInfo &LI = getAnalysis<LoopInfo>();
188
189 // Induction Variables live in the header nodes of loops
190 return reduce_apply_bool(LI.getTopLevelLoops().begin(),
191 LI.getTopLevelLoops().end(),
192 std::bind1st(std::ptr_fun(TransformLoop), &LI));
Chris Lattner04805fa2002-02-26 21:46:54 +0000193 }
194
Chris Lattnerc8e66542002-04-27 06:56:12 +0000195 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner78dd56f2002-04-28 16:21:30 +0000196 AU.addRequired(LoopInfo::ID);
Chris Lattnerf12cc842002-04-28 21:27:06 +0000197 AU.preservesCFG();
Chris Lattner04805fa2002-02-26 21:46:54 +0000198 }
199 };
Chris Lattnerc8b70922002-07-26 21:12:46 +0000200 RegisterOpt<InductionVariableSimplify> X("indvars",
Chris Lattnerb28b6802002-07-23 18:06:35 +0000201 "Cannonicalize Induction Variables");
Chris Lattnerd5d56782002-01-31 00:45:11 +0000202}
203
Chris Lattner04805fa2002-02-26 21:46:54 +0000204Pass *createIndVarSimplifyPass() {
205 return new InductionVariableSimplify();
Chris Lattnerd5d56782002-01-31 00:45:11 +0000206}