blob: 954844be40092c50702fe45a22671b11d25690a5 [file] [log] [blame]
Chris Lattner476e6df2001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner476e6df2001-12-03 17:28:42 +00009//
Chris Lattner36257f02003-09-10 05:10:34 +000010// Guarantees that all loops with identifiable, linear, induction variables will
Chris Lattner4e621cd2003-09-10 05:24:46 +000011// be transformed to have a single, canonical, induction variable. After this
Chris Lattner36257f02003-09-10 05:10:34 +000012// pass runs, it guarantees the the first PHI node of the header block in the
Chris Lattner4e621cd2003-09-10 05:24:46 +000013// loop is the canonical induction variable if there is one.
Chris Lattner476e6df2001-12-03 17:28:42 +000014//
15//===----------------------------------------------------------------------===//
16
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000017#include "llvm/Transforms/Scalar.h"
John Criswellb22e9b42003-12-18 17:19:19 +000018#include "llvm/Constants.h"
19#include "llvm/Type.h"
John Criswell86a3a482003-12-18 16:43:17 +000020#include "llvm/iPHINode.h"
21#include "llvm/iOther.h"
John Criswellb22e9b42003-12-18 17:19:19 +000022#include "llvm/Analysis/InductionVariable.h"
23#include "llvm/Analysis/LoopInfo.h"
Chris Lattner83d485b2002-02-12 22:39:50 +000024#include "llvm/Support/CFG.h"
Chris Lattnerd3678bc2003-12-22 03:58:44 +000025#include "llvm/Target/TargetData.h"
John Criswellb22e9b42003-12-18 17:19:19 +000026#include "llvm/Transforms/Utils/Local.h"
Chris Lattner8abcd562003-08-01 22:15:03 +000027#include "Support/Debug.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000028#include "Support/Statistic.h"
John Criswellb22e9b42003-12-18 17:19:19 +000029using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000030
Chris Lattner4184bcc2002-09-10 05:24:05 +000031namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000032 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
Chris Lattner4e621cd2003-09-10 05:24:46 +000033 Statistic<> NumInserted("indvars", "Number of canonical indvars added");
Chris Lattnerd3678bc2003-12-22 03:58:44 +000034
35 class IndVarSimplify : public FunctionPass {
36 LoopInfo *Loops;
37 TargetData *TD;
38 public:
39 virtual bool runOnFunction(Function &) {
40 Loops = &getAnalysis<LoopInfo>();
41 TD = &getAnalysis<TargetData>();
42
43 // Induction Variables live in the header nodes of loops
44 bool Changed = false;
45 for (unsigned i = 0, e = Loops->getTopLevelLoops().size(); i != e; ++i)
46 Changed |= runOnLoop(Loops->getTopLevelLoops()[i]);
47 return Changed;
48 }
49
50 unsigned getTypeSize(const Type *Ty) {
51 if (unsigned Size = Ty->getPrimitiveSize())
52 return Size;
53 return TD->getTypeSize(Ty); // Must be a pointer
54 }
55
56 bool runOnLoop(Loop *L);
57
58 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59 AU.addRequired<TargetData>(); // Need pointer size
60 AU.addRequired<LoopInfo>();
61 AU.addRequiredID(LoopSimplifyID);
62 AU.addPreservedID(LoopSimplifyID);
63 AU.setPreservesCFG();
64 }
65 };
66 RegisterOpt<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
Chris Lattner4184bcc2002-09-10 05:24:05 +000067}
Chris Lattner91daaab2001-12-04 04:32:29 +000068
Chris Lattnerd3678bc2003-12-22 03:58:44 +000069Pass *llvm::createIndVarSimplifyPass() {
70 return new IndVarSimplify();
Chris Lattner91daaab2001-12-04 04:32:29 +000071}
72
Chris Lattnerd3678bc2003-12-22 03:58:44 +000073
74bool IndVarSimplify::runOnLoop(Loop *Loop) {
Chris Lattner476e6df2001-12-03 17:28:42 +000075 // Transform all subloops before this loop...
Chris Lattnerd3678bc2003-12-22 03:58:44 +000076 bool Changed = false;
77 for (unsigned i = 0, e = Loop->getSubLoops().size(); i != e; ++i)
78 Changed |= runOnLoop(Loop->getSubLoops()[i]);
79
Chris Lattner476e6df2001-12-03 17:28:42 +000080 // Get the header node for this loop. All of the phi nodes that could be
81 // induction variables must live in this basic block.
Chris Lattner0b18c1d2002-05-10 15:38:35 +000082 //
Chris Lattner4e621cd2003-09-10 05:24:46 +000083 BasicBlock *Header = Loop->getHeader();
Chris Lattner476e6df2001-12-03 17:28:42 +000084
85 // Loop over all of the PHI nodes in the basic block, calculating the
86 // induction variables that they represent... stuffing the induction variable
87 // info into a vector...
88 //
Chris Lattner7f74a562002-01-20 22:54:45 +000089 std::vector<InductionVariable> IndVars; // Induction variables for block
Chris Lattner113f4f42002-06-25 16:13:24 +000090 BasicBlock::iterator AfterPHIIt = Header->begin();
Chris Lattner889f6202003-04-23 16:37:45 +000091 for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt)
Chris Lattner476e6df2001-12-03 17:28:42 +000092 IndVars.push_back(InductionVariable(PN, Loops));
Misha Brukman8b2bd4e2003-10-10 17:57:28 +000093 // AfterPHIIt now points to first non-phi instruction...
Chris Lattner476e6df2001-12-03 17:28:42 +000094
Chris Lattner91daaab2001-12-04 04:32:29 +000095 // If there are no phi nodes in this basic block, there can't be indvars...
Chris Lattner476e6df2001-12-03 17:28:42 +000096 if (IndVars.empty()) return Changed;
97
Chris Lattner4e621cd2003-09-10 05:24:46 +000098 // Loop over the induction variables, looking for a canonical induction
Chris Lattner476e6df2001-12-03 17:28:42 +000099 // variable, and checking to make sure they are not all unknown induction
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000100 // variables. Keep track of the largest integer size of the induction
101 // variable.
Chris Lattner476e6df2001-12-03 17:28:42 +0000102 //
Chris Lattner4e621cd2003-09-10 05:24:46 +0000103 InductionVariable *Canonical = 0;
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000104 unsigned MaxSize = 0;
105
106 for (unsigned i = 0; i != IndVars.size(); ++i) {
107 InductionVariable &IV = IndVars[i];
108
109 if (IV.InductionType != InductionVariable::Unknown) {
110 unsigned IVSize = getTypeSize(IV.Phi->getType());
111
112 if (IV.InductionType == InductionVariable::Canonical &&
113 !isa<PointerType>(IV.Phi->getType()) && IVSize >= MaxSize)
114 Canonical = &IV;
115
116 if (IVSize > MaxSize) MaxSize = IVSize;
117
118 // If this variable is larger than the currently identified canonical
119 // indvar, the canonical indvar is not usable.
120 if (Canonical && IVSize > getTypeSize(Canonical->Phi->getType()))
121 Canonical = 0;
122 }
Chris Lattner476e6df2001-12-03 17:28:42 +0000123 }
124
Chris Lattner4e621cd2003-09-10 05:24:46 +0000125 // No induction variables, bail early... don't add a canonical indvar
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000126 if (MaxSize == 0) return Changed;
Chris Lattner476e6df2001-12-03 17:28:42 +0000127
Chris Lattner4e621cd2003-09-10 05:24:46 +0000128 // Okay, we want to convert other induction variables to use a canonical
Chris Lattner476e6df2001-12-03 17:28:42 +0000129 // indvar. If we don't have one, add one now...
Chris Lattner4e621cd2003-09-10 05:24:46 +0000130 if (!Canonical) {
Chris Lattner28a8d242002-09-10 17:04:02 +0000131 // Create the PHI node for the new induction variable, and insert the phi
Chris Lattner295b9072003-09-23 20:26:48 +0000132 // node at the start of the PHI nodes...
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000133 const Type *IVType;
134 switch (MaxSize) {
135 default: assert(0 && "Unknown integer type size!");
136 case 1: IVType = Type::UByteTy; break;
137 case 2: IVType = Type::UShortTy; break;
138 case 4: IVType = Type::UIntTy; break;
139 case 8: IVType = Type::ULongTy; break;
140 }
141
142 PHINode *PN = new PHINode(IVType, "cann-indvar", Header->begin());
Chris Lattner91daaab2001-12-04 04:32:29 +0000143
144 // Create the increment instruction to add one to the counter...
145 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000146 ConstantUInt::get(IVType, 1),
147 "next-indvar", AfterPHIIt);
Chris Lattner91daaab2001-12-04 04:32:29 +0000148
149 // Figure out which block is incoming and which is the backedge for the loop
150 BasicBlock *Incoming, *BackEdgeBlock;
Chris Lattner83d485b2002-02-12 22:39:50 +0000151 pred_iterator PI = pred_begin(Header);
152 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner91daaab2001-12-04 04:32:29 +0000153 if (Loop->contains(*PI)) { // First pred is back edge...
154 BackEdgeBlock = *PI++;
155 Incoming = *PI++;
156 } else {
157 Incoming = *PI++;
158 BackEdgeBlock = *PI++;
159 }
Chris Lattner83d485b2002-02-12 22:39:50 +0000160 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner91daaab2001-12-04 04:32:29 +0000161
162 // Add incoming values for the PHI node...
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000163 PN->addIncoming(Constant::getNullValue(IVType), Incoming);
Chris Lattner91daaab2001-12-04 04:32:29 +0000164 PN->addIncoming(Add, BackEdgeBlock);
165
166 // Analyze the new induction variable...
167 IndVars.push_back(InductionVariable(PN, Loops));
Chris Lattner4e621cd2003-09-10 05:24:46 +0000168 assert(IndVars.back().InductionType == InductionVariable::Canonical &&
169 "Just inserted canonical indvar that is not canonical!");
170 Canonical = &IndVars.back();
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000171 ++NumInserted;
Chris Lattner67439402001-12-05 19:41:33 +0000172 Changed = true;
Chris Lattner295b9072003-09-23 20:26:48 +0000173 } else {
174 // If we have a canonical induction variable, make sure that it is the first
175 // one in the basic block.
176 if (&Header->front() != Canonical->Phi)
177 Header->getInstList().splice(Header->begin(), Header->getInstList(),
178 Canonical->Phi);
Chris Lattner91daaab2001-12-04 04:32:29 +0000179 }
180
Anand Shukla2bc64192002-06-25 21:07:58 +0000181 DEBUG(std::cerr << "Induction variables:\n");
Chris Lattner91daaab2001-12-04 04:32:29 +0000182
183 // Get the current loop iteration count, which is always the value of the
Chris Lattner4e621cd2003-09-10 05:24:46 +0000184 // canonical phi node...
Chris Lattner91daaab2001-12-04 04:32:29 +0000185 //
Chris Lattner4e621cd2003-09-10 05:24:46 +0000186 PHINode *IterCount = Canonical->Phi;
Chris Lattner91daaab2001-12-04 04:32:29 +0000187
Chris Lattner4e621cd2003-09-10 05:24:46 +0000188 // Loop through and replace all of the auxiliary induction variables with
189 // references to the canonical induction variable...
Chris Lattner91daaab2001-12-04 04:32:29 +0000190 //
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000191 for (unsigned i = 0; i != IndVars.size(); ++i) {
Chris Lattner91daaab2001-12-04 04:32:29 +0000192 InductionVariable *IV = &IndVars[i];
Chris Lattner71cbd422002-05-22 17:17:27 +0000193
Chris Lattner26750072002-07-27 01:12:17 +0000194 DEBUG(IV->print(std::cerr));
Chris Lattner71cbd422002-05-22 17:17:27 +0000195
John Criswellb22e9b42003-12-18 17:19:19 +0000196 while (isa<PHINode>(AfterPHIIt)) ++AfterPHIIt;
197
Chris Lattner4184bcc2002-09-10 05:24:05 +0000198 // Don't do math with pointers...
199 const Type *IVTy = IV->Phi->getType();
200 if (isa<PointerType>(IVTy)) IVTy = Type::ULongTy;
201
Chris Lattner4e621cd2003-09-10 05:24:46 +0000202 // Don't modify the canonical indvar or unrecognized indvars...
203 if (IV != Canonical && IV->InductionType != InductionVariable::Unknown) {
Chris Lattner91daaab2001-12-04 04:32:29 +0000204 Instruction *Val = IterCount;
205 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
206 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
Chris Lattner91daaab2001-12-04 04:32:29 +0000207
208 // If the types are not compatible, insert a cast now...
Chris Lattner4184bcc2002-09-10 05:24:05 +0000209 if (Val->getType() != IVTy)
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000210 Val = new CastInst(Val, IVTy, Val->getName(), AfterPHIIt);
Chris Lattner4184bcc2002-09-10 05:24:05 +0000211 if (IV->Step->getType() != IVTy)
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000212 IV->Step = new CastInst(IV->Step, IVTy, IV->Step->getName(),
213 AfterPHIIt);
Chris Lattner91daaab2001-12-04 04:32:29 +0000214
Chris Lattner4184bcc2002-09-10 05:24:05 +0000215 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step,
Chris Lattner28a8d242002-09-10 17:04:02 +0000216 IV->Phi->getName()+"-scale", AfterPHIIt);
Chris Lattner91daaab2001-12-04 04:32:29 +0000217 }
218
Chris Lattner4184bcc2002-09-10 05:24:05 +0000219 // If the start != 0
220 if (IV->Start != Constant::getNullValue(IV->Start->getType())) {
Chris Lattner91daaab2001-12-04 04:32:29 +0000221 // If the types are not compatible, insert a cast now...
Chris Lattner4184bcc2002-09-10 05:24:05 +0000222 if (Val->getType() != IVTy)
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000223 Val = new CastInst(Val, IVTy, Val->getName(), AfterPHIIt);
Chris Lattner4184bcc2002-09-10 05:24:05 +0000224 if (IV->Start->getType() != IVTy)
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000225 IV->Start = new CastInst(IV->Start, IVTy, IV->Start->getName(),
226 AfterPHIIt);
Chris Lattner91daaab2001-12-04 04:32:29 +0000227
Chris Lattner28a8d242002-09-10 17:04:02 +0000228 // Insert the instruction after the phi nodes...
Chris Lattner4184bcc2002-09-10 05:24:05 +0000229 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start,
Chris Lattner28a8d242002-09-10 17:04:02 +0000230 IV->Phi->getName()+"-offset", AfterPHIIt);
Chris Lattner91daaab2001-12-04 04:32:29 +0000231 }
232
233 // If the PHI node has a different type than val is, insert a cast now...
234 if (Val->getType() != IV->Phi->getType())
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000235 Val = new CastInst(Val, IV->Phi->getType(), Val->getName(), AfterPHIIt);
Chris Lattner91daaab2001-12-04 04:32:29 +0000236
237 // Replace all uses of the old PHI node with the new computed value...
238 IV->Phi->replaceAllUsesWith(Val);
239
240 // Move the PHI name to it's new equivalent value...
Chris Lattner7f74a562002-01-20 22:54:45 +0000241 std::string OldName = IV->Phi->getName();
Chris Lattner91daaab2001-12-04 04:32:29 +0000242 IV->Phi->setName("");
243 Val->setName(OldName);
244
John Criswellb22e9b42003-12-18 17:19:19 +0000245 // Get the incoming values used by the PHI node
246 std::vector<Value*> PHIOps;
247 PHIOps.reserve(IV->Phi->getNumIncomingValues());
248 for (unsigned i = 0, e = IV->Phi->getNumIncomingValues(); i != e; ++i)
249 PHIOps.push_back(IV->Phi->getIncomingValue(i));
250
Chris Lattner91daaab2001-12-04 04:32:29 +0000251 // Delete the old, now unused, phi node...
Chris Lattner113f4f42002-06-25 16:13:24 +0000252 Header->getInstList().erase(IV->Phi);
Chris Lattnerccd9f3c2003-12-10 18:06:47 +0000253
254 // If the PHI is the last user of any instructions for computing PHI nodes
255 // that are irrelevant now, delete those instructions.
256 while (!PHIOps.empty()) {
257 Instruction *MaybeDead = dyn_cast<Instruction>(PHIOps.back());
258 PHIOps.pop_back();
259
260 if (MaybeDead && isInstructionTriviallyDead(MaybeDead)) {
261 PHIOps.insert(PHIOps.end(), MaybeDead->op_begin(),
262 MaybeDead->op_end());
263 MaybeDead->getParent()->getInstList().erase(MaybeDead);
Chris Lattner6c08bb82003-12-15 17:34:02 +0000264
265 // Erase any duplicates entries in the PHIOps list.
266 std::vector<Value*>::iterator It =
267 std::find(PHIOps.begin(), PHIOps.end(), MaybeDead);
268 while (It != PHIOps.end()) {
269 PHIOps.erase(It);
270 It = std::find(PHIOps.begin(), PHIOps.end(), MaybeDead);
271 }
Chris Lattner713907e2003-12-10 20:43:04 +0000272
273 // Erasing the instruction could invalidate the AfterPHI iterator!
274 AfterPHIIt = Header->begin();
Chris Lattnerccd9f3c2003-12-10 18:06:47 +0000275 }
276 }
277
Chris Lattner67439402001-12-05 19:41:33 +0000278 Changed = true;
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000279 ++NumRemoved;
Chris Lattner91daaab2001-12-04 04:32:29 +0000280 }
Chris Lattner476e6df2001-12-03 17:28:42 +0000281 }
282
283 return Changed;
284}
285