blob: 01c9574123d7e92899e02f2ff1cc8eed0a47f0fa [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"
Dan Gohman2d1be872009-04-16 03:18:22 +000053#include "llvm/Target/TargetData.h"
John Criswell47df12d2003-12-18 17:19:19 +000054#include "llvm/Transforms/Utils/Local.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000055#include "llvm/Support/CommandLine.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000056#include "llvm/ADT/SmallVector.h"
Dan Gohmanc2390b12009-02-12 22:19:27 +000057#include "llvm/ADT/SetVector.h"
Chris Lattner1a6111f2008-11-16 07:17:51 +000058#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000059#include "llvm/ADT/Statistic.h"
John Criswell47df12d2003-12-18 17:19:19 +000060using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000061
Chris Lattner0e5f4992006-12-19 21:40:18 +000062STATISTIC(NumRemoved , "Number of aux indvars removed");
Chris Lattner0e5f4992006-12-19 21:40:18 +000063STATISTIC(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;
Dan Gohman2d1be872009-04-16 03:18:22 +000070 TargetData *TD;
Chris Lattner40bf8b42004-04-02 20:24:31 +000071 ScalarEvolution *SE;
Chris Lattner15cad752003-12-23 07:47:09 +000072 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000073 public:
Devang Patel794fd752007-05-01 21:15:47 +000074
Nick Lewyckyecd94c82007-05-06 13:37:16 +000075 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000076 IndVarSimplify() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000077
Dan Gohman60f8a632009-02-17 20:49:49 +000078 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
79
Devang Patel5ee99972007-03-07 06:39:01 +000080 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patelbc533cd2007-09-10 18:08:23 +000081 AU.addRequired<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000082 AU.addRequiredID(LCSSAID);
83 AU.addRequiredID(LoopSimplifyID);
Devang Patel5ee99972007-03-07 06:39:01 +000084 AU.addRequired<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +000085 AU.addRequired<TargetData>();
Dan Gohman474cecf2009-02-23 16:29:41 +000086 AU.addPreserved<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000087 AU.addPreservedID(LoopSimplifyID);
88 AU.addPreservedID(LCSSAID);
89 AU.setPreservesCFG();
90 }
Chris Lattner15cad752003-12-23 07:47:09 +000091
Chris Lattner40bf8b42004-04-02 20:24:31 +000092 private:
Devang Patel5ee99972007-03-07 06:39:01 +000093
Dan Gohman60f8a632009-02-17 20:49:49 +000094 void RewriteNonIntegerIVs(Loop *L);
95
Dan Gohman46bdfb02009-02-24 18:55:53 +000096 void LinearFunctionTestReplace(Loop *L, SCEVHandle BackedgeTakenCount,
Dan Gohmana5758712009-02-17 15:57:39 +000097 Value *IndVar,
Dan Gohmanc2390b12009-02-12 22:19:27 +000098 BasicBlock *ExitingBlock,
99 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000100 SCEVExpander &Rewriter);
Dan Gohman46bdfb02009-02-24 18:55:53 +0000101 void RewriteLoopExitValues(Loop *L, SCEV *BackedgeTakenCount);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000102
Chris Lattner1a6111f2008-11-16 07:17:51 +0000103 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
Devang Pateld22a8492008-09-09 21:41:07 +0000104
Dan Gohmancafb8132009-02-17 19:13:57 +0000105 void HandleFloatingPointIV(Loop *L, PHINode *PH,
Devang Patel84e35152008-11-17 21:32:02 +0000106 SmallPtrSet<Instruction*, 16> &DeadInsts);
Chris Lattner3324e712003-12-22 03:58:44 +0000107 };
Chris Lattner5e761402002-09-10 05:24:05 +0000108}
Chris Lattner394437f2001-12-04 04:32:29 +0000109
Dan Gohman844731a2008-05-13 00:00:25 +0000110char IndVarSimplify::ID = 0;
111static RegisterPass<IndVarSimplify>
112X("indvars", "Canonicalize Induction Variables");
113
Daniel Dunbar394f0442008-10-22 23:32:42 +0000114Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000115 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000116}
117
Chris Lattner40bf8b42004-04-02 20:24:31 +0000118/// DeleteTriviallyDeadInstructions - If any of the instructions is the
119/// specified set are trivially dead, delete them and see if this makes any of
120/// their operands subsequently dead.
121void IndVarSimplify::
Chris Lattner1a6111f2008-11-16 07:17:51 +0000122DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000123 while (!Insts.empty()) {
124 Instruction *I = *Insts.begin();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000125 Insts.erase(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000126 if (isInstructionTriviallyDead(I)) {
127 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
128 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
129 Insts.insert(U);
Dan Gohman5cec4db2007-06-19 14:28:31 +0000130 SE->deleteValueFromRecords(I);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000131 DOUT << "INDVARS: Deleting: " << *I;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000132 I->eraseFromParent();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000133 Changed = true;
134 }
135 }
136}
137
Chris Lattner40bf8b42004-04-02 20:24:31 +0000138/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000139/// loop to be a canonical != comparison against the incremented loop induction
140/// variable. This pass is able to rewrite the exit tests of any loop where the
141/// SCEV analysis can determine a loop-invariant trip count of the loop, which
142/// is actually a much broader range than just linear tests.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000143void IndVarSimplify::LinearFunctionTestReplace(Loop *L,
Dan Gohman46bdfb02009-02-24 18:55:53 +0000144 SCEVHandle BackedgeTakenCount,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000145 Value *IndVar,
146 BasicBlock *ExitingBlock,
147 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000148 SCEVExpander &Rewriter) {
Chris Lattnerd2440572004-04-15 20:26:22 +0000149 // If the exiting block is not the same as the backedge block, we must compare
150 // against the preincremented value, otherwise we prefer to compare against
151 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000152 Value *CmpIndVar;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000153 SCEVHandle RHS = BackedgeTakenCount;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000154 if (ExitingBlock == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000155 // Add one to the "backedge-taken" count to get the trip count.
156 // If this addition may overflow, we have to be more pessimistic and
157 // cast the induction variable before doing the add.
158 SCEVHandle Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000159 SCEVHandle N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000160 SE->getAddExpr(BackedgeTakenCount,
161 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000162 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
163 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
164 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000165 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000166 } else {
167 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000168 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
169 IndVar->getType());
170 RHS = SE->getAddExpr(RHS,
171 SE->getIntegerSCEV(1, IndVar->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000172 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000173
Dan Gohman46bdfb02009-02-24 18:55:53 +0000174 // The BackedgeTaken expression contains the number of times that the
175 // backedge branches to the loop header. This is one less than the
176 // number of times the loop executes, so use the incremented indvar.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000177 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Chris Lattnerd2440572004-04-15 20:26:22 +0000178 } else {
179 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000180 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
181 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000182 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000183 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000184
Chris Lattner40bf8b42004-04-02 20:24:31 +0000185 // Expand the code for the iteration count into the preheader of the loop.
186 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman2d1be872009-04-16 03:18:22 +0000187 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(),
Dan Gohmanc2390b12009-02-12 22:19:27 +0000188 Preheader->getTerminator());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000189
Reid Spencere4d87aa2006-12-23 06:05:41 +0000190 // Insert a new icmp_ne or icmp_eq instruction before the branch.
191 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000192 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000193 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000194 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000195 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000196
Dan Gohmanc2390b12009-02-12 22:19:27 +0000197 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
198 << " LHS:" << *CmpIndVar // includes a newline
199 << " op:\t"
Dan Gohmanf108e2e2009-02-14 02:26:50 +0000200 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohman46bdfb02009-02-24 18:55:53 +0000201 << " RHS:\t" << *RHS << "\n";
Dan Gohmanc2390b12009-02-12 22:19:27 +0000202
203 Value *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000204 BI->setCondition(Cond);
205 ++NumLFTR;
206 Changed = true;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000207}
208
Chris Lattner40bf8b42004-04-02 20:24:31 +0000209/// RewriteLoopExitValues - Check to see if this loop has a computable
210/// loop-invariant execution count. If so, this means that we can compute the
211/// final value of any expressions that are recurrent in the loop, and
212/// substitute the exit values from the loop into any instructions outside of
213/// the loop that use the final values of the current expressions.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000214void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *BackedgeTakenCount) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000215 BasicBlock *Preheader = L->getLoopPreheader();
216
217 // Scan all of the instructions in the loop, looking at those that have
218 // extra-loop users and which are recurrences.
Dan Gohman2d1be872009-04-16 03:18:22 +0000219 SCEVExpander Rewriter(*SE, *LI, *TD);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000220
221 // We insert the code into the preheader of the loop if the loop contains
222 // multiple exit blocks, or in the exit block if there is exactly one.
223 BasicBlock *BlockToInsertInto;
Devang Patelb7211a22007-08-21 00:31:24 +0000224 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000225 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000226 if (ExitBlocks.size() == 1)
227 BlockToInsertInto = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000228 else
229 BlockToInsertInto = Preheader;
Dan Gohman02dea8b2008-05-23 21:05:58 +0000230 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000231
Dan Gohman46bdfb02009-02-24 18:55:53 +0000232 bool HasConstantItCount = isa<SCEVConstant>(BackedgeTakenCount);
Chris Lattner20aa0982004-04-17 18:44:09 +0000233
Chris Lattner1a6111f2008-11-16 07:17:51 +0000234 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000235 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanfd939082005-04-21 23:48:37 +0000236
Chris Lattner9f3d7382007-03-04 03:43:23 +0000237 // Find all values that are computed inside the loop, but used outside of it.
238 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
239 // the exit blocks of the loop to find them.
240 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
241 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000242
Chris Lattner9f3d7382007-03-04 03:43:23 +0000243 // If there are no PHI nodes in this exit block, then no values defined
244 // inside the loop are used on this path, skip it.
245 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
246 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000247
Chris Lattner9f3d7382007-03-04 03:43:23 +0000248 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000249
Chris Lattner9f3d7382007-03-04 03:43:23 +0000250 // Iterate over all of the PHI nodes.
251 BasicBlock::iterator BBI = ExitBB->begin();
252 while ((PN = dyn_cast<PHINode>(BBI++))) {
Dan Gohmancafb8132009-02-17 19:13:57 +0000253
Chris Lattner9f3d7382007-03-04 03:43:23 +0000254 // Iterate over all of the values in all the PHI nodes.
255 for (unsigned i = 0; i != NumPreds; ++i) {
256 // If the value being merged in is not integer or is not defined
257 // in the loop, skip it.
258 Value *InVal = PN->getIncomingValue(i);
259 if (!isa<Instruction>(InVal) ||
260 // SCEV only supports integer expressions for now.
Dan Gohman2d1be872009-04-16 03:18:22 +0000261 (!isa<IntegerType>(InVal->getType()) &&
262 !isa<PointerType>(InVal->getType())))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000263 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000264
Chris Lattner9f3d7382007-03-04 03:43:23 +0000265 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000266 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000267 continue; // The Block is in a subloop, skip it.
268
269 // Check that InVal is defined in the loop.
270 Instruction *Inst = cast<Instruction>(InVal);
271 if (!L->contains(Inst->getParent()))
272 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000273
Chris Lattner9f3d7382007-03-04 03:43:23 +0000274 // We require that this value either have a computable evolution or that
275 // the loop have a constant iteration count. In the case where the loop
276 // has a constant iteration count, we can sometimes force evaluation of
277 // the exit value through brute force.
278 SCEVHandle SH = SE->getSCEV(Inst);
279 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
280 continue; // Cannot get exit evolution for the loop value.
Dan Gohmancafb8132009-02-17 19:13:57 +0000281
Chris Lattner9f3d7382007-03-04 03:43:23 +0000282 // Okay, this instruction has a user outside of the current loop
283 // and varies predictably *inside* the loop. Evaluate the value it
284 // contains when the loop exits, if possible.
285 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
286 if (isa<SCEVCouldNotCompute>(ExitValue) ||
287 !ExitValue->isLoopInvariant(L))
288 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000289
Chris Lattner9f3d7382007-03-04 03:43:23 +0000290 Changed = true;
291 ++NumReplaced;
Dan Gohmancafb8132009-02-17 19:13:57 +0000292
Chris Lattner9f3d7382007-03-04 03:43:23 +0000293 // See if we already computed the exit value for the instruction, if so,
294 // just reuse it.
295 Value *&ExitVal = ExitValues[Inst];
296 if (!ExitVal)
Dan Gohman2d1be872009-04-16 03:18:22 +0000297 ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), InsertPt);
Dan Gohmancafb8132009-02-17 19:13:57 +0000298
Chris Lattner9f3d7382007-03-04 03:43:23 +0000299 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
300 << " LoopVal = " << *Inst << "\n";
301
302 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000303
Chris Lattner9f3d7382007-03-04 03:43:23 +0000304 // If this instruction is dead now, schedule it to be removed.
305 if (Inst->use_empty())
306 InstructionsToDelete.insert(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000307
Chris Lattner9f3d7382007-03-04 03:43:23 +0000308 // See if this is a single-entry LCSSA PHI node. If so, we can (and
309 // have to) remove
Chris Lattner9caed542007-03-04 01:00:28 +0000310 // the PHI entirely. This is safe, because the NewVal won't be variant
311 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000312 if (NumPreds == 1) {
Dan Gohman5cec4db2007-06-19 14:28:31 +0000313 SE->deleteValueFromRecords(PN);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000314 PN->replaceAllUsesWith(ExitVal);
315 PN->eraseFromParent();
316 break;
Chris Lattnerc9838f22007-03-03 22:48:48 +0000317 }
318 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000319 }
320 }
Dan Gohmancafb8132009-02-17 19:13:57 +0000321
Chris Lattner40bf8b42004-04-02 20:24:31 +0000322 DeleteTriviallyDeadInstructions(InstructionsToDelete);
323}
324
Dan Gohman60f8a632009-02-17 20:49:49 +0000325void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000326 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000327 // If there are, change them into integer recurrences, permitting analysis by
328 // the SCEV routines.
329 //
330 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000331
Chris Lattner1a6111f2008-11-16 07:17:51 +0000332 SmallPtrSet<Instruction*, 16> DeadInsts;
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000333 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
334 PHINode *PN = cast<PHINode>(I);
Dan Gohman2d1be872009-04-16 03:18:22 +0000335 HandleFloatingPointIV(L, PN, DeadInsts);
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000336 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000337
Dan Gohman2d1be872009-04-16 03:18:22 +0000338 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000339 // may not have been able to compute a trip count. Now that we've done some
340 // re-writing, the trip count may be computable.
341 if (Changed)
Dan Gohman46bdfb02009-02-24 18:55:53 +0000342 SE->forgetLoopBackedgeTakenCount(L);
Dan Gohman60f8a632009-02-17 20:49:49 +0000343
Chris Lattner40bf8b42004-04-02 20:24:31 +0000344 if (!DeadInsts.empty())
345 DeleteTriviallyDeadInstructions(DeadInsts);
Devang Patel5ee99972007-03-07 06:39:01 +0000346}
Chris Lattner40bf8b42004-04-02 20:24:31 +0000347
Dan Gohmanc2390b12009-02-12 22:19:27 +0000348/// getEffectiveIndvarType - Determine the widest type that the
349/// induction-variable PHINode Phi is cast to.
350///
Dan Gohman2d1be872009-04-16 03:18:22 +0000351static const Type *getEffectiveIndvarType(const PHINode *Phi,
352 const TargetData *TD) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000353 const Type *Ty = Phi->getType();
Chris Lattner3324e712003-12-22 03:58:44 +0000354
Dan Gohmanc2390b12009-02-12 22:19:27 +0000355 for (Value::use_const_iterator UI = Phi->use_begin(), UE = Phi->use_end();
356 UI != UE; ++UI) {
357 const Type *CandidateType = NULL;
358 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
359 CandidateType = ZI->getDestTy();
360 else if (const SExtInst *SI = dyn_cast<SExtInst>(UI))
361 CandidateType = SI->getDestTy();
362 if (CandidateType &&
Dan Gohman2d1be872009-04-16 03:18:22 +0000363 TD->getTypeSizeInBits(CandidateType) > TD->getTypeSizeInBits(Ty))
Dan Gohmanc2390b12009-02-12 22:19:27 +0000364 Ty = CandidateType;
365 }
366
367 return Ty;
368}
369
Dan Gohmanaa036492009-02-14 02:31:09 +0000370/// TestOrigIVForWrap - Analyze the original induction variable
Dan Gohmand2067fd2009-02-18 00:52:00 +0000371/// that controls the loop's iteration to determine whether it
Dan Gohmanf5a309e2009-02-18 17:22:41 +0000372/// would ever undergo signed or unsigned overflow. Also, check
373/// whether an induction variable in the same type that starts
374/// at 0 would undergo signed overflow.
Dan Gohmand2067fd2009-02-18 00:52:00 +0000375///
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000376/// In addition to setting the NoSignedWrap and NoUnsignedWrap
377/// variables to true when appropriate (they are not set to false here),
378/// return the PHI for this induction variable. Also record the initial
379/// and final values and the increment; these are not meaningful unless
380/// either NoSignedWrap or NoUnsignedWrap is true, and are always meaningful
381/// in that case, although the final value may be 0 indicating a nonconstant.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000382///
383/// TODO: This duplicates a fair amount of ScalarEvolution logic.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000384/// Perhaps this can be merged with
385/// ScalarEvolution::getBackedgeTakenCount
Dan Gohmanaa036492009-02-14 02:31:09 +0000386/// and/or ScalarEvolution::get{Sign,Zero}ExtendExpr.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000387///
Dan Gohmand2067fd2009-02-18 00:52:00 +0000388static const PHINode *TestOrigIVForWrap(const Loop *L,
389 const BranchInst *BI,
390 const Instruction *OrigCond,
Dan Gohman2d1be872009-04-16 03:18:22 +0000391 const TargetData *TD,
Dan Gohmand2067fd2009-02-18 00:52:00 +0000392 bool &NoSignedWrap,
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000393 bool &NoUnsignedWrap,
394 const ConstantInt* &InitialVal,
395 const ConstantInt* &IncrVal,
396 const ConstantInt* &LimitVal) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000397 // Verify that the loop is sane and find the exit condition.
398 const ICmpInst *Cmp = dyn_cast<ICmpInst>(OrigCond);
Dan Gohmand2067fd2009-02-18 00:52:00 +0000399 if (!Cmp) return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000400
Dan Gohmanaa036492009-02-14 02:31:09 +0000401 const Value *CmpLHS = Cmp->getOperand(0);
402 const Value *CmpRHS = Cmp->getOperand(1);
403 const BasicBlock *TrueBB = BI->getSuccessor(0);
404 const BasicBlock *FalseBB = BI->getSuccessor(1);
405 ICmpInst::Predicate Pred = Cmp->getPredicate();
Dan Gohmanc2390b12009-02-12 22:19:27 +0000406
Dan Gohmanaa036492009-02-14 02:31:09 +0000407 // Canonicalize a constant to the RHS.
408 if (isa<ConstantInt>(CmpLHS)) {
409 Pred = ICmpInst::getSwappedPredicate(Pred);
410 std::swap(CmpLHS, CmpRHS);
411 }
412 // Canonicalize SLE to SLT.
413 if (Pred == ICmpInst::ICMP_SLE)
414 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
415 if (!CI->getValue().isMaxSignedValue()) {
416 CmpRHS = ConstantInt::get(CI->getValue() + 1);
417 Pred = ICmpInst::ICMP_SLT;
418 }
419 // Canonicalize SGT to SGE.
420 if (Pred == ICmpInst::ICMP_SGT)
421 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
422 if (!CI->getValue().isMaxSignedValue()) {
423 CmpRHS = ConstantInt::get(CI->getValue() + 1);
424 Pred = ICmpInst::ICMP_SGE;
425 }
426 // Canonicalize SGE to SLT.
427 if (Pred == ICmpInst::ICMP_SGE) {
428 std::swap(TrueBB, FalseBB);
429 Pred = ICmpInst::ICMP_SLT;
430 }
431 // Canonicalize ULE to ULT.
432 if (Pred == ICmpInst::ICMP_ULE)
433 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
434 if (!CI->getValue().isMaxValue()) {
435 CmpRHS = ConstantInt::get(CI->getValue() + 1);
436 Pred = ICmpInst::ICMP_ULT;
437 }
438 // Canonicalize UGT to UGE.
439 if (Pred == ICmpInst::ICMP_UGT)
440 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
441 if (!CI->getValue().isMaxValue()) {
442 CmpRHS = ConstantInt::get(CI->getValue() + 1);
443 Pred = ICmpInst::ICMP_UGE;
444 }
445 // Canonicalize UGE to ULT.
446 if (Pred == ICmpInst::ICMP_UGE) {
447 std::swap(TrueBB, FalseBB);
448 Pred = ICmpInst::ICMP_ULT;
449 }
450 // For now, analyze only LT loops for signed overflow.
451 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_ULT)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000452 return 0;
Dan Gohmanaa036492009-02-14 02:31:09 +0000453
454 bool isSigned = Pred == ICmpInst::ICMP_SLT;
455
456 // Get the increment instruction. Look past casts if we will
Dan Gohmanc2390b12009-02-12 22:19:27 +0000457 // be able to prove that the original induction variable doesn't
Dan Gohmanaa036492009-02-14 02:31:09 +0000458 // undergo signed or unsigned overflow, respectively.
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000459 const Value *IncrInst = CmpLHS;
Dan Gohmanaa036492009-02-14 02:31:09 +0000460 if (isSigned) {
461 if (const SExtInst *SI = dyn_cast<SExtInst>(CmpLHS)) {
462 if (!isa<ConstantInt>(CmpRHS) ||
463 !cast<ConstantInt>(CmpRHS)->getValue()
Dan Gohman2d1be872009-04-16 03:18:22 +0000464 .isSignedIntN(TD->getTypeSizeInBits(IncrInst->getType())))
Dan Gohmand2067fd2009-02-18 00:52:00 +0000465 return 0;
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000466 IncrInst = SI->getOperand(0);
Dan Gohmanaa036492009-02-14 02:31:09 +0000467 }
468 } else {
469 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(CmpLHS)) {
470 if (!isa<ConstantInt>(CmpRHS) ||
471 !cast<ConstantInt>(CmpRHS)->getValue()
Dan Gohman2d1be872009-04-16 03:18:22 +0000472 .isIntN(TD->getTypeSizeInBits(IncrInst->getType())))
Dan Gohmand2067fd2009-02-18 00:52:00 +0000473 return 0;
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000474 IncrInst = ZI->getOperand(0);
Dan Gohmanaa036492009-02-14 02:31:09 +0000475 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000476 }
477
478 // For now, only analyze induction variables that have simple increments.
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000479 const BinaryOperator *IncrOp = dyn_cast<BinaryOperator>(IncrInst);
480 if (!IncrOp || IncrOp->getOpcode() != Instruction::Add)
481 return 0;
482 IncrVal = dyn_cast<ConstantInt>(IncrOp->getOperand(1));
483 if (!IncrVal)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000484 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000485
486 // Make sure the PHI looks like a normal IV.
487 const PHINode *PN = dyn_cast<PHINode>(IncrOp->getOperand(0));
488 if (!PN || PN->getNumIncomingValues() != 2)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000489 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000490 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
491 unsigned BackEdge = !IncomingEdge;
492 if (!L->contains(PN->getIncomingBlock(BackEdge)) ||
493 PN->getIncomingValue(BackEdge) != IncrOp)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000494 return 0;
Dan Gohmanaa036492009-02-14 02:31:09 +0000495 if (!L->contains(TrueBB))
Dan Gohmand2067fd2009-02-18 00:52:00 +0000496 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000497
498 // For now, only analyze loops with a constant start value, so that
Dan Gohmanaa036492009-02-14 02:31:09 +0000499 // we can easily determine if the start value is not a maximum value
500 // which would wrap on the first iteration.
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000501 InitialVal = dyn_cast<ConstantInt>(PN->getIncomingValue(IncomingEdge));
Dan Gohmancad24c92009-02-18 16:54:33 +0000502 if (!InitialVal)
Dan Gohmand2067fd2009-02-18 00:52:00 +0000503 return 0;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000504
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000505 // The upper limit need not be a constant; we'll check later.
506 LimitVal = dyn_cast<ConstantInt>(CmpRHS);
507
508 // We detect the impossibility of wrapping in two cases, both of
509 // which require starting with a non-max value:
510 // - The IV counts up by one, and the loop iterates only while it remains
511 // less than a limiting value (any) in the same type.
512 // - The IV counts up by a positive increment other than 1, and the
513 // constant limiting value + the increment is less than the max value
514 // (computed as max-increment to avoid overflow)
Dan Gohmanf5a309e2009-02-18 17:22:41 +0000515 if (isSigned && !InitialVal->getValue().isMaxSignedValue()) {
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000516 if (IncrVal->equalsInt(1))
517 NoSignedWrap = true; // LimitVal need not be constant
518 else if (LimitVal) {
519 uint64_t numBits = LimitVal->getValue().getBitWidth();
520 if (IncrVal->getValue().sgt(APInt::getNullValue(numBits)) &&
521 (APInt::getSignedMaxValue(numBits) - IncrVal->getValue())
522 .sgt(LimitVal->getValue()))
523 NoSignedWrap = true;
524 }
525 } else if (!isSigned && !InitialVal->getValue().isMaxValue()) {
526 if (IncrVal->equalsInt(1))
527 NoUnsignedWrap = true; // LimitVal need not be constant
528 else if (LimitVal) {
529 uint64_t numBits = LimitVal->getValue().getBitWidth();
530 if (IncrVal->getValue().ugt(APInt::getNullValue(numBits)) &&
531 (APInt::getMaxValue(numBits) - IncrVal->getValue())
532 .ugt(LimitVal->getValue()))
533 NoUnsignedWrap = true;
534 }
535 }
Dan Gohmand2067fd2009-02-18 00:52:00 +0000536 return PN;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000537}
538
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000539static Value *getSignExtendedTruncVar(const SCEVAddRecExpr *AR,
540 ScalarEvolution *SE,
541 const Type *LargestType, Loop *L,
542 const Type *myType,
543 SCEVExpander &Rewriter,
544 BasicBlock::iterator InsertPt) {
545 SCEVHandle ExtendedStart =
546 SE->getSignExtendExpr(AR->getStart(), LargestType);
547 SCEVHandle ExtendedStep =
548 SE->getSignExtendExpr(AR->getStepRecurrence(*SE), LargestType);
549 SCEVHandle ExtendedAddRec =
550 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
551 if (LargestType != myType)
552 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, myType);
Dan Gohman2d1be872009-04-16 03:18:22 +0000553 return Rewriter.expandCodeFor(ExtendedAddRec, myType, InsertPt);
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000554}
555
556static Value *getZeroExtendedTruncVar(const SCEVAddRecExpr *AR,
557 ScalarEvolution *SE,
558 const Type *LargestType, Loop *L,
559 const Type *myType,
560 SCEVExpander &Rewriter,
561 BasicBlock::iterator InsertPt) {
562 SCEVHandle ExtendedStart =
563 SE->getZeroExtendExpr(AR->getStart(), LargestType);
564 SCEVHandle ExtendedStep =
565 SE->getZeroExtendExpr(AR->getStepRecurrence(*SE), LargestType);
566 SCEVHandle ExtendedAddRec =
567 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
568 if (LargestType != myType)
569 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, myType);
Dan Gohman2d1be872009-04-16 03:18:22 +0000570 return Rewriter.expandCodeFor(ExtendedAddRec, myType, InsertPt);
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000571}
572
Dale Johannesenc671d892009-04-15 23:31:51 +0000573/// allUsesAreSameTyped - See whether all Uses of I are instructions
574/// with the same Opcode and the same type.
575static bool allUsesAreSameTyped(unsigned int Opcode, Instruction *I) {
576 const Type* firstType = NULL;
577 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
578 UI != UE; ++UI) {
579 Instruction *II = dyn_cast<Instruction>(*UI);
580 if (!II || II->getOpcode() != Opcode)
581 return false;
582 if (!firstType)
583 firstType = II->getType();
584 else if (firstType != II->getType())
585 return false;
586 }
587 return true;
588}
589
Dan Gohmanc2390b12009-02-12 22:19:27 +0000590bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Devang Patel5ee99972007-03-07 06:39:01 +0000591 LI = &getAnalysis<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +0000592 TD = &getAnalysis<TargetData>();
Devang Patel5ee99972007-03-07 06:39:01 +0000593 SE = &getAnalysis<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +0000594 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +0000595
Dan Gohman2d1be872009-04-16 03:18:22 +0000596 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +0000597 // transform them to use integer recurrences.
598 RewriteNonIntegerIVs(L);
599
Dan Gohmanc2390b12009-02-12 22:19:27 +0000600 BasicBlock *Header = L->getHeader();
601 BasicBlock *ExitingBlock = L->getExitingBlock();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000602 SmallPtrSet<Instruction*, 16> DeadInsts;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000603
Chris Lattner9caed542007-03-04 01:00:28 +0000604 // Verify the input to the pass in already in LCSSA form.
605 assert(L->isLCSSAForm());
606
Chris Lattner40bf8b42004-04-02 20:24:31 +0000607 // Check to see if this loop has a computable loop-invariant execution count.
608 // If so, this means that we can compute the final value of any expressions
609 // that are recurrent in the loop, and substitute the exit values from the
610 // loop into any instructions outside of the loop that use the final values of
611 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000612 //
Dan Gohman46bdfb02009-02-24 18:55:53 +0000613 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
614 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
615 RewriteLoopExitValues(L, BackedgeTakenCount);
Chris Lattner6148c022001-12-03 17:28:42 +0000616
Chris Lattner40bf8b42004-04-02 20:24:31 +0000617 // Next, analyze all of the induction variables in the loop, canonicalizing
618 // auxillary induction variables.
619 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
620
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000621 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
622 PHINode *PN = cast<PHINode>(I);
Dan Gohman2d1be872009-04-16 03:18:22 +0000623 if (PN->getType()->isInteger() || isa<PointerType>(PN->getType())) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000624 SCEVHandle SCEV = SE->getSCEV(PN);
Dan Gohmancd3eb9b2009-02-14 02:25:19 +0000625 // FIXME: It is an extremely bad idea to indvar substitute anything more
626 // complex than affine induction variables. Doing so will put expensive
627 // polynomial evaluations inside of the loop, and the str reduction pass
628 // currently can only reduce affine polynomials. For now just disable
629 // indvar subst on anything more complex than an affine addrec.
630 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
631 if (AR->getLoop() == L && AR->isAffine())
632 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000633 }
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000634 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000635
Dan Gohmanc2390b12009-02-12 22:19:27 +0000636 // Compute the type of the largest recurrence expression, and collect
637 // the set of the types of the other recurrence expressions.
638 const Type *LargestType = 0;
639 SmallSetVector<const Type *, 4> SizesToInsert;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000640 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
641 LargestType = BackedgeTakenCount->getType();
Dan Gohman2d1be872009-04-16 03:18:22 +0000642 if (isa<PointerType>(LargestType))
643 LargestType = TD->getIntPtrType();
644 SizesToInsert.insert(LargestType);
Chris Lattnerf50af082004-04-17 18:08:33 +0000645 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000646 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
647 const PHINode *PN = IndVars[i].first;
Dan Gohman2d1be872009-04-16 03:18:22 +0000648 const Type *PNTy = PN->getType();
649 if (isa<PointerType>(PNTy)) PNTy = TD->getIntPtrType();
650 SizesToInsert.insert(PNTy);
651 const Type *EffTy = getEffectiveIndvarType(PN, TD);
652 if (isa<PointerType>(EffTy)) EffTy = TD->getIntPtrType();
Dan Gohmanc2390b12009-02-12 22:19:27 +0000653 SizesToInsert.insert(EffTy);
654 if (!LargestType ||
Dan Gohman2d1be872009-04-16 03:18:22 +0000655 TD->getTypeSizeInBits(EffTy) >
656 TD->getTypeSizeInBits(LargestType))
Dan Gohmanc2390b12009-02-12 22:19:27 +0000657 LargestType = EffTy;
Chris Lattner6148c022001-12-03 17:28:42 +0000658 }
659
Chris Lattner40bf8b42004-04-02 20:24:31 +0000660 // Create a rewriter object which we'll use to transform the code with.
Dan Gohman2d1be872009-04-16 03:18:22 +0000661 SCEVExpander Rewriter(*SE, *LI, *TD);
Chris Lattner15cad752003-12-23 07:47:09 +0000662
Chris Lattner40bf8b42004-04-02 20:24:31 +0000663 // Now that we know the largest of of the induction variables in this loop,
664 // insert a canonical induction variable of the largest size.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000665 Value *IndVar = 0;
666 if (!SizesToInsert.empty()) {
667 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
668 ++NumInserted;
669 Changed = true;
670 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohmand19534a2007-06-15 14:38:12 +0000671 }
Chris Lattner15cad752003-12-23 07:47:09 +0000672
Dan Gohmanc2390b12009-02-12 22:19:27 +0000673 // If we have a trip count expression, rewrite the loop's exit condition
674 // using it. We can currently only handle loops with a single exit.
Dan Gohmanaa036492009-02-14 02:31:09 +0000675 bool NoSignedWrap = false;
676 bool NoUnsignedWrap = false;
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000677 const ConstantInt* InitialVal, * IncrVal, * LimitVal;
Dan Gohmand2067fd2009-02-18 00:52:00 +0000678 const PHINode *OrigControllingPHI = 0;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000679 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && ExitingBlock)
Dan Gohmanc2390b12009-02-12 22:19:27 +0000680 // Can't rewrite non-branch yet.
681 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
682 if (Instruction *OrigCond = dyn_cast<Instruction>(BI->getCondition())) {
Dan Gohmanaa036492009-02-14 02:31:09 +0000683 // Determine if the OrigIV will ever undergo overflow.
Dan Gohmand2067fd2009-02-18 00:52:00 +0000684 OrigControllingPHI =
Dan Gohman2d1be872009-04-16 03:18:22 +0000685 TestOrigIVForWrap(L, BI, OrigCond, TD,
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000686 NoSignedWrap, NoUnsignedWrap,
687 InitialVal, IncrVal, LimitVal);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000688
689 // We'll be replacing the original condition, so it'll be dead.
690 DeadInsts.insert(OrigCond);
691 }
692
Dan Gohman46bdfb02009-02-24 18:55:53 +0000693 LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
Dan Gohman15cab282009-02-23 23:20:35 +0000694 ExitingBlock, BI, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000695 }
696
Chris Lattner40bf8b42004-04-02 20:24:31 +0000697 // Now that we have a canonical induction variable, we can rewrite any
698 // recurrences in terms of the induction variable. Start with the auxillary
699 // induction variables, and recursively rewrite any of their uses.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000700 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Chris Lattner6148c022001-12-03 17:28:42 +0000701
Chris Lattner5d461d22004-04-21 22:22:01 +0000702 // If there were induction variables of other sizes, cast the primary
703 // induction variable to the right size for them, avoiding the need for the
704 // code evaluation methods to insert induction variables of different sizes.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000705 for (unsigned i = 0, e = SizesToInsert.size(); i != e; ++i) {
706 const Type *Ty = SizesToInsert[i];
707 if (Ty != LargestType) {
708 Instruction *New = new TruncInst(IndVar, Ty, "indvar", InsertPt);
709 Rewriter.addInsertedValue(New, SE->getSCEV(New));
710 DOUT << "INDVARS: Made trunc IV for type " << *Ty << ": "
711 << *New << "\n";
Reid Spencera54b7cb2007-01-12 07:05:14 +0000712 }
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000713 }
714
Chris Lattneree4f13a2007-01-07 01:14:12 +0000715 // Rewrite all induction variables in terms of the canonical induction
716 // variable.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000717 while (!IndVars.empty()) {
718 PHINode *PN = IndVars.back().first;
Dan Gohman1a5e9362009-02-17 00:10:53 +0000719 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(IndVars.back().second);
Dan Gohman2d1be872009-04-16 03:18:22 +0000720 Value *NewVal = Rewriter.expandCodeFor(AR, PN->getType(), InsertPt);
Dan Gohman1a5e9362009-02-17 00:10:53 +0000721 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *PN
Chris Lattneree4f13a2007-01-07 01:14:12 +0000722 << " into = " << *NewVal << "\n";
Chris Lattner6934a042007-02-11 01:23:03 +0000723 NewVal->takeName(PN);
Chris Lattner5d461d22004-04-21 22:22:01 +0000724
Dan Gohmanc2390b12009-02-12 22:19:27 +0000725 /// If the new canonical induction variable is wider than the original,
726 /// and the original has uses that are casts to wider types, see if the
727 /// truncate and extend can be omitted.
Dan Gohmand2067fd2009-02-18 00:52:00 +0000728 if (PN == OrigControllingPHI && PN->getType() != LargestType)
Dan Gohmanc2390b12009-02-12 22:19:27 +0000729 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
Dan Gohmanaa036492009-02-14 02:31:09 +0000730 UI != UE; ++UI) {
Dale Johannesend3325d282009-04-15 20:41:02 +0000731 Instruction *UInst = dyn_cast<Instruction>(*UI);
732 if (UInst && isa<SExtInst>(UInst) && NoSignedWrap) {
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000733 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType, L,
Dale Johannesend3325d282009-04-15 20:41:02 +0000734 UInst->getType(), Rewriter, InsertPt);
735 UInst->replaceAllUsesWith(TruncIndVar);
736 DeadInsts.insert(UInst);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000737 }
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000738 // See if we can figure out sext(i+constant) doesn't wrap, so we can
739 // use a larger add. This is common in subscripting.
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000740 if (UInst && UInst->getOpcode()==Instruction::Add &&
Dale Johannesenc671d892009-04-15 23:31:51 +0000741 allUsesAreSameTyped(Instruction::SExt, UInst) &&
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000742 isa<ConstantInt>(UInst->getOperand(1)) &&
Dale Johannesend3325d282009-04-15 20:41:02 +0000743 NoSignedWrap && LimitVal) {
744 uint64_t oldBitSize = LimitVal->getValue().getBitWidth();
745 uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
746 ConstantInt* AddRHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
747 if (((APInt::getSignedMaxValue(oldBitSize) - IncrVal->getValue()) -
748 AddRHS->getValue()).sgt(LimitVal->getValue())) {
749 // We've determined this is (i+constant) and it won't overflow.
750 if (isa<SExtInst>(UInst->use_begin())) {
751 SExtInst* oldSext = dyn_cast<SExtInst>(UInst->use_begin());
752 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
753 L, oldSext->getType(), Rewriter,
754 InsertPt);
755 APInt APcopy = APInt(AddRHS->getValue());
756 ConstantInt* newAddRHS =ConstantInt::get(APcopy.sext(newBitSize));
757 Value *NewAdd =
758 BinaryOperator::CreateAdd(TruncIndVar, newAddRHS,
759 UInst->getName()+".nosex", UInst);
Dale Johannesenc671d892009-04-15 23:31:51 +0000760 for (Value::use_iterator UI2 = UInst->use_begin(),
761 UE2 = UInst->use_end(); UI2 != UE2; ++UI2) {
762 Instruction *II = dyn_cast<Instruction>(UI2);
763 II->replaceAllUsesWith(NewAdd);
764 DeadInsts.insert(II);
765 }
Dale Johannesend3325d282009-04-15 20:41:02 +0000766 DeadInsts.insert(UInst);
767 }
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000768 }
769 }
Dale Johannesenc671d892009-04-15 23:31:51 +0000770 // Try for sext(i | constant). This is safe as long as the
771 // high bit of the constant is not set.
772 if (UInst && UInst->getOpcode()==Instruction::Or &&
773 allUsesAreSameTyped(Instruction::SExt, UInst) && NoSignedWrap &&
774 isa<ConstantInt>(UInst->getOperand(1))) {
775 ConstantInt* RHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
776 if (!RHS->getValue().isNegative()) {
777 uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
778 SExtInst* oldSext = dyn_cast<SExtInst>(UInst->use_begin());
779 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
780 L, oldSext->getType(), Rewriter,
781 InsertPt);
782 APInt APcopy = APInt(RHS->getValue());
783 ConstantInt* newRHS =ConstantInt::get(APcopy.sext(newBitSize));
784 Value *NewAdd =
785 BinaryOperator::CreateOr(TruncIndVar, newRHS,
786 UInst->getName()+".nosex", UInst);
787 for (Value::use_iterator UI2 = UInst->use_begin(),
788 UE2 = UInst->use_end(); UI2 != UE2; ++UI2) {
789 Instruction *II = dyn_cast<Instruction>(UI2);
790 II->replaceAllUsesWith(NewAdd);
791 DeadInsts.insert(II);
792 }
793 DeadInsts.insert(UInst);
794 }
795 }
796 // A zext of a signed variable known not to overflow is still safe.
797 if (UInst && isa<ZExtInst>(UInst) && (NoUnsignedWrap || NoSignedWrap)) {
Dale Johannesendd1f9e42009-04-15 01:10:12 +0000798 Value *TruncIndVar = getZeroExtendedTruncVar(AR, SE, LargestType, L,
Dale Johannesend3325d282009-04-15 20:41:02 +0000799 UInst->getType(), Rewriter, InsertPt);
800 UInst->replaceAllUsesWith(TruncIndVar);
801 DeadInsts.insert(UInst);
802 }
Dale Johannesenc671d892009-04-15 23:31:51 +0000803 // If we have zext(i&constant), it's always safe to use the larger
804 // variable. This is not common but is a bottleneck in Openssl.
Dale Johannesend3325d282009-04-15 20:41:02 +0000805 // (RHS doesn't have to be constant. There should be a better approach
806 // than bottom-up pattern matching for this...)
807 if (UInst && UInst->getOpcode()==Instruction::And &&
Dale Johannesenc671d892009-04-15 23:31:51 +0000808 allUsesAreSameTyped(Instruction::ZExt, UInst) &&
809 isa<ConstantInt>(UInst->getOperand(1))) {
Dale Johannesend3325d282009-04-15 20:41:02 +0000810 uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
811 ConstantInt* AndRHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
812 ZExtInst* oldZext = dyn_cast<ZExtInst>(UInst->use_begin());
813 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
814 L, oldZext->getType(), Rewriter, InsertPt);
815 APInt APcopy = APInt(AndRHS->getValue());
816 ConstantInt* newAndRHS = ConstantInt::get(APcopy.zext(newBitSize));
817 Value *NewAnd =
818 BinaryOperator::CreateAnd(TruncIndVar, newAndRHS,
819 UInst->getName()+".nozex", UInst);
Dale Johannesenc671d892009-04-15 23:31:51 +0000820 for (Value::use_iterator UI2 = UInst->use_begin(),
821 UE2 = UInst->use_end(); UI2 != UE2; ++UI2) {
822 Instruction *II = dyn_cast<Instruction>(UI2);
823 II->replaceAllUsesWith(NewAnd);
824 DeadInsts.insert(II);
825 }
Dale Johannesend3325d282009-04-15 20:41:02 +0000826 DeadInsts.insert(UInst);
827 }
828 // If we have zext((i+constant)&constant), we can use the larger
829 // variable even if the add does overflow. This works whenever the
830 // constant being ANDed is the same size as i, which it presumably is.
831 // We don't need to restrict the expression being and'ed to i+const,
832 // but we have to promote everything in it, so it's convenient.
Dale Johannesenc671d892009-04-15 23:31:51 +0000833 // zext((i | constant)&constant) is also valid and accepted here.
834 if (UInst && (UInst->getOpcode()==Instruction::Add ||
835 UInst->getOpcode()==Instruction::Or) &&
Dale Johannesend3325d282009-04-15 20:41:02 +0000836 UInst->hasOneUse() &&
837 isa<ConstantInt>(UInst->getOperand(1))) {
838 uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
839 ConstantInt* AddRHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
840 Instruction *UInst2 = dyn_cast<Instruction>(UInst->use_begin());
841 if (UInst2 && UInst2->getOpcode() == Instruction::And &&
Dale Johannesenc671d892009-04-15 23:31:51 +0000842 allUsesAreSameTyped(Instruction::ZExt, UInst2) &&
843 isa<ConstantInt>(UInst2->getOperand(1))) {
Dale Johannesend3325d282009-04-15 20:41:02 +0000844 ZExtInst* oldZext = dyn_cast<ZExtInst>(UInst2->use_begin());
845 Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
846 L, oldZext->getType(), Rewriter, InsertPt);
847 ConstantInt* AndRHS = dyn_cast<ConstantInt>(UInst2->getOperand(1));
848 APInt APcopy = APInt(AddRHS->getValue());
849 ConstantInt* newAddRHS = ConstantInt::get(APcopy.zext(newBitSize));
Dale Johannesenc671d892009-04-15 23:31:51 +0000850 Value *NewAdd = ((UInst->getOpcode()==Instruction::Add) ?
Dale Johannesend3325d282009-04-15 20:41:02 +0000851 BinaryOperator::CreateAdd(TruncIndVar, newAddRHS,
Dale Johannesenc671d892009-04-15 23:31:51 +0000852 UInst->getName()+".nozex", UInst2) :
853 BinaryOperator::CreateOr(TruncIndVar, newAddRHS,
854 UInst->getName()+".nozex", UInst2));
Dale Johannesend3325d282009-04-15 20:41:02 +0000855 APInt APcopy2 = APInt(AndRHS->getValue());
856 ConstantInt* newAndRHS = ConstantInt::get(APcopy2.zext(newBitSize));
857 Value *NewAnd =
858 BinaryOperator::CreateAnd(NewAdd, newAndRHS,
859 UInst->getName()+".nozex", UInst2);
Dale Johannesenc671d892009-04-15 23:31:51 +0000860 for (Value::use_iterator UI2 = UInst2->use_begin(),
861 UE2 = UInst2->use_end(); UI2 != UE2; ++UI2) {
862 Instruction *II = dyn_cast<Instruction>(UI2);
863 II->replaceAllUsesWith(NewAnd);
864 DeadInsts.insert(II);
865 }
Dale Johannesend3325d282009-04-15 20:41:02 +0000866 DeadInsts.insert(UInst);
867 DeadInsts.insert(UInst2);
868 }
Dan Gohmanaa036492009-02-14 02:31:09 +0000869 }
870 }
Dan Gohmanc2390b12009-02-12 22:19:27 +0000871
Chris Lattner40bf8b42004-04-02 20:24:31 +0000872 // Replace the old PHI Node with the inserted computation.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000873 PN->replaceAllUsesWith(NewVal);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000874 DeadInsts.insert(PN);
875 IndVars.pop_back();
876 ++NumRemoved;
Chris Lattner4753bf22001-12-05 19:41:33 +0000877 Changed = true;
Chris Lattner394437f2001-12-04 04:32:29 +0000878 }
879
Chris Lattner1363e852004-04-21 23:36:08 +0000880 DeleteTriviallyDeadInstructions(DeadInsts);
Chris Lattner9caed542007-03-04 01:00:28 +0000881 assert(L->isLCSSAForm());
Devang Patel5ee99972007-03-07 06:39:01 +0000882 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000883}
Devang Pateld22a8492008-09-09 21:41:07 +0000884
Devang Patel13877bf2008-11-18 00:40:02 +0000885/// Return true if it is OK to use SIToFPInst for an inducation variable
886/// with given inital and exit values.
887static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
888 uint64_t intIV, uint64_t intEV) {
889
Dan Gohmancafb8132009-02-17 19:13:57 +0000890 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patel13877bf2008-11-18 00:40:02 +0000891 return true;
892
893 // If the iteration range can be handled by SIToFPInst then use it.
894 APInt Max = APInt::getSignedMaxValue(32);
Bill Wendling9bef7062008-11-18 10:57:27 +0000895 if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
Devang Patel13877bf2008-11-18 00:40:02 +0000896 return true;
Dan Gohmancafb8132009-02-17 19:13:57 +0000897
Devang Patel13877bf2008-11-18 00:40:02 +0000898 return false;
899}
900
901/// convertToInt - Convert APF to an integer, if possible.
Devang Patelcd402332008-11-17 23:27:13 +0000902static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
903
904 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000905 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
906 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000907 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patelcd402332008-11-17 23:27:13 +0000908 APFloat::rmTowardZero, &isExact)
909 != APFloat::opOK)
910 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000911 if (!isExact)
Devang Patelcd402332008-11-17 23:27:13 +0000912 return false;
913 return true;
914
915}
916
Devang Patel58d43d42008-11-03 18:32:19 +0000917/// HandleFloatingPointIV - If the loop has floating induction variable
918/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000919/// For example,
920/// for(double i = 0; i < 10000; ++i)
921/// bar(i)
922/// is converted into
923/// for(int i = 0; i < 10000; ++i)
924/// bar((double)i);
925///
Dan Gohmancafb8132009-02-17 19:13:57 +0000926void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
Devang Patel84e35152008-11-17 21:32:02 +0000927 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Devang Patel58d43d42008-11-03 18:32:19 +0000928
Devang Patel84e35152008-11-17 21:32:02 +0000929 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
930 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +0000931
Devang Patel84e35152008-11-17 21:32:02 +0000932 // Check incoming value.
Devang Patelcd402332008-11-17 23:27:13 +0000933 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
934 if (!InitValue) return;
935 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
936 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
937 return;
938
939 // Check IV increment. Reject this PH if increement operation is not
940 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +0000941 BinaryOperator *Incr =
Devang Patel84e35152008-11-17 21:32:02 +0000942 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
943 if (!Incr) return;
944 if (Incr->getOpcode() != Instruction::Add) return;
945 ConstantFP *IncrValue = NULL;
946 unsigned IncrVIndex = 1;
947 if (Incr->getOperand(1) == PH)
948 IncrVIndex = 0;
949 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
950 if (!IncrValue) return;
Devang Patelcd402332008-11-17 23:27:13 +0000951 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
952 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
953 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000954
Devang Patelcd402332008-11-17 23:27:13 +0000955 // Check Incr uses. One user is PH and the other users is exit condition used
956 // by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000957 Value::use_iterator IncrUse = Incr->use_begin();
958 Instruction *U1 = cast<Instruction>(IncrUse++);
959 if (IncrUse == Incr->use_end()) return;
960 Instruction *U2 = cast<Instruction>(IncrUse++);
961 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000962
Devang Patel84e35152008-11-17 21:32:02 +0000963 // Find exit condition.
964 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
965 if (!EC)
966 EC = dyn_cast<FCmpInst>(U2);
967 if (!EC) return;
968
969 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
970 if (!BI->isConditional()) return;
971 if (BI->getCondition() != EC) return;
Devang Patel58d43d42008-11-03 18:32:19 +0000972 }
Devang Patel58d43d42008-11-03 18:32:19 +0000973
Devang Patelcd402332008-11-17 23:27:13 +0000974 // Find exit value. If exit value can not be represented as an interger then
975 // do not handle this floating point PH.
Devang Patel84e35152008-11-17 21:32:02 +0000976 ConstantFP *EV = NULL;
977 unsigned EVIndex = 1;
978 if (EC->getOperand(1) == Incr)
979 EVIndex = 0;
980 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
981 if (!EV) return;
Devang Patel84e35152008-11-17 21:32:02 +0000982 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000983 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patel84e35152008-11-17 21:32:02 +0000984 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000985
Devang Patel84e35152008-11-17 21:32:02 +0000986 // Find new predicate for integer comparison.
987 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
988 switch (EC->getPredicate()) {
989 case CmpInst::FCMP_OEQ:
990 case CmpInst::FCMP_UEQ:
991 NewPred = CmpInst::ICMP_EQ;
992 break;
993 case CmpInst::FCMP_OGT:
994 case CmpInst::FCMP_UGT:
995 NewPred = CmpInst::ICMP_UGT;
996 break;
997 case CmpInst::FCMP_OGE:
998 case CmpInst::FCMP_UGE:
999 NewPred = CmpInst::ICMP_UGE;
1000 break;
1001 case CmpInst::FCMP_OLT:
1002 case CmpInst::FCMP_ULT:
1003 NewPred = CmpInst::ICMP_ULT;
1004 break;
1005 case CmpInst::FCMP_OLE:
1006 case CmpInst::FCMP_ULE:
1007 NewPred = CmpInst::ICMP_ULE;
1008 break;
1009 default:
1010 break;
Devang Patel58d43d42008-11-03 18:32:19 +00001011 }
Devang Patel84e35152008-11-17 21:32:02 +00001012 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohmancafb8132009-02-17 19:13:57 +00001013
Devang Patel84e35152008-11-17 21:32:02 +00001014 // Insert new integer induction variable.
1015 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
1016 PH->getName()+".int", PH);
Devang Patelcd402332008-11-17 23:27:13 +00001017 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patel84e35152008-11-17 21:32:02 +00001018 PH->getIncomingBlock(IncomingEdge));
1019
Dan Gohmancafb8132009-02-17 19:13:57 +00001020 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
1021 ConstantInt::get(Type::Int32Ty,
Devang Patelcd402332008-11-17 23:27:13 +00001022 newIncrValue),
Devang Patel84e35152008-11-17 21:32:02 +00001023 Incr->getName()+".int", Incr);
1024 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
1025
1026 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
1027 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
1028 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
Dan Gohmancafb8132009-02-17 19:13:57 +00001029 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
Devang Patel84e35152008-11-17 21:32:02 +00001030 EC->getParent()->getTerminator());
Dan Gohmancafb8132009-02-17 19:13:57 +00001031
Devang Patel84e35152008-11-17 21:32:02 +00001032 // Delete old, floating point, exit comparision instruction.
1033 EC->replaceAllUsesWith(NewEC);
1034 DeadInsts.insert(EC);
Dan Gohmancafb8132009-02-17 19:13:57 +00001035
Devang Patel84e35152008-11-17 21:32:02 +00001036 // Delete old, floating point, increment instruction.
1037 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
1038 DeadInsts.insert(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +00001039
Devang Patel13877bf2008-11-18 00:40:02 +00001040 // Replace floating induction variable. Give SIToFPInst preference over
1041 // UIToFPInst because it is faster on platforms that are widely used.
1042 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
Dan Gohmancafb8132009-02-17 19:13:57 +00001043 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patelcd402332008-11-17 23:27:13 +00001044 PH->getParent()->getFirstNonPHI());
1045 PH->replaceAllUsesWith(Conv);
1046 } else {
Dan Gohmancafb8132009-02-17 19:13:57 +00001047 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
Devang Patelcd402332008-11-17 23:27:13 +00001048 PH->getParent()->getFirstNonPHI());
1049 PH->replaceAllUsesWith(Conv);
1050 }
Devang Patel84e35152008-11-17 21:32:02 +00001051 DeadInsts.insert(PH);
Devang Patel58d43d42008-11-03 18:32:19 +00001052}
1053