blob: 53d3ab5f048e999b6f433f635b059841377adbcc [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This transformation analyzes and transforms the induction variables (and
11// computations derived from them) into simpler forms suitable for subsequent
12// analysis and transformation.
13//
14// This transformation makes the following changes to each loop with an
15// identifiable induction variable:
16// 1. All loops are transformed to have a SINGLE canonical induction variable
17// which starts at zero and steps by one.
18// 2. The canonical induction variable is guaranteed to be the first PHI node
19// in the loop header block.
20// 3. Any pointer arithmetic recurrences are raised to use array subscripts.
21//
22// If the trip count of a loop is computable, this pass also makes the following
23// changes:
24// 1. The exit condition for the loop is canonicalized to compare the
25// induction value against the exit value. This turns loops like:
26// 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
27// 2. Any use outside of the loop of an expression derived from the indvar
28// is changed to compute the derived value outside of the loop, eliminating
29// the dependence on the exit value of the induction variable. If the only
30// purpose of the loop is to compute the exit value of some derived
31// expression, this transformation will make the loop dead.
32//
33// This transformation should be followed by strength reduction after all of the
34// desired loop transformations have been performed. Additionally, on targets
35// where it is profitable, the loop could be transformed to count down to zero
36// (the "do loop" optimization).
37//
38//===----------------------------------------------------------------------===//
39
40#define DEBUG_TYPE "indvars"
41#include "llvm/Transforms/Scalar.h"
42#include "llvm/BasicBlock.h"
43#include "llvm/Constants.h"
44#include "llvm/Instructions.h"
45#include "llvm/Type.h"
46#include "llvm/Analysis/ScalarEvolutionExpander.h"
47#include "llvm/Analysis/LoopInfo.h"
48#include "llvm/Analysis/LoopPass.h"
49#include "llvm/Support/CFG.h"
50#include "llvm/Support/Compiler.h"
51#include "llvm/Support/Debug.h"
52#include "llvm/Support/GetElementPtrTypeIterator.h"
53#include "llvm/Transforms/Utils/Local.h"
54#include "llvm/Support/CommandLine.h"
55#include "llvm/ADT/SmallVector.h"
Chris Lattnerb25465e2008-11-16 07:17:51 +000056#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000057#include "llvm/ADT/Statistic.h"
58using namespace llvm;
59
60STATISTIC(NumRemoved , "Number of aux indvars removed");
61STATISTIC(NumPointer , "Number of pointer indvars promoted");
62STATISTIC(NumInserted, "Number of canonical indvars added");
63STATISTIC(NumReplaced, "Number of exit values replaced");
64STATISTIC(NumLFTR , "Number of loop exit tests replaced");
65
66namespace {
67 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
68 LoopInfo *LI;
69 ScalarEvolution *SE;
70 bool Changed;
71 public:
72
73 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000074 IndVarSimplify() : LoopPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000075
76 bool runOnLoop(Loop *L, LPPassManager &LPM);
77 bool doInitialization(Loop *L, LPPassManager &LPM);
78 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patele6a8d482007-09-10 18:08:23 +000079 AU.addRequired<ScalarEvolution>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000080 AU.addRequiredID(LCSSAID);
81 AU.addRequiredID(LoopSimplifyID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082 AU.addRequired<LoopInfo>();
83 AU.addPreservedID(LoopSimplifyID);
84 AU.addPreservedID(LCSSAID);
85 AU.setPreservesCFG();
86 }
87
88 private:
89
90 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
Chris Lattnerb25465e2008-11-16 07:17:51 +000091 SmallPtrSet<Instruction*, 16> &DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000092 Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
93 SCEVExpander &RW);
Dan Gohmand8dc3bb2008-08-05 22:34:21 +000094 void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000095
Chris Lattnerb25465e2008-11-16 07:17:51 +000096 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
Devang Patelbda43802008-09-09 21:41:07 +000097
98 void OptimizeCanonicalIVType(Loop *L);
Devang Patelc8dac622008-11-17 21:32:02 +000099 void HandleFloatingPointIV(Loop *L, PHINode *PH,
100 SmallPtrSet<Instruction*, 16> &DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000101 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000102}
103
Dan Gohman089efff2008-05-13 00:00:25 +0000104char IndVarSimplify::ID = 0;
105static RegisterPass<IndVarSimplify>
106X("indvars", "Canonicalize Induction Variables");
107
Daniel Dunbar163555a2008-10-22 23:32:42 +0000108Pass *llvm::createIndVarSimplifyPass() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000109 return new IndVarSimplify();
110}
111
112/// DeleteTriviallyDeadInstructions - If any of the instructions is the
113/// specified set are trivially dead, delete them and see if this makes any of
114/// their operands subsequently dead.
115void IndVarSimplify::
Chris Lattnerb25465e2008-11-16 07:17:51 +0000116DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117 while (!Insts.empty()) {
118 Instruction *I = *Insts.begin();
Chris Lattnerb25465e2008-11-16 07:17:51 +0000119 Insts.erase(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120 if (isInstructionTriviallyDead(I)) {
121 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
122 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
123 Insts.insert(U);
124 SE->deleteValueFromRecords(I);
125 DOUT << "INDVARS: Deleting: " << *I;
126 I->eraseFromParent();
127 Changed = true;
128 }
129 }
130}
131
132
133/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
134/// recurrence. If so, change it into an integer recurrence, permitting
135/// analysis by the SCEV routines.
136void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
137 BasicBlock *Preheader,
Chris Lattnerb25465e2008-11-16 07:17:51 +0000138 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000139 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
140 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
141 unsigned BackedgeIdx = PreheaderIdx^1;
142 if (GetElementPtrInst *GEPI =
143 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
144 if (GEPI->getOperand(0) == PN) {
145 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
146 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
147
148 // Okay, we found a pointer recurrence. Transform this pointer
149 // recurrence into an integer recurrence. Compute the value that gets
150 // added to the pointer at every iteration.
151 Value *AddedVal = GEPI->getOperand(1);
152
153 // Insert a new integer PHI node into the top of the block.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000154 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
155 PN->getName()+".rec", PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
157
158 // Create the new add instruction.
Gabor Greifa645dd32008-05-16 19:29:10 +0000159 Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000160 GEPI->getName()+".rec", GEPI);
161 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
162
163 // Update the existing GEP to use the recurrence.
164 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
165
166 // Update the GEP to use the new recurrence we just inserted.
167 GEPI->setOperand(1, NewAdd);
168
169 // If the incoming value is a constant expr GEP, try peeling out the array
170 // 0 index if possible to make things simpler.
171 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
172 if (CE->getOpcode() == Instruction::GetElementPtr) {
173 unsigned NumOps = CE->getNumOperands();
174 assert(NumOps > 1 && "CE folding didn't work!");
175 if (CE->getOperand(NumOps-1)->isNullValue()) {
176 // Check to make sure the last index really is an array index.
177 gep_type_iterator GTI = gep_type_begin(CE);
178 for (unsigned i = 1, e = CE->getNumOperands()-1;
179 i != e; ++i, ++GTI)
180 /*empty*/;
181 if (isa<SequentialType>(*GTI)) {
182 // Pull the last index out of the constant expr GEP.
183 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
184 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
185 &CEIdxs[0],
186 CEIdxs.size());
David Greene393be882007-09-04 15:46:09 +0000187 Value *Idx[2];
188 Idx[0] = Constant::getNullValue(Type::Int32Ty);
189 Idx[1] = NewAdd;
Gabor Greifd6da1d02008-04-06 20:25:17 +0000190 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
David Greene393be882007-09-04 15:46:09 +0000191 NCE, Idx, Idx + 2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000192 GEPI->getName(), GEPI);
193 SE->deleteValueFromRecords(GEPI);
194 GEPI->replaceAllUsesWith(NGEPI);
195 GEPI->eraseFromParent();
196 GEPI = NGEPI;
197 }
198 }
199 }
200
201
202 // Finally, if there are any other users of the PHI node, we must
203 // insert a new GEP instruction that uses the pre-incremented version
204 // of the induction amount.
205 if (!PN->use_empty()) {
206 BasicBlock::iterator InsertPos = PN; ++InsertPos;
207 while (isa<PHINode>(InsertPos)) ++InsertPos;
208 Value *PreInc =
Gabor Greifd6da1d02008-04-06 20:25:17 +0000209 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
210 NewPhi, "", InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211 PreInc->takeName(PN);
212 PN->replaceAllUsesWith(PreInc);
213 }
214
215 // Delete the old PHI for sure, and the GEP if its otherwise unused.
216 DeadInsts.insert(PN);
217
218 ++NumPointer;
219 Changed = true;
220 }
221}
222
223/// LinearFunctionTestReplace - This method rewrites the exit condition of the
224/// loop to be a canonical != comparison against the incremented loop induction
225/// variable. This pass is able to rewrite the exit tests of any loop where the
226/// SCEV analysis can determine a loop-invariant trip count of the loop, which
227/// is actually a much broader range than just linear tests.
228///
229/// This method returns a "potentially dead" instruction whose computation chain
230/// should be deleted when convenient.
231Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
232 SCEV *IterationCount,
233 SCEVExpander &RW) {
234 // Find the exit block for the loop. We can currently only handle loops with
235 // a single exit.
Devang Patel02451fa2007-08-21 00:31:24 +0000236 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237 L->getExitBlocks(ExitBlocks);
238 if (ExitBlocks.size() != 1) return 0;
239 BasicBlock *ExitBlock = ExitBlocks[0];
240
241 // Make sure there is only one predecessor block in the loop.
242 BasicBlock *ExitingBlock = 0;
243 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
244 PI != PE; ++PI)
245 if (L->contains(*PI)) {
246 if (ExitingBlock == 0)
247 ExitingBlock = *PI;
248 else
249 return 0; // Multiple exits from loop to this block.
250 }
251 assert(ExitingBlock && "Loop info is broken");
252
253 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
254 return 0; // Can't rewrite non-branch yet
255 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
256 assert(BI->isConditional() && "Must be conditional to be part of loop!");
257
258 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
259
260 // If the exiting block is not the same as the backedge block, we must compare
261 // against the preincremented value, otherwise we prefer to compare against
262 // the post-incremented value.
263 BasicBlock *Header = L->getHeader();
264 pred_iterator HPI = pred_begin(Header);
265 assert(HPI != pred_end(Header) && "Loop with zero preds???");
266 if (!L->contains(*HPI)) ++HPI;
267 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
268 "No backedge in loop?");
269
270 SCEVHandle TripCount = IterationCount;
271 Value *IndVar;
272 if (*HPI == ExitingBlock) {
273 // The IterationCount expression contains the number of times that the
274 // backedge actually branches to the loop header. This is one less than the
275 // number of times the loop executes, so add one to it.
276 ConstantInt *OneC = ConstantInt::get(IterationCount->getType(), 1);
Dan Gohman89f85052007-10-22 18:31:58 +0000277 TripCount = SE->getAddExpr(IterationCount, SE->getConstant(OneC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278 IndVar = L->getCanonicalInductionVariableIncrement();
279 } else {
280 // We have to use the preincremented value...
281 IndVar = L->getCanonicalInductionVariable();
282 }
283
284 DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
285 << " IndVar = " << *IndVar << "\n";
286
287 // Expand the code for the iteration count into the preheader of the loop.
288 BasicBlock *Preheader = L->getLoopPreheader();
289 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator());
290
291 // Insert a new icmp_ne or icmp_eq instruction before the branch.
292 ICmpInst::Predicate Opcode;
293 if (L->contains(BI->getSuccessor(0)))
294 Opcode = ICmpInst::ICMP_NE;
295 else
296 Opcode = ICmpInst::ICMP_EQ;
297
298 Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
299 BI->setCondition(Cond);
300 ++NumLFTR;
301 Changed = true;
302 return PotentiallyDeadInst;
303}
304
305
306/// RewriteLoopExitValues - Check to see if this loop has a computable
307/// loop-invariant execution count. If so, this means that we can compute the
308/// final value of any expressions that are recurrent in the loop, and
309/// substitute the exit values from the loop into any instructions outside of
310/// the loop that use the final values of the current expressions.
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000311void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312 BasicBlock *Preheader = L->getLoopPreheader();
313
314 // Scan all of the instructions in the loop, looking at those that have
315 // extra-loop users and which are recurrences.
316 SCEVExpander Rewriter(*SE, *LI);
317
318 // We insert the code into the preheader of the loop if the loop contains
319 // multiple exit blocks, or in the exit block if there is exactly one.
320 BasicBlock *BlockToInsertInto;
Devang Patel02451fa2007-08-21 00:31:24 +0000321 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000322 L->getUniqueExitBlocks(ExitBlocks);
323 if (ExitBlocks.size() == 1)
324 BlockToInsertInto = ExitBlocks[0];
325 else
326 BlockToInsertInto = Preheader;
Dan Gohman514277c2008-05-23 21:05:58 +0000327 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000328
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000329 bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330
Chris Lattnerb25465e2008-11-16 07:17:51 +0000331 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000332 std::map<Instruction*, Value*> ExitValues;
333
334 // Find all values that are computed inside the loop, but used outside of it.
335 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
336 // the exit blocks of the loop to find them.
337 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
338 BasicBlock *ExitBB = ExitBlocks[i];
339
340 // If there are no PHI nodes in this exit block, then no values defined
341 // inside the loop are used on this path, skip it.
342 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
343 if (!PN) continue;
344
345 unsigned NumPreds = PN->getNumIncomingValues();
346
347 // Iterate over all of the PHI nodes.
348 BasicBlock::iterator BBI = ExitBB->begin();
349 while ((PN = dyn_cast<PHINode>(BBI++))) {
350
351 // Iterate over all of the values in all the PHI nodes.
352 for (unsigned i = 0; i != NumPreds; ++i) {
353 // If the value being merged in is not integer or is not defined
354 // in the loop, skip it.
355 Value *InVal = PN->getIncomingValue(i);
356 if (!isa<Instruction>(InVal) ||
357 // SCEV only supports integer expressions for now.
358 !isa<IntegerType>(InVal->getType()))
359 continue;
360
361 // If this pred is for a subloop, not L itself, skip it.
362 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
363 continue; // The Block is in a subloop, skip it.
364
365 // Check that InVal is defined in the loop.
366 Instruction *Inst = cast<Instruction>(InVal);
367 if (!L->contains(Inst->getParent()))
368 continue;
369
370 // We require that this value either have a computable evolution or that
371 // the loop have a constant iteration count. In the case where the loop
372 // has a constant iteration count, we can sometimes force evaluation of
373 // the exit value through brute force.
374 SCEVHandle SH = SE->getSCEV(Inst);
375 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
376 continue; // Cannot get exit evolution for the loop value.
377
378 // Okay, this instruction has a user outside of the current loop
379 // and varies predictably *inside* the loop. Evaluate the value it
380 // contains when the loop exits, if possible.
381 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
382 if (isa<SCEVCouldNotCompute>(ExitValue) ||
383 !ExitValue->isLoopInvariant(L))
384 continue;
385
386 Changed = true;
387 ++NumReplaced;
388
389 // See if we already computed the exit value for the instruction, if so,
390 // just reuse it.
391 Value *&ExitVal = ExitValues[Inst];
392 if (!ExitVal)
393 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
394
395 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
396 << " LoopVal = " << *Inst << "\n";
397
398 PN->setIncomingValue(i, ExitVal);
399
400 // If this instruction is dead now, schedule it to be removed.
401 if (Inst->use_empty())
402 InstructionsToDelete.insert(Inst);
403
404 // See if this is a single-entry LCSSA PHI node. If so, we can (and
405 // have to) remove
406 // the PHI entirely. This is safe, because the NewVal won't be variant
407 // in the loop, so we don't need an LCSSA phi node anymore.
408 if (NumPreds == 1) {
409 SE->deleteValueFromRecords(PN);
410 PN->replaceAllUsesWith(ExitVal);
411 PN->eraseFromParent();
412 break;
413 }
414 }
415 }
416 }
417
418 DeleteTriviallyDeadInstructions(InstructionsToDelete);
419}
420
421bool IndVarSimplify::doInitialization(Loop *L, LPPassManager &LPM) {
422
423 Changed = false;
424 // First step. Check to see if there are any trivial GEP pointer recurrences.
425 // If there are, change them into integer recurrences, permitting analysis by
426 // the SCEV routines.
427 //
428 BasicBlock *Header = L->getHeader();
429 BasicBlock *Preheader = L->getLoopPreheader();
430 SE = &LPM.getAnalysis<ScalarEvolution>();
431
Chris Lattnerb25465e2008-11-16 07:17:51 +0000432 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
434 PHINode *PN = cast<PHINode>(I);
435 if (isa<PointerType>(PN->getType()))
436 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Devang Patelc8dac622008-11-17 21:32:02 +0000437 else
438 HandleFloatingPointIV(L, PN, DeadInsts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000439 }
440
441 if (!DeadInsts.empty())
442 DeleteTriviallyDeadInstructions(DeadInsts);
443
444 return Changed;
445}
446
447bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
448
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000449 LI = &getAnalysis<LoopInfo>();
450 SE = &getAnalysis<ScalarEvolution>();
451
452 Changed = false;
453 BasicBlock *Header = L->getHeader();
Chris Lattnerb25465e2008-11-16 07:17:51 +0000454 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000455
456 // Verify the input to the pass in already in LCSSA form.
457 assert(L->isLCSSAForm());
458
459 // Check to see if this loop has a computable loop-invariant execution count.
460 // If so, this means that we can compute the final value of any expressions
461 // that are recurrent in the loop, and substitute the exit values from the
462 // loop into any instructions outside of the loop that use the final values of
463 // the current expressions.
464 //
465 SCEVHandle IterationCount = SE->getIterationCount(L);
466 if (!isa<SCEVCouldNotCompute>(IterationCount))
Dan Gohmand8dc3bb2008-08-05 22:34:21 +0000467 RewriteLoopExitValues(L, IterationCount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000468
469 // Next, analyze all of the induction variables in the loop, canonicalizing
470 // auxillary induction variables.
471 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
472
473 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
474 PHINode *PN = cast<PHINode>(I);
475 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
476 SCEVHandle SCEV = SE->getSCEV(PN);
477 if (SCEV->hasComputableLoopEvolution(L))
478 // FIXME: It is an extremely bad idea to indvar substitute anything more
479 // complex than affine induction variables. Doing so will put expensive
480 // polynomial evaluations inside of the loop, and the str reduction pass
481 // currently can only reduce affine polynomials. For now just disable
482 // indvar subst on anything more complex than an affine addrec.
483 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
484 if (AR->isAffine())
485 IndVars.push_back(std::make_pair(PN, SCEV));
486 }
487 }
488
489 // If there are no induction variables in the loop, there is nothing more to
490 // do.
491 if (IndVars.empty()) {
492 // Actually, if we know how many times the loop iterates, lets insert a
493 // canonical induction variable to help subsequent passes.
494 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
495 SCEVExpander Rewriter(*SE, *LI);
496 Rewriter.getOrInsertCanonicalInductionVariable(L,
497 IterationCount->getType());
498 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
499 Rewriter)) {
Chris Lattnerb25465e2008-11-16 07:17:51 +0000500 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000501 InstructionsToDelete.insert(I);
502 DeleteTriviallyDeadInstructions(InstructionsToDelete);
503 }
504 }
505 return Changed;
506 }
507
508 // Compute the type of the largest recurrence expression.
509 //
510 const Type *LargestType = IndVars[0].first->getType();
511 bool DifferingSizes = false;
512 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
513 const Type *Ty = IndVars[i].first->getType();
514 DifferingSizes |=
515 Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
516 if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
517 LargestType = Ty;
518 }
519
520 // Create a rewriter object which we'll use to transform the code with.
521 SCEVExpander Rewriter(*SE, *LI);
522
523 // Now that we know the largest of of the induction variables in this loop,
524 // insert a canonical induction variable of the largest size.
525 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
526 ++NumInserted;
527 Changed = true;
528 DOUT << "INDVARS: New CanIV: " << *IndVar;
529
530 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Wojciech Matyjewiczc561c132008-06-13 17:02:03 +0000531 IterationCount = SE->getTruncateOrZeroExtend(IterationCount, LargestType);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000532 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
533 DeadInsts.insert(DI);
534 }
535
536 // Now that we have a canonical induction variable, we can rewrite any
537 // recurrences in terms of the induction variable. Start with the auxillary
538 // induction variables, and recursively rewrite any of their uses.
Dan Gohman514277c2008-05-23 21:05:58 +0000539 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000540
541 // If there were induction variables of other sizes, cast the primary
542 // induction variable to the right size for them, avoiding the need for the
543 // code evaluation methods to insert induction variables of different sizes.
544 if (DifferingSizes) {
545 SmallVector<unsigned,4> InsertedSizes;
546 InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
547 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
548 unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
549 if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
550 == InsertedSizes.end()) {
551 PHINode *PN = IndVars[i].first;
552 InsertedSizes.push_back(ithSize);
553 Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
554 InsertPt);
555 Rewriter.addInsertedValue(New, SE->getSCEV(New));
556 DOUT << "INDVARS: Made trunc IV for " << *PN
557 << " NewVal = " << *New << "\n";
558 }
559 }
560 }
561
562 // Rewrite all induction variables in terms of the canonical induction
563 // variable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000564 while (!IndVars.empty()) {
565 PHINode *PN = IndVars.back().first;
566 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt);
567 DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
568 << " into = " << *NewVal << "\n";
569 NewVal->takeName(PN);
570
571 // Replace the old PHI Node with the inserted computation.
572 PN->replaceAllUsesWith(NewVal);
573 DeadInsts.insert(PN);
574 IndVars.pop_back();
575 ++NumRemoved;
576 Changed = true;
577 }
578
579#if 0
580 // Now replace all derived expressions in the loop body with simpler
581 // expressions.
Dan Gohman4d2e8ae2008-06-22 20:18:58 +0000582 for (LoopInfo::block_iterator I = L->block_begin(), E = L->block_end();
583 I != E; ++I) {
584 BasicBlock *BB = *I;
585 if (LI->getLoopFor(BB) == L) { // Not in a subloop...
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
587 if (I->getType()->isInteger() && // Is an integer instruction
588 !I->use_empty() &&
589 !Rewriter.isInsertedInstruction(I)) {
590 SCEVHandle SH = SE->getSCEV(I);
591 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
592 if (V != I) {
593 if (isa<Instruction>(V))
594 V->takeName(I);
595 I->replaceAllUsesWith(V);
596 DeadInsts.insert(I);
597 ++NumRemoved;
598 Changed = true;
599 }
600 }
601 }
Dan Gohman4d2e8ae2008-06-22 20:18:58 +0000602 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603#endif
604
605 DeleteTriviallyDeadInstructions(DeadInsts);
Devang Patelbda43802008-09-09 21:41:07 +0000606 OptimizeCanonicalIVType(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000607 assert(L->isLCSSAForm());
608 return Changed;
609}
Devang Patelbda43802008-09-09 21:41:07 +0000610
611/// OptimizeCanonicalIVType - If loop induction variable is always
Devang Patel7c9fc2a2008-09-10 14:49:55 +0000612/// sign or zero extended then extend the type of the induction
Devang Patelbda43802008-09-09 21:41:07 +0000613/// variable.
614void IndVarSimplify::OptimizeCanonicalIVType(Loop *L) {
615 PHINode *PH = L->getCanonicalInductionVariable();
616 if (!PH) return;
617
618 // Check loop iteration count.
619 SCEVHandle IC = SE->getIterationCount(L);
620 if (isa<SCEVCouldNotCompute>(IC)) return;
621 SCEVConstant *IterationCount = dyn_cast<SCEVConstant>(IC);
622 if (!IterationCount) return;
623
624 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
625 unsigned BackEdge = IncomingEdge^1;
626
627 // Check IV uses. If all IV uses are either SEXT or ZEXT (except
628 // IV increment instruction) then this IV is suitable for this
Devang Patel7c9fc2a2008-09-10 14:49:55 +0000629 // transformation.
630 bool isSEXT = false;
Devang Patelbda43802008-09-09 21:41:07 +0000631 BinaryOperator *Incr = NULL;
Devang Patel7c9fc2a2008-09-10 14:49:55 +0000632 const Type *NewType = NULL;
Devang Patelbda43802008-09-09 21:41:07 +0000633 for(Value::use_iterator UI = PH->use_begin(), UE = PH->use_end();
634 UI != UE; ++UI) {
635 const Type *CandidateType = NULL;
636 if (ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
637 CandidateType = ZI->getDestTy();
638 else if (SExtInst *SI = dyn_cast<SExtInst>(UI)) {
639 CandidateType = SI->getDestTy();
Devang Patel7c9fc2a2008-09-10 14:49:55 +0000640 isSEXT = true;
Devang Patelbda43802008-09-09 21:41:07 +0000641 }
642 else if ((Incr = dyn_cast<BinaryOperator>(UI))) {
643 // Validate IV increment instruction.
644 if (PH->getIncomingValue(BackEdge) == Incr)
645 continue;
646 }
647 if (!CandidateType) {
648 NewType = NULL;
649 break;
650 }
651 if (!NewType)
652 NewType = CandidateType;
653 else if (NewType != CandidateType) {
654 NewType = NULL;
655 break;
656 }
657 }
658
659 // IV uses are not suitable then avoid this transformation.
660 if (!NewType || !Incr)
661 return;
662
663 // IV increment instruction has two uses, one is loop exit condition
664 // and second is the IV (phi node) itself.
665 ICmpInst *Exit = NULL;
666 for(Value::use_iterator II = Incr->use_begin(), IE = Incr->use_end();
667 II != IE; ++II) {
668 if (PH == *II) continue;
669 Exit = dyn_cast<ICmpInst>(*II);
670 break;
671 }
672 if (!Exit) return;
673 ConstantInt *EV = dyn_cast<ConstantInt>(Exit->getOperand(0));
674 if (!EV)
675 EV = dyn_cast<ConstantInt>(Exit->getOperand(1));
676 if (!EV) return;
677
678 // Check iteration count max value to avoid loops that wrap around IV.
679 APInt ICount = IterationCount->getValue()->getValue();
680 if (ICount.isNegative()) return;
681 uint32_t BW = PH->getType()->getPrimitiveSizeInBits();
682 APInt Max = (isSEXT ? APInt::getSignedMaxValue(BW) : APInt::getMaxValue(BW));
683 if (ICount.getZExtValue() > Max.getZExtValue()) return;
684
685 // Extend IV type.
686
687 SCEVExpander Rewriter(*SE, *LI);
688 Value *NewIV = Rewriter.getOrInsertCanonicalInductionVariable(L,NewType);
689 PHINode *NewPH = cast<PHINode>(NewIV);
690 Instruction *NewIncr = cast<Instruction>(NewPH->getIncomingValue(BackEdge));
691
692 // Replace all SEXT or ZEXT uses.
693 SmallVector<Instruction *, 4> PHUses;
694 for(Value::use_iterator UI = PH->use_begin(), UE = PH->use_end();
695 UI != UE; ++UI) {
696 Instruction *I = cast<Instruction>(UI);
697 PHUses.push_back(I);
698 }
699 while (!PHUses.empty()){
700 Instruction *Use = PHUses.back(); PHUses.pop_back();
701 if (Incr == Use) continue;
702
703 SE->deleteValueFromRecords(Use);
704 Use->replaceAllUsesWith(NewIV);
705 Use->eraseFromParent();
706 }
707
708 // Replace exit condition.
709 ConstantInt *NEV = ConstantInt::get(NewType, EV->getZExtValue());
710 Instruction *NE = new ICmpInst(Exit->getPredicate(),
711 NewIncr, NEV, "new.exit",
712 Exit->getParent()->getTerminator());
713 SE->deleteValueFromRecords(Exit);
714 Exit->replaceAllUsesWith(NE);
715 Exit->eraseFromParent();
716
717 // Remove old IV and increment instructions.
718 SE->deleteValueFromRecords(PH);
719 PH->removeIncomingValue((unsigned)0);
720 PH->removeIncomingValue((unsigned)0);
721 SE->deleteValueFromRecords(Incr);
722 Incr->eraseFromParent();
723}
724
Devang Patelb8ccf572008-11-18 00:40:02 +0000725/// Return true if it is OK to use SIToFPInst for an inducation variable
726/// with given inital and exit values.
727static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
728 uint64_t intIV, uint64_t intEV) {
729
730 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
731 return true;
732
733 // If the iteration range can be handled by SIToFPInst then use it.
734 APInt Max = APInt::getSignedMaxValue(32);
735 if (Max.getZExtValue() > abs(intEV - intIV))
736 return true;
737
738 return false;
739}
740
741/// convertToInt - Convert APF to an integer, if possible.
Devang Patele2ba01d2008-11-17 23:27:13 +0000742static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
743
744 bool isExact = false;
745 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
746 APFloat::rmTowardZero, &isExact)
747 != APFloat::opOK)
748 return false;
749 if (!isExact)
750 return false;
751 return true;
752
753}
754
Devang Patel7ca23c92008-11-03 18:32:19 +0000755/// HandleFloatingPointIV - If the loop has floating induction variable
756/// then insert corresponding integer induction variable if possible.
Devang Patelc8dac622008-11-17 21:32:02 +0000757/// For example,
758/// for(double i = 0; i < 10000; ++i)
759/// bar(i)
760/// is converted into
761/// for(int i = 0; i < 10000; ++i)
762/// bar((double)i);
763///
764void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
765 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Devang Patel7ca23c92008-11-03 18:32:19 +0000766
Devang Patelc8dac622008-11-17 21:32:02 +0000767 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
768 unsigned BackEdge = IncomingEdge^1;
769
770 // Check incoming value.
Devang Patele2ba01d2008-11-17 23:27:13 +0000771 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
772 if (!InitValue) return;
773 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
774 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
775 return;
776
777 // Check IV increment. Reject this PH if increement operation is not
778 // an add or increment value can not be represented by an integer.
Devang Patelc8dac622008-11-17 21:32:02 +0000779 BinaryOperator *Incr =
780 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
781 if (!Incr) return;
782 if (Incr->getOpcode() != Instruction::Add) return;
783 ConstantFP *IncrValue = NULL;
784 unsigned IncrVIndex = 1;
785 if (Incr->getOperand(1) == PH)
786 IncrVIndex = 0;
787 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
788 if (!IncrValue) return;
Devang Patele2ba01d2008-11-17 23:27:13 +0000789 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
790 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
791 return;
Devang Patelc8dac622008-11-17 21:32:02 +0000792
Devang Patele2ba01d2008-11-17 23:27:13 +0000793 // Check Incr uses. One user is PH and the other users is exit condition used
794 // by the conditional terminator.
Devang Patelc8dac622008-11-17 21:32:02 +0000795 Value::use_iterator IncrUse = Incr->use_begin();
796 Instruction *U1 = cast<Instruction>(IncrUse++);
797 if (IncrUse == Incr->use_end()) return;
798 Instruction *U2 = cast<Instruction>(IncrUse++);
799 if (IncrUse != Incr->use_end()) return;
800
801 // Find exit condition.
802 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
803 if (!EC)
804 EC = dyn_cast<FCmpInst>(U2);
805 if (!EC) return;
806
807 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
808 if (!BI->isConditional()) return;
809 if (BI->getCondition() != EC) return;
Devang Patel7ca23c92008-11-03 18:32:19 +0000810 }
Devang Patel7ca23c92008-11-03 18:32:19 +0000811
Devang Patele2ba01d2008-11-17 23:27:13 +0000812 // Find exit value. If exit value can not be represented as an interger then
813 // do not handle this floating point PH.
Devang Patelc8dac622008-11-17 21:32:02 +0000814 ConstantFP *EV = NULL;
815 unsigned EVIndex = 1;
816 if (EC->getOperand(1) == Incr)
817 EVIndex = 0;
818 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
819 if (!EV) return;
Devang Patelc8dac622008-11-17 21:32:02 +0000820 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patele2ba01d2008-11-17 23:27:13 +0000821 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patelc8dac622008-11-17 21:32:02 +0000822 return;
Devang Patelc8dac622008-11-17 21:32:02 +0000823
824 // Find new predicate for integer comparison.
825 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
826 switch (EC->getPredicate()) {
827 case CmpInst::FCMP_OEQ:
828 case CmpInst::FCMP_UEQ:
829 NewPred = CmpInst::ICMP_EQ;
830 break;
831 case CmpInst::FCMP_OGT:
832 case CmpInst::FCMP_UGT:
833 NewPred = CmpInst::ICMP_UGT;
834 break;
835 case CmpInst::FCMP_OGE:
836 case CmpInst::FCMP_UGE:
837 NewPred = CmpInst::ICMP_UGE;
838 break;
839 case CmpInst::FCMP_OLT:
840 case CmpInst::FCMP_ULT:
841 NewPred = CmpInst::ICMP_ULT;
842 break;
843 case CmpInst::FCMP_OLE:
844 case CmpInst::FCMP_ULE:
845 NewPred = CmpInst::ICMP_ULE;
846 break;
847 default:
848 break;
Devang Patel7ca23c92008-11-03 18:32:19 +0000849 }
Devang Patelc8dac622008-11-17 21:32:02 +0000850 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
851
852 // Insert new integer induction variable.
853 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
854 PH->getName()+".int", PH);
Devang Patele2ba01d2008-11-17 23:27:13 +0000855 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patelc8dac622008-11-17 21:32:02 +0000856 PH->getIncomingBlock(IncomingEdge));
857
858 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
Devang Patele2ba01d2008-11-17 23:27:13 +0000859 ConstantInt::get(Type::Int32Ty,
860 newIncrValue),
Devang Patelc8dac622008-11-17 21:32:02 +0000861 Incr->getName()+".int", Incr);
862 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
863
864 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
865 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
866 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
867 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
868 EC->getParent()->getTerminator());
869
870 // Delete old, floating point, exit comparision instruction.
871 EC->replaceAllUsesWith(NewEC);
872 DeadInsts.insert(EC);
873
874 // Delete old, floating point, increment instruction.
875 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
876 DeadInsts.insert(Incr);
877
Devang Patelb8ccf572008-11-18 00:40:02 +0000878 // Replace floating induction variable. Give SIToFPInst preference over
879 // UIToFPInst because it is faster on platforms that are widely used.
880 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
Devang Patele2ba01d2008-11-17 23:27:13 +0000881 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
882 PH->getParent()->getFirstNonPHI());
883 PH->replaceAllUsesWith(Conv);
884 } else {
885 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
886 PH->getParent()->getFirstNonPHI());
887 PH->replaceAllUsesWith(Conv);
888 }
Devang Patelc8dac622008-11-17 21:32:02 +0000889 DeadInsts.insert(PH);
Devang Patel7ca23c92008-11-03 18:32:19 +0000890}
891