blob: f631b69f0a08d35688fd0e5382b346a305e6fd94 [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 Lattner15cad752003-12-23 07:47:09 +000017#define DEBUG_TYPE "indvar"
Chris Lattner022103b2002-05-07 20:03:00 +000018#include "llvm/Transforms/Scalar.h"
John Criswell47df12d2003-12-18 17:19:19 +000019#include "llvm/Constants.h"
20#include "llvm/Type.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000021#include "llvm/Instructions.h"
John Criswell47df12d2003-12-18 17:19:19 +000022#include "llvm/Analysis/InductionVariable.h"
23#include "llvm/Analysis/LoopInfo.h"
Chris Lattner455889a2002-02-12 22:39:50 +000024#include "llvm/Support/CFG.h"
Chris Lattner3324e712003-12-22 03:58:44 +000025#include "llvm/Target/TargetData.h"
John Criswell47df12d2003-12-18 17:19:19 +000026#include "llvm/Transforms/Utils/Local.h"
Chris Lattner6806f562003-08-01 22:15:03 +000027#include "Support/Debug.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000028#include "Support/Statistic.h"
John Criswell47df12d2003-12-18 17:19:19 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattner5e761402002-09-10 05:24:05 +000031namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000032 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
Chris Lattner3adf51d2003-09-10 05:24:46 +000033 Statistic<> NumInserted("indvars", "Number of canonical indvars added");
Chris Lattner3324e712003-12-22 03:58:44 +000034
35 class IndVarSimplify : public FunctionPass {
36 LoopInfo *Loops;
37 TargetData *TD;
Chris Lattner15cad752003-12-23 07:47:09 +000038 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000039 public:
40 virtual bool runOnFunction(Function &) {
41 Loops = &getAnalysis<LoopInfo>();
42 TD = &getAnalysis<TargetData>();
Chris Lattner15cad752003-12-23 07:47:09 +000043 Changed = false;
44
Chris Lattner3324e712003-12-22 03:58:44 +000045 // Induction Variables live in the header nodes of loops
Chris Lattner329c1c62004-01-08 00:09:44 +000046 for (LoopInfo::iterator I = Loops->begin(), E = Loops->end(); I != E; ++I)
47 runOnLoop(*I);
Chris Lattner3324e712003-12-22 03:58:44 +000048 return Changed;
49 }
50
51 unsigned getTypeSize(const Type *Ty) {
52 if (unsigned Size = Ty->getPrimitiveSize())
53 return Size;
54 return TD->getTypeSize(Ty); // Must be a pointer
55 }
56
Chris Lattner500597a2003-12-22 09:53:29 +000057 Value *ComputeAuxIndVarValue(InductionVariable &IV, Value *CIV);
58 void ReplaceIndVar(InductionVariable &IV, Value *Counter);
59
Chris Lattner15cad752003-12-23 07:47:09 +000060 void runOnLoop(Loop *L);
Chris Lattner3324e712003-12-22 03:58:44 +000061
62 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
63 AU.addRequired<TargetData>(); // Need pointer size
64 AU.addRequired<LoopInfo>();
65 AU.addRequiredID(LoopSimplifyID);
66 AU.addPreservedID(LoopSimplifyID);
67 AU.setPreservesCFG();
68 }
69 };
70 RegisterOpt<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
Chris Lattner5e761402002-09-10 05:24:05 +000071}
Chris Lattner394437f2001-12-04 04:32:29 +000072
Chris Lattner3324e712003-12-22 03:58:44 +000073Pass *llvm::createIndVarSimplifyPass() {
74 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +000075}
76
Chris Lattner3324e712003-12-22 03:58:44 +000077
Chris Lattner15cad752003-12-23 07:47:09 +000078void IndVarSimplify::runOnLoop(Loop *Loop) {
Chris Lattner6148c022001-12-03 17:28:42 +000079 // Transform all subloops before this loop...
Chris Lattner329c1c62004-01-08 00:09:44 +000080 for (LoopInfo::iterator I = Loop->begin(), E = Loop->end(); I != E; ++I)
81 runOnLoop(*I);
Chris Lattner3324e712003-12-22 03:58:44 +000082
Chris Lattner6148c022001-12-03 17:28:42 +000083 // Get the header node for this loop. All of the phi nodes that could be
84 // induction variables must live in this basic block.
Chris Lattner3dec1f22002-05-10 15:38:35 +000085 //
Chris Lattner3adf51d2003-09-10 05:24:46 +000086 BasicBlock *Header = Loop->getHeader();
Chris Lattner6148c022001-12-03 17:28:42 +000087
88 // Loop over all of the PHI nodes in the basic block, calculating the
89 // induction variables that they represent... stuffing the induction variable
90 // info into a vector...
91 //
Chris Lattner697954c2002-01-20 22:54:45 +000092 std::vector<InductionVariable> IndVars; // Induction variables for block
Chris Lattner7e708292002-06-25 16:13:24 +000093 BasicBlock::iterator AfterPHIIt = Header->begin();
Chris Lattnere408e252003-04-23 16:37:45 +000094 for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt)
Chris Lattner6148c022001-12-03 17:28:42 +000095 IndVars.push_back(InductionVariable(PN, Loops));
Misha Brukmancf00c4a2003-10-10 17:57:28 +000096 // AfterPHIIt now points to first non-phi instruction...
Chris Lattner6148c022001-12-03 17:28:42 +000097
Chris Lattner394437f2001-12-04 04:32:29 +000098 // If there are no phi nodes in this basic block, there can't be indvars...
Chris Lattner15cad752003-12-23 07:47:09 +000099 if (IndVars.empty()) return;
Chris Lattner6148c022001-12-03 17:28:42 +0000100
Chris Lattner3adf51d2003-09-10 05:24:46 +0000101 // Loop over the induction variables, looking for a canonical induction
Chris Lattner6148c022001-12-03 17:28:42 +0000102 // variable, and checking to make sure they are not all unknown induction
Chris Lattner3324e712003-12-22 03:58:44 +0000103 // variables. Keep track of the largest integer size of the induction
104 // variable.
Chris Lattner6148c022001-12-03 17:28:42 +0000105 //
Chris Lattner3adf51d2003-09-10 05:24:46 +0000106 InductionVariable *Canonical = 0;
Chris Lattner3324e712003-12-22 03:58:44 +0000107 unsigned MaxSize = 0;
108
109 for (unsigned i = 0; i != IndVars.size(); ++i) {
110 InductionVariable &IV = IndVars[i];
111
112 if (IV.InductionType != InductionVariable::Unknown) {
113 unsigned IVSize = getTypeSize(IV.Phi->getType());
114
115 if (IV.InductionType == InductionVariable::Canonical &&
116 !isa<PointerType>(IV.Phi->getType()) && IVSize >= MaxSize)
117 Canonical = &IV;
118
119 if (IVSize > MaxSize) MaxSize = IVSize;
120
121 // If this variable is larger than the currently identified canonical
122 // indvar, the canonical indvar is not usable.
123 if (Canonical && IVSize > getTypeSize(Canonical->Phi->getType()))
124 Canonical = 0;
125 }
Chris Lattner6148c022001-12-03 17:28:42 +0000126 }
127
Chris Lattner3adf51d2003-09-10 05:24:46 +0000128 // No induction variables, bail early... don't add a canonical indvar
Chris Lattner15cad752003-12-23 07:47:09 +0000129 if (MaxSize == 0) return;
130
131
132 // Figure out what the exit condition of the loop is. We can currently only
133 // handle loops with a single exit. If we cannot figure out what the
134 // termination condition is, we leave this variable set to null.
135 //
136 SetCondInst *TermCond = 0;
137 if (Loop->getExitBlocks().size() == 1) {
138 // Get ExitingBlock - the basic block in the loop which contains the branch
139 // out of the loop.
140 BasicBlock *Exit = Loop->getExitBlocks()[0];
141 pred_iterator PI = pred_begin(Exit);
142 assert(PI != pred_end(Exit) && "Should have one predecessor in loop!");
143 BasicBlock *ExitingBlock = *PI;
144 assert(++PI == pred_end(Exit) && "Exit block should have one pred!");
145 assert(Loop->isLoopExit(ExitingBlock) && "Exiting block is not loop exit!");
146
147 // Since the block is in the loop, yet branches out of it, we know that the
148 // block must end with multiple destination terminator. Which means it is
149 // either a conditional branch, a switch instruction, or an invoke.
150 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
151 assert(BI->isConditional() && "Unconditional branch has multiple succs?");
152 TermCond = dyn_cast<SetCondInst>(BI->getCondition());
153 } else {
154 // NOTE: if people actually exit loops with switch instructions, we could
155 // handle them, but I don't think this is important enough to spend time
156 // thinking about.
157 assert(isa<SwitchInst>(ExitingBlock->getTerminator()) ||
158 isa<InvokeInst>(ExitingBlock->getTerminator()) &&
159 "Unknown multi-successor terminator!");
160 }
161 }
162
163 if (TermCond)
164 DEBUG(std::cerr << "INDVAR: Found termination condition: " << *TermCond);
Chris Lattner6148c022001-12-03 17:28:42 +0000165
Chris Lattner3adf51d2003-09-10 05:24:46 +0000166 // Okay, we want to convert other induction variables to use a canonical
Chris Lattner6148c022001-12-03 17:28:42 +0000167 // indvar. If we don't have one, add one now...
Chris Lattner3adf51d2003-09-10 05:24:46 +0000168 if (!Canonical) {
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000169 // Create the PHI node for the new induction variable, and insert the phi
Chris Lattner332ae7f2003-09-23 20:26:48 +0000170 // node at the start of the PHI nodes...
Chris Lattner3324e712003-12-22 03:58:44 +0000171 const Type *IVType;
172 switch (MaxSize) {
173 default: assert(0 && "Unknown integer type size!");
174 case 1: IVType = Type::UByteTy; break;
175 case 2: IVType = Type::UShortTy; break;
176 case 4: IVType = Type::UIntTy; break;
177 case 8: IVType = Type::ULongTy; break;
178 }
179
180 PHINode *PN = new PHINode(IVType, "cann-indvar", Header->begin());
Chris Lattner394437f2001-12-04 04:32:29 +0000181
182 // Create the increment instruction to add one to the counter...
183 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
Chris Lattner3324e712003-12-22 03:58:44 +0000184 ConstantUInt::get(IVType, 1),
185 "next-indvar", AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +0000186
187 // Figure out which block is incoming and which is the backedge for the loop
188 BasicBlock *Incoming, *BackEdgeBlock;
Chris Lattner455889a2002-02-12 22:39:50 +0000189 pred_iterator PI = pred_begin(Header);
190 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner394437f2001-12-04 04:32:29 +0000191 if (Loop->contains(*PI)) { // First pred is back edge...
192 BackEdgeBlock = *PI++;
193 Incoming = *PI++;
194 } else {
195 Incoming = *PI++;
196 BackEdgeBlock = *PI++;
197 }
Chris Lattner455889a2002-02-12 22:39:50 +0000198 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner394437f2001-12-04 04:32:29 +0000199
200 // Add incoming values for the PHI node...
Chris Lattner3324e712003-12-22 03:58:44 +0000201 PN->addIncoming(Constant::getNullValue(IVType), Incoming);
Chris Lattner394437f2001-12-04 04:32:29 +0000202 PN->addIncoming(Add, BackEdgeBlock);
203
204 // Analyze the new induction variable...
205 IndVars.push_back(InductionVariable(PN, Loops));
Chris Lattner3adf51d2003-09-10 05:24:46 +0000206 assert(IndVars.back().InductionType == InductionVariable::Canonical &&
207 "Just inserted canonical indvar that is not canonical!");
208 Canonical = &IndVars.back();
Chris Lattner3dec1f22002-05-10 15:38:35 +0000209 ++NumInserted;
Chris Lattner4753bf22001-12-05 19:41:33 +0000210 Changed = true;
Chris Lattner15cad752003-12-23 07:47:09 +0000211 DEBUG(std::cerr << "INDVAR: Inserted canonical iv: " << *PN);
Chris Lattner332ae7f2003-09-23 20:26:48 +0000212 } else {
213 // If we have a canonical induction variable, make sure that it is the first
214 // one in the basic block.
215 if (&Header->front() != Canonical->Phi)
216 Header->getInstList().splice(Header->begin(), Header->getInstList(),
217 Canonical->Phi);
Chris Lattner15cad752003-12-23 07:47:09 +0000218 DEBUG(std::cerr << "IndVar: Existing canonical iv used: "
219 << *Canonical->Phi);
Chris Lattner394437f2001-12-04 04:32:29 +0000220 }
221
Chris Lattner15cad752003-12-23 07:47:09 +0000222 DEBUG(std::cerr << "INDVAR: Replacing Induction variables:\n");
Chris Lattner394437f2001-12-04 04:32:29 +0000223
224 // Get the current loop iteration count, which is always the value of the
Chris Lattner3adf51d2003-09-10 05:24:46 +0000225 // canonical phi node...
Chris Lattner394437f2001-12-04 04:32:29 +0000226 //
Chris Lattner3adf51d2003-09-10 05:24:46 +0000227 PHINode *IterCount = Canonical->Phi;
Chris Lattner394437f2001-12-04 04:32:29 +0000228
Chris Lattner3adf51d2003-09-10 05:24:46 +0000229 // Loop through and replace all of the auxiliary induction variables with
230 // references to the canonical induction variable...
Chris Lattner394437f2001-12-04 04:32:29 +0000231 //
Chris Lattner3324e712003-12-22 03:58:44 +0000232 for (unsigned i = 0; i != IndVars.size(); ++i) {
Chris Lattner394437f2001-12-04 04:32:29 +0000233 InductionVariable *IV = &IndVars[i];
Chris Lattnerf016ea42002-05-22 17:17:27 +0000234
Chris Lattnera59cbb22002-07-27 01:12:17 +0000235 DEBUG(IV->print(std::cerr));
Chris Lattnerf016ea42002-05-22 17:17:27 +0000236
Chris Lattner3adf51d2003-09-10 05:24:46 +0000237 // Don't modify the canonical indvar or unrecognized indvars...
238 if (IV != Canonical && IV->InductionType != InductionVariable::Unknown) {
Chris Lattner500597a2003-12-22 09:53:29 +0000239 ReplaceIndVar(*IV, IterCount);
Chris Lattner4753bf22001-12-05 19:41:33 +0000240 Changed = true;
Chris Lattner3dec1f22002-05-10 15:38:35 +0000241 ++NumRemoved;
Chris Lattner394437f2001-12-04 04:32:29 +0000242 }
Chris Lattner6148c022001-12-03 17:28:42 +0000243 }
Chris Lattner6148c022001-12-03 17:28:42 +0000244}
245
Chris Lattner500597a2003-12-22 09:53:29 +0000246/// ComputeAuxIndVarValue - Given an auxillary induction variable, compute and
247/// return a value which will always be equal to the induction variable PHI, but
248/// is based off of the canonical induction variable CIV.
249///
250Value *IndVarSimplify::ComputeAuxIndVarValue(InductionVariable &IV, Value *CIV){
251 Instruction *Phi = IV.Phi;
252 const Type *IVTy = Phi->getType();
253 if (isa<PointerType>(IVTy)) // If indexing into a pointer, make the
254 IVTy = TD->getIntPtrType(); // index the appropriate type.
255
256 BasicBlock::iterator AfterPHIIt = Phi;
257 while (isa<PHINode>(AfterPHIIt)) ++AfterPHIIt;
258
259 Value *Val = CIV;
260 if (Val->getType() != IVTy)
261 Val = new CastInst(Val, IVTy, Val->getName(), AfterPHIIt);
262
263 if (!isa<ConstantInt>(IV.Step) || // If the step != 1
264 !cast<ConstantInt>(IV.Step)->equalsInt(1)) {
265
266 // If the types are not compatible, insert a cast now...
267 if (IV.Step->getType() != IVTy)
268 IV.Step = new CastInst(IV.Step, IVTy, IV.Step->getName(), AfterPHIIt);
269
270 Val = BinaryOperator::create(Instruction::Mul, Val, IV.Step,
271 Phi->getName()+"-scale", AfterPHIIt);
272 }
273
274 // If this is a pointer indvar...
275 if (isa<PointerType>(Phi->getType())) {
276 std::vector<Value*> Idx;
277 // FIXME: this should not be needed when we fix PR82!
278 if (Val->getType() != Type::LongTy)
279 Val = new CastInst(Val, Type::LongTy, Val->getName(), AfterPHIIt);
280 Idx.push_back(Val);
281 Val = new GetElementPtrInst(IV.Start, Idx,
282 Phi->getName()+"-offset",
283 AfterPHIIt);
284
285 } else if (!isa<Constant>(IV.Start) || // If Start != 0...
286 !cast<Constant>(IV.Start)->isNullValue()) {
287 // If the types are not compatible, insert a cast now...
288 if (IV.Start->getType() != IVTy)
289 IV.Start = new CastInst(IV.Start, IVTy, IV.Start->getName(),
290 AfterPHIIt);
291
292 // Insert the instruction after the phi nodes...
293 Val = BinaryOperator::create(Instruction::Add, Val, IV.Start,
294 Phi->getName()+"-offset", AfterPHIIt);
295 }
296
297 // If the PHI node has a different type than val is, insert a cast now...
298 if (Val->getType() != Phi->getType())
299 Val = new CastInst(Val, Phi->getType(), Val->getName(), AfterPHIIt);
300
301 // Move the PHI name to it's new equivalent value...
302 std::string OldName = Phi->getName();
303 Phi->setName("");
304 Val->setName(OldName);
305
306 return Val;
307}
308
Chris Lattner500597a2003-12-22 09:53:29 +0000309// ReplaceIndVar - Replace all uses of the specified induction variable with
310// expressions computed from the specified loop iteration counter variable.
311// Return true if instructions were deleted.
312void IndVarSimplify::ReplaceIndVar(InductionVariable &IV, Value *CIV) {
313 Value *IndVarVal = 0;
314 PHINode *Phi = IV.Phi;
315
316 assert(Phi->getNumOperands() == 4 &&
317 "Only expect induction variables in canonical loops!");
318
319 // Remember the incoming values used by the PHI node
320 std::vector<Value*> PHIOps;
321 PHIOps.reserve(2);
322 PHIOps.push_back(Phi->getIncomingValue(0));
323 PHIOps.push_back(Phi->getIncomingValue(1));
324
Chris Lattner15cad752003-12-23 07:47:09 +0000325 // Delete all of the operands of the PHI node... so that the to-be-deleted PHI
326 // node does not cause any expressions to be computed that would not otherwise
327 // be.
Chris Lattner500597a2003-12-22 09:53:29 +0000328 Phi->dropAllReferences();
329
330 // Now that we are rid of unneeded uses of the PHI node, replace any remaining
331 // ones with the appropriate code using the canonical induction variable.
332 while (!Phi->use_empty()) {
333 Instruction *U = cast<Instruction>(Phi->use_back());
334
335 // TODO: Perform LFTR here if possible
336 if (0) {
337
338 } else {
339 // Replace all uses of the old PHI node with the new computed value...
340 if (IndVarVal == 0)
341 IndVarVal = ComputeAuxIndVarValue(IV, CIV);
342 U->replaceUsesOfWith(Phi, IndVarVal);
343 }
344 }
345
346 // If the PHI is the last user of any instructions for computing PHI nodes
347 // that are irrelevant now, delete those instructions.
348 while (!PHIOps.empty()) {
349 Instruction *MaybeDead = dyn_cast<Instruction>(PHIOps.back());
350 PHIOps.pop_back();
351
352 if (MaybeDead && isInstructionTriviallyDead(MaybeDead) &&
353 (!isa<PHINode>(MaybeDead) ||
354 MaybeDead->getParent() != Phi->getParent())) {
355 PHIOps.insert(PHIOps.end(), MaybeDead->op_begin(),
356 MaybeDead->op_end());
357 MaybeDead->getParent()->getInstList().erase(MaybeDead);
358
359 // Erase any duplicates entries in the PHIOps list.
360 std::vector<Value*>::iterator It =
361 std::find(PHIOps.begin(), PHIOps.end(), MaybeDead);
362 while (It != PHIOps.end()) {
363 PHIOps.erase(It);
364 It = std::find(PHIOps.begin(), PHIOps.end(), MaybeDead);
365 }
366 }
367 }
368
369 // Delete the old, now unused, phi node...
370 Phi->getParent()->getInstList().erase(Phi);
371}
372