blob: e774905976e2c9055ce46288b5605c6ac49040b7 [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
Devang Patel5ee99972007-03-07 06:39:01 +000077 bool runOnLoop(Loop *L, LPPassManager &LPM);
78 bool doInitialization(Loop *L, LPPassManager &LPM);
79 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
Chris Lattner40bf8b42004-04-02 20:24:31 +000091 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
Chris Lattner1a6111f2008-11-16 07:17:51 +000092 SmallPtrSet<Instruction*, 16> &DeadInsts);
Dan Gohmanc2390b12009-02-12 22:19:27 +000093 void LinearFunctionTestReplace(Loop *L, SCEVHandle IterationCount, Value *IndVar,
94 BasicBlock *ExitingBlock,
95 BranchInst *BI,
96 SCEVExpander &Rewriter);
Dan Gohman5a6c4482008-08-05 22:34:21 +000097 void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
Chris Lattner40bf8b42004-04-02 20:24:31 +000098
Chris Lattner1a6111f2008-11-16 07:17:51 +000099 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
Devang Pateld22a8492008-09-09 21:41:07 +0000100
Devang Patel84e35152008-11-17 21:32:02 +0000101 void HandleFloatingPointIV(Loop *L, PHINode *PH,
102 SmallPtrSet<Instruction*, 16> &DeadInsts);
Chris Lattner3324e712003-12-22 03:58:44 +0000103 };
Chris Lattner5e761402002-09-10 05:24:05 +0000104}
Chris Lattner394437f2001-12-04 04:32:29 +0000105
Dan Gohman844731a2008-05-13 00:00:25 +0000106char IndVarSimplify::ID = 0;
107static RegisterPass<IndVarSimplify>
108X("indvars", "Canonicalize Induction Variables");
109
Daniel Dunbar394f0442008-10-22 23:32:42 +0000110Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000111 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000112}
113
Chris Lattner40bf8b42004-04-02 20:24:31 +0000114/// DeleteTriviallyDeadInstructions - If any of the instructions is the
115/// specified set are trivially dead, delete them and see if this makes any of
116/// their operands subsequently dead.
117void IndVarSimplify::
Chris Lattner1a6111f2008-11-16 07:17:51 +0000118DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000119 while (!Insts.empty()) {
120 Instruction *I = *Insts.begin();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000121 Insts.erase(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000122 if (isInstructionTriviallyDead(I)) {
123 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
124 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
125 Insts.insert(U);
Dan Gohman5cec4db2007-06-19 14:28:31 +0000126 SE->deleteValueFromRecords(I);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000127 DOUT << "INDVARS: Deleting: " << *I;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000128 I->eraseFromParent();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000129 Changed = true;
130 }
131 }
132}
133
134
135/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
136/// recurrence. If so, change it into an integer recurrence, permitting
137/// analysis by the SCEV routines.
Misha Brukmanfd939082005-04-21 23:48:37 +0000138void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
Chris Lattner40bf8b42004-04-02 20:24:31 +0000139 BasicBlock *Preheader,
Chris Lattner1a6111f2008-11-16 07:17:51 +0000140 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000141 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
142 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
143 unsigned BackedgeIdx = PreheaderIdx^1;
144 if (GetElementPtrInst *GEPI =
Chris Lattnercda9ca52005-08-10 01:12:06 +0000145 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
Chris Lattner40bf8b42004-04-02 20:24:31 +0000146 if (GEPI->getOperand(0) == PN) {
Chris Lattnercda9ca52005-08-10 01:12:06 +0000147 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
Chris Lattneree4f13a2007-01-07 01:14:12 +0000148 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
149
Chris Lattner40bf8b42004-04-02 20:24:31 +0000150 // Okay, we found a pointer recurrence. Transform this pointer
151 // recurrence into an integer recurrence. Compute the value that gets
152 // added to the pointer at every iteration.
153 Value *AddedVal = GEPI->getOperand(1);
154
155 // Insert a new integer PHI node into the top of the block.
Gabor Greif051a9502008-04-06 20:25:17 +0000156 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
157 PN->getName()+".rec", PN);
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000158 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
159
Chris Lattner40bf8b42004-04-02 20:24:31 +0000160 // Create the new add instruction.
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000161 Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000162 GEPI->getName()+".rec", GEPI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000163 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000164
Chris Lattner40bf8b42004-04-02 20:24:31 +0000165 // Update the existing GEP to use the recurrence.
166 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000167
Chris Lattner40bf8b42004-04-02 20:24:31 +0000168 // Update the GEP to use the new recurrence we just inserted.
169 GEPI->setOperand(1, NewAdd);
170
Chris Lattnera4b9c782004-10-11 23:06:50 +0000171 // If the incoming value is a constant expr GEP, try peeling out the array
172 // 0 index if possible to make things simpler.
173 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
174 if (CE->getOpcode() == Instruction::GetElementPtr) {
175 unsigned NumOps = CE->getNumOperands();
176 assert(NumOps > 1 && "CE folding didn't work!");
177 if (CE->getOperand(NumOps-1)->isNullValue()) {
178 // Check to make sure the last index really is an array index.
Chris Lattner17300782005-11-18 18:30:47 +0000179 gep_type_iterator GTI = gep_type_begin(CE);
Chris Lattnerceda6052005-11-17 19:35:42 +0000180 for (unsigned i = 1, e = CE->getNumOperands()-1;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000181 i != e; ++i, ++GTI)
182 /*empty*/;
183 if (isa<SequentialType>(*GTI)) {
184 // Pull the last index out of the constant expr GEP.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000185 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000186 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000187 &CEIdxs[0],
188 CEIdxs.size());
David Greeneb8f74792007-09-04 15:46:09 +0000189 Value *Idx[2];
190 Idx[0] = Constant::getNullValue(Type::Int32Ty);
191 Idx[1] = NewAdd;
Gabor Greif051a9502008-04-06 20:25:17 +0000192 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
David Greeneb8f74792007-09-04 15:46:09 +0000193 NCE, Idx, Idx + 2,
Reid Spencercae57542007-03-02 00:28:52 +0000194 GEPI->getName(), GEPI);
Dan Gohman5cec4db2007-06-19 14:28:31 +0000195 SE->deleteValueFromRecords(GEPI);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000196 GEPI->replaceAllUsesWith(NGEPI);
197 GEPI->eraseFromParent();
198 GEPI = NGEPI;
199 }
200 }
201 }
202
203
Chris Lattner40bf8b42004-04-02 20:24:31 +0000204 // Finally, if there are any other users of the PHI node, we must
205 // insert a new GEP instruction that uses the pre-incremented version
206 // of the induction amount.
207 if (!PN->use_empty()) {
208 BasicBlock::iterator InsertPos = PN; ++InsertPos;
209 while (isa<PHINode>(InsertPos)) ++InsertPos;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000210 Value *PreInc =
Gabor Greif051a9502008-04-06 20:25:17 +0000211 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
212 NewPhi, "", InsertPos);
Chris Lattner6934a042007-02-11 01:23:03 +0000213 PreInc->takeName(PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000214 PN->replaceAllUsesWith(PreInc);
215 }
216
217 // Delete the old PHI for sure, and the GEP if its otherwise unused.
218 DeadInsts.insert(PN);
219
220 ++NumPointer;
221 Changed = true;
222 }
223}
224
225/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000226/// loop to be a canonical != comparison against the incremented loop induction
227/// variable. This pass is able to rewrite the exit tests of any loop where the
228/// SCEV analysis can determine a loop-invariant trip count of the loop, which
229/// is actually a much broader range than just linear tests.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000230void IndVarSimplify::LinearFunctionTestReplace(Loop *L,
231 SCEVHandle IterationCount,
232 Value *IndVar,
233 BasicBlock *ExitingBlock,
234 BranchInst *BI,
235 SCEVExpander &Rewriter) {
Chris Lattnerd2440572004-04-15 20:26:22 +0000236 // If the exiting block is not the same as the backedge block, we must compare
237 // against the preincremented value, otherwise we prefer to compare against
238 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000239 Value *CmpIndVar;
240 if (ExitingBlock == L->getLoopLatch()) {
241 // What ScalarEvolution calls the "iteration count" is actually the
242 // number of times the branch is taken. Add one to get the number
243 // of times the branch is executed. If this addition may overflow,
244 // we have to be more pessimistic and cast the induction variable
245 // before doing the add.
246 SCEVHandle Zero = SE->getIntegerSCEV(0, IterationCount->getType());
247 SCEVHandle N =
248 SE->getAddExpr(IterationCount,
249 SE->getIntegerSCEV(1, IterationCount->getType()));
250 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
251 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
252 // No overflow. Cast the sum.
253 IterationCount = SE->getTruncateOrZeroExtend(N, IndVar->getType());
254 } else {
255 // Potential overflow. Cast before doing the add.
256 IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
257 IndVar->getType());
258 IterationCount =
259 SE->getAddExpr(IterationCount,
260 SE->getIntegerSCEV(1, IndVar->getType()));
261 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000262
Chris Lattnerd2440572004-04-15 20:26:22 +0000263 // The IterationCount expression contains the number of times that the
264 // backedge actually branches to the loop header. This is one less than the
265 // number of times the loop executes, so add one to it.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000266 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Chris Lattnerd2440572004-04-15 20:26:22 +0000267 } else {
268 // We have to use the preincremented value...
Dan Gohmanc2390b12009-02-12 22:19:27 +0000269 IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
270 IndVar->getType());
271 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000272 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000273
Chris Lattner40bf8b42004-04-02 20:24:31 +0000274 // Expand the code for the iteration count into the preheader of the loop.
275 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohmanc2390b12009-02-12 22:19:27 +0000276 Value *ExitCnt = Rewriter.expandCodeFor(IterationCount,
277 Preheader->getTerminator());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000278
Reid Spencere4d87aa2006-12-23 06:05:41 +0000279 // Insert a new icmp_ne or icmp_eq instruction before the branch.
280 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000281 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000282 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000283 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000284 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000285
Dan Gohmanc2390b12009-02-12 22:19:27 +0000286 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
287 << " LHS:" << *CmpIndVar // includes a newline
288 << " op:\t"
Dan Gohmanf108e2e2009-02-14 02:26:50 +0000289 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohmanc2390b12009-02-12 22:19:27 +0000290 << " RHS:\t" << *IterationCount << "\n";
291
292 Value *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000293 BI->setCondition(Cond);
294 ++NumLFTR;
295 Changed = true;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000296}
297
Chris Lattner40bf8b42004-04-02 20:24:31 +0000298/// RewriteLoopExitValues - Check to see if this loop has a computable
299/// loop-invariant execution count. If so, this means that we can compute the
300/// final value of any expressions that are recurrent in the loop, and
301/// substitute the exit values from the loop into any instructions outside of
302/// the loop that use the final values of the current expressions.
Dan Gohman5a6c4482008-08-05 22:34:21 +0000303void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000304 BasicBlock *Preheader = L->getLoopPreheader();
305
306 // Scan all of the instructions in the loop, looking at those that have
307 // extra-loop users and which are recurrences.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000308 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000309
310 // We insert the code into the preheader of the loop if the loop contains
311 // multiple exit blocks, or in the exit block if there is exactly one.
312 BasicBlock *BlockToInsertInto;
Devang Patelb7211a22007-08-21 00:31:24 +0000313 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000314 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000315 if (ExitBlocks.size() == 1)
316 BlockToInsertInto = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000317 else
318 BlockToInsertInto = Preheader;
Dan Gohman02dea8b2008-05-23 21:05:58 +0000319 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000320
Dan Gohman5a6c4482008-08-05 22:34:21 +0000321 bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
Chris Lattner20aa0982004-04-17 18:44:09 +0000322
Chris Lattner1a6111f2008-11-16 07:17:51 +0000323 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000324 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanfd939082005-04-21 23:48:37 +0000325
Chris Lattner9f3d7382007-03-04 03:43:23 +0000326 // Find all values that are computed inside the loop, but used outside of it.
327 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
328 // the exit blocks of the loop to find them.
329 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
330 BasicBlock *ExitBB = ExitBlocks[i];
331
332 // If there are no PHI nodes in this exit block, then no values defined
333 // inside the loop are used on this path, skip it.
334 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
335 if (!PN) continue;
336
337 unsigned NumPreds = PN->getNumIncomingValues();
338
339 // Iterate over all of the PHI nodes.
340 BasicBlock::iterator BBI = ExitBB->begin();
341 while ((PN = dyn_cast<PHINode>(BBI++))) {
Chris Lattnerc9838f22007-03-03 22:48:48 +0000342
Chris Lattner9f3d7382007-03-04 03:43:23 +0000343 // Iterate over all of the values in all the PHI nodes.
344 for (unsigned i = 0; i != NumPreds; ++i) {
345 // If the value being merged in is not integer or is not defined
346 // in the loop, skip it.
347 Value *InVal = PN->getIncomingValue(i);
348 if (!isa<Instruction>(InVal) ||
349 // SCEV only supports integer expressions for now.
350 !isa<IntegerType>(InVal->getType()))
351 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000352
Chris Lattner9f3d7382007-03-04 03:43:23 +0000353 // If this pred is for a subloop, not L itself, skip it.
354 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
355 continue; // The Block is in a subloop, skip it.
356
357 // Check that InVal is defined in the loop.
358 Instruction *Inst = cast<Instruction>(InVal);
359 if (!L->contains(Inst->getParent()))
360 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000361
Chris Lattner9f3d7382007-03-04 03:43:23 +0000362 // We require that this value either have a computable evolution or that
363 // the loop have a constant iteration count. In the case where the loop
364 // has a constant iteration count, we can sometimes force evaluation of
365 // the exit value through brute force.
366 SCEVHandle SH = SE->getSCEV(Inst);
367 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
368 continue; // Cannot get exit evolution for the loop value.
369
370 // Okay, this instruction has a user outside of the current loop
371 // and varies predictably *inside* the loop. Evaluate the value it
372 // contains when the loop exits, if possible.
373 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
374 if (isa<SCEVCouldNotCompute>(ExitValue) ||
375 !ExitValue->isLoopInvariant(L))
376 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000377
Chris Lattner9f3d7382007-03-04 03:43:23 +0000378 Changed = true;
379 ++NumReplaced;
380
381 // See if we already computed the exit value for the instruction, if so,
382 // just reuse it.
383 Value *&ExitVal = ExitValues[Inst];
384 if (!ExitVal)
Dan Gohmand19534a2007-06-15 14:38:12 +0000385 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000386
387 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
388 << " LoopVal = " << *Inst << "\n";
389
390 PN->setIncomingValue(i, ExitVal);
391
392 // If this instruction is dead now, schedule it to be removed.
393 if (Inst->use_empty())
394 InstructionsToDelete.insert(Inst);
395
396 // See if this is a single-entry LCSSA PHI node. If so, we can (and
397 // have to) remove
Chris Lattner9caed542007-03-04 01:00:28 +0000398 // the PHI entirely. This is safe, because the NewVal won't be variant
399 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000400 if (NumPreds == 1) {
Dan Gohman5cec4db2007-06-19 14:28:31 +0000401 SE->deleteValueFromRecords(PN);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000402 PN->replaceAllUsesWith(ExitVal);
403 PN->eraseFromParent();
404 break;
Chris Lattnerc9838f22007-03-03 22:48:48 +0000405 }
406 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000407 }
408 }
409
Chris Lattner40bf8b42004-04-02 20:24:31 +0000410 DeleteTriviallyDeadInstructions(InstructionsToDelete);
411}
412
Devang Patel5ee99972007-03-07 06:39:01 +0000413bool IndVarSimplify::doInitialization(Loop *L, LPPassManager &LPM) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000414
Devang Patel5ee99972007-03-07 06:39:01 +0000415 Changed = false;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000416 // First step. Check to see if there are any trivial GEP pointer recurrences.
417 // If there are, change them into integer recurrences, permitting analysis by
418 // the SCEV routines.
419 //
420 BasicBlock *Header = L->getHeader();
421 BasicBlock *Preheader = L->getLoopPreheader();
Devang Patel5ee99972007-03-07 06:39:01 +0000422 SE = &LPM.getAnalysis<ScalarEvolution>();
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
433 if (!DeadInsts.empty())
434 DeleteTriviallyDeadInstructions(DeadInsts);
435
Devang Patel5ee99972007-03-07 06:39:01 +0000436 return Changed;
437}
Chris Lattner40bf8b42004-04-02 20:24:31 +0000438
Dan Gohmanc2390b12009-02-12 22:19:27 +0000439/// getEffectiveIndvarType - Determine the widest type that the
440/// induction-variable PHINode Phi is cast to.
441///
442static const Type *getEffectiveIndvarType(const PHINode *Phi) {
443 const Type *Ty = Phi->getType();
Chris Lattner3324e712003-12-22 03:58:44 +0000444
Dan Gohmanc2390b12009-02-12 22:19:27 +0000445 for (Value::use_const_iterator UI = Phi->use_begin(), UE = Phi->use_end();
446 UI != UE; ++UI) {
447 const Type *CandidateType = NULL;
448 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
449 CandidateType = ZI->getDestTy();
450 else if (const SExtInst *SI = dyn_cast<SExtInst>(UI))
451 CandidateType = SI->getDestTy();
452 if (CandidateType &&
453 CandidateType->getPrimitiveSizeInBits() >
454 Ty->getPrimitiveSizeInBits())
455 Ty = CandidateType;
456 }
457
458 return Ty;
459}
460
Dan Gohmanaa036492009-02-14 02:31:09 +0000461/// TestOrigIVForWrap - Analyze the original induction variable
462/// in the loop to determine whether it would ever undergo signed
463/// or unsigned overflow.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000464///
465/// TODO: This duplicates a fair amount of ScalarEvolution logic.
Dan Gohmanaa036492009-02-14 02:31:09 +0000466/// Perhaps this can be merged with ScalarEvolution::getIterationCount
467/// and/or ScalarEvolution::get{Sign,Zero}ExtendExpr.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000468///
Dan Gohmanaa036492009-02-14 02:31:09 +0000469static void TestOrigIVForWrap(const Loop *L,
470 const BranchInst *BI,
471 const Instruction *OrigCond,
472 bool &NoSignedWrap,
473 bool &NoUnsignedWrap) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000474 // Verify that the loop is sane and find the exit condition.
475 const ICmpInst *Cmp = dyn_cast<ICmpInst>(OrigCond);
Dan Gohmanaa036492009-02-14 02:31:09 +0000476 if (!Cmp) return;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000477
Dan Gohmanaa036492009-02-14 02:31:09 +0000478 const Value *CmpLHS = Cmp->getOperand(0);
479 const Value *CmpRHS = Cmp->getOperand(1);
480 const BasicBlock *TrueBB = BI->getSuccessor(0);
481 const BasicBlock *FalseBB = BI->getSuccessor(1);
482 ICmpInst::Predicate Pred = Cmp->getPredicate();
Dan Gohmanc2390b12009-02-12 22:19:27 +0000483
Dan Gohmanaa036492009-02-14 02:31:09 +0000484 // Canonicalize a constant to the RHS.
485 if (isa<ConstantInt>(CmpLHS)) {
486 Pred = ICmpInst::getSwappedPredicate(Pred);
487 std::swap(CmpLHS, CmpRHS);
488 }
489 // Canonicalize SLE to SLT.
490 if (Pred == ICmpInst::ICMP_SLE)
491 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
492 if (!CI->getValue().isMaxSignedValue()) {
493 CmpRHS = ConstantInt::get(CI->getValue() + 1);
494 Pred = ICmpInst::ICMP_SLT;
495 }
496 // Canonicalize SGT to SGE.
497 if (Pred == ICmpInst::ICMP_SGT)
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_SGE;
502 }
503 // Canonicalize SGE to SLT.
504 if (Pred == ICmpInst::ICMP_SGE) {
505 std::swap(TrueBB, FalseBB);
506 Pred = ICmpInst::ICMP_SLT;
507 }
508 // Canonicalize ULE to ULT.
509 if (Pred == ICmpInst::ICMP_ULE)
510 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
511 if (!CI->getValue().isMaxValue()) {
512 CmpRHS = ConstantInt::get(CI->getValue() + 1);
513 Pred = ICmpInst::ICMP_ULT;
514 }
515 // Canonicalize UGT to UGE.
516 if (Pred == ICmpInst::ICMP_UGT)
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_UGE;
521 }
522 // Canonicalize UGE to ULT.
523 if (Pred == ICmpInst::ICMP_UGE) {
524 std::swap(TrueBB, FalseBB);
525 Pred = ICmpInst::ICMP_ULT;
526 }
527 // For now, analyze only LT loops for signed overflow.
528 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_ULT)
529 return;
530
531 bool isSigned = Pred == ICmpInst::ICMP_SLT;
532
533 // Get the increment instruction. Look past casts if we will
Dan Gohmanc2390b12009-02-12 22:19:27 +0000534 // be able to prove that the original induction variable doesn't
Dan Gohmanaa036492009-02-14 02:31:09 +0000535 // undergo signed or unsigned overflow, respectively.
536 const Value *IncrVal = CmpLHS;
537 if (isSigned) {
538 if (const SExtInst *SI = dyn_cast<SExtInst>(CmpLHS)) {
539 if (!isa<ConstantInt>(CmpRHS) ||
540 !cast<ConstantInt>(CmpRHS)->getValue()
541 .isSignedIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
542 return;
543 IncrVal = SI->getOperand(0);
544 }
545 } else {
546 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(CmpLHS)) {
547 if (!isa<ConstantInt>(CmpRHS) ||
548 !cast<ConstantInt>(CmpRHS)->getValue()
549 .isIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
550 return;
551 IncrVal = ZI->getOperand(0);
552 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000553 }
554
555 // For now, only analyze induction variables that have simple increments.
556 const BinaryOperator *IncrOp = dyn_cast<BinaryOperator>(IncrVal);
557 if (!IncrOp ||
558 IncrOp->getOpcode() != Instruction::Add ||
559 !isa<ConstantInt>(IncrOp->getOperand(1)) ||
560 !cast<ConstantInt>(IncrOp->getOperand(1))->equalsInt(1))
Dan Gohmanaa036492009-02-14 02:31:09 +0000561 return;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000562
563 // Make sure the PHI looks like a normal IV.
564 const PHINode *PN = dyn_cast<PHINode>(IncrOp->getOperand(0));
565 if (!PN || PN->getNumIncomingValues() != 2)
Dan Gohmanaa036492009-02-14 02:31:09 +0000566 return;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000567 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
568 unsigned BackEdge = !IncomingEdge;
569 if (!L->contains(PN->getIncomingBlock(BackEdge)) ||
570 PN->getIncomingValue(BackEdge) != IncrOp)
Dan Gohmanaa036492009-02-14 02:31:09 +0000571 return;
572 if (!L->contains(TrueBB))
573 return;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000574
575 // For now, only analyze loops with a constant start value, so that
Dan Gohmanaa036492009-02-14 02:31:09 +0000576 // we can easily determine if the start value is not a maximum value
577 // which would wrap on the first iteration.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000578 const Value *InitialVal = PN->getIncomingValue(IncomingEdge);
Dan Gohmanaa036492009-02-14 02:31:09 +0000579 if (!isa<ConstantInt>(InitialVal))
580 return;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000581
Dan Gohmanaa036492009-02-14 02:31:09 +0000582 // The original induction variable will start at some non-max value,
583 // it counts up by one, and the loop iterates only while it remans
584 // less than some value in the same type. As such, it will never wrap.
585 if (isSigned &&
586 !cast<ConstantInt>(InitialVal)->getValue().isMaxSignedValue())
587 NoSignedWrap = true;
588 else if (!isSigned &&
589 !cast<ConstantInt>(InitialVal)->getValue().isMaxValue())
590 NoUnsignedWrap = true;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000591}
592
593bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Devang Patel5ee99972007-03-07 06:39:01 +0000594 LI = &getAnalysis<LoopInfo>();
595 SE = &getAnalysis<ScalarEvolution>();
596
597 Changed = false;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000598 BasicBlock *Header = L->getHeader();
599 BasicBlock *ExitingBlock = L->getExitingBlock();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000600 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000601
Chris Lattner9caed542007-03-04 01:00:28 +0000602 // Verify the input to the pass in already in LCSSA form.
603 assert(L->isLCSSAForm());
604
Chris Lattner40bf8b42004-04-02 20:24:31 +0000605 // Check to see if this loop has a computable loop-invariant execution count.
606 // If so, this means that we can compute the final value of any expressions
607 // that are recurrent in the loop, and substitute the exit values from the
608 // loop into any instructions outside of the loop that use the final values of
609 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000610 //
Chris Lattner40bf8b42004-04-02 20:24:31 +0000611 SCEVHandle IterationCount = SE->getIterationCount(L);
612 if (!isa<SCEVCouldNotCompute>(IterationCount))
Dan Gohman5a6c4482008-08-05 22:34:21 +0000613 RewriteLoopExitValues(L, IterationCount);
Chris Lattner6148c022001-12-03 17:28:42 +0000614
Chris Lattner40bf8b42004-04-02 20:24:31 +0000615 // Next, analyze all of the induction variables in the loop, canonicalizing
616 // auxillary induction variables.
617 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
618
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000619 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
620 PHINode *PN = cast<PHINode>(I);
Chris Lattner42a75512007-01-15 02:27:26 +0000621 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
Chris Lattner40bf8b42004-04-02 20:24:31 +0000622 SCEVHandle SCEV = SE->getSCEV(PN);
Dan Gohmancd3eb9b2009-02-14 02:25:19 +0000623 // FIXME: It is an extremely bad idea to indvar substitute anything more
624 // complex than affine induction variables. Doing so will put expensive
625 // polynomial evaluations inside of the loop, and the str reduction pass
626 // currently can only reduce affine polynomials. For now just disable
627 // indvar subst on anything more complex than an affine addrec.
628 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
629 if (AR->getLoop() == L && AR->isAffine())
630 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000631 }
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000632 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000633
Dan Gohmanc2390b12009-02-12 22:19:27 +0000634 // Compute the type of the largest recurrence expression, and collect
635 // the set of the types of the other recurrence expressions.
636 const Type *LargestType = 0;
637 SmallSetVector<const Type *, 4> SizesToInsert;
638 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
639 LargestType = IterationCount->getType();
640 SizesToInsert.insert(IterationCount->getType());
Chris Lattnerf50af082004-04-17 18:08:33 +0000641 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000642 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
643 const PHINode *PN = IndVars[i].first;
644 SizesToInsert.insert(PN->getType());
645 const Type *EffTy = getEffectiveIndvarType(PN);
646 SizesToInsert.insert(EffTy);
647 if (!LargestType ||
648 EffTy->getPrimitiveSizeInBits() >
649 LargestType->getPrimitiveSizeInBits())
650 LargestType = EffTy;
Chris Lattner6148c022001-12-03 17:28:42 +0000651 }
652
Chris Lattner40bf8b42004-04-02 20:24:31 +0000653 // Create a rewriter object which we'll use to transform the code with.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000654 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner15cad752003-12-23 07:47:09 +0000655
Chris Lattner40bf8b42004-04-02 20:24:31 +0000656 // Now that we know the largest of of the induction variables in this loop,
657 // insert a canonical induction variable of the largest size.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000658 Value *IndVar = 0;
659 if (!SizesToInsert.empty()) {
660 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
661 ++NumInserted;
662 Changed = true;
663 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohmand19534a2007-06-15 14:38:12 +0000664 }
Chris Lattner15cad752003-12-23 07:47:09 +0000665
Dan Gohmanc2390b12009-02-12 22:19:27 +0000666 // If we have a trip count expression, rewrite the loop's exit condition
667 // using it. We can currently only handle loops with a single exit.
Dan Gohmanaa036492009-02-14 02:31:09 +0000668 bool NoSignedWrap = false;
669 bool NoUnsignedWrap = false;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000670 if (!isa<SCEVCouldNotCompute>(IterationCount) && ExitingBlock)
671 // Can't rewrite non-branch yet.
672 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
673 if (Instruction *OrigCond = dyn_cast<Instruction>(BI->getCondition())) {
Dan Gohmanaa036492009-02-14 02:31:09 +0000674 // Determine if the OrigIV will ever undergo overflow.
675 TestOrigIVForWrap(L, BI, OrigCond,
676 NoSignedWrap, NoUnsignedWrap);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000677
678 // We'll be replacing the original condition, so it'll be dead.
679 DeadInsts.insert(OrigCond);
680 }
681
682 LinearFunctionTestReplace(L, IterationCount, IndVar,
683 ExitingBlock, BI, Rewriter);
684 }
685
Chris Lattner40bf8b42004-04-02 20:24:31 +0000686 // Now that we have a canonical induction variable, we can rewrite any
687 // recurrences in terms of the induction variable. Start with the auxillary
688 // induction variables, and recursively rewrite any of their uses.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000689 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Chris Lattner6148c022001-12-03 17:28:42 +0000690
Chris Lattner5d461d22004-04-21 22:22:01 +0000691 // If there were induction variables of other sizes, cast the primary
692 // induction variable to the right size for them, avoiding the need for the
693 // code evaluation methods to insert induction variables of different sizes.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000694 for (unsigned i = 0, e = SizesToInsert.size(); i != e; ++i) {
695 const Type *Ty = SizesToInsert[i];
696 if (Ty != LargestType) {
697 Instruction *New = new TruncInst(IndVar, Ty, "indvar", InsertPt);
698 Rewriter.addInsertedValue(New, SE->getSCEV(New));
699 DOUT << "INDVARS: Made trunc IV for type " << *Ty << ": "
700 << *New << "\n";
Reid Spencera54b7cb2007-01-12 07:05:14 +0000701 }
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000702 }
703
Chris Lattneree4f13a2007-01-07 01:14:12 +0000704 // Rewrite all induction variables in terms of the canonical induction
705 // variable.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000706 while (!IndVars.empty()) {
707 PHINode *PN = IndVars.back().first;
Dan Gohman1a5e9362009-02-17 00:10:53 +0000708 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(IndVars.back().second);
709 Value *NewVal = Rewriter.expandCodeFor(AR, InsertPt);
710 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *PN
Chris Lattneree4f13a2007-01-07 01:14:12 +0000711 << " into = " << *NewVal << "\n";
Chris Lattner6934a042007-02-11 01:23:03 +0000712 NewVal->takeName(PN);
Chris Lattner5d461d22004-04-21 22:22:01 +0000713
Dan Gohmanc2390b12009-02-12 22:19:27 +0000714 /// If the new canonical induction variable is wider than the original,
715 /// and the original has uses that are casts to wider types, see if the
716 /// truncate and extend can be omitted.
Dan Gohmanaa036492009-02-14 02:31:09 +0000717 if (PN->getType() != LargestType)
Dan Gohmanc2390b12009-02-12 22:19:27 +0000718 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
Dan Gohmanaa036492009-02-14 02:31:09 +0000719 UI != UE; ++UI) {
720 if (isa<SExtInst>(UI) && NoSignedWrap) {
721 SCEVHandle ExtendedStart =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000722 SE->getSignExtendExpr(AR->getStart(), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000723 SCEVHandle ExtendedStep =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000724 SE->getSignExtendExpr(AR->getStepRecurrence(*SE), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000725 SCEVHandle ExtendedAddRec =
726 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
727 if (LargestType != UI->getType())
728 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
729 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000730 UI->replaceAllUsesWith(TruncIndVar);
731 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
732 DeadInsts.insert(DeadUse);
733 }
Dan Gohmanaa036492009-02-14 02:31:09 +0000734 if (isa<ZExtInst>(UI) && NoUnsignedWrap) {
735 SCEVHandle ExtendedStart =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000736 SE->getZeroExtendExpr(AR->getStart(), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000737 SCEVHandle ExtendedStep =
Dan Gohman1a5e9362009-02-17 00:10:53 +0000738 SE->getZeroExtendExpr(AR->getStepRecurrence(*SE), LargestType);
Dan Gohmanaa036492009-02-14 02:31:09 +0000739 SCEVHandle ExtendedAddRec =
740 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
741 if (LargestType != UI->getType())
742 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
743 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
744 UI->replaceAllUsesWith(TruncIndVar);
745 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
746 DeadInsts.insert(DeadUse);
747 }
748 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000749
Chris Lattner40bf8b42004-04-02 20:24:31 +0000750 // Replace the old PHI Node with the inserted computation.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000751 PN->replaceAllUsesWith(NewVal);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000752 DeadInsts.insert(PN);
753 IndVars.pop_back();
754 ++NumRemoved;
Chris Lattner4753bf22001-12-05 19:41:33 +0000755 Changed = true;
Chris Lattner394437f2001-12-04 04:32:29 +0000756 }
757
Chris Lattner1363e852004-04-21 23:36:08 +0000758 DeleteTriviallyDeadInstructions(DeadInsts);
Chris Lattner9caed542007-03-04 01:00:28 +0000759 assert(L->isLCSSAForm());
Devang Patel5ee99972007-03-07 06:39:01 +0000760 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000761}
Devang Pateld22a8492008-09-09 21:41:07 +0000762
Devang Patel13877bf2008-11-18 00:40:02 +0000763/// Return true if it is OK to use SIToFPInst for an inducation variable
764/// with given inital and exit values.
765static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
766 uint64_t intIV, uint64_t intEV) {
767
768 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
769 return true;
770
771 // If the iteration range can be handled by SIToFPInst then use it.
772 APInt Max = APInt::getSignedMaxValue(32);
Bill Wendling9bef7062008-11-18 10:57:27 +0000773 if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
Devang Patel13877bf2008-11-18 00:40:02 +0000774 return true;
775
776 return false;
777}
778
779/// convertToInt - Convert APF to an integer, if possible.
Devang Patelcd402332008-11-17 23:27:13 +0000780static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
781
782 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000783 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
784 return false;
Devang Patelcd402332008-11-17 23:27:13 +0000785 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
786 APFloat::rmTowardZero, &isExact)
787 != APFloat::opOK)
788 return false;
789 if (!isExact)
790 return false;
791 return true;
792
793}
794
Devang Patel58d43d42008-11-03 18:32:19 +0000795/// HandleFloatingPointIV - If the loop has floating induction variable
796/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000797/// For example,
798/// for(double i = 0; i < 10000; ++i)
799/// bar(i)
800/// is converted into
801/// for(int i = 0; i < 10000; ++i)
802/// bar((double)i);
803///
804void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
805 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Devang Patel58d43d42008-11-03 18:32:19 +0000806
Devang Patel84e35152008-11-17 21:32:02 +0000807 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
808 unsigned BackEdge = IncomingEdge^1;
809
810 // Check incoming value.
Devang Patelcd402332008-11-17 23:27:13 +0000811 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
812 if (!InitValue) return;
813 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
814 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
815 return;
816
817 // Check IV increment. Reject this PH if increement operation is not
818 // an add or increment value can not be represented by an integer.
Devang Patel84e35152008-11-17 21:32:02 +0000819 BinaryOperator *Incr =
820 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
821 if (!Incr) return;
822 if (Incr->getOpcode() != Instruction::Add) return;
823 ConstantFP *IncrValue = NULL;
824 unsigned IncrVIndex = 1;
825 if (Incr->getOperand(1) == PH)
826 IncrVIndex = 0;
827 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
828 if (!IncrValue) return;
Devang Patelcd402332008-11-17 23:27:13 +0000829 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
830 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
831 return;
Devang Patel84e35152008-11-17 21:32:02 +0000832
Devang Patelcd402332008-11-17 23:27:13 +0000833 // Check Incr uses. One user is PH and the other users is exit condition used
834 // by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000835 Value::use_iterator IncrUse = Incr->use_begin();
836 Instruction *U1 = cast<Instruction>(IncrUse++);
837 if (IncrUse == Incr->use_end()) return;
838 Instruction *U2 = cast<Instruction>(IncrUse++);
839 if (IncrUse != Incr->use_end()) return;
840
841 // Find exit condition.
842 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
843 if (!EC)
844 EC = dyn_cast<FCmpInst>(U2);
845 if (!EC) return;
846
847 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
848 if (!BI->isConditional()) return;
849 if (BI->getCondition() != EC) return;
Devang Patel58d43d42008-11-03 18:32:19 +0000850 }
Devang Patel58d43d42008-11-03 18:32:19 +0000851
Devang Patelcd402332008-11-17 23:27:13 +0000852 // Find exit value. If exit value can not be represented as an interger then
853 // do not handle this floating point PH.
Devang Patel84e35152008-11-17 21:32:02 +0000854 ConstantFP *EV = NULL;
855 unsigned EVIndex = 1;
856 if (EC->getOperand(1) == Incr)
857 EVIndex = 0;
858 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
859 if (!EV) return;
Devang Patel84e35152008-11-17 21:32:02 +0000860 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000861 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patel84e35152008-11-17 21:32:02 +0000862 return;
Devang Patel84e35152008-11-17 21:32:02 +0000863
864 // Find new predicate for integer comparison.
865 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
866 switch (EC->getPredicate()) {
867 case CmpInst::FCMP_OEQ:
868 case CmpInst::FCMP_UEQ:
869 NewPred = CmpInst::ICMP_EQ;
870 break;
871 case CmpInst::FCMP_OGT:
872 case CmpInst::FCMP_UGT:
873 NewPred = CmpInst::ICMP_UGT;
874 break;
875 case CmpInst::FCMP_OGE:
876 case CmpInst::FCMP_UGE:
877 NewPred = CmpInst::ICMP_UGE;
878 break;
879 case CmpInst::FCMP_OLT:
880 case CmpInst::FCMP_ULT:
881 NewPred = CmpInst::ICMP_ULT;
882 break;
883 case CmpInst::FCMP_OLE:
884 case CmpInst::FCMP_ULE:
885 NewPred = CmpInst::ICMP_ULE;
886 break;
887 default:
888 break;
Devang Patel58d43d42008-11-03 18:32:19 +0000889 }
Devang Patel84e35152008-11-17 21:32:02 +0000890 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
891
892 // Insert new integer induction variable.
893 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
894 PH->getName()+".int", PH);
Devang Patelcd402332008-11-17 23:27:13 +0000895 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patel84e35152008-11-17 21:32:02 +0000896 PH->getIncomingBlock(IncomingEdge));
897
898 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
Devang Patelcd402332008-11-17 23:27:13 +0000899 ConstantInt::get(Type::Int32Ty,
900 newIncrValue),
Devang Patel84e35152008-11-17 21:32:02 +0000901 Incr->getName()+".int", Incr);
902 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
903
904 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
905 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
906 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
907 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
908 EC->getParent()->getTerminator());
909
910 // Delete old, floating point, exit comparision instruction.
911 EC->replaceAllUsesWith(NewEC);
912 DeadInsts.insert(EC);
913
914 // Delete old, floating point, increment instruction.
915 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
916 DeadInsts.insert(Incr);
917
Devang Patel13877bf2008-11-18 00:40:02 +0000918 // Replace floating induction variable. Give SIToFPInst preference over
919 // UIToFPInst because it is faster on platforms that are widely used.
920 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
Devang Patelcd402332008-11-17 23:27:13 +0000921 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
922 PH->getParent()->getFirstNonPHI());
923 PH->replaceAllUsesWith(Conv);
924 } else {
925 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
926 PH->getParent()->getFirstNonPHI());
927 PH->replaceAllUsesWith(Conv);
928 }
Devang Patel84e35152008-11-17 21:32:02 +0000929 DeadInsts.insert(PH);
Devang Patel58d43d42008-11-03 18:32:19 +0000930}
931