blob: ac986eaac41e4bb43b316467198f27b81389d375 [file] [log] [blame]
Chris Lattner6148c022001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
John Criswellb576c942003-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 Lattner6148c022001-12-03 17:28:42 +00009//
Chris Lattnerc01ccfd2003-09-10 05:10:34 +000010// Guarantees that all loops with identifiable, linear, induction variables will
Chris Lattner3adf51d2003-09-10 05:24:46 +000011// be transformed to have a single, canonical, induction variable. After this
Chris Lattnerc01ccfd2003-09-10 05:10:34 +000012// pass runs, it guarantees the the first PHI node of the header block in the
Chris Lattner3adf51d2003-09-10 05:24:46 +000013// loop is the canonical induction variable if there is one.
Chris Lattner6148c022001-12-03 17:28:42 +000014//
15//===----------------------------------------------------------------------===//
16
Chris Lattner022103b2002-05-07 20:03:00 +000017#include "llvm/Transforms/Scalar.h"
John Criswell47df12d2003-12-18 17:19:19 +000018#include "llvm/Constants.h"
19#include "llvm/Type.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000020#include "llvm/Instructions.h"
John Criswell47df12d2003-12-18 17:19:19 +000021#include "llvm/Analysis/InductionVariable.h"
22#include "llvm/Analysis/LoopInfo.h"
Chris Lattner455889a2002-02-12 22:39:50 +000023#include "llvm/Support/CFG.h"
Chris Lattner3324e712003-12-22 03:58:44 +000024#include "llvm/Target/TargetData.h"
John Criswell47df12d2003-12-18 17:19:19 +000025#include "llvm/Transforms/Utils/Local.h"
Chris Lattner6806f562003-08-01 22:15:03 +000026#include "Support/Debug.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000027#include "Support/Statistic.h"
John Criswell47df12d2003-12-18 17:19:19 +000028using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000029
Chris Lattner5e761402002-09-10 05:24:05 +000030namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000031 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
Chris Lattner3adf51d2003-09-10 05:24:46 +000032 Statistic<> NumInserted("indvars", "Number of canonical indvars added");
Chris Lattner3324e712003-12-22 03:58:44 +000033
34 class IndVarSimplify : public FunctionPass {
35 LoopInfo *Loops;
36 TargetData *TD;
37 public:
38 virtual bool runOnFunction(Function &) {
39 Loops = &getAnalysis<LoopInfo>();
40 TD = &getAnalysis<TargetData>();
41
42 // Induction Variables live in the header nodes of loops
43 bool Changed = false;
44 for (unsigned i = 0, e = Loops->getTopLevelLoops().size(); i != e; ++i)
45 Changed |= runOnLoop(Loops->getTopLevelLoops()[i]);
46 return Changed;
47 }
48
49 unsigned getTypeSize(const Type *Ty) {
50 if (unsigned Size = Ty->getPrimitiveSize())
51 return Size;
52 return TD->getTypeSize(Ty); // Must be a pointer
53 }
54
55 bool runOnLoop(Loop *L);
56
57 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
58 AU.addRequired<TargetData>(); // Need pointer size
59 AU.addRequired<LoopInfo>();
60 AU.addRequiredID(LoopSimplifyID);
61 AU.addPreservedID(LoopSimplifyID);
62 AU.setPreservesCFG();
63 }
64 };
65 RegisterOpt<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
Chris Lattner5e761402002-09-10 05:24:05 +000066}
Chris Lattner394437f2001-12-04 04:32:29 +000067
Chris Lattner3324e712003-12-22 03:58:44 +000068Pass *llvm::createIndVarSimplifyPass() {
69 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +000070}
71
Chris Lattner3324e712003-12-22 03:58:44 +000072
73bool IndVarSimplify::runOnLoop(Loop *Loop) {
Chris Lattner6148c022001-12-03 17:28:42 +000074 // Transform all subloops before this loop...
Chris Lattner3324e712003-12-22 03:58:44 +000075 bool Changed = false;
76 for (unsigned i = 0, e = Loop->getSubLoops().size(); i != e; ++i)
77 Changed |= runOnLoop(Loop->getSubLoops()[i]);
78
Chris Lattner6148c022001-12-03 17:28:42 +000079 // Get the header node for this loop. All of the phi nodes that could be
80 // induction variables must live in this basic block.
Chris Lattner3dec1f22002-05-10 15:38:35 +000081 //
Chris Lattner3adf51d2003-09-10 05:24:46 +000082 BasicBlock *Header = Loop->getHeader();
Chris Lattner6148c022001-12-03 17:28:42 +000083
84 // Loop over all of the PHI nodes in the basic block, calculating the
85 // induction variables that they represent... stuffing the induction variable
86 // info into a vector...
87 //
Chris Lattner697954c2002-01-20 22:54:45 +000088 std::vector<InductionVariable> IndVars; // Induction variables for block
Chris Lattner7e708292002-06-25 16:13:24 +000089 BasicBlock::iterator AfterPHIIt = Header->begin();
Chris Lattnere408e252003-04-23 16:37:45 +000090 for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt)
Chris Lattner6148c022001-12-03 17:28:42 +000091 IndVars.push_back(InductionVariable(PN, Loops));
Misha Brukmancf00c4a2003-10-10 17:57:28 +000092 // AfterPHIIt now points to first non-phi instruction...
Chris Lattner6148c022001-12-03 17:28:42 +000093
Chris Lattner394437f2001-12-04 04:32:29 +000094 // If there are no phi nodes in this basic block, there can't be indvars...
Chris Lattner6148c022001-12-03 17:28:42 +000095 if (IndVars.empty()) return Changed;
96
Chris Lattner3adf51d2003-09-10 05:24:46 +000097 // Loop over the induction variables, looking for a canonical induction
Chris Lattner6148c022001-12-03 17:28:42 +000098 // variable, and checking to make sure they are not all unknown induction
Chris Lattner3324e712003-12-22 03:58:44 +000099 // variables. Keep track of the largest integer size of the induction
100 // variable.
Chris Lattner6148c022001-12-03 17:28:42 +0000101 //
Chris Lattner3adf51d2003-09-10 05:24:46 +0000102 InductionVariable *Canonical = 0;
Chris Lattner3324e712003-12-22 03:58:44 +0000103 unsigned MaxSize = 0;
104
105 for (unsigned i = 0; i != IndVars.size(); ++i) {
106 InductionVariable &IV = IndVars[i];
107
108 if (IV.InductionType != InductionVariable::Unknown) {
109 unsigned IVSize = getTypeSize(IV.Phi->getType());
110
111 if (IV.InductionType == InductionVariable::Canonical &&
112 !isa<PointerType>(IV.Phi->getType()) && IVSize >= MaxSize)
113 Canonical = &IV;
114
115 if (IVSize > MaxSize) MaxSize = IVSize;
116
117 // If this variable is larger than the currently identified canonical
118 // indvar, the canonical indvar is not usable.
119 if (Canonical && IVSize > getTypeSize(Canonical->Phi->getType()))
120 Canonical = 0;
121 }
Chris Lattner6148c022001-12-03 17:28:42 +0000122 }
123
Chris Lattner3adf51d2003-09-10 05:24:46 +0000124 // No induction variables, bail early... don't add a canonical indvar
Chris Lattner3324e712003-12-22 03:58:44 +0000125 if (MaxSize == 0) return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000126
Chris Lattner3adf51d2003-09-10 05:24:46 +0000127 // Okay, we want to convert other induction variables to use a canonical
Chris Lattner6148c022001-12-03 17:28:42 +0000128 // indvar. If we don't have one, add one now...
Chris Lattner3adf51d2003-09-10 05:24:46 +0000129 if (!Canonical) {
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000130 // Create the PHI node for the new induction variable, and insert the phi
Chris Lattner332ae7f2003-09-23 20:26:48 +0000131 // node at the start of the PHI nodes...
Chris Lattner3324e712003-12-22 03:58:44 +0000132 const Type *IVType;
133 switch (MaxSize) {
134 default: assert(0 && "Unknown integer type size!");
135 case 1: IVType = Type::UByteTy; break;
136 case 2: IVType = Type::UShortTy; break;
137 case 4: IVType = Type::UIntTy; break;
138 case 8: IVType = Type::ULongTy; break;
139 }
140
141 PHINode *PN = new PHINode(IVType, "cann-indvar", Header->begin());
Chris Lattner394437f2001-12-04 04:32:29 +0000142
143 // Create the increment instruction to add one to the counter...
144 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
Chris Lattner3324e712003-12-22 03:58:44 +0000145 ConstantUInt::get(IVType, 1),
146 "next-indvar", AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +0000147
148 // Figure out which block is incoming and which is the backedge for the loop
149 BasicBlock *Incoming, *BackEdgeBlock;
Chris Lattner455889a2002-02-12 22:39:50 +0000150 pred_iterator PI = pred_begin(Header);
151 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner394437f2001-12-04 04:32:29 +0000152 if (Loop->contains(*PI)) { // First pred is back edge...
153 BackEdgeBlock = *PI++;
154 Incoming = *PI++;
155 } else {
156 Incoming = *PI++;
157 BackEdgeBlock = *PI++;
158 }
Chris Lattner455889a2002-02-12 22:39:50 +0000159 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner394437f2001-12-04 04:32:29 +0000160
161 // Add incoming values for the PHI node...
Chris Lattner3324e712003-12-22 03:58:44 +0000162 PN->addIncoming(Constant::getNullValue(IVType), Incoming);
Chris Lattner394437f2001-12-04 04:32:29 +0000163 PN->addIncoming(Add, BackEdgeBlock);
164
165 // Analyze the new induction variable...
166 IndVars.push_back(InductionVariable(PN, Loops));
Chris Lattner3adf51d2003-09-10 05:24:46 +0000167 assert(IndVars.back().InductionType == InductionVariable::Canonical &&
168 "Just inserted canonical indvar that is not canonical!");
169 Canonical = &IndVars.back();
Chris Lattner3dec1f22002-05-10 15:38:35 +0000170 ++NumInserted;
Chris Lattner4753bf22001-12-05 19:41:33 +0000171 Changed = true;
Chris Lattner332ae7f2003-09-23 20:26:48 +0000172 } else {
173 // If we have a canonical induction variable, make sure that it is the first
174 // one in the basic block.
175 if (&Header->front() != Canonical->Phi)
176 Header->getInstList().splice(Header->begin(), Header->getInstList(),
177 Canonical->Phi);
Chris Lattner394437f2001-12-04 04:32:29 +0000178 }
179
Anand Shukla5ba99bd2002-06-25 21:07:58 +0000180 DEBUG(std::cerr << "Induction variables:\n");
Chris Lattner394437f2001-12-04 04:32:29 +0000181
182 // Get the current loop iteration count, which is always the value of the
Chris Lattner3adf51d2003-09-10 05:24:46 +0000183 // canonical phi node...
Chris Lattner394437f2001-12-04 04:32:29 +0000184 //
Chris Lattner3adf51d2003-09-10 05:24:46 +0000185 PHINode *IterCount = Canonical->Phi;
Chris Lattner394437f2001-12-04 04:32:29 +0000186
Chris Lattner3adf51d2003-09-10 05:24:46 +0000187 // Loop through and replace all of the auxiliary induction variables with
188 // references to the canonical induction variable...
Chris Lattner394437f2001-12-04 04:32:29 +0000189 //
Chris Lattner3324e712003-12-22 03:58:44 +0000190 for (unsigned i = 0; i != IndVars.size(); ++i) {
Chris Lattner394437f2001-12-04 04:32:29 +0000191 InductionVariable *IV = &IndVars[i];
Chris Lattnerf016ea42002-05-22 17:17:27 +0000192
Chris Lattnera59cbb22002-07-27 01:12:17 +0000193 DEBUG(IV->print(std::cerr));
Chris Lattnerf016ea42002-05-22 17:17:27 +0000194
John Criswell47df12d2003-12-18 17:19:19 +0000195 while (isa<PHINode>(AfterPHIIt)) ++AfterPHIIt;
196
Chris Lattner3adf51d2003-09-10 05:24:46 +0000197 // Don't modify the canonical indvar or unrecognized indvars...
198 if (IV != Canonical && IV->InductionType != InductionVariable::Unknown) {
Chris Lattner18b3c972003-12-22 05:02:01 +0000199 const Type *IVTy = IV->Phi->getType();
200 if (isa<PointerType>(IVTy)) // If indexing into a pointer, make the
201 IVTy = TD->getIntPtrType(); // index the appropriate type.
202
Chris Lattner394437f2001-12-04 04:32:29 +0000203 Instruction *Val = IterCount;
204 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
205 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
Chris Lattner394437f2001-12-04 04:32:29 +0000206
207 // If the types are not compatible, insert a cast now...
Chris Lattner5e761402002-09-10 05:24:05 +0000208 if (Val->getType() != IVTy)
Chris Lattner3324e712003-12-22 03:58:44 +0000209 Val = new CastInst(Val, IVTy, Val->getName(), AfterPHIIt);
Chris Lattner5e761402002-09-10 05:24:05 +0000210 if (IV->Step->getType() != IVTy)
Chris Lattner3324e712003-12-22 03:58:44 +0000211 IV->Step = new CastInst(IV->Step, IVTy, IV->Step->getName(),
212 AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +0000213
Chris Lattner5e761402002-09-10 05:24:05 +0000214 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step,
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000215 IV->Phi->getName()+"-scale", AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +0000216 }
217
Chris Lattner18b3c972003-12-22 05:02:01 +0000218 // If this is a pointer indvar...
219 if (isa<PointerType>(IV->Phi->getType())) {
220 std::vector<Value*> Idx;
221 // FIXME: this should not be needed when we fix PR82!
222 if (Val->getType() != Type::LongTy)
223 Val = new CastInst(Val, Type::LongTy, Val->getName(), AfterPHIIt);
224 Idx.push_back(Val);
225 Val = new GetElementPtrInst(IV->Start, Idx,
226 IV->Phi->getName()+"-offset",
227 AfterPHIIt);
228
229 } else if (!isa<Constant>(IV->Start) || // If Start != 0...
230 !cast<Constant>(IV->Start)->isNullValue()) {
Chris Lattner394437f2001-12-04 04:32:29 +0000231 // If the types are not compatible, insert a cast now...
Chris Lattner5e761402002-09-10 05:24:05 +0000232 if (Val->getType() != IVTy)
Chris Lattner3324e712003-12-22 03:58:44 +0000233 Val = new CastInst(Val, IVTy, Val->getName(), AfterPHIIt);
Chris Lattner5e761402002-09-10 05:24:05 +0000234 if (IV->Start->getType() != IVTy)
Chris Lattner3324e712003-12-22 03:58:44 +0000235 IV->Start = new CastInst(IV->Start, IVTy, IV->Start->getName(),
236 AfterPHIIt);
Chris Lattner18b3c972003-12-22 05:02:01 +0000237
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000238 // Insert the instruction after the phi nodes...
Chris Lattner5e761402002-09-10 05:24:05 +0000239 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start,
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000240 IV->Phi->getName()+"-offset", AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +0000241 }
242
243 // If the PHI node has a different type than val is, insert a cast now...
244 if (Val->getType() != IV->Phi->getType())
Chris Lattner3324e712003-12-22 03:58:44 +0000245 Val = new CastInst(Val, IV->Phi->getType(), Val->getName(), AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +0000246
247 // Replace all uses of the old PHI node with the new computed value...
248 IV->Phi->replaceAllUsesWith(Val);
249
250 // Move the PHI name to it's new equivalent value...
Chris Lattner697954c2002-01-20 22:54:45 +0000251 std::string OldName = IV->Phi->getName();
Chris Lattner394437f2001-12-04 04:32:29 +0000252 IV->Phi->setName("");
253 Val->setName(OldName);
254
John Criswell47df12d2003-12-18 17:19:19 +0000255 // Get the incoming values used by the PHI node
256 std::vector<Value*> PHIOps;
257 PHIOps.reserve(IV->Phi->getNumIncomingValues());
258 for (unsigned i = 0, e = IV->Phi->getNumIncomingValues(); i != e; ++i)
259 PHIOps.push_back(IV->Phi->getIncomingValue(i));
260
Chris Lattner394437f2001-12-04 04:32:29 +0000261 // Delete the old, now unused, phi node...
Chris Lattner7e708292002-06-25 16:13:24 +0000262 Header->getInstList().erase(IV->Phi);
Chris Lattnerba4f3f62003-12-10 18:06:47 +0000263
264 // If the PHI is the last user of any instructions for computing PHI nodes
265 // that are irrelevant now, delete those instructions.
266 while (!PHIOps.empty()) {
267 Instruction *MaybeDead = dyn_cast<Instruction>(PHIOps.back());
268 PHIOps.pop_back();
269
270 if (MaybeDead && isInstructionTriviallyDead(MaybeDead)) {
271 PHIOps.insert(PHIOps.end(), MaybeDead->op_begin(),
272 MaybeDead->op_end());
273 MaybeDead->getParent()->getInstList().erase(MaybeDead);
Chris Lattner9e45d2e2003-12-15 17:34:02 +0000274
275 // Erase any duplicates entries in the PHIOps list.
276 std::vector<Value*>::iterator It =
277 std::find(PHIOps.begin(), PHIOps.end(), MaybeDead);
278 while (It != PHIOps.end()) {
279 PHIOps.erase(It);
280 It = std::find(PHIOps.begin(), PHIOps.end(), MaybeDead);
281 }
Chris Lattner88369d22003-12-10 20:43:04 +0000282
283 // Erasing the instruction could invalidate the AfterPHI iterator!
284 AfterPHIIt = Header->begin();
Chris Lattnerba4f3f62003-12-10 18:06:47 +0000285 }
286 }
287
Chris Lattner4753bf22001-12-05 19:41:33 +0000288 Changed = true;
Chris Lattner3dec1f22002-05-10 15:38:35 +0000289 ++NumRemoved;
Chris Lattner394437f2001-12-04 04:32:29 +0000290 }
Chris Lattner6148c022001-12-03 17:28:42 +0000291 }
292
293 return Changed;
294}
295