blob: 3e944d3857ace83ad65be1fe7bd3fef2e48d8d01 [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");
Chris Lattner0e5f4992006-12-19 21:40:18 +000062STATISTIC(NumInserted, "Number of canonical indvars added");
63STATISTIC(NumReplaced, "Number of exit values replaced");
64STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000065
Chris Lattner0e5f4992006-12-19 21:40:18 +000066namespace {
Devang Patel5ee99972007-03-07 06:39:01 +000067 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
Chris Lattner40bf8b42004-04-02 20:24:31 +000068 LoopInfo *LI;
69 ScalarEvolution *SE;
Chris Lattner15cad752003-12-23 07:47:09 +000070 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000071 public:
Devang Patel794fd752007-05-01 21:15:47 +000072
Nick Lewyckyecd94c82007-05-06 13:37:16 +000073 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000074 IndVarSimplify() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000075
Dan Gohman60f8a632009-02-17 20:49:49 +000076 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
77
Devang Patel5ee99972007-03-07 06:39:01 +000078 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patelbc533cd2007-09-10 18:08:23 +000079 AU.addRequired<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000080 AU.addRequiredID(LCSSAID);
81 AU.addRequiredID(LoopSimplifyID);
Devang Patel5ee99972007-03-07 06:39:01 +000082 AU.addRequired<LoopInfo>();
Dan Gohman474cecf2009-02-23 16:29:41 +000083 AU.addPreserved<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000084 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
Dan Gohman46bdfb02009-02-24 18:55:53 +000093 void LinearFunctionTestReplace(Loop *L, SCEVHandle BackedgeTakenCount,
Dan Gohmana5758712009-02-17 15:57:39 +000094 Value *IndVar,
Dan Gohmanc2390b12009-02-12 22:19:27 +000095 BasicBlock *ExitingBlock,
96 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +000097 SCEVExpander &Rewriter);
Dan Gohman890f92b2009-04-18 17:56:28 +000098 void RewriteLoopExitValues(Loop *L, const SCEV *BackedgeTakenCount);
Chris Lattner40bf8b42004-04-02 20:24:31 +000099
Chris Lattner1a6111f2008-11-16 07:17:51 +0000100 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
Devang Pateld22a8492008-09-09 21:41:07 +0000101
Dan Gohmancafb8132009-02-17 19:13:57 +0000102 void HandleFloatingPointIV(Loop *L, PHINode *PH,
Devang Patel84e35152008-11-17 21:32:02 +0000103 SmallPtrSet<Instruction*, 16> &DeadInsts);
Chris Lattner3324e712003-12-22 03:58:44 +0000104 };
Chris Lattner5e761402002-09-10 05:24:05 +0000105}
Chris Lattner394437f2001-12-04 04:32:29 +0000106
Dan Gohman844731a2008-05-13 00:00:25 +0000107char IndVarSimplify::ID = 0;
108static RegisterPass<IndVarSimplify>
109X("indvars", "Canonicalize Induction Variables");
110
Daniel Dunbar394f0442008-10-22 23:32:42 +0000111Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000112 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000113}
114
Chris Lattner40bf8b42004-04-02 20:24:31 +0000115/// DeleteTriviallyDeadInstructions - If any of the instructions is the
116/// specified set are trivially dead, delete them and see if this makes any of
117/// their operands subsequently dead.
118void IndVarSimplify::
Chris Lattner1a6111f2008-11-16 07:17:51 +0000119DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000120 while (!Insts.empty()) {
121 Instruction *I = *Insts.begin();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000122 Insts.erase(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000123 if (isInstructionTriviallyDead(I)) {
124 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
125 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
126 Insts.insert(U);
Dan Gohman5cec4db2007-06-19 14:28:31 +0000127 SE->deleteValueFromRecords(I);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000128 DOUT << "INDVARS: Deleting: " << *I;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000129 I->eraseFromParent();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000130 Changed = true;
131 }
132 }
133}
134
Chris Lattner40bf8b42004-04-02 20:24:31 +0000135/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000136/// loop to be a canonical != comparison against the incremented loop induction
137/// variable. This pass is able to rewrite the exit tests of any loop where the
138/// SCEV analysis can determine a loop-invariant trip count of the loop, which
139/// is actually a much broader range than just linear tests.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000140void IndVarSimplify::LinearFunctionTestReplace(Loop *L,
Dan Gohman46bdfb02009-02-24 18:55:53 +0000141 SCEVHandle BackedgeTakenCount,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000142 Value *IndVar,
143 BasicBlock *ExitingBlock,
144 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000145 SCEVExpander &Rewriter) {
Chris Lattnerd2440572004-04-15 20:26:22 +0000146 // If the exiting block is not the same as the backedge block, we must compare
147 // against the preincremented value, otherwise we prefer to compare against
148 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000149 Value *CmpIndVar;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000150 SCEVHandle RHS = BackedgeTakenCount;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000151 if (ExitingBlock == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000152 // Add one to the "backedge-taken" count to get the trip count.
153 // If this addition may overflow, we have to be more pessimistic and
154 // cast the induction variable before doing the add.
155 SCEVHandle Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000156 SCEVHandle N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000157 SE->getAddExpr(BackedgeTakenCount,
158 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000159 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
160 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
161 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000162 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000163 } else {
164 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000165 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
166 IndVar->getType());
167 RHS = SE->getAddExpr(RHS,
168 SE->getIntegerSCEV(1, IndVar->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000169 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000170
Dan Gohman46bdfb02009-02-24 18:55:53 +0000171 // The BackedgeTaken expression contains the number of times that the
172 // backedge branches to the loop header. This is one less than the
173 // number of times the loop executes, so use the incremented indvar.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000174 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Chris Lattnerd2440572004-04-15 20:26:22 +0000175 } else {
176 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000177 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
178 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000179 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000180 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000181
Chris Lattner40bf8b42004-04-02 20:24:31 +0000182 // Expand the code for the iteration count into the preheader of the loop.
183 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman2d1be872009-04-16 03:18:22 +0000184 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(),
Dan Gohmanc2390b12009-02-12 22:19:27 +0000185 Preheader->getTerminator());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000186
Reid Spencere4d87aa2006-12-23 06:05:41 +0000187 // Insert a new icmp_ne or icmp_eq instruction before the branch.
188 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000189 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000190 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000191 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000192 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000193
Dan Gohmanc2390b12009-02-12 22:19:27 +0000194 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
195 << " LHS:" << *CmpIndVar // includes a newline
196 << " op:\t"
Dan Gohmanf108e2e2009-02-14 02:26:50 +0000197 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohman46bdfb02009-02-24 18:55:53 +0000198 << " RHS:\t" << *RHS << "\n";
Dan Gohmanc2390b12009-02-12 22:19:27 +0000199
200 Value *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000201 BI->setCondition(Cond);
202 ++NumLFTR;
203 Changed = true;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000204}
205
Chris Lattner40bf8b42004-04-02 20:24:31 +0000206/// RewriteLoopExitValues - Check to see if this loop has a computable
207/// loop-invariant execution count. If so, this means that we can compute the
208/// final value of any expressions that are recurrent in the loop, and
209/// substitute the exit values from the loop into any instructions outside of
210/// the loop that use the final values of the current expressions.
Dan Gohman890f92b2009-04-18 17:56:28 +0000211void IndVarSimplify::RewriteLoopExitValues(Loop *L,
212 const SCEV *BackedgeTakenCount) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000213 BasicBlock *Preheader = L->getLoopPreheader();
214
215 // Scan all of the instructions in the loop, looking at those that have
216 // extra-loop users and which are recurrences.
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000217 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000218
219 // We insert the code into the preheader of the loop if the loop contains
220 // multiple exit blocks, or in the exit block if there is exactly one.
221 BasicBlock *BlockToInsertInto;
Devang Patelb7211a22007-08-21 00:31:24 +0000222 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000223 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000224 if (ExitBlocks.size() == 1)
225 BlockToInsertInto = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000226 else
227 BlockToInsertInto = Preheader;
Dan Gohman02dea8b2008-05-23 21:05:58 +0000228 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000229
Dan Gohman46bdfb02009-02-24 18:55:53 +0000230 bool HasConstantItCount = isa<SCEVConstant>(BackedgeTakenCount);
Chris Lattner20aa0982004-04-17 18:44:09 +0000231
Chris Lattner1a6111f2008-11-16 07:17:51 +0000232 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000233 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanfd939082005-04-21 23:48:37 +0000234
Chris Lattner9f3d7382007-03-04 03:43:23 +0000235 // Find all values that are computed inside the loop, but used outside of it.
236 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
237 // the exit blocks of the loop to find them.
238 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
239 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000240
Chris Lattner9f3d7382007-03-04 03:43:23 +0000241 // If there are no PHI nodes in this exit block, then no values defined
242 // inside the loop are used on this path, skip it.
243 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
244 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000245
Chris Lattner9f3d7382007-03-04 03:43:23 +0000246 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000247
Chris Lattner9f3d7382007-03-04 03:43:23 +0000248 // Iterate over all of the PHI nodes.
249 BasicBlock::iterator BBI = ExitBB->begin();
250 while ((PN = dyn_cast<PHINode>(BBI++))) {
Dan Gohmancafb8132009-02-17 19:13:57 +0000251
Chris Lattner9f3d7382007-03-04 03:43:23 +0000252 // Iterate over all of the values in all the PHI nodes.
253 for (unsigned i = 0; i != NumPreds; ++i) {
254 // If the value being merged in is not integer or is not defined
255 // in the loop, skip it.
256 Value *InVal = PN->getIncomingValue(i);
257 if (!isa<Instruction>(InVal) ||
258 // SCEV only supports integer expressions for now.
Dan Gohman2d1be872009-04-16 03:18:22 +0000259 (!isa<IntegerType>(InVal->getType()) &&
260 !isa<PointerType>(InVal->getType())))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000261 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000262
Chris Lattner9f3d7382007-03-04 03:43:23 +0000263 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000264 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000265 continue; // The Block is in a subloop, skip it.
266
267 // Check that InVal is defined in the loop.
268 Instruction *Inst = cast<Instruction>(InVal);
269 if (!L->contains(Inst->getParent()))
270 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000271
Chris Lattner9f3d7382007-03-04 03:43:23 +0000272 // We require that this value either have a computable evolution or that
273 // the loop have a constant iteration count. In the case where the loop
274 // has a constant iteration count, we can sometimes force evaluation of
275 // the exit value through brute force.
276 SCEVHandle SH = SE->getSCEV(Inst);
277 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
278 continue; // Cannot get exit evolution for the loop value.
Dan Gohmancafb8132009-02-17 19:13:57 +0000279
Chris Lattner9f3d7382007-03-04 03:43:23 +0000280 // Okay, this instruction has a user outside of the current loop
281 // and varies predictably *inside* the loop. Evaluate the value it
282 // contains when the loop exits, if possible.
283 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
284 if (isa<SCEVCouldNotCompute>(ExitValue) ||
285 !ExitValue->isLoopInvariant(L))
286 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000287
Chris Lattner9f3d7382007-03-04 03:43:23 +0000288 Changed = true;
289 ++NumReplaced;
Dan Gohmancafb8132009-02-17 19:13:57 +0000290
Chris Lattner9f3d7382007-03-04 03:43:23 +0000291 // See if we already computed the exit value for the instruction, if so,
292 // just reuse it.
293 Value *&ExitVal = ExitValues[Inst];
294 if (!ExitVal)
Dan Gohman2d1be872009-04-16 03:18:22 +0000295 ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), InsertPt);
Dan Gohmancafb8132009-02-17 19:13:57 +0000296
Chris Lattner9f3d7382007-03-04 03:43:23 +0000297 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
298 << " LoopVal = " << *Inst << "\n";
299
300 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000301
Chris Lattner9f3d7382007-03-04 03:43:23 +0000302 // If this instruction is dead now, schedule it to be removed.
303 if (Inst->use_empty())
304 InstructionsToDelete.insert(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000305
Chris Lattner9f3d7382007-03-04 03:43:23 +0000306 // See if this is a single-entry LCSSA PHI node. If so, we can (and
307 // have to) remove
Chris Lattner9caed542007-03-04 01:00:28 +0000308 // the PHI entirely. This is safe, because the NewVal won't be variant
309 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000310 if (NumPreds == 1) {
Dan Gohman5cec4db2007-06-19 14:28:31 +0000311 SE->deleteValueFromRecords(PN);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000312 PN->replaceAllUsesWith(ExitVal);
313 PN->eraseFromParent();
314 break;
Chris Lattnerc9838f22007-03-03 22:48:48 +0000315 }
316 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000317 }
318 }
Dan Gohmancafb8132009-02-17 19:13:57 +0000319
Chris Lattner40bf8b42004-04-02 20:24:31 +0000320 DeleteTriviallyDeadInstructions(InstructionsToDelete);
321}
322
Dan Gohman60f8a632009-02-17 20:49:49 +0000323void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000324 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000325 // If there are, change them into integer recurrences, permitting analysis by
326 // the SCEV routines.
327 //
328 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000329
Chris Lattner1a6111f2008-11-16 07:17:51 +0000330 SmallPtrSet<Instruction*, 16> DeadInsts;
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000331 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
332 PHINode *PN = cast<PHINode>(I);
Dan Gohman2d1be872009-04-16 03:18:22 +0000333 HandleFloatingPointIV(L, PN, DeadInsts);
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000334 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000335
Dan Gohman2d1be872009-04-16 03:18:22 +0000336 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000337 // may not have been able to compute a trip count. Now that we've done some
338 // re-writing, the trip count may be computable.
339 if (Changed)
Dan Gohman46bdfb02009-02-24 18:55:53 +0000340 SE->forgetLoopBackedgeTakenCount(L);
Dan Gohman60f8a632009-02-17 20:49:49 +0000341
Chris Lattner40bf8b42004-04-02 20:24:31 +0000342 if (!DeadInsts.empty())
343 DeleteTriviallyDeadInstructions(DeadInsts);
Devang Patel5ee99972007-03-07 06:39:01 +0000344}
Chris Lattner40bf8b42004-04-02 20:24:31 +0000345
Dan Gohmanc2390b12009-02-12 22:19:27 +0000346/// getEffectiveIndvarType - Determine the widest type that the
347/// induction-variable PHINode Phi is cast to.
348///
Dan Gohman2d1be872009-04-16 03:18:22 +0000349static const Type *getEffectiveIndvarType(const PHINode *Phi,
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000350 const ScalarEvolution *SE) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000351 const Type *Ty = Phi->getType();
Chris Lattner3324e712003-12-22 03:58:44 +0000352
Dan Gohmanc2390b12009-02-12 22:19:27 +0000353 for (Value::use_const_iterator UI = Phi->use_begin(), UE = Phi->use_end();
354 UI != UE; ++UI) {
355 const Type *CandidateType = NULL;
356 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
357 CandidateType = ZI->getDestTy();
358 else if (const SExtInst *SI = dyn_cast<SExtInst>(UI))
359 CandidateType = SI->getDestTy();
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000360 else if (const IntToPtrInst *IP = dyn_cast<IntToPtrInst>(UI))
361 CandidateType = IP->getDestTy();
362 else if (const PtrToIntInst *PI = dyn_cast<PtrToIntInst>(UI))
363 CandidateType = PI->getDestTy();
Dan Gohmanc2390b12009-02-12 22:19:27 +0000364 if (CandidateType &&
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000365 SE->isSCEVable(CandidateType) &&
366 SE->getTypeSizeInBits(CandidateType) > SE->getTypeSizeInBits(Ty))
Dan Gohmanc2390b12009-02-12 22:19:27 +0000367 Ty = CandidateType;
368 }
369
370 return Ty;
371}
372
Dan Gohmanaa036492009-02-14 02:31:09 +0000373/// TestOrigIVForWrap - Analyze the original induction variable
Dan Gohmand2067fd2009-02-18 00:52:00 +0000374/// that controls the loop's iteration to determine whether it
Dan Gohmanf5a309e2009-02-18 17:22:41 +0000375/// would ever undergo signed or unsigned overflow. Also, check
376/// whether an induction variable in the same type that starts
377/// at 0 would undergo signed overflow.
Dan Gohmand2067fd2009-02-18 00:52:00 +0000378///
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000379/// In addition to setting the NoSignedWrap and NoUnsignedWrap
380/// variables to true when appropriate (they are not set to false here),
381/// return the PHI for this induction variable. Also record the initial
382/// and final values and the increment; these are not meaningful unless
383/// either NoSignedWrap or NoUnsignedWrap is true, and are always meaningful
384/// in that case, although the final value may be 0 indicating a nonconstant.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000385///
386/// TODO: This duplicates a fair amount of ScalarEvolution logic.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000387/// Perhaps this can be merged with
388/// ScalarEvolution::getBackedgeTakenCount
Dan Gohmanaa036492009-02-14 02:31:09 +0000389/// and/or ScalarEvolution::get{Sign,Zero}ExtendExpr.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000390///
Dan Gohmand2067fd2009-02-18 00:52:00 +0000391static const PHINode *TestOrigIVForWrap(const Loop *L,
392 const BranchInst *BI,
393 const Instruction *OrigCond,
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000394 const ScalarEvolution &SE,
Dan Gohmand2067fd2009-02-18 00:52:00 +0000395 bool &NoSignedWrap,
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000396 bool &NoUnsignedWrap,
397 const ConstantInt* &InitialVal,
398 const ConstantInt* &IncrVal,
399 const ConstantInt* &LimitVal) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000400 // Verify that the loop is sane and find the exit condition.
401 const ICmpInst *Cmp = dyn_cast<ICmpInst>(OrigCond);
Dan Gohmand2067fd2009-02-18 00:52:00 +0000402 if (!Cmp) return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000403
Dan Gohmanaa036492009-02-14 02:31:09 +0000404 const Value *CmpLHS = Cmp->getOperand(0);
405 const Value *CmpRHS = Cmp->getOperand(1);
406 const BasicBlock *TrueBB = BI->getSuccessor(0);
407 const BasicBlock *FalseBB = BI->getSuccessor(1);
408 ICmpInst::Predicate Pred = Cmp->getPredicate();
Dan Gohmanc2390b12009-02-12 22:19:27 +0000409
Dan Gohmanaa036492009-02-14 02:31:09 +0000410 // Canonicalize a constant to the RHS.
411 if (isa<ConstantInt>(CmpLHS)) {
412 Pred = ICmpInst::getSwappedPredicate(Pred);
413 std::swap(CmpLHS, CmpRHS);
414 }
415 // Canonicalize SLE to SLT.
416 if (Pred == ICmpInst::ICMP_SLE)
417 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
418 if (!CI->getValue().isMaxSignedValue()) {
419 CmpRHS = ConstantInt::get(CI->getValue() + 1);
420 Pred = ICmpInst::ICMP_SLT;
421 }
422 // Canonicalize SGT to SGE.
423 if (Pred == ICmpInst::ICMP_SGT)
424 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
425 if (!CI->getValue().isMaxSignedValue()) {
426 CmpRHS = ConstantInt::get(CI->getValue() + 1);
427 Pred = ICmpInst::ICMP_SGE;
428 }
429 // Canonicalize SGE to SLT.
430 if (Pred == ICmpInst::ICMP_SGE) {
431 std::swap(TrueBB, FalseBB);
432 Pred = ICmpInst::ICMP_SLT;
433 }
434 // Canonicalize ULE to ULT.
435 if (Pred == ICmpInst::ICMP_ULE)
436 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
437 if (!CI->getValue().isMaxValue()) {
438 CmpRHS = ConstantInt::get(CI->getValue() + 1);
439 Pred = ICmpInst::ICMP_ULT;
440 }
441 // Canonicalize UGT to UGE.
442 if (Pred == ICmpInst::ICMP_UGT)
443 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
444 if (!CI->getValue().isMaxValue()) {
445 CmpRHS = ConstantInt::get(CI->getValue() + 1);
446 Pred = ICmpInst::ICMP_UGE;
447 }
448 // Canonicalize UGE to ULT.
449 if (Pred == ICmpInst::ICMP_UGE) {
450 std::swap(TrueBB, FalseBB);
451 Pred = ICmpInst::ICMP_ULT;
452 }
453 // For now, analyze only LT loops for signed overflow.
454 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_ULT)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000455 return 0;
Dan Gohmanaa036492009-02-14 02:31:09 +0000456
457 bool isSigned = Pred == ICmpInst::ICMP_SLT;
458
459 // Get the increment instruction. Look past casts if we will
Dan Gohmanc2390b12009-02-12 22:19:27 +0000460 // be able to prove that the original induction variable doesn't
Dan Gohmanaa036492009-02-14 02:31:09 +0000461 // undergo signed or unsigned overflow, respectively.
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000462 const Value *IncrInst = CmpLHS;
Dan Gohmanaa036492009-02-14 02:31:09 +0000463 if (isSigned) {
464 if (const SExtInst *SI = dyn_cast<SExtInst>(CmpLHS)) {
465 if (!isa<ConstantInt>(CmpRHS) ||
466 !cast<ConstantInt>(CmpRHS)->getValue()
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000467 .isSignedIntN(SE.getTypeSizeInBits(IncrInst->getType())))
Dan Gohmand2067fd2009-02-18 00:52:00 +0000468 return 0;
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000469 IncrInst = SI->getOperand(0);
Dan Gohmanaa036492009-02-14 02:31:09 +0000470 }
471 } else {
472 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(CmpLHS)) {
473 if (!isa<ConstantInt>(CmpRHS) ||
474 !cast<ConstantInt>(CmpRHS)->getValue()
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000475 .isIntN(SE.getTypeSizeInBits(IncrInst->getType())))
Dan Gohmand2067fd2009-02-18 00:52:00 +0000476 return 0;
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000477 IncrInst = ZI->getOperand(0);
Dan Gohmanaa036492009-02-14 02:31:09 +0000478 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000479 }
480
481 // For now, only analyze induction variables that have simple increments.
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000482 const BinaryOperator *IncrOp = dyn_cast<BinaryOperator>(IncrInst);
483 if (!IncrOp || IncrOp->getOpcode() != Instruction::Add)
484 return 0;
485 IncrVal = dyn_cast<ConstantInt>(IncrOp->getOperand(1));
486 if (!IncrVal)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000487 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000488
489 // Make sure the PHI looks like a normal IV.
490 const PHINode *PN = dyn_cast<PHINode>(IncrOp->getOperand(0));
491 if (!PN || PN->getNumIncomingValues() != 2)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000492 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000493 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
494 unsigned BackEdge = !IncomingEdge;
495 if (!L->contains(PN->getIncomingBlock(BackEdge)) ||
496 PN->getIncomingValue(BackEdge) != IncrOp)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000497 return 0;
Dan Gohmanaa036492009-02-14 02:31:09 +0000498 if (!L->contains(TrueBB))
Dan Gohmand2067fd2009-02-18 00:52:00 +0000499 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000500
501 // For now, only analyze loops with a constant start value, so that
Dan Gohmanaa036492009-02-14 02:31:09 +0000502 // we can easily determine if the start value is not a maximum value
503 // which would wrap on the first iteration.
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000504 InitialVal = dyn_cast<ConstantInt>(PN->getIncomingValue(IncomingEdge));
Dan Gohmancad24c92009-02-18 16:54:33 +0000505 if (!InitialVal)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000506 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000507
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000508 // The upper limit need not be a constant; we'll check later.
509 LimitVal = dyn_cast<ConstantInt>(CmpRHS);
510
511 // We detect the impossibility of wrapping in two cases, both of
512 // which require starting with a non-max value:
513 // - The IV counts up by one, and the loop iterates only while it remains
514 // less than a limiting value (any) in the same type.
515 // - The IV counts up by a positive increment other than 1, and the
516 // constant limiting value + the increment is less than the max value
517 // (computed as max-increment to avoid overflow)
Dan Gohmanf5a309e2009-02-18 17:22:41 +0000518 if (isSigned && !InitialVal->getValue().isMaxSignedValue()) {
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000519 if (IncrVal->equalsInt(1))
520 NoSignedWrap = true; // LimitVal need not be constant
521 else if (LimitVal) {
522 uint64_t numBits = LimitVal->getValue().getBitWidth();
523 if (IncrVal->getValue().sgt(APInt::getNullValue(numBits)) &&
524 (APInt::getSignedMaxValue(numBits) - IncrVal->getValue())
525 .sgt(LimitVal->getValue()))
526 NoSignedWrap = true;
527 }
528 } else if (!isSigned && !InitialVal->getValue().isMaxValue()) {
529 if (IncrVal->equalsInt(1))
530 NoUnsignedWrap = true; // LimitVal need not be constant
531 else if (LimitVal) {
532 uint64_t numBits = LimitVal->getValue().getBitWidth();
533 if (IncrVal->getValue().ugt(APInt::getNullValue(numBits)) &&
534 (APInt::getMaxValue(numBits) - IncrVal->getValue())
535 .ugt(LimitVal->getValue()))
536 NoUnsignedWrap = true;
537 }
538 }
Dan Gohmand2067fd2009-02-18 00:52:00 +0000539 return PN;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000540}
541
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000542static Value *getSignExtendedTruncVar(const SCEVAddRecExpr *AR,
543 ScalarEvolution *SE,
544 const Type *LargestType, Loop *L,
545 const Type *myType,
546 SCEVExpander &Rewriter,
547 BasicBlock::iterator InsertPt) {
548 SCEVHandle ExtendedStart =
549 SE->getSignExtendExpr(AR->getStart(), LargestType);
550 SCEVHandle ExtendedStep =
551 SE->getSignExtendExpr(AR->getStepRecurrence(*SE), LargestType);
552 SCEVHandle ExtendedAddRec =
553 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
554 if (LargestType != myType)
555 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, myType);
Dan Gohman2d1be872009-04-16 03:18:22 +0000556 return Rewriter.expandCodeFor(ExtendedAddRec, myType, InsertPt);
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000557}
558
559static Value *getZeroExtendedTruncVar(const SCEVAddRecExpr *AR,
560 ScalarEvolution *SE,
561 const Type *LargestType, Loop *L,
562 const Type *myType,
563 SCEVExpander &Rewriter,
564 BasicBlock::iterator InsertPt) {
565 SCEVHandle ExtendedStart =
566 SE->getZeroExtendExpr(AR->getStart(), LargestType);
567 SCEVHandle ExtendedStep =
568 SE->getZeroExtendExpr(AR->getStepRecurrence(*SE), LargestType);
569 SCEVHandle ExtendedAddRec =
570 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
571 if (LargestType != myType)
572 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, myType);
Dan Gohman2d1be872009-04-16 03:18:22 +0000573 return Rewriter.expandCodeFor(ExtendedAddRec, myType, InsertPt);
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000574}
575
Dale Johannesenc671d892009-04-15 23:31:51 +0000576/// allUsesAreSameTyped - See whether all Uses of I are instructions
577/// with the same Opcode and the same type.
578static bool allUsesAreSameTyped(unsigned int Opcode, Instruction *I) {
579 const Type* firstType = NULL;
580 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
581 UI != UE; ++UI) {
582 Instruction *II = dyn_cast<Instruction>(*UI);
583 if (!II || II->getOpcode() != Opcode)
584 return false;
585 if (!firstType)
586 firstType = II->getType();
587 else if (firstType != II->getType())
588 return false;
589 }
590 return true;
591}
592
Dan Gohmanc2390b12009-02-12 22:19:27 +0000593bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Devang Patel5ee99972007-03-07 06:39:01 +0000594 LI = &getAnalysis<LoopInfo>();
595 SE = &getAnalysis<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +0000596 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +0000597
Dan Gohman2d1be872009-04-16 03:18:22 +0000598 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +0000599 // transform them to use integer recurrences.
600 RewriteNonIntegerIVs(L);
601
Dan Gohmanc2390b12009-02-12 22:19:27 +0000602 BasicBlock *Header = L->getHeader();
603 BasicBlock *ExitingBlock = L->getExitingBlock();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000604 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000605
Chris Lattner9caed542007-03-04 01:00:28 +0000606 // Verify the input to the pass in already in LCSSA form.
607 assert(L->isLCSSAForm());
608
Chris Lattner40bf8b42004-04-02 20:24:31 +0000609 // Check to see if this loop has a computable loop-invariant execution count.
610 // If so, this means that we can compute the final value of any expressions
611 // that are recurrent in the loop, and substitute the exit values from the
612 // loop into any instructions outside of the loop that use the final values of
613 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000614 //
Dan Gohman46bdfb02009-02-24 18:55:53 +0000615 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
616 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
617 RewriteLoopExitValues(L, BackedgeTakenCount);
Chris Lattner6148c022001-12-03 17:28:42 +0000618
Chris Lattner40bf8b42004-04-02 20:24:31 +0000619 // Next, analyze all of the induction variables in the loop, canonicalizing
620 // auxillary induction variables.
621 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
622
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000623 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
624 PHINode *PN = cast<PHINode>(I);
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000625 if (SE->isSCEVable(PN->getType())) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000626 SCEVHandle SCEV = SE->getSCEV(PN);
Dan Gohmancd3eb9b2009-02-14 02:25:19 +0000627 // FIXME: It is an extremely bad idea to indvar substitute anything more
628 // complex than affine induction variables. Doing so will put expensive
629 // polynomial evaluations inside of the loop, and the str reduction pass
630 // currently can only reduce affine polynomials. For now just disable
631 // indvar subst on anything more complex than an affine addrec.
Dan Gohman890f92b2009-04-18 17:56:28 +0000632 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
Dan Gohmancd3eb9b2009-02-14 02:25:19 +0000633 if (AR->getLoop() == L && AR->isAffine())
634 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000635 }
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000636 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000637
Dan Gohmanc2390b12009-02-12 22:19:27 +0000638 // Compute the type of the largest recurrence expression, and collect
639 // the set of the types of the other recurrence expressions.
640 const Type *LargestType = 0;
641 SmallSetVector<const Type *, 4> SizesToInsert;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000642 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
643 LargestType = BackedgeTakenCount->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000644 LargestType = SE->getEffectiveSCEVType(LargestType);
Dan Gohman2d1be872009-04-16 03:18:22 +0000645 SizesToInsert.insert(LargestType);
Chris Lattnerf50af082004-04-17 18:08:33 +0000646 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000647 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
648 const PHINode *PN = IndVars[i].first;
Dan Gohman2d1be872009-04-16 03:18:22 +0000649 const Type *PNTy = PN->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000650 PNTy = SE->getEffectiveSCEVType(PNTy);
Dan Gohman2d1be872009-04-16 03:18:22 +0000651 SizesToInsert.insert(PNTy);
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000652 const Type *EffTy = getEffectiveIndvarType(PN, SE);
653 EffTy = SE->getEffectiveSCEVType(EffTy);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000654 SizesToInsert.insert(EffTy);
655 if (!LargestType ||
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000656 SE->getTypeSizeInBits(EffTy) >
657 SE->getTypeSizeInBits(LargestType))
Dan Gohmanc2390b12009-02-12 22:19:27 +0000658 LargestType = EffTy;
Chris Lattner6148c022001-12-03 17:28:42 +0000659 }
660
Chris Lattner40bf8b42004-04-02 20:24:31 +0000661 // Create a rewriter object which we'll use to transform the code with.
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000662 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner15cad752003-12-23 07:47:09 +0000663
Chris Lattner40bf8b42004-04-02 20:24:31 +0000664 // Now that we know the largest of of the induction variables in this loop,
665 // insert a canonical induction variable of the largest size.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000666 Value *IndVar = 0;
667 if (!SizesToInsert.empty()) {
668 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
669 ++NumInserted;
670 Changed = true;
671 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohmand19534a2007-06-15 14:38:12 +0000672 }
Chris Lattner15cad752003-12-23 07:47:09 +0000673
Dan Gohmanc2390b12009-02-12 22:19:27 +0000674 // If we have a trip count expression, rewrite the loop's exit condition
675 // using it. We can currently only handle loops with a single exit.
Dan Gohmanaa036492009-02-14 02:31:09 +0000676 bool NoSignedWrap = false;
677 bool NoUnsignedWrap = false;
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000678 const ConstantInt* InitialVal, * IncrVal, * LimitVal;
Dan Gohmand2067fd2009-02-18 00:52:00 +0000679 const PHINode *OrigControllingPHI = 0;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000680 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && ExitingBlock)
Dan Gohmanc2390b12009-02-12 22:19:27 +0000681 // Can't rewrite non-branch yet.
682 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
683 if (Instruction *OrigCond = dyn_cast<Instruction>(BI->getCondition())) {
Dan Gohmanaa036492009-02-14 02:31:09 +0000684 // Determine if the OrigIV will ever undergo overflow.
Dan Gohmand2067fd2009-02-18 00:52:00 +0000685 OrigControllingPHI =
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000686 TestOrigIVForWrap(L, BI, OrigCond, *SE,
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000687 NoSignedWrap, NoUnsignedWrap,
688 InitialVal, IncrVal, LimitVal);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000689
690 // We'll be replacing the original condition, so it'll be dead.
691 DeadInsts.insert(OrigCond);
692 }
693
Dan Gohman46bdfb02009-02-24 18:55:53 +0000694 LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
Dan Gohman15cab282009-02-23 23:20:35 +0000695 ExitingBlock, BI, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000696 }
697
Chris Lattner40bf8b42004-04-02 20:24:31 +0000698 // Now that we have a canonical induction variable, we can rewrite any
699 // recurrences in terms of the induction variable. Start with the auxillary
700 // induction variables, and recursively rewrite any of their uses.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000701 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Chris Lattner6148c022001-12-03 17:28:42 +0000702
Chris Lattner5d461d22004-04-21 22:22:01 +0000703 // If there were induction variables of other sizes, cast the primary
704 // induction variable to the right size for them, avoiding the need for the
705 // code evaluation methods to insert induction variables of different sizes.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000706 for (unsigned i = 0, e = SizesToInsert.size(); i != e; ++i) {
707 const Type *Ty = SizesToInsert[i];
708 if (Ty != LargestType) {
709 Instruction *New = new TruncInst(IndVar, Ty, "indvar", InsertPt);
710 Rewriter.addInsertedValue(New, SE->getSCEV(New));
711 DOUT << "INDVARS: Made trunc IV for type " << *Ty << ": "
712 << *New << "\n";
Reid Spencera54b7cb2007-01-12 07:05:14 +0000713 }
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000714 }
715
Chris Lattneree4f13a2007-01-07 01:14:12 +0000716 // Rewrite all induction variables in terms of the canonical induction
717 // variable.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000718 while (!IndVars.empty()) {
719 PHINode *PN = IndVars.back().first;
Dan Gohman890f92b2009-04-18 17:56:28 +0000720 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(IndVars.back().second);
Dan Gohman2d1be872009-04-16 03:18:22 +0000721 Value *NewVal = Rewriter.expandCodeFor(AR, PN->getType(), InsertPt);
Dan Gohman1a5e9362009-02-17 00:10:53 +0000722 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *PN
Chris Lattneree4f13a2007-01-07 01:14:12 +0000723 << " into = " << *NewVal << "\n";
Chris Lattner6934a042007-02-11 01:23:03 +0000724 NewVal->takeName(PN);
Chris Lattner5d461d22004-04-21 22:22:01 +0000725
Dan Gohmanc2390b12009-02-12 22:19:27 +0000726 /// If the new canonical induction variable is wider than the original,
727 /// and the original has uses that are casts to wider types, see if the
728 /// truncate and extend can be omitted.
Dan Gohmand2067fd2009-02-18 00:52:00 +0000729 if (PN == OrigControllingPHI && PN->getType() != LargestType)
Dan Gohmanc2390b12009-02-12 22:19:27 +0000730 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
Dan Gohmanaa036492009-02-14 02:31:09 +0000731 UI != UE; ++UI) {
Dale Johannesend3325d282009-04-15 20:41:02 +0000732 Instruction *UInst = dyn_cast<Instruction>(*UI);
733 if (UInst && isa<SExtInst>(UInst) && NoSignedWrap) {
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000734 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType, L,
Dale Johannesend3325d282009-04-15 20:41:02 +0000735 UInst->getType(), Rewriter, InsertPt);
736 UInst->replaceAllUsesWith(TruncIndVar);
737 DeadInsts.insert(UInst);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000738 }
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000739 // See if we can figure out sext(i+constant) doesn't wrap, so we can
740 // use a larger add. This is common in subscripting.
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000741 if (UInst && UInst->getOpcode()==Instruction::Add &&
Dale Johannesenc671d892009-04-15 23:31:51 +0000742 allUsesAreSameTyped(Instruction::SExt, UInst) &&
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000743 isa<ConstantInt>(UInst->getOperand(1)) &&
Dale Johannesend3325d282009-04-15 20:41:02 +0000744 NoSignedWrap && LimitVal) {
745 uint64_t oldBitSize = LimitVal->getValue().getBitWidth();
746 uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
747 ConstantInt* AddRHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
748 if (((APInt::getSignedMaxValue(oldBitSize) - IncrVal->getValue()) -
749 AddRHS->getValue()).sgt(LimitVal->getValue())) {
750 // We've determined this is (i+constant) and it won't overflow.
751 if (isa<SExtInst>(UInst->use_begin())) {
752 SExtInst* oldSext = dyn_cast<SExtInst>(UInst->use_begin());
753 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
754 L, oldSext->getType(), Rewriter,
755 InsertPt);
756 APInt APcopy = APInt(AddRHS->getValue());
757 ConstantInt* newAddRHS =ConstantInt::get(APcopy.sext(newBitSize));
758 Value *NewAdd =
759 BinaryOperator::CreateAdd(TruncIndVar, newAddRHS,
760 UInst->getName()+".nosex", UInst);
Dale Johannesenc671d892009-04-15 23:31:51 +0000761 for (Value::use_iterator UI2 = UInst->use_begin(),
762 UE2 = UInst->use_end(); UI2 != UE2; ++UI2) {
763 Instruction *II = dyn_cast<Instruction>(UI2);
764 II->replaceAllUsesWith(NewAdd);
765 DeadInsts.insert(II);
766 }
Dale Johannesend3325d282009-04-15 20:41:02 +0000767 DeadInsts.insert(UInst);
768 }
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000769 }
770 }
Dale Johannesenc671d892009-04-15 23:31:51 +0000771 // Try for sext(i | constant). This is safe as long as the
772 // high bit of the constant is not set.
773 if (UInst && UInst->getOpcode()==Instruction::Or &&
774 allUsesAreSameTyped(Instruction::SExt, UInst) && NoSignedWrap &&
775 isa<ConstantInt>(UInst->getOperand(1))) {
776 ConstantInt* RHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
777 if (!RHS->getValue().isNegative()) {
778 uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
779 SExtInst* oldSext = dyn_cast<SExtInst>(UInst->use_begin());
780 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
781 L, oldSext->getType(), Rewriter,
782 InsertPt);
783 APInt APcopy = APInt(RHS->getValue());
784 ConstantInt* newRHS =ConstantInt::get(APcopy.sext(newBitSize));
785 Value *NewAdd =
786 BinaryOperator::CreateOr(TruncIndVar, newRHS,
787 UInst->getName()+".nosex", UInst);
788 for (Value::use_iterator UI2 = UInst->use_begin(),
789 UE2 = UInst->use_end(); UI2 != UE2; ++UI2) {
790 Instruction *II = dyn_cast<Instruction>(UI2);
791 II->replaceAllUsesWith(NewAdd);
792 DeadInsts.insert(II);
793 }
794 DeadInsts.insert(UInst);
795 }
796 }
797 // A zext of a signed variable known not to overflow is still safe.
798 if (UInst && isa<ZExtInst>(UInst) && (NoUnsignedWrap || NoSignedWrap)) {
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000799 Value *TruncIndVar = getZeroExtendedTruncVar(AR, SE, LargestType, L,
Dale Johannesend3325d282009-04-15 20:41:02 +0000800 UInst->getType(), Rewriter, InsertPt);
801 UInst->replaceAllUsesWith(TruncIndVar);
802 DeadInsts.insert(UInst);
803 }
Dale Johannesenc671d892009-04-15 23:31:51 +0000804 // If we have zext(i&constant), it's always safe to use the larger
805 // variable. This is not common but is a bottleneck in Openssl.
Dale Johannesend3325d282009-04-15 20:41:02 +0000806 // (RHS doesn't have to be constant. There should be a better approach
807 // than bottom-up pattern matching for this...)
808 if (UInst && UInst->getOpcode()==Instruction::And &&
Dale Johannesenc671d892009-04-15 23:31:51 +0000809 allUsesAreSameTyped(Instruction::ZExt, UInst) &&
810 isa<ConstantInt>(UInst->getOperand(1))) {
Dale Johannesend3325d282009-04-15 20:41:02 +0000811 uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
812 ConstantInt* AndRHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
813 ZExtInst* oldZext = dyn_cast<ZExtInst>(UInst->use_begin());
814 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
815 L, oldZext->getType(), Rewriter, InsertPt);
816 APInt APcopy = APInt(AndRHS->getValue());
817 ConstantInt* newAndRHS = ConstantInt::get(APcopy.zext(newBitSize));
818 Value *NewAnd =
819 BinaryOperator::CreateAnd(TruncIndVar, newAndRHS,
820 UInst->getName()+".nozex", UInst);
Dale Johannesenc671d892009-04-15 23:31:51 +0000821 for (Value::use_iterator UI2 = UInst->use_begin(),
822 UE2 = UInst->use_end(); UI2 != UE2; ++UI2) {
823 Instruction *II = dyn_cast<Instruction>(UI2);
824 II->replaceAllUsesWith(NewAnd);
825 DeadInsts.insert(II);
826 }
Dale Johannesend3325d282009-04-15 20:41:02 +0000827 DeadInsts.insert(UInst);
828 }
829 // If we have zext((i+constant)&constant), we can use the larger
830 // variable even if the add does overflow. This works whenever the
831 // constant being ANDed is the same size as i, which it presumably is.
832 // We don't need to restrict the expression being and'ed to i+const,
833 // but we have to promote everything in it, so it's convenient.
Dale Johannesenc671d892009-04-15 23:31:51 +0000834 // zext((i | constant)&constant) is also valid and accepted here.
835 if (UInst && (UInst->getOpcode()==Instruction::Add ||
836 UInst->getOpcode()==Instruction::Or) &&
Dale Johannesend3325d282009-04-15 20:41:02 +0000837 UInst->hasOneUse() &&
838 isa<ConstantInt>(UInst->getOperand(1))) {
839 uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
840 ConstantInt* AddRHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
841 Instruction *UInst2 = dyn_cast<Instruction>(UInst->use_begin());
842 if (UInst2 && UInst2->getOpcode() == Instruction::And &&
Dale Johannesenc671d892009-04-15 23:31:51 +0000843 allUsesAreSameTyped(Instruction::ZExt, UInst2) &&
844 isa<ConstantInt>(UInst2->getOperand(1))) {
Dale Johannesend3325d282009-04-15 20:41:02 +0000845 ZExtInst* oldZext = dyn_cast<ZExtInst>(UInst2->use_begin());
846 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
847 L, oldZext->getType(), Rewriter, InsertPt);
848 ConstantInt* AndRHS = dyn_cast<ConstantInt>(UInst2->getOperand(1));
849 APInt APcopy = APInt(AddRHS->getValue());
850 ConstantInt* newAddRHS = ConstantInt::get(APcopy.zext(newBitSize));
Dale Johannesenc671d892009-04-15 23:31:51 +0000851 Value *NewAdd = ((UInst->getOpcode()==Instruction::Add) ?
Dale Johannesend3325d282009-04-15 20:41:02 +0000852 BinaryOperator::CreateAdd(TruncIndVar, newAddRHS,
Dale Johannesenc671d892009-04-15 23:31:51 +0000853 UInst->getName()+".nozex", UInst2) :
854 BinaryOperator::CreateOr(TruncIndVar, newAddRHS,
855 UInst->getName()+".nozex", UInst2));
Dale Johannesend3325d282009-04-15 20:41:02 +0000856 APInt APcopy2 = APInt(AndRHS->getValue());
857 ConstantInt* newAndRHS = ConstantInt::get(APcopy2.zext(newBitSize));
858 Value *NewAnd =
859 BinaryOperator::CreateAnd(NewAdd, newAndRHS,
860 UInst->getName()+".nozex", UInst2);
Dale Johannesenc671d892009-04-15 23:31:51 +0000861 for (Value::use_iterator UI2 = UInst2->use_begin(),
862 UE2 = UInst2->use_end(); UI2 != UE2; ++UI2) {
863 Instruction *II = dyn_cast<Instruction>(UI2);
864 II->replaceAllUsesWith(NewAnd);
865 DeadInsts.insert(II);
866 }
Dale Johannesend3325d282009-04-15 20:41:02 +0000867 DeadInsts.insert(UInst);
868 DeadInsts.insert(UInst2);
869 }
Dan Gohmanaa036492009-02-14 02:31:09 +0000870 }
871 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000872
Chris Lattner40bf8b42004-04-02 20:24:31 +0000873 // Replace the old PHI Node with the inserted computation.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000874 PN->replaceAllUsesWith(NewVal);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000875 DeadInsts.insert(PN);
876 IndVars.pop_back();
877 ++NumRemoved;
Chris Lattner4753bf22001-12-05 19:41:33 +0000878 Changed = true;
Chris Lattner394437f2001-12-04 04:32:29 +0000879 }
880
Chris Lattner1363e852004-04-21 23:36:08 +0000881 DeleteTriviallyDeadInstructions(DeadInsts);
Chris Lattner9caed542007-03-04 01:00:28 +0000882 assert(L->isLCSSAForm());
Devang Patel5ee99972007-03-07 06:39:01 +0000883 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000884}
Devang Pateld22a8492008-09-09 21:41:07 +0000885
Devang Patel13877bf2008-11-18 00:40:02 +0000886/// Return true if it is OK to use SIToFPInst for an inducation variable
887/// with given inital and exit values.
888static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
889 uint64_t intIV, uint64_t intEV) {
890
Dan Gohmancafb8132009-02-17 19:13:57 +0000891 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patel13877bf2008-11-18 00:40:02 +0000892 return true;
893
894 // If the iteration range can be handled by SIToFPInst then use it.
895 APInt Max = APInt::getSignedMaxValue(32);
Bill Wendling9bef7062008-11-18 10:57:27 +0000896 if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
Devang Patel13877bf2008-11-18 00:40:02 +0000897 return true;
Dan Gohmancafb8132009-02-17 19:13:57 +0000898
Devang Patel13877bf2008-11-18 00:40:02 +0000899 return false;
900}
901
902/// convertToInt - Convert APF to an integer, if possible.
Devang Patelcd402332008-11-17 23:27:13 +0000903static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
904
905 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000906 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
907 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000908 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patelcd402332008-11-17 23:27:13 +0000909 APFloat::rmTowardZero, &isExact)
910 != APFloat::opOK)
911 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000912 if (!isExact)
Devang Patelcd402332008-11-17 23:27:13 +0000913 return false;
914 return true;
915
916}
917
Devang Patel58d43d42008-11-03 18:32:19 +0000918/// HandleFloatingPointIV - If the loop has floating induction variable
919/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000920/// For example,
921/// for(double i = 0; i < 10000; ++i)
922/// bar(i)
923/// is converted into
924/// for(int i = 0; i < 10000; ++i)
925/// bar((double)i);
926///
Dan Gohmancafb8132009-02-17 19:13:57 +0000927void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
Devang Patel84e35152008-11-17 21:32:02 +0000928 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Devang Patel58d43d42008-11-03 18:32:19 +0000929
Devang Patel84e35152008-11-17 21:32:02 +0000930 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
931 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +0000932
Devang Patel84e35152008-11-17 21:32:02 +0000933 // Check incoming value.
Devang Patelcd402332008-11-17 23:27:13 +0000934 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
935 if (!InitValue) return;
936 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
937 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
938 return;
939
940 // Check IV increment. Reject this PH if increement operation is not
941 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +0000942 BinaryOperator *Incr =
Devang Patel84e35152008-11-17 21:32:02 +0000943 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
944 if (!Incr) return;
945 if (Incr->getOpcode() != Instruction::Add) return;
946 ConstantFP *IncrValue = NULL;
947 unsigned IncrVIndex = 1;
948 if (Incr->getOperand(1) == PH)
949 IncrVIndex = 0;
950 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
951 if (!IncrValue) return;
Devang Patelcd402332008-11-17 23:27:13 +0000952 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
953 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
954 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000955
Devang Patelcd402332008-11-17 23:27:13 +0000956 // Check Incr uses. One user is PH and the other users is exit condition used
957 // by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000958 Value::use_iterator IncrUse = Incr->use_begin();
959 Instruction *U1 = cast<Instruction>(IncrUse++);
960 if (IncrUse == Incr->use_end()) return;
961 Instruction *U2 = cast<Instruction>(IncrUse++);
962 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000963
Devang Patel84e35152008-11-17 21:32:02 +0000964 // Find exit condition.
965 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
966 if (!EC)
967 EC = dyn_cast<FCmpInst>(U2);
968 if (!EC) return;
969
970 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
971 if (!BI->isConditional()) return;
972 if (BI->getCondition() != EC) return;
Devang Patel58d43d42008-11-03 18:32:19 +0000973 }
Devang Patel58d43d42008-11-03 18:32:19 +0000974
Devang Patelcd402332008-11-17 23:27:13 +0000975 // Find exit value. If exit value can not be represented as an interger then
976 // do not handle this floating point PH.
Devang Patel84e35152008-11-17 21:32:02 +0000977 ConstantFP *EV = NULL;
978 unsigned EVIndex = 1;
979 if (EC->getOperand(1) == Incr)
980 EVIndex = 0;
981 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
982 if (!EV) return;
Devang Patel84e35152008-11-17 21:32:02 +0000983 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000984 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patel84e35152008-11-17 21:32:02 +0000985 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000986
Devang Patel84e35152008-11-17 21:32:02 +0000987 // Find new predicate for integer comparison.
988 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
989 switch (EC->getPredicate()) {
990 case CmpInst::FCMP_OEQ:
991 case CmpInst::FCMP_UEQ:
992 NewPred = CmpInst::ICMP_EQ;
993 break;
994 case CmpInst::FCMP_OGT:
995 case CmpInst::FCMP_UGT:
996 NewPred = CmpInst::ICMP_UGT;
997 break;
998 case CmpInst::FCMP_OGE:
999 case CmpInst::FCMP_UGE:
1000 NewPred = CmpInst::ICMP_UGE;
1001 break;
1002 case CmpInst::FCMP_OLT:
1003 case CmpInst::FCMP_ULT:
1004 NewPred = CmpInst::ICMP_ULT;
1005 break;
1006 case CmpInst::FCMP_OLE:
1007 case CmpInst::FCMP_ULE:
1008 NewPred = CmpInst::ICMP_ULE;
1009 break;
1010 default:
1011 break;
Devang Patel58d43d42008-11-03 18:32:19 +00001012 }
Devang Patel84e35152008-11-17 21:32:02 +00001013 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohmancafb8132009-02-17 19:13:57 +00001014
Devang Patel84e35152008-11-17 21:32:02 +00001015 // Insert new integer induction variable.
1016 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
1017 PH->getName()+".int", PH);
Devang Patelcd402332008-11-17 23:27:13 +00001018 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patel84e35152008-11-17 21:32:02 +00001019 PH->getIncomingBlock(IncomingEdge));
1020
Dan Gohmancafb8132009-02-17 19:13:57 +00001021 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
1022 ConstantInt::get(Type::Int32Ty,
Devang Patelcd402332008-11-17 23:27:13 +00001023 newIncrValue),
Devang Patel84e35152008-11-17 21:32:02 +00001024 Incr->getName()+".int", Incr);
1025 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
1026
1027 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
1028 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
1029 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
Dan Gohmancafb8132009-02-17 19:13:57 +00001030 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
Devang Patel84e35152008-11-17 21:32:02 +00001031 EC->getParent()->getTerminator());
Dan Gohmancafb8132009-02-17 19:13:57 +00001032
Devang Patel84e35152008-11-17 21:32:02 +00001033 // Delete old, floating point, exit comparision instruction.
1034 EC->replaceAllUsesWith(NewEC);
1035 DeadInsts.insert(EC);
Dan Gohmancafb8132009-02-17 19:13:57 +00001036
Devang Patel84e35152008-11-17 21:32:02 +00001037 // Delete old, floating point, increment instruction.
1038 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
1039 DeadInsts.insert(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +00001040
Devang Patel13877bf2008-11-18 00:40:02 +00001041 // Replace floating induction variable. Give SIToFPInst preference over
1042 // UIToFPInst because it is faster on platforms that are widely used.
1043 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
Dan Gohmancafb8132009-02-17 19:13:57 +00001044 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patelcd402332008-11-17 23:27:13 +00001045 PH->getParent()->getFirstNonPHI());
1046 PH->replaceAllUsesWith(Conv);
1047 } else {
Dan Gohmancafb8132009-02-17 19:13:57 +00001048 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patelcd402332008-11-17 23:27:13 +00001049 PH->getParent()->getFirstNonPHI());
1050 PH->replaceAllUsesWith(Conv);
1051 }
Devang Patel84e35152008-11-17 21:32:02 +00001052 DeadInsts.insert(PH);
Devang Patel58d43d42008-11-03 18:32:19 +00001053}
1054