blob: 38b11985519f20ee527e44145ccda946759062e1 [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
Dan Gohmanc2c4cbf2009-05-19 20:38:47 +000034// desired loop transformations have been performed.
Chris Lattner6148c022001-12-03 17:28:42 +000035//
36//===----------------------------------------------------------------------===//
37
Chris Lattner0e5f4992006-12-19 21:40:18 +000038#define DEBUG_TYPE "indvars"
Chris Lattner022103b2002-05-07 20:03:00 +000039#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000040#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000041#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000042#include "llvm/Instructions.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000043#include "llvm/Type.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000044#include "llvm/Analysis/Dominators.h"
45#include "llvm/Analysis/IVUsers.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"
John Criswell47df12d2003-12-18 17:19:19 +000052#include "llvm/Transforms/Utils/Local.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000053#include "llvm/Transforms/Utils/BasicBlockUtils.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"
Reid Spencer551ccae2004-09-01 22:55:40 +000056#include "llvm/ADT/Statistic.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000057#include "llvm/ADT/STLExtras.h"
John Criswell47df12d2003-12-18 17:19:19 +000058using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000059
Chris Lattner0e5f4992006-12-19 21:40:18 +000060STATISTIC(NumRemoved , "Number of aux indvars removed");
Chris Lattner0e5f4992006-12-19 21:40:18 +000061STATISTIC(NumInserted, "Number of canonical indvars added");
62STATISTIC(NumReplaced, "Number of exit values replaced");
63STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065namespace {
Devang Patel5ee99972007-03-07 06:39:01 +000066 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000067 IVUsers *IU;
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 {
Dan Gohman81db61a2009-05-12 02:17:14 +000079 AU.addRequired<DominatorTree>();
Devang Patelbc533cd2007-09-10 18:08:23 +000080 AU.addRequired<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000081 AU.addRequiredID(LCSSAID);
82 AU.addRequiredID(LoopSimplifyID);
Devang Patel5ee99972007-03-07 06:39:01 +000083 AU.addRequired<LoopInfo>();
Dan Gohman81db61a2009-05-12 02:17:14 +000084 AU.addRequired<IVUsers>();
Dan Gohman474cecf2009-02-23 16:29:41 +000085 AU.addPreserved<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000086 AU.addPreservedID(LoopSimplifyID);
Dan Gohman81db61a2009-05-12 02:17:14 +000087 AU.addPreserved<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +000088 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 Gohman81db61a2009-05-12 02:17:14 +000096 ICmpInst *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 Gohman890f92b2009-04-18 17:56:28 +0000101 void RewriteLoopExitValues(Loop *L, const SCEV *BackedgeTakenCount);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000102
Dan Gohman81db61a2009-05-12 02:17:14 +0000103 void RewriteIVExpressions(Loop *L, const Type *LargestType,
104 SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000105
Dan Gohman81db61a2009-05-12 02:17:14 +0000106 void SinkUnusedInvariants(Loop *L, SCEVExpander &Rewriter);
107
108 void FixUsesBeforeDefs(Loop *L, SCEVExpander &Rewriter);
109
110 void HandleFloatingPointIV(Loop *L, PHINode *PH);
Chris Lattner3324e712003-12-22 03:58:44 +0000111 };
Chris Lattner5e761402002-09-10 05:24:05 +0000112}
Chris Lattner394437f2001-12-04 04:32:29 +0000113
Dan Gohman844731a2008-05-13 00:00:25 +0000114char IndVarSimplify::ID = 0;
115static RegisterPass<IndVarSimplify>
116X("indvars", "Canonicalize Induction Variables");
117
Daniel Dunbar394f0442008-10-22 23:32:42 +0000118Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000119 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000120}
121
Chris Lattner40bf8b42004-04-02 20:24:31 +0000122/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000123/// loop to be a canonical != comparison against the incremented loop induction
124/// variable. This pass is able to rewrite the exit tests of any loop where the
125/// SCEV analysis can determine a loop-invariant trip count of the loop, which
126/// is actually a much broader range than just linear tests.
Dan Gohman81db61a2009-05-12 02:17:14 +0000127ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
Dan Gohman46bdfb02009-02-24 18:55:53 +0000128 SCEVHandle BackedgeTakenCount,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000129 Value *IndVar,
130 BasicBlock *ExitingBlock,
131 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000132 SCEVExpander &Rewriter) {
Chris Lattnerd2440572004-04-15 20:26:22 +0000133 // If the exiting block is not the same as the backedge block, we must compare
134 // against the preincremented value, otherwise we prefer to compare against
135 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000136 Value *CmpIndVar;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000137 SCEVHandle RHS = BackedgeTakenCount;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000138 if (ExitingBlock == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000139 // Add one to the "backedge-taken" count to get the trip count.
140 // If this addition may overflow, we have to be more pessimistic and
141 // cast the induction variable before doing the add.
142 SCEVHandle Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000143 SCEVHandle N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000144 SE->getAddExpr(BackedgeTakenCount,
145 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000146 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
147 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
148 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000149 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000150 } else {
151 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000152 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
153 IndVar->getType());
154 RHS = SE->getAddExpr(RHS,
155 SE->getIntegerSCEV(1, IndVar->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000156 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000157
Dan Gohman46bdfb02009-02-24 18:55:53 +0000158 // The BackedgeTaken expression contains the number of times that the
159 // backedge branches to the loop header. This is one less than the
160 // number of times the loop executes, so use the incremented indvar.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000161 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Chris Lattnerd2440572004-04-15 20:26:22 +0000162 } else {
163 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000164 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
165 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000166 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000167 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000168
Chris Lattner40bf8b42004-04-02 20:24:31 +0000169 // Expand the code for the iteration count into the preheader of the loop.
170 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman4d8414f2009-06-13 16:25:49 +0000171 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(),
Dan Gohmanc2390b12009-02-12 22:19:27 +0000172 Preheader->getTerminator());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000173
Reid Spencere4d87aa2006-12-23 06:05:41 +0000174 // Insert a new icmp_ne or icmp_eq instruction before the branch.
175 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000176 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000177 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000178 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000179 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000180
Dan Gohmanc2390b12009-02-12 22:19:27 +0000181 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
182 << " LHS:" << *CmpIndVar // includes a newline
183 << " op:\t"
Dan Gohmanf108e2e2009-02-14 02:26:50 +0000184 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohman46bdfb02009-02-24 18:55:53 +0000185 << " RHS:\t" << *RHS << "\n";
Dan Gohmanc2390b12009-02-12 22:19:27 +0000186
Dan Gohman81db61a2009-05-12 02:17:14 +0000187 ICmpInst *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
188
189 Instruction *OrigCond = cast<Instruction>(BI->getCondition());
Dan Gohman95bdbfa2009-05-24 19:11:38 +0000190 // It's tempting to use replaceAllUsesWith here to fully replace the old
191 // comparison, but that's not immediately safe, since users of the old
192 // comparison may not be dominated by the new comparison. Instead, just
193 // update the branch to use the new comparison; in the common case this
194 // will make old comparison dead.
195 BI->setCondition(Cond);
Dan Gohman81db61a2009-05-12 02:17:14 +0000196 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
197
Chris Lattner40bf8b42004-04-02 20:24:31 +0000198 ++NumLFTR;
199 Changed = true;
Dan Gohman81db61a2009-05-12 02:17:14 +0000200 return Cond;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000201}
202
Chris Lattner40bf8b42004-04-02 20:24:31 +0000203/// RewriteLoopExitValues - Check to see if this loop has a computable
204/// loop-invariant execution count. If so, this means that we can compute the
205/// final value of any expressions that are recurrent in the loop, and
206/// substitute the exit values from the loop into any instructions outside of
207/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000208///
209/// This is mostly redundant with the regular IndVarSimplify activities that
210/// happen later, except that it's more powerful in some cases, because it's
211/// able to brute-force evaluate arbitrary instructions as long as they have
212/// constant operands at the beginning of the loop.
Dan Gohman890f92b2009-04-18 17:56:28 +0000213void IndVarSimplify::RewriteLoopExitValues(Loop *L,
214 const SCEV *BackedgeTakenCount) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000215 // Verify the input to the pass in already in LCSSA form.
216 assert(L->isLCSSAForm());
217
Chris Lattner40bf8b42004-04-02 20:24:31 +0000218 BasicBlock *Preheader = L->getLoopPreheader();
219
220 // Scan all of the instructions in the loop, looking at those that have
221 // extra-loop users and which are recurrences.
Dan Gohman5be18e82009-05-19 02:15:55 +0000222 SCEVExpander Rewriter(*SE);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000223
224 // We insert the code into the preheader of the loop if the loop contains
225 // multiple exit blocks, or in the exit block if there is exactly one.
226 BasicBlock *BlockToInsertInto;
Devang Patelb7211a22007-08-21 00:31:24 +0000227 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000228 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000229 if (ExitBlocks.size() == 1)
230 BlockToInsertInto = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000231 else
232 BlockToInsertInto = Preheader;
Dan Gohman02dea8b2008-05-23 21:05:58 +0000233 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000234
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++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000253 if (PN->use_empty())
254 continue; // dead use, don't replace it
Chris Lattner9f3d7382007-03-04 03:43:23 +0000255 // Iterate over all of the values in all the PHI nodes.
256 for (unsigned i = 0; i != NumPreds; ++i) {
257 // If the value being merged in is not integer or is not defined
258 // in the loop, skip it.
259 Value *InVal = PN->getIncomingValue(i);
260 if (!isa<Instruction>(InVal) ||
261 // SCEV only supports integer expressions for now.
Dan Gohman2d1be872009-04-16 03:18:22 +0000262 (!isa<IntegerType>(InVal->getType()) &&
263 !isa<PointerType>(InVal->getType())))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000264 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000265
Chris Lattner9f3d7382007-03-04 03:43:23 +0000266 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000267 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000268 continue; // The Block is in a subloop, skip it.
269
270 // Check that InVal is defined in the loop.
271 Instruction *Inst = cast<Instruction>(InVal);
272 if (!L->contains(Inst->getParent()))
273 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000274
Chris Lattner9f3d7382007-03-04 03:43:23 +0000275 // Okay, this instruction has a user outside of the current loop
276 // and varies predictably *inside* the loop. Evaluate the value it
277 // contains when the loop exits, if possible.
Dan Gohmand594e6f2009-05-24 23:25:42 +0000278 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
279 if (!ExitValue->isLoopInvariant(L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000280 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000281
Chris Lattner9f3d7382007-03-04 03:43:23 +0000282 Changed = true;
283 ++NumReplaced;
Dan Gohmancafb8132009-02-17 19:13:57 +0000284
Chris Lattner9f3d7382007-03-04 03:43:23 +0000285 // See if we already computed the exit value for the instruction, if so,
286 // just reuse it.
287 Value *&ExitVal = ExitValues[Inst];
288 if (!ExitVal)
Dan Gohman2d1be872009-04-16 03:18:22 +0000289 ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), InsertPt);
Dan Gohmancafb8132009-02-17 19:13:57 +0000290
Chris Lattner9f3d7382007-03-04 03:43:23 +0000291 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
292 << " LoopVal = " << *Inst << "\n";
293
294 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000295
Dan Gohman81db61a2009-05-12 02:17:14 +0000296 // If this instruction is dead now, delete it.
297 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000298
Chris Lattner9f3d7382007-03-04 03:43:23 +0000299 // See if this is a single-entry LCSSA PHI node. If so, we can (and
300 // have to) remove
Chris Lattner9caed542007-03-04 01:00:28 +0000301 // the PHI entirely. This is safe, because the NewVal won't be variant
302 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000303 if (NumPreds == 1) {
304 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000305 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000306 break;
Chris Lattnerc9838f22007-03-03 22:48:48 +0000307 }
308 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000309 }
310 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000311}
312
Dan Gohman60f8a632009-02-17 20:49:49 +0000313void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000314 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000315 // If there are, change them into integer recurrences, permitting analysis by
316 // the SCEV routines.
317 //
318 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000319
Dan Gohman81db61a2009-05-12 02:17:14 +0000320 SmallVector<WeakVH, 8> PHIs;
321 for (BasicBlock::iterator I = Header->begin();
322 PHINode *PN = dyn_cast<PHINode>(I); ++I)
323 PHIs.push_back(PN);
324
325 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
326 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i]))
327 HandleFloatingPointIV(L, PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000328
Dan Gohman2d1be872009-04-16 03:18:22 +0000329 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000330 // may not have been able to compute a trip count. Now that we've done some
331 // re-writing, the trip count may be computable.
332 if (Changed)
Dan Gohman46bdfb02009-02-24 18:55:53 +0000333 SE->forgetLoopBackedgeTakenCount(L);
Dale Johannesenc671d892009-04-15 23:31:51 +0000334}
335
Dan Gohmanc2390b12009-02-12 22:19:27 +0000336bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000337 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +0000338 LI = &getAnalysis<LoopInfo>();
339 SE = &getAnalysis<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +0000340 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +0000341
Dan Gohman2d1be872009-04-16 03:18:22 +0000342 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +0000343 // transform them to use integer recurrences.
344 RewriteNonIntegerIVs(L);
345
Dan Gohmanc2390b12009-02-12 22:19:27 +0000346 BasicBlock *Header = L->getHeader();
Dan Gohman81db61a2009-05-12 02:17:14 +0000347 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
348 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +0000349
Chris Lattner40bf8b42004-04-02 20:24:31 +0000350 // Check to see if this loop has a computable loop-invariant execution count.
351 // If so, this means that we can compute the final value of any expressions
352 // that are recurrent in the loop, and substitute the exit values from the
353 // loop into any instructions outside of the loop that use the final values of
354 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000355 //
Dan Gohman46bdfb02009-02-24 18:55:53 +0000356 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
357 RewriteLoopExitValues(L, BackedgeTakenCount);
Chris Lattner6148c022001-12-03 17:28:42 +0000358
Dan Gohman81db61a2009-05-12 02:17:14 +0000359 // Compute the type of the largest recurrence expression, and decide whether
360 // a canonical induction variable should be inserted.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000361 const Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000362 bool NeedCannIV = false;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000363 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
364 LargestType = BackedgeTakenCount->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000365 LargestType = SE->getEffectiveSCEVType(LargestType);
Dan Gohman81db61a2009-05-12 02:17:14 +0000366 // If we have a known trip count and a single exit block, we'll be
367 // rewriting the loop exit test condition below, which requires a
368 // canonical induction variable.
369 if (ExitingBlock)
370 NeedCannIV = true;
Chris Lattnerf50af082004-04-17 18:08:33 +0000371 }
Dan Gohman81db61a2009-05-12 02:17:14 +0000372 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
373 SCEVHandle Stride = IU->StrideOrder[i];
374 const Type *Ty = SE->getEffectiveSCEVType(Stride->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000375 if (!LargestType ||
Dan Gohman81db61a2009-05-12 02:17:14 +0000376 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000377 SE->getTypeSizeInBits(LargestType))
Dan Gohman81db61a2009-05-12 02:17:14 +0000378 LargestType = Ty;
379
380 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
381 IU->IVUsesByStride.find(IU->StrideOrder[i]);
382 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
383
384 if (!SI->second->Users.empty())
385 NeedCannIV = true;
Chris Lattner6148c022001-12-03 17:28:42 +0000386 }
387
Chris Lattner40bf8b42004-04-02 20:24:31 +0000388 // Create a rewriter object which we'll use to transform the code with.
Dan Gohman5be18e82009-05-19 02:15:55 +0000389 SCEVExpander Rewriter(*SE);
Chris Lattner15cad752003-12-23 07:47:09 +0000390
Dan Gohman81db61a2009-05-12 02:17:14 +0000391 // Now that we know the largest of of the induction variable expressions
392 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000393 Value *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000394 if (NeedCannIV) {
Dan Gohman4d8414f2009-06-13 16:25:49 +0000395 // Check to see if the loop already has a canonical-looking induction
396 // variable. If one is present and it's wider than the planned canonical
397 // induction variable, temporarily remove it, so that the Rewriter
398 // doesn't attempt to reuse it.
399 PHINode *OldCannIV = L->getCanonicalInductionVariable();
400 if (OldCannIV) {
401 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
402 SE->getTypeSizeInBits(LargestType))
403 OldCannIV->removeFromParent();
404 else
405 OldCannIV = 0;
406 }
407
Dan Gohmanc2390b12009-02-12 22:19:27 +0000408 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000409
Dan Gohmanc2390b12009-02-12 22:19:27 +0000410 ++NumInserted;
411 Changed = true;
412 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohman4d8414f2009-06-13 16:25:49 +0000413
414 // Now that the official induction variable is established, reinsert
415 // the old canonical-looking variable after it so that the IR remains
416 // consistent. It will be deleted as part of the dead-PHI deletion at
417 // the end of the pass.
418 if (OldCannIV)
419 OldCannIV->insertAfter(cast<Instruction>(IndVar));
Dan Gohmand19534a2007-06-15 14:38:12 +0000420 }
Chris Lattner15cad752003-12-23 07:47:09 +0000421
Dan Gohmanc2390b12009-02-12 22:19:27 +0000422 // If we have a trip count expression, rewrite the loop's exit condition
423 // using it. We can currently only handle loops with a single exit.
Dan Gohman81db61a2009-05-12 02:17:14 +0000424 ICmpInst *NewICmp = 0;
425 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && ExitingBlock) {
426 assert(NeedCannIV &&
427 "LinearFunctionTestReplace requires a canonical induction variable");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000428 // Can't rewrite non-branch yet.
Dan Gohman81db61a2009-05-12 02:17:14 +0000429 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
430 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
431 ExitingBlock, BI, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000432 }
433
Dan Gohman81db61a2009-05-12 02:17:14 +0000434 Rewriter.setInsertionPoint(Header->getFirstNonPHI());
Chris Lattner5d461d22004-04-21 22:22:01 +0000435
Torok Edwin3d431382009-05-24 20:08:21 +0000436 // Rewrite IV-derived expressions. Clears the rewriter cache.
Dan Gohman81db61a2009-05-12 02:17:14 +0000437 RewriteIVExpressions(L, LargestType, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000438
Torok Edwin3d431382009-05-24 20:08:21 +0000439 // The Rewriter may only be used for isInsertedInstruction queries from this
440 // point on.
441
Dan Gohman81db61a2009-05-12 02:17:14 +0000442 // Loop-invariant instructions in the preheader that aren't used in the
443 // loop may be sunk below the loop to reduce register pressure.
444 SinkUnusedInvariants(L, Rewriter);
Chris Lattner394437f2001-12-04 04:32:29 +0000445
Dan Gohman81db61a2009-05-12 02:17:14 +0000446 // Reorder instructions to avoid use-before-def conditions.
447 FixUsesBeforeDefs(L, Rewriter);
448
449 // For completeness, inform IVUsers of the IV use in the newly-created
450 // loop exit test instruction.
451 if (NewICmp)
452 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
453
454 // Clean up dead instructions.
455 DeleteDeadPHIs(L->getHeader());
456 // Check a post-condition.
457 assert(L->isLCSSAForm() && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +0000458 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000459}
Devang Pateld22a8492008-09-09 21:41:07 +0000460
Dan Gohman81db61a2009-05-12 02:17:14 +0000461void IndVarSimplify::RewriteIVExpressions(Loop *L, const Type *LargestType,
462 SCEVExpander &Rewriter) {
463 SmallVector<WeakVH, 16> DeadInsts;
464
465 // Rewrite all induction variable expressions in terms of the canonical
466 // induction variable.
467 //
468 // If there were induction variables of other sizes or offsets, manually
469 // add the offsets to the primary induction variable and cast, avoiding
470 // the need for the code evaluation methods to insert induction variables
471 // of different sizes.
472 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
473 SCEVHandle Stride = IU->StrideOrder[i];
474
475 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
476 IU->IVUsesByStride.find(IU->StrideOrder[i]);
477 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
478 ilist<IVStrideUse> &List = SI->second->Users;
479 for (ilist<IVStrideUse>::iterator UI = List.begin(),
480 E = List.end(); UI != E; ++UI) {
481 SCEVHandle Offset = UI->getOffset();
482 Value *Op = UI->getOperandValToReplace();
Dan Gohman4d8414f2009-06-13 16:25:49 +0000483 const Type *UseTy = Op->getType();
Dan Gohman81db61a2009-05-12 02:17:14 +0000484 Instruction *User = UI->getUser();
Dan Gohman81db61a2009-05-12 02:17:14 +0000485
486 // Compute the final addrec to expand into code.
487 SCEVHandle AR = IU->getReplacementExpr(*UI);
488
Dan Gohman81db61a2009-05-12 02:17:14 +0000489 Value *NewVal = 0;
490 if (AR->isLoopInvariant(L)) {
491 BasicBlock::iterator I = Rewriter.getInsertionPoint();
492 // Expand loop-invariant values in the loop preheader. They will
493 // be sunk to the exit block later, if possible.
Dan Gohman5be18e82009-05-19 02:15:55 +0000494 NewVal =
Dan Gohman4d8414f2009-06-13 16:25:49 +0000495 Rewriter.expandCodeFor(AR, UseTy,
Dan Gohman81db61a2009-05-12 02:17:14 +0000496 L->getLoopPreheader()->getTerminator());
497 Rewriter.setInsertionPoint(I);
498 ++NumReplaced;
499 } else {
Dan Gohman68c93442009-06-03 19:11:31 +0000500 // FIXME: It is an extremely bad idea to indvar substitute anything more
501 // complex than affine induction variables. Doing so will put expensive
502 // polynomial evaluations inside of the loop, and the str reduction pass
503 // currently can only reduce affine polynomials. For now just disable
504 // indvar subst on anything more complex than an affine addrec, unless
505 // it can be expanded to a trivial value.
506 if (!Stride->isLoopInvariant(L))
507 continue;
508
Dan Gohman81db61a2009-05-12 02:17:14 +0000509 // Now expand it into actual Instructions and patch it into place.
510 NewVal = Rewriter.expandCodeFor(AR, UseTy);
511 }
512
513 // Patch the new value into place.
514 if (Op->hasName())
515 NewVal->takeName(Op);
516 User->replaceUsesOfWith(Op, NewVal);
517 UI->setOperandValToReplace(NewVal);
518 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *Op
519 << " into = " << *NewVal << "\n";
520 ++NumRemoved;
521 Changed = true;
522
523 // The old value may be dead now.
524 DeadInsts.push_back(Op);
525 }
526 }
527
Torok Edwin3d431382009-05-24 20:08:21 +0000528 // Clear the rewriter cache, because values that are in the rewriter's cache
529 // can be deleted in the loop below, causing the AssertingVH in the cache to
530 // trigger.
531 Rewriter.clear();
Dan Gohman81db61a2009-05-12 02:17:14 +0000532 // Now that we're done iterating through lists, clean up any instructions
533 // which are now dead.
534 while (!DeadInsts.empty()) {
535 Instruction *Inst = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
536 if (Inst)
537 RecursivelyDeleteTriviallyDeadInstructions(Inst);
538 }
539}
540
541/// If there's a single exit block, sink any loop-invariant values that
542/// were defined in the preheader but not used inside the loop into the
543/// exit block to reduce register pressure in the loop.
544void IndVarSimplify::SinkUnusedInvariants(Loop *L, SCEVExpander &Rewriter) {
545 BasicBlock *ExitBlock = L->getExitBlock();
546 if (!ExitBlock) return;
547
548 Instruction *NonPHI = ExitBlock->getFirstNonPHI();
549 BasicBlock *Preheader = L->getLoopPreheader();
550 BasicBlock::iterator I = Preheader->getTerminator();
551 while (I != Preheader->begin()) {
552 --I;
553 // New instructions were inserted at the end of the preheader. Only
554 // consider those new instructions.
555 if (!Rewriter.isInsertedInstruction(I))
556 break;
557 // Determine if there is a use in or before the loop (direct or
558 // otherwise).
559 bool UsedInLoop = false;
560 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
561 UI != UE; ++UI) {
562 BasicBlock *UseBB = cast<Instruction>(UI)->getParent();
563 if (PHINode *P = dyn_cast<PHINode>(UI)) {
564 unsigned i =
565 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
566 UseBB = P->getIncomingBlock(i);
567 }
568 if (UseBB == Preheader || L->contains(UseBB)) {
569 UsedInLoop = true;
570 break;
571 }
572 }
573 // If there is, the def must remain in the preheader.
574 if (UsedInLoop)
575 continue;
576 // Otherwise, sink it to the exit block.
577 Instruction *ToMove = I;
578 bool Done = false;
579 if (I != Preheader->begin())
580 --I;
581 else
582 Done = true;
583 ToMove->moveBefore(NonPHI);
584 if (Done)
585 break;
586 }
587}
588
589/// Re-schedule the inserted instructions to put defs before uses. This
590/// fixes problems that arrise when SCEV expressions contain loop-variant
591/// values unrelated to the induction variable which are defined inside the
592/// loop. FIXME: It would be better to insert instructions in the right
593/// place so that this step isn't needed.
594void IndVarSimplify::FixUsesBeforeDefs(Loop *L, SCEVExpander &Rewriter) {
595 // Visit all the blocks in the loop in pre-order dom-tree dfs order.
596 DominatorTree *DT = &getAnalysis<DominatorTree>();
597 std::map<Instruction *, unsigned> NumPredsLeft;
598 SmallVector<DomTreeNode *, 16> Worklist;
599 Worklist.push_back(DT->getNode(L->getHeader()));
600 do {
601 DomTreeNode *Node = Worklist.pop_back_val();
602 for (DomTreeNode::iterator I = Node->begin(), E = Node->end(); I != E; ++I)
603 if (L->contains((*I)->getBlock()))
604 Worklist.push_back(*I);
605 BasicBlock *BB = Node->getBlock();
606 // Visit all the instructions in the block top down.
607 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
608 // Count the number of operands that aren't properly dominating.
609 unsigned NumPreds = 0;
610 if (Rewriter.isInsertedInstruction(I) && !isa<PHINode>(I))
611 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
612 OI != OE; ++OI)
613 if (Instruction *Inst = dyn_cast<Instruction>(OI))
614 if (L->contains(Inst->getParent()) && !NumPredsLeft.count(Inst))
615 ++NumPreds;
616 NumPredsLeft[I] = NumPreds;
617 // Notify uses of the position of this instruction, and move the
618 // users (and their dependents, recursively) into place after this
619 // instruction if it is their last outstanding operand.
620 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
621 UI != UE; ++UI) {
622 Instruction *Inst = cast<Instruction>(UI);
623 std::map<Instruction *, unsigned>::iterator Z = NumPredsLeft.find(Inst);
624 if (Z != NumPredsLeft.end() && Z->second != 0 && --Z->second == 0) {
625 SmallVector<Instruction *, 4> UseWorkList;
626 UseWorkList.push_back(Inst);
Dan Gohmand6d02942009-05-22 16:47:11 +0000627 BasicBlock::iterator InsertPt = I;
628 if (InvokeInst *II = dyn_cast<InvokeInst>(InsertPt))
629 InsertPt = II->getNormalDest()->begin();
630 else
631 ++InsertPt;
Dan Gohman81db61a2009-05-12 02:17:14 +0000632 while (isa<PHINode>(InsertPt)) ++InsertPt;
633 do {
634 Instruction *Use = UseWorkList.pop_back_val();
635 Use->moveBefore(InsertPt);
636 NumPredsLeft.erase(Use);
637 for (Value::use_iterator IUI = Use->use_begin(),
638 IUE = Use->use_end(); IUI != IUE; ++IUI) {
639 Instruction *IUIInst = cast<Instruction>(IUI);
640 if (L->contains(IUIInst->getParent()) &&
641 Rewriter.isInsertedInstruction(IUIInst) &&
642 !isa<PHINode>(IUIInst))
643 UseWorkList.push_back(IUIInst);
644 }
645 } while (!UseWorkList.empty());
646 }
647 }
648 }
649 } while (!Worklist.empty());
650}
651
Devang Patel13877bf2008-11-18 00:40:02 +0000652/// Return true if it is OK to use SIToFPInst for an inducation variable
653/// with given inital and exit values.
654static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
655 uint64_t intIV, uint64_t intEV) {
656
Dan Gohmancafb8132009-02-17 19:13:57 +0000657 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patel13877bf2008-11-18 00:40:02 +0000658 return true;
659
660 // If the iteration range can be handled by SIToFPInst then use it.
661 APInt Max = APInt::getSignedMaxValue(32);
Dale Johannesenbae7d6d2009-05-14 16:47:34 +0000662 if (Max.getZExtValue() > static_cast<uint64_t>(abs64(intEV - intIV)))
Devang Patel13877bf2008-11-18 00:40:02 +0000663 return true;
Dan Gohmancafb8132009-02-17 19:13:57 +0000664
Devang Patel13877bf2008-11-18 00:40:02 +0000665 return false;
666}
667
668/// convertToInt - Convert APF to an integer, if possible.
Devang Patelcd402332008-11-17 23:27:13 +0000669static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
670
671 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000672 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
673 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000674 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patelcd402332008-11-17 23:27:13 +0000675 APFloat::rmTowardZero, &isExact)
676 != APFloat::opOK)
677 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000678 if (!isExact)
Devang Patelcd402332008-11-17 23:27:13 +0000679 return false;
680 return true;
681
682}
683
Devang Patel58d43d42008-11-03 18:32:19 +0000684/// HandleFloatingPointIV - If the loop has floating induction variable
685/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000686/// For example,
687/// for(double i = 0; i < 10000; ++i)
688/// bar(i)
689/// is converted into
690/// for(int i = 0; i < 10000; ++i)
691/// bar((double)i);
692///
Dan Gohman81db61a2009-05-12 02:17:14 +0000693void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH) {
Devang Patel58d43d42008-11-03 18:32:19 +0000694
Devang Patel84e35152008-11-17 21:32:02 +0000695 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
696 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +0000697
Devang Patel84e35152008-11-17 21:32:02 +0000698 // Check incoming value.
Devang Patelcd402332008-11-17 23:27:13 +0000699 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
700 if (!InitValue) return;
701 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
702 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
703 return;
704
705 // Check IV increment. Reject this PH if increement operation is not
706 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +0000707 BinaryOperator *Incr =
Devang Patel84e35152008-11-17 21:32:02 +0000708 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
709 if (!Incr) return;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000710 if (Incr->getOpcode() != Instruction::FAdd) return;
Devang Patel84e35152008-11-17 21:32:02 +0000711 ConstantFP *IncrValue = NULL;
712 unsigned IncrVIndex = 1;
713 if (Incr->getOperand(1) == PH)
714 IncrVIndex = 0;
715 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
716 if (!IncrValue) return;
Devang Patelcd402332008-11-17 23:27:13 +0000717 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
718 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
719 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000720
Devang Patelcd402332008-11-17 23:27:13 +0000721 // Check Incr uses. One user is PH and the other users is exit condition used
722 // by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000723 Value::use_iterator IncrUse = Incr->use_begin();
724 Instruction *U1 = cast<Instruction>(IncrUse++);
725 if (IncrUse == Incr->use_end()) return;
726 Instruction *U2 = cast<Instruction>(IncrUse++);
727 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000728
Devang Patel84e35152008-11-17 21:32:02 +0000729 // Find exit condition.
730 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
731 if (!EC)
732 EC = dyn_cast<FCmpInst>(U2);
733 if (!EC) return;
734
735 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
736 if (!BI->isConditional()) return;
737 if (BI->getCondition() != EC) return;
Devang Patel58d43d42008-11-03 18:32:19 +0000738 }
Devang Patel58d43d42008-11-03 18:32:19 +0000739
Devang Patelcd402332008-11-17 23:27:13 +0000740 // Find exit value. If exit value can not be represented as an interger then
741 // do not handle this floating point PH.
Devang Patel84e35152008-11-17 21:32:02 +0000742 ConstantFP *EV = NULL;
743 unsigned EVIndex = 1;
744 if (EC->getOperand(1) == Incr)
745 EVIndex = 0;
746 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
747 if (!EV) return;
Devang Patel84e35152008-11-17 21:32:02 +0000748 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000749 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patel84e35152008-11-17 21:32:02 +0000750 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000751
Devang Patel84e35152008-11-17 21:32:02 +0000752 // Find new predicate for integer comparison.
753 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
754 switch (EC->getPredicate()) {
755 case CmpInst::FCMP_OEQ:
756 case CmpInst::FCMP_UEQ:
757 NewPred = CmpInst::ICMP_EQ;
758 break;
759 case CmpInst::FCMP_OGT:
760 case CmpInst::FCMP_UGT:
761 NewPred = CmpInst::ICMP_UGT;
762 break;
763 case CmpInst::FCMP_OGE:
764 case CmpInst::FCMP_UGE:
765 NewPred = CmpInst::ICMP_UGE;
766 break;
767 case CmpInst::FCMP_OLT:
768 case CmpInst::FCMP_ULT:
769 NewPred = CmpInst::ICMP_ULT;
770 break;
771 case CmpInst::FCMP_OLE:
772 case CmpInst::FCMP_ULE:
773 NewPred = CmpInst::ICMP_ULE;
774 break;
775 default:
776 break;
Devang Patel58d43d42008-11-03 18:32:19 +0000777 }
Devang Patel84e35152008-11-17 21:32:02 +0000778 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000779
Devang Patel84e35152008-11-17 21:32:02 +0000780 // Insert new integer induction variable.
781 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
782 PH->getName()+".int", PH);
Devang Patelcd402332008-11-17 23:27:13 +0000783 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patel84e35152008-11-17 21:32:02 +0000784 PH->getIncomingBlock(IncomingEdge));
785
Dan Gohmancafb8132009-02-17 19:13:57 +0000786 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
787 ConstantInt::get(Type::Int32Ty,
Devang Patelcd402332008-11-17 23:27:13 +0000788 newIncrValue),
Devang Patel84e35152008-11-17 21:32:02 +0000789 Incr->getName()+".int", Incr);
790 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
791
Dale Johannesen617d1082009-04-27 21:03:15 +0000792 // The back edge is edge 1 of newPHI, whatever it may have been in the
793 // original PHI.
Devang Patel84e35152008-11-17 21:32:02 +0000794 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
Dale Johannesen617d1082009-04-27 21:03:15 +0000795 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(1) : NewEV);
796 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(1));
Dan Gohmancafb8132009-02-17 19:13:57 +0000797 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
Devang Patel84e35152008-11-17 21:32:02 +0000798 EC->getParent()->getTerminator());
Dan Gohmancafb8132009-02-17 19:13:57 +0000799
Dan Gohman81db61a2009-05-12 02:17:14 +0000800 // In the following deltions, PH may become dead and may be deleted.
801 // Use a WeakVH to observe whether this happens.
802 WeakVH WeakPH = PH;
803
Devang Patel84e35152008-11-17 21:32:02 +0000804 // Delete old, floating point, exit comparision instruction.
Dan Gohman14fba292009-05-24 18:09:01 +0000805 NewEC->takeName(EC);
Devang Patel84e35152008-11-17 21:32:02 +0000806 EC->replaceAllUsesWith(NewEC);
Dan Gohman81db61a2009-05-12 02:17:14 +0000807 RecursivelyDeleteTriviallyDeadInstructions(EC);
Dan Gohmancafb8132009-02-17 19:13:57 +0000808
Devang Patel84e35152008-11-17 21:32:02 +0000809 // Delete old, floating point, increment instruction.
810 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman81db61a2009-05-12 02:17:14 +0000811 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +0000812
Dan Gohman81db61a2009-05-12 02:17:14 +0000813 // Replace floating induction variable, if it isn't already deleted.
814 // Give SIToFPInst preference over UIToFPInst because it is faster on
815 // platforms that are widely used.
816 if (WeakPH && !PH->use_empty()) {
817 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
818 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
819 PH->getParent()->getFirstNonPHI());
820 PH->replaceAllUsesWith(Conv);
821 } else {
822 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
823 PH->getParent()->getFirstNonPHI());
824 PH->replaceAllUsesWith(Conv);
825 }
826 RecursivelyDeleteTriviallyDeadInstructions(PH);
Devang Patelcd402332008-11-17 23:27:13 +0000827 }
Devang Patel58d43d42008-11-03 18:32:19 +0000828
Dan Gohman81db61a2009-05-12 02:17:14 +0000829 // Add a new IVUsers entry for the newly-created integer PHI.
830 IU->AddUsersIfInteresting(NewPHI);
831}