blob: e31b514b2faf5cedd51f7e2774c32721d46701a6 [file] [log] [blame]
Chris Lattner6148c022001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6148c022001-12-03 17:28:42 +00009//
Chris Lattner40bf8b42004-04-02 20:24:31 +000010// 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//
Reid Spencer47a53ac2006-08-18 09:01:07 +000014// This transformation makes the following changes to each loop with an
Chris Lattner40bf8b42004-04-02 20:24:31 +000015// 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).
Chris Lattner6148c022001-12-03 17:28:42 +000037//
38//===----------------------------------------------------------------------===//
39
Chris Lattner0e5f4992006-12-19 21:40:18 +000040#define DEBUG_TYPE "indvars"
Chris Lattner022103b2002-05-07 20:03:00 +000041#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000042#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000043#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000044#include "llvm/Instructions.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000045#include "llvm/Type.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000046#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000047#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000048#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000049#include "llvm/Support/CFG.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000050#include "llvm/Support/Compiler.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000051#include "llvm/Support/Debug.h"
Chris Lattnera4b9c782004-10-11 23:06:50 +000052#include "llvm/Support/GetElementPtrTypeIterator.h"
John Criswell47df12d2003-12-18 17:19:19 +000053#include "llvm/Transforms/Utils/Local.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000054#include "llvm/Support/CommandLine.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000055#include "llvm/ADT/SmallVector.h"
Dan Gohmanc2390b12009-02-12 22:19:27 +000056#include "llvm/ADT/SetVector.h"
Chris Lattner1a6111f2008-11-16 07:17:51 +000057#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000058#include "llvm/ADT/Statistic.h"
John Criswell47df12d2003-12-18 17:19:19 +000059using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000060
Chris Lattner0e5f4992006-12-19 21:40:18 +000061STATISTIC(NumRemoved , "Number of aux indvars removed");
62STATISTIC(NumPointer , "Number of pointer indvars promoted");
63STATISTIC(NumInserted, "Number of canonical indvars added");
64STATISTIC(NumReplaced, "Number of exit values replaced");
65STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000066
Chris Lattner0e5f4992006-12-19 21:40:18 +000067namespace {
Devang Patel5ee99972007-03-07 06:39:01 +000068 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
Chris Lattner40bf8b42004-04-02 20:24:31 +000069 LoopInfo *LI;
70 ScalarEvolution *SE;
Chris Lattner15cad752003-12-23 07:47:09 +000071 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000072 public:
Devang Patel794fd752007-05-01 21:15:47 +000073
Nick Lewyckyecd94c82007-05-06 13:37:16 +000074 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000075 IndVarSimplify() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000076
Dan Gohman60f8a632009-02-17 20:49:49 +000077 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
78
Devang Patel5ee99972007-03-07 06:39:01 +000079 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patelbc533cd2007-09-10 18:08:23 +000080 AU.addRequired<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000081 AU.addRequiredID(LCSSAID);
82 AU.addRequiredID(LoopSimplifyID);
Devang Patel5ee99972007-03-07 06:39:01 +000083 AU.addRequired<LoopInfo>();
84 AU.addPreservedID(LoopSimplifyID);
85 AU.addPreservedID(LCSSAID);
86 AU.setPreservesCFG();
87 }
Chris Lattner15cad752003-12-23 07:47:09 +000088
Chris Lattner40bf8b42004-04-02 20:24:31 +000089 private:
Devang Patel5ee99972007-03-07 06:39:01 +000090
Dan Gohman60f8a632009-02-17 20:49:49 +000091 void RewriteNonIntegerIVs(Loop *L);
92
Chris Lattner40bf8b42004-04-02 20:24:31 +000093 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
Chris Lattner1a6111f2008-11-16 07:17:51 +000094 SmallPtrSet<Instruction*, 16> &DeadInsts);
Dan Gohmana5758712009-02-17 15:57:39 +000095 void LinearFunctionTestReplace(Loop *L, SCEVHandle IterationCount,
96 Value *IndVar,
Dan Gohmanc2390b12009-02-12 22:19:27 +000097 BasicBlock *ExitingBlock,
98 BranchInst *BI,
99 SCEVExpander &Rewriter);
Dan Gohman5a6c4482008-08-05 22:34:21 +0000100 void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000101
Chris Lattner1a6111f2008-11-16 07:17:51 +0000102 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
Devang Pateld22a8492008-09-09 21:41:07 +0000103
Dan Gohmancafb8132009-02-17 19:13:57 +0000104 void HandleFloatingPointIV(Loop *L, PHINode *PH,
Devang Patel84e35152008-11-17 21:32:02 +0000105 SmallPtrSet<Instruction*, 16> &DeadInsts);
Chris Lattner3324e712003-12-22 03:58:44 +0000106 };
Chris Lattner5e761402002-09-10 05:24:05 +0000107}
Chris Lattner394437f2001-12-04 04:32:29 +0000108
Dan Gohman844731a2008-05-13 00:00:25 +0000109char IndVarSimplify::ID = 0;
110static RegisterPass<IndVarSimplify>
111X("indvars", "Canonicalize Induction Variables");
112
Daniel Dunbar394f0442008-10-22 23:32:42 +0000113Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000114 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000115}
116
Chris Lattner40bf8b42004-04-02 20:24:31 +0000117/// DeleteTriviallyDeadInstructions - If any of the instructions is the
118/// specified set are trivially dead, delete them and see if this makes any of
119/// their operands subsequently dead.
120void IndVarSimplify::
Chris Lattner1a6111f2008-11-16 07:17:51 +0000121DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000122 while (!Insts.empty()) {
123 Instruction *I = *Insts.begin();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000124 Insts.erase(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000125 if (isInstructionTriviallyDead(I)) {
126 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
127 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
128 Insts.insert(U);
Dan Gohman5cec4db2007-06-19 14:28:31 +0000129 SE->deleteValueFromRecords(I);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000130 DOUT << "INDVARS: Deleting: " << *I;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000131 I->eraseFromParent();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000132 Changed = true;
133 }
134 }
135}
136
137
138/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
139/// recurrence. If so, change it into an integer recurrence, permitting
140/// analysis by the SCEV routines.
Misha Brukmanfd939082005-04-21 23:48:37 +0000141void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
Chris Lattner40bf8b42004-04-02 20:24:31 +0000142 BasicBlock *Preheader,
Chris Lattner1a6111f2008-11-16 07:17:51 +0000143 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000144 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
145 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
146 unsigned BackedgeIdx = PreheaderIdx^1;
147 if (GetElementPtrInst *GEPI =
Chris Lattnercda9ca52005-08-10 01:12:06 +0000148 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
Chris Lattner40bf8b42004-04-02 20:24:31 +0000149 if (GEPI->getOperand(0) == PN) {
Chris Lattnercda9ca52005-08-10 01:12:06 +0000150 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
Chris Lattneree4f13a2007-01-07 01:14:12 +0000151 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
Dan Gohmancafb8132009-02-17 19:13:57 +0000152
Chris Lattner40bf8b42004-04-02 20:24:31 +0000153 // Okay, we found a pointer recurrence. Transform this pointer
154 // recurrence into an integer recurrence. Compute the value that gets
155 // added to the pointer at every iteration.
156 Value *AddedVal = GEPI->getOperand(1);
157
158 // Insert a new integer PHI node into the top of the block.
Gabor Greif051a9502008-04-06 20:25:17 +0000159 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
160 PN->getName()+".rec", PN);
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000161 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
162
Chris Lattner40bf8b42004-04-02 20:24:31 +0000163 // Create the new add instruction.
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000164 Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000165 GEPI->getName()+".rec", GEPI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000166 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000167
Chris Lattner40bf8b42004-04-02 20:24:31 +0000168 // Update the existing GEP to use the recurrence.
169 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000170
Chris Lattner40bf8b42004-04-02 20:24:31 +0000171 // Update the GEP to use the new recurrence we just inserted.
172 GEPI->setOperand(1, NewAdd);
173
Chris Lattnera4b9c782004-10-11 23:06:50 +0000174 // If the incoming value is a constant expr GEP, try peeling out the array
175 // 0 index if possible to make things simpler.
176 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
177 if (CE->getOpcode() == Instruction::GetElementPtr) {
178 unsigned NumOps = CE->getNumOperands();
179 assert(NumOps > 1 && "CE folding didn't work!");
180 if (CE->getOperand(NumOps-1)->isNullValue()) {
181 // Check to make sure the last index really is an array index.
Chris Lattner17300782005-11-18 18:30:47 +0000182 gep_type_iterator GTI = gep_type_begin(CE);
Chris Lattnerceda6052005-11-17 19:35:42 +0000183 for (unsigned i = 1, e = CE->getNumOperands()-1;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000184 i != e; ++i, ++GTI)
185 /*empty*/;
186 if (isa<SequentialType>(*GTI)) {
187 // Pull the last index out of the constant expr GEP.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000188 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000189 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000190 &CEIdxs[0],
191 CEIdxs.size());
David Greeneb8f74792007-09-04 15:46:09 +0000192 Value *Idx[2];
193 Idx[0] = Constant::getNullValue(Type::Int32Ty);
194 Idx[1] = NewAdd;
Gabor Greif051a9502008-04-06 20:25:17 +0000195 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
Dan Gohmancafb8132009-02-17 19:13:57 +0000196 NCE, Idx, Idx + 2,
Reid Spencercae57542007-03-02 00:28:52 +0000197 GEPI->getName(), GEPI);
Dan Gohman5cec4db2007-06-19 14:28:31 +0000198 SE->deleteValueFromRecords(GEPI);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000199 GEPI->replaceAllUsesWith(NGEPI);
200 GEPI->eraseFromParent();
201 GEPI = NGEPI;
202 }
203 }
204 }
205
206
Chris Lattner40bf8b42004-04-02 20:24:31 +0000207 // Finally, if there are any other users of the PHI node, we must
208 // insert a new GEP instruction that uses the pre-incremented version
209 // of the induction amount.
210 if (!PN->use_empty()) {
211 BasicBlock::iterator InsertPos = PN; ++InsertPos;
212 while (isa<PHINode>(InsertPos)) ++InsertPos;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000213 Value *PreInc =
Gabor Greif051a9502008-04-06 20:25:17 +0000214 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
215 NewPhi, "", InsertPos);
Chris Lattner6934a042007-02-11 01:23:03 +0000216 PreInc->takeName(PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000217 PN->replaceAllUsesWith(PreInc);
218 }
219
220 // Delete the old PHI for sure, and the GEP if its otherwise unused.
221 DeadInsts.insert(PN);
222
223 ++NumPointer;
224 Changed = true;
225 }
226}
227
228/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000229/// loop to be a canonical != comparison against the incremented loop induction
230/// variable. This pass is able to rewrite the exit tests of any loop where the
231/// SCEV analysis can determine a loop-invariant trip count of the loop, which
232/// is actually a much broader range than just linear tests.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000233void IndVarSimplify::LinearFunctionTestReplace(Loop *L,
234 SCEVHandle IterationCount,
235 Value *IndVar,
236 BasicBlock *ExitingBlock,
237 BranchInst *BI,
238 SCEVExpander &Rewriter) {
Chris Lattnerd2440572004-04-15 20:26:22 +0000239 // If the exiting block is not the same as the backedge block, we must compare
240 // against the preincremented value, otherwise we prefer to compare against
241 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000242 Value *CmpIndVar;
243 if (ExitingBlock == L->getLoopLatch()) {
244 // What ScalarEvolution calls the "iteration count" is actually the
245 // number of times the branch is taken. Add one to get the number
246 // of times the branch is executed. If this addition may overflow,
247 // we have to be more pessimistic and cast the induction variable
248 // before doing the add.
249 SCEVHandle Zero = SE->getIntegerSCEV(0, IterationCount->getType());
250 SCEVHandle N =
251 SE->getAddExpr(IterationCount,
252 SE->getIntegerSCEV(1, IterationCount->getType()));
253 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
254 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
255 // No overflow. Cast the sum.
256 IterationCount = SE->getTruncateOrZeroExtend(N, IndVar->getType());
257 } else {
258 // Potential overflow. Cast before doing the add.
259 IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
260 IndVar->getType());
261 IterationCount =
262 SE->getAddExpr(IterationCount,
263 SE->getIntegerSCEV(1, IndVar->getType()));
264 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000265
Chris Lattnerd2440572004-04-15 20:26:22 +0000266 // The IterationCount expression contains the number of times that the
267 // backedge actually branches to the loop header. This is one less than the
268 // number of times the loop executes, so add one to it.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000269 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Chris Lattnerd2440572004-04-15 20:26:22 +0000270 } else {
271 // We have to use the preincremented value...
Dan Gohmanc2390b12009-02-12 22:19:27 +0000272 IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
273 IndVar->getType());
274 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000275 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000276
Chris Lattner40bf8b42004-04-02 20:24:31 +0000277 // Expand the code for the iteration count into the preheader of the loop.
278 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohmanc2390b12009-02-12 22:19:27 +0000279 Value *ExitCnt = Rewriter.expandCodeFor(IterationCount,
280 Preheader->getTerminator());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000281
Reid Spencere4d87aa2006-12-23 06:05:41 +0000282 // Insert a new icmp_ne or icmp_eq instruction before the branch.
283 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000284 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000285 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000286 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000287 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000288
Dan Gohmanc2390b12009-02-12 22:19:27 +0000289 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
290 << " LHS:" << *CmpIndVar // includes a newline
291 << " op:\t"
Dan Gohmanf108e2e2009-02-14 02:26:50 +0000292 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohmanc2390b12009-02-12 22:19:27 +0000293 << " RHS:\t" << *IterationCount << "\n";
294
295 Value *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000296 BI->setCondition(Cond);
297 ++NumLFTR;
298 Changed = true;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000299}
300
Chris Lattner40bf8b42004-04-02 20:24:31 +0000301/// RewriteLoopExitValues - Check to see if this loop has a computable
302/// loop-invariant execution count. If so, this means that we can compute the
303/// final value of any expressions that are recurrent in the loop, and
304/// substitute the exit values from the loop into any instructions outside of
305/// the loop that use the final values of the current expressions.
Dan Gohman5a6c4482008-08-05 22:34:21 +0000306void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000307 BasicBlock *Preheader = L->getLoopPreheader();
308
309 // Scan all of the instructions in the loop, looking at those that have
310 // extra-loop users and which are recurrences.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000311 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000312
313 // We insert the code into the preheader of the loop if the loop contains
314 // multiple exit blocks, or in the exit block if there is exactly one.
315 BasicBlock *BlockToInsertInto;
Devang Patelb7211a22007-08-21 00:31:24 +0000316 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000317 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000318 if (ExitBlocks.size() == 1)
319 BlockToInsertInto = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000320 else
321 BlockToInsertInto = Preheader;
Dan Gohman02dea8b2008-05-23 21:05:58 +0000322 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000323
Dan Gohman5a6c4482008-08-05 22:34:21 +0000324 bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
Chris Lattner20aa0982004-04-17 18:44:09 +0000325
Chris Lattner1a6111f2008-11-16 07:17:51 +0000326 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000327 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanfd939082005-04-21 23:48:37 +0000328
Chris Lattner9f3d7382007-03-04 03:43:23 +0000329 // Find all values that are computed inside the loop, but used outside of it.
330 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
331 // the exit blocks of the loop to find them.
332 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
333 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000334
Chris Lattner9f3d7382007-03-04 03:43:23 +0000335 // If there are no PHI nodes in this exit block, then no values defined
336 // inside the loop are used on this path, skip it.
337 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
338 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000339
Chris Lattner9f3d7382007-03-04 03:43:23 +0000340 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000341
Chris Lattner9f3d7382007-03-04 03:43:23 +0000342 // Iterate over all of the PHI nodes.
343 BasicBlock::iterator BBI = ExitBB->begin();
344 while ((PN = dyn_cast<PHINode>(BBI++))) {
Dan Gohmancafb8132009-02-17 19:13:57 +0000345
Chris Lattner9f3d7382007-03-04 03:43:23 +0000346 // Iterate over all of the values in all the PHI nodes.
347 for (unsigned i = 0; i != NumPreds; ++i) {
348 // If the value being merged in is not integer or is not defined
349 // in the loop, skip it.
350 Value *InVal = PN->getIncomingValue(i);
351 if (!isa<Instruction>(InVal) ||
352 // SCEV only supports integer expressions for now.
353 !isa<IntegerType>(InVal->getType()))
354 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000355
Chris Lattner9f3d7382007-03-04 03:43:23 +0000356 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000357 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000358 continue; // The Block is in a subloop, skip it.
359
360 // Check that InVal is defined in the loop.
361 Instruction *Inst = cast<Instruction>(InVal);
362 if (!L->contains(Inst->getParent()))
363 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000364
Chris Lattner9f3d7382007-03-04 03:43:23 +0000365 // We require that this value either have a computable evolution or that
366 // the loop have a constant iteration count. In the case where the loop
367 // has a constant iteration count, we can sometimes force evaluation of
368 // the exit value through brute force.
369 SCEVHandle SH = SE->getSCEV(Inst);
370 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
371 continue; // Cannot get exit evolution for the loop value.
Dan Gohmancafb8132009-02-17 19:13:57 +0000372
Chris Lattner9f3d7382007-03-04 03:43:23 +0000373 // Okay, this instruction has a user outside of the current loop
374 // and varies predictably *inside* the loop. Evaluate the value it
375 // contains when the loop exits, if possible.
376 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
377 if (isa<SCEVCouldNotCompute>(ExitValue) ||
378 !ExitValue->isLoopInvariant(L))
379 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000380
Chris Lattner9f3d7382007-03-04 03:43:23 +0000381 Changed = true;
382 ++NumReplaced;
Dan Gohmancafb8132009-02-17 19:13:57 +0000383
Chris Lattner9f3d7382007-03-04 03:43:23 +0000384 // See if we already computed the exit value for the instruction, if so,
385 // just reuse it.
386 Value *&ExitVal = ExitValues[Inst];
387 if (!ExitVal)
Dan Gohmand19534a2007-06-15 14:38:12 +0000388 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
Dan Gohmancafb8132009-02-17 19:13:57 +0000389
Chris Lattner9f3d7382007-03-04 03:43:23 +0000390 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
391 << " LoopVal = " << *Inst << "\n";
392
393 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000394
Chris Lattner9f3d7382007-03-04 03:43:23 +0000395 // If this instruction is dead now, schedule it to be removed.
396 if (Inst->use_empty())
397 InstructionsToDelete.insert(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000398
Chris Lattner9f3d7382007-03-04 03:43:23 +0000399 // See if this is a single-entry LCSSA PHI node. If so, we can (and
400 // have to) remove
Chris Lattner9caed542007-03-04 01:00:28 +0000401 // the PHI entirely. This is safe, because the NewVal won't be variant
402 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000403 if (NumPreds == 1) {
Dan Gohman5cec4db2007-06-19 14:28:31 +0000404 SE->deleteValueFromRecords(PN);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000405 PN->replaceAllUsesWith(ExitVal);
406 PN->eraseFromParent();
407 break;
Chris Lattnerc9838f22007-03-03 22:48:48 +0000408 }
409 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000410 }
411 }
Dan Gohmancafb8132009-02-17 19:13:57 +0000412
Chris Lattner40bf8b42004-04-02 20:24:31 +0000413 DeleteTriviallyDeadInstructions(InstructionsToDelete);
414}
415
Dan Gohman60f8a632009-02-17 20:49:49 +0000416void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000417 // First step. Check to see if there are any trivial GEP pointer recurrences.
418 // If there are, change them into integer recurrences, permitting analysis by
419 // the SCEV routines.
420 //
421 BasicBlock *Header = L->getHeader();
422 BasicBlock *Preheader = L->getLoopPreheader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000423
Chris Lattner1a6111f2008-11-16 07:17:51 +0000424 SmallPtrSet<Instruction*, 16> DeadInsts;
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000425 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
426 PHINode *PN = cast<PHINode>(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000427 if (isa<PointerType>(PN->getType()))
428 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Devang Patel84e35152008-11-17 21:32:02 +0000429 else
430 HandleFloatingPointIV(L, PN, DeadInsts);
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000431 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000432
Dan Gohman60f8a632009-02-17 20:49:49 +0000433 // If the loop previously had a pointer or floating-point IV, ScalarEvolution
434 // may not have been able to compute a trip count. Now that we've done some
435 // re-writing, the trip count may be computable.
436 if (Changed)
437 SE->forgetLoopIterationCount(L);
438
Chris Lattner40bf8b42004-04-02 20:24:31 +0000439 if (!DeadInsts.empty())
440 DeleteTriviallyDeadInstructions(DeadInsts);
Devang Patel5ee99972007-03-07 06:39:01 +0000441}
Chris Lattner40bf8b42004-04-02 20:24:31 +0000442
Dan Gohmanc2390b12009-02-12 22:19:27 +0000443/// getEffectiveIndvarType - Determine the widest type that the
444/// induction-variable PHINode Phi is cast to.
445///
446static const Type *getEffectiveIndvarType(const PHINode *Phi) {
447 const Type *Ty = Phi->getType();
Chris Lattner3324e712003-12-22 03:58:44 +0000448
Dan Gohmanc2390b12009-02-12 22:19:27 +0000449 for (Value::use_const_iterator UI = Phi->use_begin(), UE = Phi->use_end();
450 UI != UE; ++UI) {
451 const Type *CandidateType = NULL;
452 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
453 CandidateType = ZI->getDestTy();
454 else if (const SExtInst *SI = dyn_cast<SExtInst>(UI))
455 CandidateType = SI->getDestTy();
456 if (CandidateType &&
457 CandidateType->getPrimitiveSizeInBits() >
458 Ty->getPrimitiveSizeInBits())
459 Ty = CandidateType;
460 }
461
462 return Ty;
463}
464
Dan Gohmanaa036492009-02-14 02:31:09 +0000465/// TestOrigIVForWrap - Analyze the original induction variable
Dan Gohmand2067fd2009-02-18 00:52:00 +0000466/// that controls the loop's iteration to determine whether it
467/// would ever undergo signed or unsigned overflow.
468///
469/// In addition to setting the NoSignedWrap and NoUnsignedWrap
470/// variables, return the PHI for this induction variable.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000471///
472/// TODO: This duplicates a fair amount of ScalarEvolution logic.
Dan Gohmanaa036492009-02-14 02:31:09 +0000473/// Perhaps this can be merged with ScalarEvolution::getIterationCount
474/// and/or ScalarEvolution::get{Sign,Zero}ExtendExpr.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000475///
Dan Gohmand2067fd2009-02-18 00:52:00 +0000476static const PHINode *TestOrigIVForWrap(const Loop *L,
477 const BranchInst *BI,
478 const Instruction *OrigCond,
479 bool &NoSignedWrap,
480 bool &NoUnsignedWrap) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000481 // Verify that the loop is sane and find the exit condition.
482 const ICmpInst *Cmp = dyn_cast<ICmpInst>(OrigCond);
Dan Gohmand2067fd2009-02-18 00:52:00 +0000483 if (!Cmp) return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000484
Dan Gohmanaa036492009-02-14 02:31:09 +0000485 const Value *CmpLHS = Cmp->getOperand(0);
486 const Value *CmpRHS = Cmp->getOperand(1);
487 const BasicBlock *TrueBB = BI->getSuccessor(0);
488 const BasicBlock *FalseBB = BI->getSuccessor(1);
489 ICmpInst::Predicate Pred = Cmp->getPredicate();
Dan Gohmanc2390b12009-02-12 22:19:27 +0000490
Dan Gohmanaa036492009-02-14 02:31:09 +0000491 // Canonicalize a constant to the RHS.
492 if (isa<ConstantInt>(CmpLHS)) {
493 Pred = ICmpInst::getSwappedPredicate(Pred);
494 std::swap(CmpLHS, CmpRHS);
495 }
496 // Canonicalize SLE to SLT.
497 if (Pred == ICmpInst::ICMP_SLE)
498 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
499 if (!CI->getValue().isMaxSignedValue()) {
500 CmpRHS = ConstantInt::get(CI->getValue() + 1);
501 Pred = ICmpInst::ICMP_SLT;
502 }
503 // Canonicalize SGT to SGE.
504 if (Pred == ICmpInst::ICMP_SGT)
505 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
506 if (!CI->getValue().isMaxSignedValue()) {
507 CmpRHS = ConstantInt::get(CI->getValue() + 1);
508 Pred = ICmpInst::ICMP_SGE;
509 }
510 // Canonicalize SGE to SLT.
511 if (Pred == ICmpInst::ICMP_SGE) {
512 std::swap(TrueBB, FalseBB);
513 Pred = ICmpInst::ICMP_SLT;
514 }
515 // Canonicalize ULE to ULT.
516 if (Pred == ICmpInst::ICMP_ULE)
517 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
518 if (!CI->getValue().isMaxValue()) {
519 CmpRHS = ConstantInt::get(CI->getValue() + 1);
520 Pred = ICmpInst::ICMP_ULT;
521 }
522 // Canonicalize UGT to UGE.
523 if (Pred == ICmpInst::ICMP_UGT)
524 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
525 if (!CI->getValue().isMaxValue()) {
526 CmpRHS = ConstantInt::get(CI->getValue() + 1);
527 Pred = ICmpInst::ICMP_UGE;
528 }
529 // Canonicalize UGE to ULT.
530 if (Pred == ICmpInst::ICMP_UGE) {
531 std::swap(TrueBB, FalseBB);
532 Pred = ICmpInst::ICMP_ULT;
533 }
534 // For now, analyze only LT loops for signed overflow.
535 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_ULT)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000536 return 0;
Dan Gohmanaa036492009-02-14 02:31:09 +0000537
538 bool isSigned = Pred == ICmpInst::ICMP_SLT;
539
540 // Get the increment instruction. Look past casts if we will
Dan Gohmanc2390b12009-02-12 22:19:27 +0000541 // be able to prove that the original induction variable doesn't
Dan Gohmanaa036492009-02-14 02:31:09 +0000542 // undergo signed or unsigned overflow, respectively.
543 const Value *IncrVal = CmpLHS;
544 if (isSigned) {
545 if (const SExtInst *SI = dyn_cast<SExtInst>(CmpLHS)) {
546 if (!isa<ConstantInt>(CmpRHS) ||
547 !cast<ConstantInt>(CmpRHS)->getValue()
548 .isSignedIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
Dan Gohmand2067fd2009-02-18 00:52:00 +0000549 return 0;
Dan Gohmanaa036492009-02-14 02:31:09 +0000550 IncrVal = SI->getOperand(0);
551 }
552 } else {
553 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(CmpLHS)) {
554 if (!isa<ConstantInt>(CmpRHS) ||
555 !cast<ConstantInt>(CmpRHS)->getValue()
556 .isIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
Dan Gohmand2067fd2009-02-18 00:52:00 +0000557 return 0;
Dan Gohmanaa036492009-02-14 02:31:09 +0000558 IncrVal = ZI->getOperand(0);
559 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000560 }
561
562 // For now, only analyze induction variables that have simple increments.
563 const BinaryOperator *IncrOp = dyn_cast<BinaryOperator>(IncrVal);
564 if (!IncrOp ||
565 IncrOp->getOpcode() != Instruction::Add ||
566 !isa<ConstantInt>(IncrOp->getOperand(1)) ||
567 !cast<ConstantInt>(IncrOp->getOperand(1))->equalsInt(1))
Dan Gohmand2067fd2009-02-18 00:52:00 +0000568 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000569
570 // Make sure the PHI looks like a normal IV.
571 const PHINode *PN = dyn_cast<PHINode>(IncrOp->getOperand(0));
572 if (!PN || PN->getNumIncomingValues() != 2)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000573 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000574 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
575 unsigned BackEdge = !IncomingEdge;
576 if (!L->contains(PN->getIncomingBlock(BackEdge)) ||
577 PN->getIncomingValue(BackEdge) != IncrOp)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000578 return 0;
Dan Gohmanaa036492009-02-14 02:31:09 +0000579 if (!L->contains(TrueBB))
Dan Gohmand2067fd2009-02-18 00:52:00 +0000580 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000581
582 // For now, only analyze loops with a constant start value, so that
Dan Gohmanaa036492009-02-14 02:31:09 +0000583 // we can easily determine if the start value is not a maximum value
584 // which would wrap on the first iteration.
Dan Gohmancad24c92009-02-18 16:54:33 +0000585 const ConstantInt *InitialVal =
586 dyn_cast<ConstantInt>(PN->getIncomingValue(IncomingEdge));
587 if (!InitialVal)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000588 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000589
Dan Gohmanaa036492009-02-14 02:31:09 +0000590 // The original induction variable will start at some non-max value,
591 // it counts up by one, and the loop iterates only while it remans
592 // less than some value in the same type. As such, it will never wrap.
Dan Gohmancad24c92009-02-18 16:54:33 +0000593 if (isSigned && !InitialVal->getValue().isMaxSignedValue())
Dan Gohmanaa036492009-02-14 02:31:09 +0000594 NoSignedWrap = true;
Dan Gohmancad24c92009-02-18 16:54:33 +0000595 else if (!isSigned && !InitialVal->getValue().isMaxValue())
Dan Gohmanaa036492009-02-14 02:31:09 +0000596 NoUnsignedWrap = true;
Dan Gohmand2067fd2009-02-18 00:52:00 +0000597 return PN;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000598}
599
600bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Devang Patel5ee99972007-03-07 06:39:01 +0000601 LI = &getAnalysis<LoopInfo>();
602 SE = &getAnalysis<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +0000603 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +0000604
605 // If there are any floating-point or pointer recurrences, attempt to
606 // transform them to use integer recurrences.
607 RewriteNonIntegerIVs(L);
608
Dan Gohmanc2390b12009-02-12 22:19:27 +0000609 BasicBlock *Header = L->getHeader();
610 BasicBlock *ExitingBlock = L->getExitingBlock();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000611 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000612
Chris Lattner9caed542007-03-04 01:00:28 +0000613 // Verify the input to the pass in already in LCSSA form.
614 assert(L->isLCSSAForm());
615
Chris Lattner40bf8b42004-04-02 20:24:31 +0000616 // Check to see if this loop has a computable loop-invariant execution count.
617 // If so, this means that we can compute the final value of any expressions
618 // that are recurrent in the loop, and substitute the exit values from the
619 // loop into any instructions outside of the loop that use the final values of
620 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000621 //
Chris Lattner40bf8b42004-04-02 20:24:31 +0000622 SCEVHandle IterationCount = SE->getIterationCount(L);
623 if (!isa<SCEVCouldNotCompute>(IterationCount))
Dan Gohman5a6c4482008-08-05 22:34:21 +0000624 RewriteLoopExitValues(L, IterationCount);
Chris Lattner6148c022001-12-03 17:28:42 +0000625
Chris Lattner40bf8b42004-04-02 20:24:31 +0000626 // Next, analyze all of the induction variables in the loop, canonicalizing
627 // auxillary induction variables.
628 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
629
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000630 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
631 PHINode *PN = cast<PHINode>(I);
Chris Lattner42a75512007-01-15 02:27:26 +0000632 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
Chris Lattner40bf8b42004-04-02 20:24:31 +0000633 SCEVHandle SCEV = SE->getSCEV(PN);
Dan Gohmancd3eb9b2009-02-14 02:25:19 +0000634 // FIXME: It is an extremely bad idea to indvar substitute anything more
635 // complex than affine induction variables. Doing so will put expensive
636 // polynomial evaluations inside of the loop, and the str reduction pass
637 // currently can only reduce affine polynomials. For now just disable
638 // indvar subst on anything more complex than an affine addrec.
639 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
640 if (AR->getLoop() == L && AR->isAffine())
641 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000642 }
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000643 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000644
Dan Gohmanc2390b12009-02-12 22:19:27 +0000645 // Compute the type of the largest recurrence expression, and collect
646 // the set of the types of the other recurrence expressions.
647 const Type *LargestType = 0;
648 SmallSetVector<const Type *, 4> SizesToInsert;
649 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
650 LargestType = IterationCount->getType();
651 SizesToInsert.insert(IterationCount->getType());
Chris Lattnerf50af082004-04-17 18:08:33 +0000652 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000653 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
654 const PHINode *PN = IndVars[i].first;
655 SizesToInsert.insert(PN->getType());
656 const Type *EffTy = getEffectiveIndvarType(PN);
657 SizesToInsert.insert(EffTy);
658 if (!LargestType ||
659 EffTy->getPrimitiveSizeInBits() >
660 LargestType->getPrimitiveSizeInBits())
661 LargestType = EffTy;
Chris Lattner6148c022001-12-03 17:28:42 +0000662 }
663
Chris Lattner40bf8b42004-04-02 20:24:31 +0000664 // Create a rewriter object which we'll use to transform the code with.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000665 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner15cad752003-12-23 07:47:09 +0000666
Chris Lattner40bf8b42004-04-02 20:24:31 +0000667 // Now that we know the largest of of the induction variables in this loop,
668 // insert a canonical induction variable of the largest size.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000669 Value *IndVar = 0;
670 if (!SizesToInsert.empty()) {
671 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
672 ++NumInserted;
673 Changed = true;
674 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohmand19534a2007-06-15 14:38:12 +0000675 }
Chris Lattner15cad752003-12-23 07:47:09 +0000676
Dan Gohmanc2390b12009-02-12 22:19:27 +0000677 // If we have a trip count expression, rewrite the loop's exit condition
678 // using it. We can currently only handle loops with a single exit.
Dan Gohmanaa036492009-02-14 02:31:09 +0000679 bool NoSignedWrap = false;
680 bool NoUnsignedWrap = false;
Dan Gohmand2067fd2009-02-18 00:52:00 +0000681 const PHINode *OrigControllingPHI = 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000682 if (!isa<SCEVCouldNotCompute>(IterationCount) && ExitingBlock)
683 // Can't rewrite non-branch yet.
684 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
685 if (Instruction *OrigCond = dyn_cast<Instruction>(BI->getCondition())) {
Dan Gohmanaa036492009-02-14 02:31:09 +0000686 // Determine if the OrigIV will ever undergo overflow.
Dan Gohmand2067fd2009-02-18 00:52:00 +0000687 OrigControllingPHI =
688 TestOrigIVForWrap(L, BI, OrigCond,
689 NoSignedWrap, NoUnsignedWrap);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000690
691 // We'll be replacing the original condition, so it'll be dead.
692 DeadInsts.insert(OrigCond);
693 }
694
695 LinearFunctionTestReplace(L, IterationCount, IndVar,
696 ExitingBlock, BI, Rewriter);
697 }
698
Chris Lattner40bf8b42004-04-02 20:24:31 +0000699 // Now that we have a canonical induction variable, we can rewrite any
700 // recurrences in terms of the induction variable. Start with the auxillary
701 // induction variables, and recursively rewrite any of their uses.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000702 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Chris Lattner6148c022001-12-03 17:28:42 +0000703
Chris Lattner5d461d22004-04-21 22:22:01 +0000704 // If there were induction variables of other sizes, cast the primary
705 // induction variable to the right size for them, avoiding the need for the
706 // code evaluation methods to insert induction variables of different sizes.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000707 for (unsigned i = 0, e = SizesToInsert.size(); i != e; ++i) {
708 const Type *Ty = SizesToInsert[i];
709 if (Ty != LargestType) {
710 Instruction *New = new TruncInst(IndVar, Ty, "indvar", InsertPt);
711 Rewriter.addInsertedValue(New, SE->getSCEV(New));
712 DOUT << "INDVARS: Made trunc IV for type " << *Ty << ": "
713 << *New << "\n";
Reid Spencera54b7cb2007-01-12 07:05:14 +0000714 }
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000715 }
716
Chris Lattneree4f13a2007-01-07 01:14:12 +0000717 // Rewrite all induction variables in terms of the canonical induction
718 // variable.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000719 while (!IndVars.empty()) {
720 PHINode *PN = IndVars.back().first;
Dan Gohman1a5e9362009-02-17 00:10:53 +0000721 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(IndVars.back().second);
722 Value *NewVal = Rewriter.expandCodeFor(AR, InsertPt);
723 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *PN
Chris Lattneree4f13a2007-01-07 01:14:12 +0000724 << " into = " << *NewVal << "\n";
Chris Lattner6934a042007-02-11 01:23:03 +0000725 NewVal->takeName(PN);
Chris Lattner5d461d22004-04-21 22:22:01 +0000726
Dan Gohmanc2390b12009-02-12 22:19:27 +0000727 /// If the new canonical induction variable is wider than the original,
728 /// and the original has uses that are casts to wider types, see if the
729 /// truncate and extend can be omitted.
Dan Gohmand2067fd2009-02-18 00:52:00 +0000730 if (PN == OrigControllingPHI && PN->getType() != LargestType)
Dan Gohmanc2390b12009-02-12 22:19:27 +0000731 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
Dan Gohmanaa036492009-02-14 02:31:09 +0000732 UI != UE; ++UI) {
733 if (isa<SExtInst>(UI) && NoSignedWrap) {
734 SCEVHandle ExtendedStart =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000735 SE->getSignExtendExpr(AR->getStart(), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000736 SCEVHandle ExtendedStep =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000737 SE->getSignExtendExpr(AR->getStepRecurrence(*SE), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000738 SCEVHandle ExtendedAddRec =
739 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
740 if (LargestType != UI->getType())
741 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
742 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000743 UI->replaceAllUsesWith(TruncIndVar);
744 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
745 DeadInsts.insert(DeadUse);
746 }
Dan Gohmanaa036492009-02-14 02:31:09 +0000747 if (isa<ZExtInst>(UI) && NoUnsignedWrap) {
748 SCEVHandle ExtendedStart =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000749 SE->getZeroExtendExpr(AR->getStart(), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000750 SCEVHandle ExtendedStep =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000751 SE->getZeroExtendExpr(AR->getStepRecurrence(*SE), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000752 SCEVHandle ExtendedAddRec =
753 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
754 if (LargestType != UI->getType())
755 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
756 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
757 UI->replaceAllUsesWith(TruncIndVar);
758 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
759 DeadInsts.insert(DeadUse);
760 }
761 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000762
Chris Lattner40bf8b42004-04-02 20:24:31 +0000763 // Replace the old PHI Node with the inserted computation.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000764 PN->replaceAllUsesWith(NewVal);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000765 DeadInsts.insert(PN);
766 IndVars.pop_back();
767 ++NumRemoved;
Chris Lattner4753bf22001-12-05 19:41:33 +0000768 Changed = true;
Chris Lattner394437f2001-12-04 04:32:29 +0000769 }
770
Chris Lattner1363e852004-04-21 23:36:08 +0000771 DeleteTriviallyDeadInstructions(DeadInsts);
Chris Lattner9caed542007-03-04 01:00:28 +0000772 assert(L->isLCSSAForm());
Devang Patel5ee99972007-03-07 06:39:01 +0000773 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000774}
Devang Pateld22a8492008-09-09 21:41:07 +0000775
Devang Patel13877bf2008-11-18 00:40:02 +0000776/// Return true if it is OK to use SIToFPInst for an inducation variable
777/// with given inital and exit values.
778static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
779 uint64_t intIV, uint64_t intEV) {
780
Dan Gohmancafb8132009-02-17 19:13:57 +0000781 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patel13877bf2008-11-18 00:40:02 +0000782 return true;
783
784 // If the iteration range can be handled by SIToFPInst then use it.
785 APInt Max = APInt::getSignedMaxValue(32);
Bill Wendling9bef7062008-11-18 10:57:27 +0000786 if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
Devang Patel13877bf2008-11-18 00:40:02 +0000787 return true;
Dan Gohmancafb8132009-02-17 19:13:57 +0000788
Devang Patel13877bf2008-11-18 00:40:02 +0000789 return false;
790}
791
792/// convertToInt - Convert APF to an integer, if possible.
Devang Patelcd402332008-11-17 23:27:13 +0000793static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
794
795 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000796 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
797 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000798 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patelcd402332008-11-17 23:27:13 +0000799 APFloat::rmTowardZero, &isExact)
800 != APFloat::opOK)
801 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000802 if (!isExact)
Devang Patelcd402332008-11-17 23:27:13 +0000803 return false;
804 return true;
805
806}
807
Devang Patel58d43d42008-11-03 18:32:19 +0000808/// HandleFloatingPointIV - If the loop has floating induction variable
809/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000810/// For example,
811/// for(double i = 0; i < 10000; ++i)
812/// bar(i)
813/// is converted into
814/// for(int i = 0; i < 10000; ++i)
815/// bar((double)i);
816///
Dan Gohmancafb8132009-02-17 19:13:57 +0000817void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
Devang Patel84e35152008-11-17 21:32:02 +0000818 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Devang Patel58d43d42008-11-03 18:32:19 +0000819
Devang Patel84e35152008-11-17 21:32:02 +0000820 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
821 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +0000822
Devang Patel84e35152008-11-17 21:32:02 +0000823 // Check incoming value.
Devang Patelcd402332008-11-17 23:27:13 +0000824 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
825 if (!InitValue) return;
826 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
827 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
828 return;
829
830 // Check IV increment. Reject this PH if increement operation is not
831 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +0000832 BinaryOperator *Incr =
Devang Patel84e35152008-11-17 21:32:02 +0000833 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
834 if (!Incr) return;
835 if (Incr->getOpcode() != Instruction::Add) return;
836 ConstantFP *IncrValue = NULL;
837 unsigned IncrVIndex = 1;
838 if (Incr->getOperand(1) == PH)
839 IncrVIndex = 0;
840 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
841 if (!IncrValue) return;
Devang Patelcd402332008-11-17 23:27:13 +0000842 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
843 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
844 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000845
Devang Patelcd402332008-11-17 23:27:13 +0000846 // Check Incr uses. One user is PH and the other users is exit condition used
847 // by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000848 Value::use_iterator IncrUse = Incr->use_begin();
849 Instruction *U1 = cast<Instruction>(IncrUse++);
850 if (IncrUse == Incr->use_end()) return;
851 Instruction *U2 = cast<Instruction>(IncrUse++);
852 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000853
Devang Patel84e35152008-11-17 21:32:02 +0000854 // Find exit condition.
855 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
856 if (!EC)
857 EC = dyn_cast<FCmpInst>(U2);
858 if (!EC) return;
859
860 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
861 if (!BI->isConditional()) return;
862 if (BI->getCondition() != EC) return;
Devang Patel58d43d42008-11-03 18:32:19 +0000863 }
Devang Patel58d43d42008-11-03 18:32:19 +0000864
Devang Patelcd402332008-11-17 23:27:13 +0000865 // Find exit value. If exit value can not be represented as an interger then
866 // do not handle this floating point PH.
Devang Patel84e35152008-11-17 21:32:02 +0000867 ConstantFP *EV = NULL;
868 unsigned EVIndex = 1;
869 if (EC->getOperand(1) == Incr)
870 EVIndex = 0;
871 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
872 if (!EV) return;
Devang Patel84e35152008-11-17 21:32:02 +0000873 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000874 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patel84e35152008-11-17 21:32:02 +0000875 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000876
Devang Patel84e35152008-11-17 21:32:02 +0000877 // Find new predicate for integer comparison.
878 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
879 switch (EC->getPredicate()) {
880 case CmpInst::FCMP_OEQ:
881 case CmpInst::FCMP_UEQ:
882 NewPred = CmpInst::ICMP_EQ;
883 break;
884 case CmpInst::FCMP_OGT:
885 case CmpInst::FCMP_UGT:
886 NewPred = CmpInst::ICMP_UGT;
887 break;
888 case CmpInst::FCMP_OGE:
889 case CmpInst::FCMP_UGE:
890 NewPred = CmpInst::ICMP_UGE;
891 break;
892 case CmpInst::FCMP_OLT:
893 case CmpInst::FCMP_ULT:
894 NewPred = CmpInst::ICMP_ULT;
895 break;
896 case CmpInst::FCMP_OLE:
897 case CmpInst::FCMP_ULE:
898 NewPred = CmpInst::ICMP_ULE;
899 break;
900 default:
901 break;
Devang Patel58d43d42008-11-03 18:32:19 +0000902 }
Devang Patel84e35152008-11-17 21:32:02 +0000903 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000904
Devang Patel84e35152008-11-17 21:32:02 +0000905 // Insert new integer induction variable.
906 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
907 PH->getName()+".int", PH);
Devang Patelcd402332008-11-17 23:27:13 +0000908 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patel84e35152008-11-17 21:32:02 +0000909 PH->getIncomingBlock(IncomingEdge));
910
Dan Gohmancafb8132009-02-17 19:13:57 +0000911 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
912 ConstantInt::get(Type::Int32Ty,
Devang Patelcd402332008-11-17 23:27:13 +0000913 newIncrValue),
Devang Patel84e35152008-11-17 21:32:02 +0000914 Incr->getName()+".int", Incr);
915 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
916
917 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
918 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
919 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
Dan Gohmancafb8132009-02-17 19:13:57 +0000920 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
Devang Patel84e35152008-11-17 21:32:02 +0000921 EC->getParent()->getTerminator());
Dan Gohmancafb8132009-02-17 19:13:57 +0000922
Devang Patel84e35152008-11-17 21:32:02 +0000923 // Delete old, floating point, exit comparision instruction.
924 EC->replaceAllUsesWith(NewEC);
925 DeadInsts.insert(EC);
Dan Gohmancafb8132009-02-17 19:13:57 +0000926
Devang Patel84e35152008-11-17 21:32:02 +0000927 // Delete old, floating point, increment instruction.
928 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
929 DeadInsts.insert(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +0000930
Devang Patel13877bf2008-11-18 00:40:02 +0000931 // Replace floating induction variable. Give SIToFPInst preference over
932 // UIToFPInst because it is faster on platforms that are widely used.
933 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
Dan Gohmancafb8132009-02-17 19:13:57 +0000934 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patelcd402332008-11-17 23:27:13 +0000935 PH->getParent()->getFirstNonPHI());
936 PH->replaceAllUsesWith(Conv);
937 } else {
Dan Gohmancafb8132009-02-17 19:13:57 +0000938 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patelcd402332008-11-17 23:27:13 +0000939 PH->getParent()->getFirstNonPHI());
940 PH->replaceAllUsesWith(Conv);
941 }
Devang Patel84e35152008-11-17 21:32:02 +0000942 DeadInsts.insert(PH);
Devang Patel58d43d42008-11-03 18:32:19 +0000943}
944