blob: 80d34f6f16c2c8c52f924e1f7a3c4fb1bb08a1ea [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"
Dan Gohman81db61a2009-05-12 02:17:14 +000046#include "llvm/Analysis/Dominators.h"
47#include "llvm/Analysis/IVUsers.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000048#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000049#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000050#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000051#include "llvm/Support/CFG.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000052#include "llvm/Support/Compiler.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000053#include "llvm/Support/Debug.h"
Chris Lattnera4b9c782004-10-11 23:06:50 +000054#include "llvm/Support/GetElementPtrTypeIterator.h"
John Criswell47df12d2003-12-18 17:19:19 +000055#include "llvm/Transforms/Utils/Local.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000056#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/Support/CommandLine.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000058#include "llvm/ADT/SmallVector.h"
Dan Gohmanc2390b12009-02-12 22:19:27 +000059#include "llvm/ADT/SetVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000060#include "llvm/ADT/Statistic.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000061#include "llvm/ADT/STLExtras.h"
John Criswell47df12d2003-12-18 17:19:19 +000062using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000063
Chris Lattner0e5f4992006-12-19 21:40:18 +000064STATISTIC(NumRemoved , "Number of aux indvars removed");
Chris Lattner0e5f4992006-12-19 21:40:18 +000065STATISTIC(NumInserted, "Number of canonical indvars added");
66STATISTIC(NumReplaced, "Number of exit values replaced");
67STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000068
Chris Lattner0e5f4992006-12-19 21:40:18 +000069namespace {
Devang Patel5ee99972007-03-07 06:39:01 +000070 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000071 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000072 LoopInfo *LI;
73 ScalarEvolution *SE;
Chris Lattner15cad752003-12-23 07:47:09 +000074 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000075 public:
Devang Patel794fd752007-05-01 21:15:47 +000076
Nick Lewyckyecd94c82007-05-06 13:37:16 +000077 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000078 IndVarSimplify() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000079
Dan Gohman60f8a632009-02-17 20:49:49 +000080 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
81
Devang Patel5ee99972007-03-07 06:39:01 +000082 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman81db61a2009-05-12 02:17:14 +000083 AU.addRequired<DominatorTree>();
Devang Patelbc533cd2007-09-10 18:08:23 +000084 AU.addRequired<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000085 AU.addRequiredID(LCSSAID);
86 AU.addRequiredID(LoopSimplifyID);
Devang Patel5ee99972007-03-07 06:39:01 +000087 AU.addRequired<LoopInfo>();
Dan Gohman81db61a2009-05-12 02:17:14 +000088 AU.addRequired<IVUsers>();
Dan Gohman474cecf2009-02-23 16:29:41 +000089 AU.addPreserved<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000090 AU.addPreservedID(LoopSimplifyID);
Dan Gohman81db61a2009-05-12 02:17:14 +000091 AU.addPreserved<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +000092 AU.addPreservedID(LCSSAID);
93 AU.setPreservesCFG();
94 }
Chris Lattner15cad752003-12-23 07:47:09 +000095
Chris Lattner40bf8b42004-04-02 20:24:31 +000096 private:
Devang Patel5ee99972007-03-07 06:39:01 +000097
Dan Gohman60f8a632009-02-17 20:49:49 +000098 void RewriteNonIntegerIVs(Loop *L);
99
Dan Gohman81db61a2009-05-12 02:17:14 +0000100 ICmpInst *LinearFunctionTestReplace(Loop *L, SCEVHandle BackedgeTakenCount,
Dan Gohmana5758712009-02-17 15:57:39 +0000101 Value *IndVar,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000102 BasicBlock *ExitingBlock,
103 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000104 SCEVExpander &Rewriter);
Dan Gohman890f92b2009-04-18 17:56:28 +0000105 void RewriteLoopExitValues(Loop *L, const SCEV *BackedgeTakenCount);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000106
Dan Gohman81db61a2009-05-12 02:17:14 +0000107 void RewriteIVExpressions(Loop *L, const Type *LargestType,
108 SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000109
Dan Gohman81db61a2009-05-12 02:17:14 +0000110 void SinkUnusedInvariants(Loop *L, SCEVExpander &Rewriter);
111
112 void FixUsesBeforeDefs(Loop *L, SCEVExpander &Rewriter);
113
114 void HandleFloatingPointIV(Loop *L, PHINode *PH);
Chris Lattner3324e712003-12-22 03:58:44 +0000115 };
Chris Lattner5e761402002-09-10 05:24:05 +0000116}
Chris Lattner394437f2001-12-04 04:32:29 +0000117
Dan Gohman844731a2008-05-13 00:00:25 +0000118char IndVarSimplify::ID = 0;
119static RegisterPass<IndVarSimplify>
120X("indvars", "Canonicalize Induction Variables");
121
Daniel Dunbar394f0442008-10-22 23:32:42 +0000122Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000123 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000124}
125
Chris Lattner40bf8b42004-04-02 20:24:31 +0000126/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000127/// loop to be a canonical != comparison against the incremented loop induction
128/// variable. This pass is able to rewrite the exit tests of any loop where the
129/// SCEV analysis can determine a loop-invariant trip count of the loop, which
130/// is actually a much broader range than just linear tests.
Dan Gohman81db61a2009-05-12 02:17:14 +0000131ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
Dan Gohman46bdfb02009-02-24 18:55:53 +0000132 SCEVHandle BackedgeTakenCount,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000133 Value *IndVar,
134 BasicBlock *ExitingBlock,
135 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000136 SCEVExpander &Rewriter) {
Chris Lattnerd2440572004-04-15 20:26:22 +0000137 // If the exiting block is not the same as the backedge block, we must compare
138 // against the preincremented value, otherwise we prefer to compare against
139 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000140 Value *CmpIndVar;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000141 SCEVHandle RHS = BackedgeTakenCount;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000142 if (ExitingBlock == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000143 // Add one to the "backedge-taken" count to get the trip count.
144 // If this addition may overflow, we have to be more pessimistic and
145 // cast the induction variable before doing the add.
146 SCEVHandle Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000147 SCEVHandle N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000148 SE->getAddExpr(BackedgeTakenCount,
149 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000150 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
151 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
152 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000153 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000154 } else {
155 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000156 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
157 IndVar->getType());
158 RHS = SE->getAddExpr(RHS,
159 SE->getIntegerSCEV(1, IndVar->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000160 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000161
Dan Gohman46bdfb02009-02-24 18:55:53 +0000162 // The BackedgeTaken expression contains the number of times that the
163 // backedge branches to the loop header. This is one less than the
164 // number of times the loop executes, so use the incremented indvar.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000165 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Chris Lattnerd2440572004-04-15 20:26:22 +0000166 } else {
167 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000168 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
169 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000170 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000171 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000172
Chris Lattner40bf8b42004-04-02 20:24:31 +0000173 // Expand the code for the iteration count into the preheader of the loop.
174 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman2d1be872009-04-16 03:18:22 +0000175 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(),
Dan Gohmanc2390b12009-02-12 22:19:27 +0000176 Preheader->getTerminator());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000177
Reid Spencere4d87aa2006-12-23 06:05:41 +0000178 // Insert a new icmp_ne or icmp_eq instruction before the branch.
179 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000180 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000181 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000182 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000183 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000184
Dan Gohmanc2390b12009-02-12 22:19:27 +0000185 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
186 << " LHS:" << *CmpIndVar // includes a newline
187 << " op:\t"
Dan Gohmanf108e2e2009-02-14 02:26:50 +0000188 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohman46bdfb02009-02-24 18:55:53 +0000189 << " RHS:\t" << *RHS << "\n";
Dan Gohmanc2390b12009-02-12 22:19:27 +0000190
Dan Gohman81db61a2009-05-12 02:17:14 +0000191 ICmpInst *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
192
193 Instruction *OrigCond = cast<Instruction>(BI->getCondition());
194 OrigCond->replaceAllUsesWith(Cond);
195 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
196
Chris Lattner40bf8b42004-04-02 20:24:31 +0000197 ++NumLFTR;
198 Changed = true;
Dan Gohman81db61a2009-05-12 02:17:14 +0000199 return Cond;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000200}
201
Chris Lattner40bf8b42004-04-02 20:24:31 +0000202/// RewriteLoopExitValues - Check to see if this loop has a computable
203/// loop-invariant execution count. If so, this means that we can compute the
204/// final value of any expressions that are recurrent in the loop, and
205/// substitute the exit values from the loop into any instructions outside of
206/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000207///
208/// This is mostly redundant with the regular IndVarSimplify activities that
209/// happen later, except that it's more powerful in some cases, because it's
210/// able to brute-force evaluate arbitrary instructions as long as they have
211/// constant operands at the beginning of the loop.
Dan Gohman890f92b2009-04-18 17:56:28 +0000212void IndVarSimplify::RewriteLoopExitValues(Loop *L,
213 const SCEV *BackedgeTakenCount) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000214 // Verify the input to the pass in already in LCSSA form.
215 assert(L->isLCSSAForm());
216
Chris Lattner40bf8b42004-04-02 20:24:31 +0000217 BasicBlock *Preheader = L->getLoopPreheader();
218
219 // Scan all of the instructions in the loop, looking at those that have
220 // extra-loop users and which are recurrences.
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000221 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000222
223 // We insert the code into the preheader of the loop if the loop contains
224 // multiple exit blocks, or in the exit block if there is exactly one.
225 BasicBlock *BlockToInsertInto;
Devang Patelb7211a22007-08-21 00:31:24 +0000226 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000227 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000228 if (ExitBlocks.size() == 1)
229 BlockToInsertInto = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000230 else
231 BlockToInsertInto = Preheader;
Dan Gohman02dea8b2008-05-23 21:05:58 +0000232 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000233
Chris Lattner9f3d7382007-03-04 03:43:23 +0000234 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanfd939082005-04-21 23:48:37 +0000235
Chris Lattner9f3d7382007-03-04 03:43:23 +0000236 // Find all values that are computed inside the loop, but used outside of it.
237 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
238 // the exit blocks of the loop to find them.
239 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
240 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000241
Chris Lattner9f3d7382007-03-04 03:43:23 +0000242 // If there are no PHI nodes in this exit block, then no values defined
243 // inside the loop are used on this path, skip it.
244 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
245 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000246
Chris Lattner9f3d7382007-03-04 03:43:23 +0000247 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000248
Chris Lattner9f3d7382007-03-04 03:43:23 +0000249 // Iterate over all of the PHI nodes.
250 BasicBlock::iterator BBI = ExitBB->begin();
251 while ((PN = dyn_cast<PHINode>(BBI++))) {
Dan Gohmancafb8132009-02-17 19:13:57 +0000252
Chris Lattner9f3d7382007-03-04 03:43:23 +0000253 // Iterate over all of the values in all the PHI nodes.
254 for (unsigned i = 0; i != NumPreds; ++i) {
255 // If the value being merged in is not integer or is not defined
256 // in the loop, skip it.
257 Value *InVal = PN->getIncomingValue(i);
258 if (!isa<Instruction>(InVal) ||
259 // SCEV only supports integer expressions for now.
Dan Gohman2d1be872009-04-16 03:18:22 +0000260 (!isa<IntegerType>(InVal->getType()) &&
261 !isa<PointerType>(InVal->getType())))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000262 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000263
Chris Lattner9f3d7382007-03-04 03:43:23 +0000264 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000265 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000266 continue; // The Block is in a subloop, skip it.
267
268 // Check that InVal is defined in the loop.
269 Instruction *Inst = cast<Instruction>(InVal);
270 if (!L->contains(Inst->getParent()))
271 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000272
Chris Lattner9f3d7382007-03-04 03:43:23 +0000273 // Okay, this instruction has a user outside of the current loop
274 // and varies predictably *inside* the loop. Evaluate the value it
275 // contains when the loop exits, if possible.
Dan Gohman81db61a2009-05-12 02:17:14 +0000276 SCEVHandle SH = SE->getSCEV(Inst);
277 SCEVHandle ExitValue = SE->getSCEVAtScope(SH, L->getParentLoop());
Chris Lattner9f3d7382007-03-04 03:43:23 +0000278 if (isa<SCEVCouldNotCompute>(ExitValue) ||
279 !ExitValue->isLoopInvariant(L))
280 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 Gohmanaf79fb52009-04-21 01:07:12 +0000389 SCEVExpander Rewriter(*SE, *LI);
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 Gohmanc2390b12009-02-12 22:19:27 +0000395 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
396 ++NumInserted;
397 Changed = true;
398 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohmand19534a2007-06-15 14:38:12 +0000399 }
Chris Lattner15cad752003-12-23 07:47:09 +0000400
Dan Gohmanc2390b12009-02-12 22:19:27 +0000401 // If we have a trip count expression, rewrite the loop's exit condition
402 // using it. We can currently only handle loops with a single exit.
Dan Gohman81db61a2009-05-12 02:17:14 +0000403 ICmpInst *NewICmp = 0;
404 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && ExitingBlock) {
405 assert(NeedCannIV &&
406 "LinearFunctionTestReplace requires a canonical induction variable");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000407 // Can't rewrite non-branch yet.
Dan Gohman81db61a2009-05-12 02:17:14 +0000408 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
409 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
410 ExitingBlock, BI, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000411 }
412
Dan Gohman81db61a2009-05-12 02:17:14 +0000413 Rewriter.setInsertionPoint(Header->getFirstNonPHI());
Chris Lattner5d461d22004-04-21 22:22:01 +0000414
Dan Gohman81db61a2009-05-12 02:17:14 +0000415 // Rewrite IV-derived expressions.
416 RewriteIVExpressions(L, LargestType, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000417
Dan Gohman81db61a2009-05-12 02:17:14 +0000418 // Loop-invariant instructions in the preheader that aren't used in the
419 // loop may be sunk below the loop to reduce register pressure.
420 SinkUnusedInvariants(L, Rewriter);
Chris Lattner394437f2001-12-04 04:32:29 +0000421
Dan Gohman81db61a2009-05-12 02:17:14 +0000422 // Reorder instructions to avoid use-before-def conditions.
423 FixUsesBeforeDefs(L, Rewriter);
424
425 // For completeness, inform IVUsers of the IV use in the newly-created
426 // loop exit test instruction.
427 if (NewICmp)
428 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
429
430 // Clean up dead instructions.
431 DeleteDeadPHIs(L->getHeader());
432 // Check a post-condition.
433 assert(L->isLCSSAForm() && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +0000434 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000435}
Devang Pateld22a8492008-09-09 21:41:07 +0000436
Dan Gohman81db61a2009-05-12 02:17:14 +0000437void IndVarSimplify::RewriteIVExpressions(Loop *L, const Type *LargestType,
438 SCEVExpander &Rewriter) {
439 SmallVector<WeakVH, 16> DeadInsts;
440
441 // Rewrite all induction variable expressions in terms of the canonical
442 // induction variable.
443 //
444 // If there were induction variables of other sizes or offsets, manually
445 // add the offsets to the primary induction variable and cast, avoiding
446 // the need for the code evaluation methods to insert induction variables
447 // of different sizes.
448 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
449 SCEVHandle Stride = IU->StrideOrder[i];
450
451 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
452 IU->IVUsesByStride.find(IU->StrideOrder[i]);
453 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
454 ilist<IVStrideUse> &List = SI->second->Users;
455 for (ilist<IVStrideUse>::iterator UI = List.begin(),
456 E = List.end(); UI != E; ++UI) {
457 SCEVHandle Offset = UI->getOffset();
458 Value *Op = UI->getOperandValToReplace();
459 Instruction *User = UI->getUser();
460 bool isSigned = UI->isSigned();
461
462 // Compute the final addrec to expand into code.
463 SCEVHandle AR = IU->getReplacementExpr(*UI);
464
465 // FIXME: It is an extremely bad idea to indvar substitute anything more
466 // complex than affine induction variables. Doing so will put expensive
467 // polynomial evaluations inside of the loop, and the str reduction pass
468 // currently can only reduce affine polynomials. For now just disable
469 // indvar subst on anything more complex than an affine addrec, unless
470 // it can be expanded to a trivial value.
471 if (!Stride->isLoopInvariant(L) &&
472 !isa<SCEVConstant>(AR) &&
473 L->contains(User->getParent()))
474 continue;
475
476 Value *NewVal = 0;
477 if (AR->isLoopInvariant(L)) {
478 BasicBlock::iterator I = Rewriter.getInsertionPoint();
479 // Expand loop-invariant values in the loop preheader. They will
480 // be sunk to the exit block later, if possible.
481 NewVal =
482 Rewriter.expandCodeFor(AR, LargestType,
483 L->getLoopPreheader()->getTerminator());
484 Rewriter.setInsertionPoint(I);
485 ++NumReplaced;
486 } else {
487 const Type *IVTy = Offset->getType();
488 const Type *UseTy = Op->getType();
489
490 // Promote the Offset and Stride up to the canonical induction
491 // variable's bit width.
492 SCEVHandle PromotedOffset = Offset;
493 SCEVHandle PromotedStride = Stride;
494 if (SE->getTypeSizeInBits(IVTy) != SE->getTypeSizeInBits(LargestType)) {
495 // It doesn't matter for correctness whether zero or sign extension
496 // is used here, since the value is truncated away below, but if the
497 // value is signed, sign extension is more likely to be folded.
498 if (isSigned) {
499 PromotedOffset = SE->getSignExtendExpr(PromotedOffset, LargestType);
500 PromotedStride = SE->getSignExtendExpr(PromotedStride, LargestType);
501 } else {
502 PromotedOffset = SE->getZeroExtendExpr(PromotedOffset, LargestType);
503 // If the stride is obviously negative, use sign extension to
504 // produce things like x-1 instead of x+255.
505 if (isa<SCEVConstant>(PromotedStride) &&
506 cast<SCEVConstant>(PromotedStride)
507 ->getValue()->getValue().isNegative())
508 PromotedStride = SE->getSignExtendExpr(PromotedStride,
509 LargestType);
510 else
511 PromotedStride = SE->getZeroExtendExpr(PromotedStride,
512 LargestType);
513 }
514 }
515
516 // Create the SCEV representing the offset from the canonical
517 // induction variable, still in the canonical induction variable's
518 // type, so that all expanded arithmetic is done in the same type.
519 SCEVHandle NewAR = SE->getAddRecExpr(SE->getIntegerSCEV(0, LargestType),
520 PromotedStride, L);
521 // Add the PromotedOffset as a separate step, because it may not be
522 // loop-invariant.
523 NewAR = SE->getAddExpr(NewAR, PromotedOffset);
524
525 // Expand the addrec into instructions.
526 Value *V = Rewriter.expandCodeFor(NewAR, LargestType);
527
528 // Insert an explicit cast if necessary to truncate the value
529 // down to the original stride type. This is done outside of
530 // SCEVExpander because in SCEV expressions, a truncate of an
531 // addrec is always folded.
532 if (LargestType != IVTy) {
533 if (SE->getTypeSizeInBits(IVTy) != SE->getTypeSizeInBits(LargestType))
534 NewAR = SE->getTruncateExpr(NewAR, IVTy);
535 if (Rewriter.isInsertedExpression(NewAR))
536 V = Rewriter.expandCodeFor(NewAR, IVTy);
537 else {
538 V = Rewriter.InsertCastOfTo(CastInst::getCastOpcode(V, false,
539 IVTy, false),
540 V, IVTy);
541 assert(!isa<SExtInst>(V) && !isa<ZExtInst>(V) &&
542 "LargestType wasn't actually the largest type!");
543 // Force the rewriter to use this trunc whenever this addrec
544 // appears so that it doesn't insert new phi nodes or
545 // arithmetic in a different type.
546 Rewriter.addInsertedValue(V, NewAR);
547 }
548 }
549
550 DOUT << "INDVARS: Made offset-and-trunc IV for offset "
551 << *IVTy << " " << *Offset << ": ";
552 DEBUG(WriteAsOperand(*DOUT, V, false));
553 DOUT << "\n";
554
555 // Now expand it into actual Instructions and patch it into place.
556 NewVal = Rewriter.expandCodeFor(AR, UseTy);
557 }
558
559 // Patch the new value into place.
560 if (Op->hasName())
561 NewVal->takeName(Op);
562 User->replaceUsesOfWith(Op, NewVal);
563 UI->setOperandValToReplace(NewVal);
564 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *Op
565 << " into = " << *NewVal << "\n";
566 ++NumRemoved;
567 Changed = true;
568
569 // The old value may be dead now.
570 DeadInsts.push_back(Op);
571 }
572 }
573
574 // Now that we're done iterating through lists, clean up any instructions
575 // which are now dead.
576 while (!DeadInsts.empty()) {
577 Instruction *Inst = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
578 if (Inst)
579 RecursivelyDeleteTriviallyDeadInstructions(Inst);
580 }
581}
582
583/// If there's a single exit block, sink any loop-invariant values that
584/// were defined in the preheader but not used inside the loop into the
585/// exit block to reduce register pressure in the loop.
586void IndVarSimplify::SinkUnusedInvariants(Loop *L, SCEVExpander &Rewriter) {
587 BasicBlock *ExitBlock = L->getExitBlock();
588 if (!ExitBlock) return;
589
590 Instruction *NonPHI = ExitBlock->getFirstNonPHI();
591 BasicBlock *Preheader = L->getLoopPreheader();
592 BasicBlock::iterator I = Preheader->getTerminator();
593 while (I != Preheader->begin()) {
594 --I;
595 // New instructions were inserted at the end of the preheader. Only
596 // consider those new instructions.
597 if (!Rewriter.isInsertedInstruction(I))
598 break;
599 // Determine if there is a use in or before the loop (direct or
600 // otherwise).
601 bool UsedInLoop = false;
602 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
603 UI != UE; ++UI) {
604 BasicBlock *UseBB = cast<Instruction>(UI)->getParent();
605 if (PHINode *P = dyn_cast<PHINode>(UI)) {
606 unsigned i =
607 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
608 UseBB = P->getIncomingBlock(i);
609 }
610 if (UseBB == Preheader || L->contains(UseBB)) {
611 UsedInLoop = true;
612 break;
613 }
614 }
615 // If there is, the def must remain in the preheader.
616 if (UsedInLoop)
617 continue;
618 // Otherwise, sink it to the exit block.
619 Instruction *ToMove = I;
620 bool Done = false;
621 if (I != Preheader->begin())
622 --I;
623 else
624 Done = true;
625 ToMove->moveBefore(NonPHI);
626 if (Done)
627 break;
628 }
629}
630
631/// Re-schedule the inserted instructions to put defs before uses. This
632/// fixes problems that arrise when SCEV expressions contain loop-variant
633/// values unrelated to the induction variable which are defined inside the
634/// loop. FIXME: It would be better to insert instructions in the right
635/// place so that this step isn't needed.
636void IndVarSimplify::FixUsesBeforeDefs(Loop *L, SCEVExpander &Rewriter) {
637 // Visit all the blocks in the loop in pre-order dom-tree dfs order.
638 DominatorTree *DT = &getAnalysis<DominatorTree>();
639 std::map<Instruction *, unsigned> NumPredsLeft;
640 SmallVector<DomTreeNode *, 16> Worklist;
641 Worklist.push_back(DT->getNode(L->getHeader()));
642 do {
643 DomTreeNode *Node = Worklist.pop_back_val();
644 for (DomTreeNode::iterator I = Node->begin(), E = Node->end(); I != E; ++I)
645 if (L->contains((*I)->getBlock()))
646 Worklist.push_back(*I);
647 BasicBlock *BB = Node->getBlock();
648 // Visit all the instructions in the block top down.
649 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
650 // Count the number of operands that aren't properly dominating.
651 unsigned NumPreds = 0;
652 if (Rewriter.isInsertedInstruction(I) && !isa<PHINode>(I))
653 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
654 OI != OE; ++OI)
655 if (Instruction *Inst = dyn_cast<Instruction>(OI))
656 if (L->contains(Inst->getParent()) && !NumPredsLeft.count(Inst))
657 ++NumPreds;
658 NumPredsLeft[I] = NumPreds;
659 // Notify uses of the position of this instruction, and move the
660 // users (and their dependents, recursively) into place after this
661 // instruction if it is their last outstanding operand.
662 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
663 UI != UE; ++UI) {
664 Instruction *Inst = cast<Instruction>(UI);
665 std::map<Instruction *, unsigned>::iterator Z = NumPredsLeft.find(Inst);
666 if (Z != NumPredsLeft.end() && Z->second != 0 && --Z->second == 0) {
667 SmallVector<Instruction *, 4> UseWorkList;
668 UseWorkList.push_back(Inst);
669 BasicBlock::iterator InsertPt = next(I);
670 while (isa<PHINode>(InsertPt)) ++InsertPt;
671 do {
672 Instruction *Use = UseWorkList.pop_back_val();
673 Use->moveBefore(InsertPt);
674 NumPredsLeft.erase(Use);
675 for (Value::use_iterator IUI = Use->use_begin(),
676 IUE = Use->use_end(); IUI != IUE; ++IUI) {
677 Instruction *IUIInst = cast<Instruction>(IUI);
678 if (L->contains(IUIInst->getParent()) &&
679 Rewriter.isInsertedInstruction(IUIInst) &&
680 !isa<PHINode>(IUIInst))
681 UseWorkList.push_back(IUIInst);
682 }
683 } while (!UseWorkList.empty());
684 }
685 }
686 }
687 } while (!Worklist.empty());
688}
689
Devang Patel13877bf2008-11-18 00:40:02 +0000690/// Return true if it is OK to use SIToFPInst for an inducation variable
691/// with given inital and exit values.
692static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
693 uint64_t intIV, uint64_t intEV) {
694
Dan Gohmancafb8132009-02-17 19:13:57 +0000695 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patel13877bf2008-11-18 00:40:02 +0000696 return true;
697
698 // If the iteration range can be handled by SIToFPInst then use it.
699 APInt Max = APInt::getSignedMaxValue(32);
Bill Wendling9bef7062008-11-18 10:57:27 +0000700 if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
Devang Patel13877bf2008-11-18 00:40:02 +0000701 return true;
Dan Gohmancafb8132009-02-17 19:13:57 +0000702
Devang Patel13877bf2008-11-18 00:40:02 +0000703 return false;
704}
705
706/// convertToInt - Convert APF to an integer, if possible.
Devang Patelcd402332008-11-17 23:27:13 +0000707static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
708
709 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000710 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
711 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000712 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patelcd402332008-11-17 23:27:13 +0000713 APFloat::rmTowardZero, &isExact)
714 != APFloat::opOK)
715 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000716 if (!isExact)
Devang Patelcd402332008-11-17 23:27:13 +0000717 return false;
718 return true;
719
720}
721
Devang Patel58d43d42008-11-03 18:32:19 +0000722/// HandleFloatingPointIV - If the loop has floating induction variable
723/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000724/// For example,
725/// for(double i = 0; i < 10000; ++i)
726/// bar(i)
727/// is converted into
728/// for(int i = 0; i < 10000; ++i)
729/// bar((double)i);
730///
Dan Gohman81db61a2009-05-12 02:17:14 +0000731void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH) {
Devang Patel58d43d42008-11-03 18:32:19 +0000732
Devang Patel84e35152008-11-17 21:32:02 +0000733 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
734 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +0000735
Devang Patel84e35152008-11-17 21:32:02 +0000736 // Check incoming value.
Devang Patelcd402332008-11-17 23:27:13 +0000737 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
738 if (!InitValue) return;
739 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
740 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
741 return;
742
743 // Check IV increment. Reject this PH if increement operation is not
744 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +0000745 BinaryOperator *Incr =
Devang Patel84e35152008-11-17 21:32:02 +0000746 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
747 if (!Incr) return;
748 if (Incr->getOpcode() != Instruction::Add) return;
749 ConstantFP *IncrValue = NULL;
750 unsigned IncrVIndex = 1;
751 if (Incr->getOperand(1) == PH)
752 IncrVIndex = 0;
753 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
754 if (!IncrValue) return;
Devang Patelcd402332008-11-17 23:27:13 +0000755 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
756 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
757 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000758
Devang Patelcd402332008-11-17 23:27:13 +0000759 // Check Incr uses. One user is PH and the other users is exit condition used
760 // by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000761 Value::use_iterator IncrUse = Incr->use_begin();
762 Instruction *U1 = cast<Instruction>(IncrUse++);
763 if (IncrUse == Incr->use_end()) return;
764 Instruction *U2 = cast<Instruction>(IncrUse++);
765 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000766
Devang Patel84e35152008-11-17 21:32:02 +0000767 // Find exit condition.
768 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
769 if (!EC)
770 EC = dyn_cast<FCmpInst>(U2);
771 if (!EC) return;
772
773 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
774 if (!BI->isConditional()) return;
775 if (BI->getCondition() != EC) return;
Devang Patel58d43d42008-11-03 18:32:19 +0000776 }
Devang Patel58d43d42008-11-03 18:32:19 +0000777
Devang Patelcd402332008-11-17 23:27:13 +0000778 // Find exit value. If exit value can not be represented as an interger then
779 // do not handle this floating point PH.
Devang Patel84e35152008-11-17 21:32:02 +0000780 ConstantFP *EV = NULL;
781 unsigned EVIndex = 1;
782 if (EC->getOperand(1) == Incr)
783 EVIndex = 0;
784 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
785 if (!EV) return;
Devang Patel84e35152008-11-17 21:32:02 +0000786 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000787 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patel84e35152008-11-17 21:32:02 +0000788 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000789
Devang Patel84e35152008-11-17 21:32:02 +0000790 // Find new predicate for integer comparison.
791 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
792 switch (EC->getPredicate()) {
793 case CmpInst::FCMP_OEQ:
794 case CmpInst::FCMP_UEQ:
795 NewPred = CmpInst::ICMP_EQ;
796 break;
797 case CmpInst::FCMP_OGT:
798 case CmpInst::FCMP_UGT:
799 NewPred = CmpInst::ICMP_UGT;
800 break;
801 case CmpInst::FCMP_OGE:
802 case CmpInst::FCMP_UGE:
803 NewPred = CmpInst::ICMP_UGE;
804 break;
805 case CmpInst::FCMP_OLT:
806 case CmpInst::FCMP_ULT:
807 NewPred = CmpInst::ICMP_ULT;
808 break;
809 case CmpInst::FCMP_OLE:
810 case CmpInst::FCMP_ULE:
811 NewPred = CmpInst::ICMP_ULE;
812 break;
813 default:
814 break;
Devang Patel58d43d42008-11-03 18:32:19 +0000815 }
Devang Patel84e35152008-11-17 21:32:02 +0000816 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000817
Devang Patel84e35152008-11-17 21:32:02 +0000818 // Insert new integer induction variable.
819 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
820 PH->getName()+".int", PH);
Devang Patelcd402332008-11-17 23:27:13 +0000821 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patel84e35152008-11-17 21:32:02 +0000822 PH->getIncomingBlock(IncomingEdge));
823
Dan Gohmancafb8132009-02-17 19:13:57 +0000824 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
825 ConstantInt::get(Type::Int32Ty,
Devang Patelcd402332008-11-17 23:27:13 +0000826 newIncrValue),
Devang Patel84e35152008-11-17 21:32:02 +0000827 Incr->getName()+".int", Incr);
828 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
829
Dale Johannesen617d1082009-04-27 21:03:15 +0000830 // The back edge is edge 1 of newPHI, whatever it may have been in the
831 // original PHI.
Devang Patel84e35152008-11-17 21:32:02 +0000832 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
Dale Johannesen617d1082009-04-27 21:03:15 +0000833 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(1) : NewEV);
834 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(1));
Dan Gohmancafb8132009-02-17 19:13:57 +0000835 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
Devang Patel84e35152008-11-17 21:32:02 +0000836 EC->getParent()->getTerminator());
Dan Gohmancafb8132009-02-17 19:13:57 +0000837
Dan Gohman81db61a2009-05-12 02:17:14 +0000838 // In the following deltions, PH may become dead and may be deleted.
839 // Use a WeakVH to observe whether this happens.
840 WeakVH WeakPH = PH;
841
Devang Patel84e35152008-11-17 21:32:02 +0000842 // Delete old, floating point, exit comparision instruction.
843 EC->replaceAllUsesWith(NewEC);
Dan Gohman81db61a2009-05-12 02:17:14 +0000844 RecursivelyDeleteTriviallyDeadInstructions(EC);
Dan Gohmancafb8132009-02-17 19:13:57 +0000845
Devang Patel84e35152008-11-17 21:32:02 +0000846 // Delete old, floating point, increment instruction.
847 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman81db61a2009-05-12 02:17:14 +0000848 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +0000849
Dan Gohman81db61a2009-05-12 02:17:14 +0000850 // Replace floating induction variable, if it isn't already deleted.
851 // Give SIToFPInst preference over UIToFPInst because it is faster on
852 // platforms that are widely used.
853 if (WeakPH && !PH->use_empty()) {
854 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
855 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
856 PH->getParent()->getFirstNonPHI());
857 PH->replaceAllUsesWith(Conv);
858 } else {
859 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
860 PH->getParent()->getFirstNonPHI());
861 PH->replaceAllUsesWith(Conv);
862 }
863 RecursivelyDeleteTriviallyDeadInstructions(PH);
Devang Patelcd402332008-11-17 23:27:13 +0000864 }
Devang Patel58d43d42008-11-03 18:32:19 +0000865
Dan Gohman81db61a2009-05-12 02:17:14 +0000866 // Add a new IVUsers entry for the newly-created integer PHI.
867 IU->AddUsersIfInteresting(NewPHI);
868}