blob: 52be52a2999a604acb95516228be3ae92281c178 [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.
Dan Gohmanea73f3c2009-06-14 22:38:41 +000020// 3. The canonical induction variable is guaranteed to be in a wide enough
21// type so that IV expressions need not be (directly) zero-extended or
22// sign-extended.
23// 4. Any pointer arithmetic recurrences are raised to use array subscripts.
Chris Lattner40bf8b42004-04-02 20:24:31 +000024//
25// If the trip count of a loop is computable, this pass also makes the following
26// changes:
27// 1. The exit condition for the loop is canonicalized to compare the
28// induction value against the exit value. This turns loops like:
29// 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
30// 2. Any use outside of the loop of an expression derived from the indvar
31// is changed to compute the derived value outside of the loop, eliminating
32// the dependence on the exit value of the induction variable. If the only
33// purpose of the loop is to compute the exit value of some derived
34// expression, this transformation will make the loop dead.
35//
36// This transformation should be followed by strength reduction after all of the
Dan Gohmanc2c4cbf2009-05-19 20:38:47 +000037// desired loop transformations have been performed.
Chris Lattner6148c022001-12-03 17:28:42 +000038//
39//===----------------------------------------------------------------------===//
40
Chris Lattner0e5f4992006-12-19 21:40:18 +000041#define DEBUG_TYPE "indvars"
Chris Lattner022103b2002-05-07 20:03:00 +000042#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000043#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000044#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000045#include "llvm/Instructions.h"
Devang Patel7b9f6b12010-03-15 22:23:03 +000046#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000047#include "llvm/LLVMContext.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000048#include "llvm/Type.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000049#include "llvm/Analysis/Dominators.h"
50#include "llvm/Analysis/IVUsers.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000051#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000052#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000053#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000054#include "llvm/Support/CFG.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000055#include "llvm/Support/CommandLine.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000056#include "llvm/Support/Debug.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000057#include "llvm/Support/raw_ostream.h"
John Criswell47df12d2003-12-18 17:19:19 +000058#include "llvm/Transforms/Utils/Local.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000059#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000060#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000061#include "llvm/ADT/Statistic.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000062#include "llvm/ADT/STLExtras.h"
John Criswell47df12d2003-12-18 17:19:19 +000063using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065STATISTIC(NumRemoved , "Number of aux indvars removed");
Chris Lattner0e5f4992006-12-19 21:40:18 +000066STATISTIC(NumInserted, "Number of canonical indvars added");
67STATISTIC(NumReplaced, "Number of exit values replaced");
68STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000071 class IndVarSimplify : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000072 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000073 LoopInfo *LI;
74 ScalarEvolution *SE;
Dan Gohmande53dc02009-06-27 05:16:57 +000075 DominatorTree *DT;
Chris Lattner15cad752003-12-23 07:47:09 +000076 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000077 public:
Devang Patel794fd752007-05-01 21:15:47 +000078
Dan Gohman5668cf72009-07-15 01:26:32 +000079 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000080 IndVarSimplify() : LoopPass(ID) {
81 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
82 }
Devang Patel794fd752007-05-01 21:15:47 +000083
Dan Gohman5668cf72009-07-15 01:26:32 +000084 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman60f8a632009-02-17 20:49:49 +000085
Dan Gohman5668cf72009-07-15 01:26:32 +000086 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
87 AU.addRequired<DominatorTree>();
88 AU.addRequired<LoopInfo>();
89 AU.addRequired<ScalarEvolution>();
90 AU.addRequiredID(LoopSimplifyID);
91 AU.addRequiredID(LCSSAID);
92 AU.addRequired<IVUsers>();
93 AU.addPreserved<ScalarEvolution>();
94 AU.addPreservedID(LoopSimplifyID);
95 AU.addPreservedID(LCSSAID);
96 AU.addPreserved<IVUsers>();
97 AU.setPreservesCFG();
98 }
Chris Lattner15cad752003-12-23 07:47:09 +000099
Chris Lattner40bf8b42004-04-02 20:24:31 +0000100 private:
Devang Patel5ee99972007-03-07 06:39:01 +0000101
Dan Gohman931e3452010-04-12 02:21:50 +0000102 void EliminateIVComparisons();
Dan Gohmana590b792010-04-13 01:46:36 +0000103 void EliminateIVRemainders();
Dan Gohman60f8a632009-02-17 20:49:49 +0000104 void RewriteNonIntegerIVs(Loop *L);
105
Dan Gohman0bba49c2009-07-07 17:06:11 +0000106 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
Dan Gohman43ef3fb2010-07-20 17:18:52 +0000107 PHINode *IndVar,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000108 BasicBlock *ExitingBlock,
109 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000110 SCEVExpander &Rewriter);
Dan Gohman454d26d2010-02-22 04:11:59 +0000111 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000112
Dan Gohman454d26d2010-02-22 04:11:59 +0000113 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000114
Dan Gohman667d7872009-06-26 22:53:46 +0000115 void SinkUnusedInvariants(Loop *L);
Dan Gohman81db61a2009-05-12 02:17:14 +0000116
117 void HandleFloatingPointIV(Loop *L, PHINode *PH);
Chris Lattner3324e712003-12-22 03:58:44 +0000118 };
Chris Lattner5e761402002-09-10 05:24:05 +0000119}
Chris Lattner394437f2001-12-04 04:32:29 +0000120
Dan Gohman844731a2008-05-13 00:00:25 +0000121char IndVarSimplify::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000122INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
123 "Canonicalize Induction Variables", false, false)
124INITIALIZE_PASS_DEPENDENCY(DominatorTree)
125INITIALIZE_PASS_DEPENDENCY(LoopInfo)
126INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
127INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
128INITIALIZE_PASS_DEPENDENCY(LCSSA)
129INITIALIZE_PASS_DEPENDENCY(IVUsers)
130INITIALIZE_PASS_END(IndVarSimplify, "indvars",
Owen Andersonce665bd2010-10-07 22:25:06 +0000131 "Canonicalize Induction Variables", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000132
Daniel Dunbar394f0442008-10-22 23:32:42 +0000133Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000134 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000135}
136
Chris Lattner40bf8b42004-04-02 20:24:31 +0000137/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000138/// loop to be a canonical != comparison against the incremented loop induction
139/// variable. This pass is able to rewrite the exit tests of any loop where the
140/// SCEV analysis can determine a loop-invariant trip count of the loop, which
141/// is actually a much broader range than just linear tests.
Dan Gohman81db61a2009-05-12 02:17:14 +0000142ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
Dan Gohman0bba49c2009-07-07 17:06:11 +0000143 const SCEV *BackedgeTakenCount,
Dan Gohman43ef3fb2010-07-20 17:18:52 +0000144 PHINode *IndVar,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000145 BasicBlock *ExitingBlock,
146 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000147 SCEVExpander &Rewriter) {
Dan Gohmanca9b7032010-04-12 21:13:43 +0000148 // Special case: If the backedge-taken count is a UDiv, it's very likely a
149 // UDiv that ScalarEvolution produced in order to compute a precise
150 // expression, rather than a UDiv from the user's code. If we can't find a
151 // UDiv in the code with some simple searching, assume the former and forego
152 // rewriting the loop.
153 if (isa<SCEVUDivExpr>(BackedgeTakenCount)) {
154 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
155 if (!OrigCond) return 0;
156 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
Dan Gohmandeff6212010-05-03 22:09:21 +0000157 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
Dan Gohmanca9b7032010-04-12 21:13:43 +0000158 if (R != BackedgeTakenCount) {
159 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
Dan Gohmandeff6212010-05-03 22:09:21 +0000160 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
Dan Gohmanca9b7032010-04-12 21:13:43 +0000161 if (L != BackedgeTakenCount)
162 return 0;
163 }
164 }
165
Chris Lattnerd2440572004-04-15 20:26:22 +0000166 // If the exiting block is not the same as the backedge block, we must compare
167 // against the preincremented value, otherwise we prefer to compare against
168 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000169 Value *CmpIndVar;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000170 const SCEV *RHS = BackedgeTakenCount;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000171 if (ExitingBlock == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000172 // Add one to the "backedge-taken" count to get the trip count.
173 // If this addition may overflow, we have to be more pessimistic and
174 // cast the induction variable before doing the add.
Dan Gohmandeff6212010-05-03 22:09:21 +0000175 const SCEV *Zero = SE->getConstant(BackedgeTakenCount->getType(), 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000176 const SCEV *N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000177 SE->getAddExpr(BackedgeTakenCount,
Dan Gohmandeff6212010-05-03 22:09:21 +0000178 SE->getConstant(BackedgeTakenCount->getType(), 1));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000179 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000180 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000181 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000182 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000183 } else {
184 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000185 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
186 IndVar->getType());
187 RHS = SE->getAddExpr(RHS,
Dan Gohmandeff6212010-05-03 22:09:21 +0000188 SE->getConstant(IndVar->getType(), 1));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000189 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000190
Dan Gohman46bdfb02009-02-24 18:55:53 +0000191 // The BackedgeTaken expression contains the number of times that the
192 // backedge branches to the loop header. This is one less than the
193 // number of times the loop executes, so use the incremented indvar.
Dan Gohman43ef3fb2010-07-20 17:18:52 +0000194 CmpIndVar = IndVar->getIncomingValueForBlock(ExitingBlock);
Chris Lattnerd2440572004-04-15 20:26:22 +0000195 } else {
196 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000197 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
198 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000199 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000200 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000201
Dan Gohman667d7872009-06-26 22:53:46 +0000202 // Expand the code for the iteration count.
Dan Gohman17ead4f2010-11-17 21:23:15 +0000203 assert(SE->isLoopInvariant(RHS, L) &&
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000204 "Computed iteration count is not loop invariant!");
Dan Gohman667d7872009-06-26 22:53:46 +0000205 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000206
Reid Spencere4d87aa2006-12-23 06:05:41 +0000207 // Insert a new icmp_ne or icmp_eq instruction before the branch.
208 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000209 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000210 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000211 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000212 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000213
David Greenef67ef312010-01-05 01:27:06 +0000214 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
Chris Lattnerbdff5482009-08-23 04:37:46 +0000215 << " LHS:" << *CmpIndVar << '\n'
216 << " op:\t"
217 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
218 << " RHS:\t" << *RHS << "\n");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000219
Owen Anderson333c4002009-07-09 23:48:35 +0000220 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
Dan Gohman81db61a2009-05-12 02:17:14 +0000221
Dan Gohman24440802010-02-22 02:07:36 +0000222 Value *OrigCond = BI->getCondition();
Dan Gohman95bdbfa2009-05-24 19:11:38 +0000223 // It's tempting to use replaceAllUsesWith here to fully replace the old
224 // comparison, but that's not immediately safe, since users of the old
225 // comparison may not be dominated by the new comparison. Instead, just
226 // update the branch to use the new comparison; in the common case this
227 // will make old comparison dead.
228 BI->setCondition(Cond);
Dan Gohman81db61a2009-05-12 02:17:14 +0000229 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
230
Chris Lattner40bf8b42004-04-02 20:24:31 +0000231 ++NumLFTR;
232 Changed = true;
Dan Gohman81db61a2009-05-12 02:17:14 +0000233 return Cond;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000234}
235
Chris Lattner40bf8b42004-04-02 20:24:31 +0000236/// RewriteLoopExitValues - Check to see if this loop has a computable
237/// loop-invariant execution count. If so, this means that we can compute the
238/// final value of any expressions that are recurrent in the loop, and
239/// substitute the exit values from the loop into any instructions outside of
240/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000241///
242/// This is mostly redundant with the regular IndVarSimplify activities that
243/// happen later, except that it's more powerful in some cases, because it's
244/// able to brute-force evaluate arbitrary instructions as long as they have
245/// constant operands at the beginning of the loop.
Chris Lattnerf1859892011-01-09 02:16:18 +0000246void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000247 // Verify the input to the pass in already in LCSSA form.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000248 assert(L->isLCSSAForm(*DT));
Dan Gohman81db61a2009-05-12 02:17:14 +0000249
Devang Patelb7211a22007-08-21 00:31:24 +0000250 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000251 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000252
Chris Lattner9f3d7382007-03-04 03:43:23 +0000253 // Find all values that are computed inside the loop, but used outside of it.
254 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
255 // the exit blocks of the loop to find them.
256 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
257 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000258
Chris Lattner9f3d7382007-03-04 03:43:23 +0000259 // If there are no PHI nodes in this exit block, then no values defined
260 // inside the loop are used on this path, skip it.
261 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
262 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000263
Chris Lattner9f3d7382007-03-04 03:43:23 +0000264 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000265
Chris Lattner9f3d7382007-03-04 03:43:23 +0000266 // Iterate over all of the PHI nodes.
267 BasicBlock::iterator BBI = ExitBB->begin();
268 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000269 if (PN->use_empty())
270 continue; // dead use, don't replace it
Dan Gohman814f2b22010-02-18 21:34:02 +0000271
272 // SCEV only supports integer expressions for now.
273 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
274 continue;
275
Dale Johannesen45a2d7d2010-02-19 07:14:22 +0000276 // It's necessary to tell ScalarEvolution about this explicitly so that
277 // it can walk the def-use list and forget all SCEVs, as it may not be
278 // watching the PHI itself. Once the new exit value is in place, there
279 // may not be a def-use connection between the loop and every instruction
280 // which got a SCEVAddRecExpr for that loop.
281 SE->forgetValue(PN);
282
Chris Lattner9f3d7382007-03-04 03:43:23 +0000283 // Iterate over all of the values in all the PHI nodes.
284 for (unsigned i = 0; i != NumPreds; ++i) {
285 // If the value being merged in is not integer or is not defined
286 // in the loop, skip it.
287 Value *InVal = PN->getIncomingValue(i);
Dan Gohman814f2b22010-02-18 21:34:02 +0000288 if (!isa<Instruction>(InVal))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000289 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000290
Chris Lattner9f3d7382007-03-04 03:43:23 +0000291 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000292 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000293 continue; // The Block is in a subloop, skip it.
294
295 // Check that InVal is defined in the loop.
296 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman92329c72009-12-18 01:24:09 +0000297 if (!L->contains(Inst))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000298 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000299
Chris Lattner9f3d7382007-03-04 03:43:23 +0000300 // Okay, this instruction has a user outside of the current loop
301 // and varies predictably *inside* the loop. Evaluate the value it
302 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000303 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +0000304 if (!SE->isLoopInvariant(ExitValue, L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000305 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000306
Chris Lattner9f3d7382007-03-04 03:43:23 +0000307 Changed = true;
308 ++NumReplaced;
Dan Gohmancafb8132009-02-17 19:13:57 +0000309
Dan Gohman667d7872009-06-26 22:53:46 +0000310 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000311
David Greenef67ef312010-01-05 01:27:06 +0000312 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000313 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000314
315 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000316
Dan Gohman81db61a2009-05-12 02:17:14 +0000317 // If this instruction is dead now, delete it.
318 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000319
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000320 if (NumPreds == 1) {
321 // Completely replace a single-pred PHI. This is safe, because the
322 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
323 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000324 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000325 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000326 }
327 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000328 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000329 // Clone the PHI and delete the original one. This lets IVUsers and
330 // any other maps purge the original user from their records.
Devang Patel50b6e332009-10-27 22:16:29 +0000331 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohman667d7872009-06-26 22:53:46 +0000332 NewPN->takeName(PN);
333 NewPN->insertBefore(PN);
334 PN->replaceAllUsesWith(NewPN);
335 PN->eraseFromParent();
336 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000337 }
338 }
Dan Gohman472fdf72010-03-20 03:53:53 +0000339
340 // The insertion point instruction may have been deleted; clear it out
341 // so that the rewriter doesn't trip over it later.
342 Rewriter.clearInsertPoint();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000343}
344
Dan Gohman60f8a632009-02-17 20:49:49 +0000345void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000346 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000347 // If there are, change them into integer recurrences, permitting analysis by
348 // the SCEV routines.
349 //
Chris Lattnerf1859892011-01-09 02:16:18 +0000350 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000351
Dan Gohman81db61a2009-05-12 02:17:14 +0000352 SmallVector<WeakVH, 8> PHIs;
353 for (BasicBlock::iterator I = Header->begin();
354 PHINode *PN = dyn_cast<PHINode>(I); ++I)
355 PHIs.push_back(PN);
356
357 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
Gabor Greifea4894a2010-09-18 11:53:39 +0000358 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
Dan Gohman81db61a2009-05-12 02:17:14 +0000359 HandleFloatingPointIV(L, PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000360
Dan Gohman2d1be872009-04-16 03:18:22 +0000361 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000362 // may not have been able to compute a trip count. Now that we've done some
363 // re-writing, the trip count may be computable.
364 if (Changed)
Dan Gohman4c7279a2009-10-31 15:04:55 +0000365 SE->forgetLoop(L);
Dale Johannesenc671d892009-04-15 23:31:51 +0000366}
367
Dan Gohman931e3452010-04-12 02:21:50 +0000368void IndVarSimplify::EliminateIVComparisons() {
Dan Gohmandd842e32010-04-12 07:29:15 +0000369 SmallVector<WeakVH, 16> DeadInsts;
370
Dan Gohman931e3452010-04-12 02:21:50 +0000371 // Look for ICmp users.
Dan Gohmandd842e32010-04-12 07:29:15 +0000372 for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
373 IVStrideUse &UI = *I;
Dan Gohman931e3452010-04-12 02:21:50 +0000374 ICmpInst *ICmp = dyn_cast<ICmpInst>(UI.getUser());
375 if (!ICmp) continue;
376
377 bool Swapped = UI.getOperandValToReplace() == ICmp->getOperand(1);
378 ICmpInst::Predicate Pred = ICmp->getPredicate();
379 if (Swapped) Pred = ICmpInst::getSwappedPredicate(Pred);
380
381 // Get the SCEVs for the ICmp operands.
382 const SCEV *S = IU->getReplacementExpr(UI);
383 const SCEV *X = SE->getSCEV(ICmp->getOperand(!Swapped));
384
385 // Simplify unnecessary loops away.
386 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
387 S = SE->getSCEVAtScope(S, ICmpLoop);
388 X = SE->getSCEVAtScope(X, ICmpLoop);
389
390 // If the condition is always true or always false, replace it with
391 // a constant value.
392 if (SE->isKnownPredicate(Pred, S, X))
393 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
394 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
395 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
396 else
397 continue;
398
399 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Dan Gohmandd842e32010-04-12 07:29:15 +0000400 DeadInsts.push_back(ICmp);
Dan Gohman931e3452010-04-12 02:21:50 +0000401 }
Dan Gohmandd842e32010-04-12 07:29:15 +0000402
403 // Now that we're done iterating through lists, clean up any instructions
404 // which are now dead.
405 while (!DeadInsts.empty())
406 if (Instruction *Inst =
Gabor Greifea4894a2010-09-18 11:53:39 +0000407 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
Dan Gohmandd842e32010-04-12 07:29:15 +0000408 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohman931e3452010-04-12 02:21:50 +0000409}
410
Dan Gohmana590b792010-04-13 01:46:36 +0000411void IndVarSimplify::EliminateIVRemainders() {
412 SmallVector<WeakVH, 16> DeadInsts;
413
414 // Look for SRem and URem users.
415 for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
416 IVStrideUse &UI = *I;
417 BinaryOperator *Rem = dyn_cast<BinaryOperator>(UI.getUser());
418 if (!Rem) continue;
419
420 bool isSigned = Rem->getOpcode() == Instruction::SRem;
421 if (!isSigned && Rem->getOpcode() != Instruction::URem)
422 continue;
423
424 // We're only interested in the case where we know something about
425 // the numerator.
426 if (UI.getOperandValToReplace() != Rem->getOperand(0))
427 continue;
428
429 // Get the SCEVs for the ICmp operands.
430 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
431 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
432
433 // Simplify unnecessary loops away.
434 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
435 S = SE->getSCEVAtScope(S, ICmpLoop);
436 X = SE->getSCEVAtScope(X, ICmpLoop);
437
438 // i % n --> i if i is in [0,n).
439 if ((!isSigned || SE->isKnownNonNegative(S)) &&
440 SE->isKnownPredicate(isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
441 S, X))
442 Rem->replaceAllUsesWith(Rem->getOperand(0));
443 else {
444 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
445 const SCEV *LessOne =
Dan Gohmandeff6212010-05-03 22:09:21 +0000446 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
Dan Gohmana590b792010-04-13 01:46:36 +0000447 if ((!isSigned || SE->isKnownNonNegative(LessOne)) &&
448 SE->isKnownPredicate(isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
449 LessOne, X)) {
450 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
451 Rem->getOperand(0), Rem->getOperand(1),
452 "tmp");
453 SelectInst *Sel =
454 SelectInst::Create(ICmp,
455 ConstantInt::get(Rem->getType(), 0),
456 Rem->getOperand(0), "tmp", Rem);
457 Rem->replaceAllUsesWith(Sel);
458 } else
459 continue;
460 }
461
462 // Inform IVUsers about the new users.
463 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
464 IU->AddUsersIfInteresting(I);
465
466 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
467 DeadInsts.push_back(Rem);
468 }
469
470 // Now that we're done iterating through lists, clean up any instructions
471 // which are now dead.
472 while (!DeadInsts.empty())
473 if (Instruction *Inst =
Gabor Greifea4894a2010-09-18 11:53:39 +0000474 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
Dan Gohmana590b792010-04-13 01:46:36 +0000475 RecursivelyDeleteTriviallyDeadInstructions(Inst);
476}
477
Dan Gohmanc2390b12009-02-12 22:19:27 +0000478bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmana5283822010-06-18 01:35:11 +0000479 // If LoopSimplify form is not available, stay out of trouble. Some notes:
480 // - LSR currently only supports LoopSimplify-form loops. Indvars'
481 // canonicalization can be a pessimization without LSR to "clean up"
482 // afterwards.
483 // - We depend on having a preheader; in particular,
484 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
485 // and we're in trouble if we can't find the induction variable even when
486 // we've manually inserted one.
487 if (!L->isLoopSimplifyForm())
488 return false;
489
Dan Gohman81db61a2009-05-12 02:17:14 +0000490 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +0000491 LI = &getAnalysis<LoopInfo>();
492 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +0000493 DT = &getAnalysis<DominatorTree>();
Devang Patel5ee99972007-03-07 06:39:01 +0000494 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +0000495
Dan Gohman2d1be872009-04-16 03:18:22 +0000496 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +0000497 // transform them to use integer recurrences.
498 RewriteNonIntegerIVs(L);
499
Dan Gohman81db61a2009-05-12 02:17:14 +0000500 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
Dan Gohman0bba49c2009-07-07 17:06:11 +0000501 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +0000502
Dan Gohman667d7872009-06-26 22:53:46 +0000503 // Create a rewriter object which we'll use to transform the code with.
504 SCEVExpander Rewriter(*SE);
505
Chris Lattner40bf8b42004-04-02 20:24:31 +0000506 // Check to see if this loop has a computable loop-invariant execution count.
507 // If so, this means that we can compute the final value of any expressions
508 // that are recurrent in the loop, and substitute the exit values from the
509 // loop into any instructions outside of the loop that use the final values of
510 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000511 //
Dan Gohman46bdfb02009-02-24 18:55:53 +0000512 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman454d26d2010-02-22 04:11:59 +0000513 RewriteLoopExitValues(L, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +0000514
Dan Gohmand890f292010-04-12 07:56:56 +0000515 // Simplify ICmp IV users.
516 EliminateIVComparisons();
517
Dan Gohmana590b792010-04-13 01:46:36 +0000518 // Simplify SRem and URem IV users.
519 EliminateIVRemainders();
520
Dan Gohman81db61a2009-05-12 02:17:14 +0000521 // Compute the type of the largest recurrence expression, and decide whether
522 // a canonical induction variable should be inserted.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000523 const Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000524 bool NeedCannIV = false;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000525 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
526 LargestType = BackedgeTakenCount->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000527 LargestType = SE->getEffectiveSCEVType(LargestType);
Dan Gohman81db61a2009-05-12 02:17:14 +0000528 // If we have a known trip count and a single exit block, we'll be
529 // rewriting the loop exit test condition below, which requires a
530 // canonical induction variable.
531 if (ExitingBlock)
532 NeedCannIV = true;
Chris Lattnerf50af082004-04-17 18:08:33 +0000533 }
Dan Gohman572645c2010-02-12 10:34:29 +0000534 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
535 const Type *Ty =
536 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000537 if (!LargestType ||
Dan Gohman81db61a2009-05-12 02:17:14 +0000538 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000539 SE->getTypeSizeInBits(LargestType))
Dan Gohman81db61a2009-05-12 02:17:14 +0000540 LargestType = Ty;
Dan Gohman572645c2010-02-12 10:34:29 +0000541 NeedCannIV = true;
Chris Lattner6148c022001-12-03 17:28:42 +0000542 }
543
Dan Gohmanf451cb82010-02-10 16:03:48 +0000544 // Now that we know the largest of the induction variable expressions
Dan Gohman81db61a2009-05-12 02:17:14 +0000545 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohman43ef3fb2010-07-20 17:18:52 +0000546 PHINode *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000547 if (NeedCannIV) {
Dan Gohman85669632010-02-25 06:57:05 +0000548 // Check to see if the loop already has any canonical-looking induction
549 // variables. If any are present and wider than the planned canonical
550 // induction variable, temporarily remove them, so that the Rewriter
551 // doesn't attempt to reuse them.
552 SmallVector<PHINode *, 2> OldCannIVs;
553 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
Dan Gohman4d8414f2009-06-13 16:25:49 +0000554 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
555 SE->getTypeSizeInBits(LargestType))
556 OldCannIV->removeFromParent();
557 else
Dan Gohman85669632010-02-25 06:57:05 +0000558 break;
559 OldCannIVs.push_back(OldCannIV);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000560 }
561
Dan Gohman667d7872009-06-26 22:53:46 +0000562 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000563
Dan Gohmanc2390b12009-02-12 22:19:27 +0000564 ++NumInserted;
565 Changed = true;
David Greenef67ef312010-01-05 01:27:06 +0000566 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +0000567
568 // Now that the official induction variable is established, reinsert
Dan Gohman85669632010-02-25 06:57:05 +0000569 // any old canonical-looking variables after it so that the IR remains
570 // consistent. They will be deleted as part of the dead-PHI deletion at
Dan Gohman4d8414f2009-06-13 16:25:49 +0000571 // the end of the pass.
Dan Gohman85669632010-02-25 06:57:05 +0000572 while (!OldCannIVs.empty()) {
573 PHINode *OldCannIV = OldCannIVs.pop_back_val();
574 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
575 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000576 }
Chris Lattner15cad752003-12-23 07:47:09 +0000577
Dan Gohmanc2390b12009-02-12 22:19:27 +0000578 // If we have a trip count expression, rewrite the loop's exit condition
579 // using it. We can currently only handle loops with a single exit.
Dan Gohman81db61a2009-05-12 02:17:14 +0000580 ICmpInst *NewICmp = 0;
Dan Gohman85669632010-02-25 06:57:05 +0000581 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
582 !BackedgeTakenCount->isZero() &&
583 ExitingBlock) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000584 assert(NeedCannIV &&
585 "LinearFunctionTestReplace requires a canonical induction variable");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000586 // Can't rewrite non-branch yet.
Dan Gohmand890f292010-04-12 07:56:56 +0000587 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
Dan Gohman81db61a2009-05-12 02:17:14 +0000588 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
589 ExitingBlock, BI, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000590 }
591
Torok Edwin3d431382009-05-24 20:08:21 +0000592 // Rewrite IV-derived expressions. Clears the rewriter cache.
Dan Gohman454d26d2010-02-22 04:11:59 +0000593 RewriteIVExpressions(L, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000594
Dan Gohman667d7872009-06-26 22:53:46 +0000595 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +0000596
Dan Gohman81db61a2009-05-12 02:17:14 +0000597 // Loop-invariant instructions in the preheader that aren't used in the
598 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +0000599 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +0000600
601 // For completeness, inform IVUsers of the IV use in the newly-created
602 // loop exit test instruction.
603 if (NewICmp)
604 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
605
606 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +0000607 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +0000608 // Check a post-condition.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000609 assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +0000610 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000611}
Devang Pateld22a8492008-09-09 21:41:07 +0000612
Dan Gohman448db1c2010-04-07 22:27:08 +0000613// FIXME: It is an extremely bad idea to indvar substitute anything more
614// complex than affine induction variables. Doing so will put expensive
615// polynomial evaluations inside of the loop, and the str reduction pass
616// currently can only reduce affine polynomials. For now just disable
617// indvar subst on anything more complex than an affine addrec, unless
618// it can be expanded to a trivial value.
Dan Gohman17ead4f2010-11-17 21:23:15 +0000619static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
Dan Gohman448db1c2010-04-07 22:27:08 +0000620 // Loop-invariant values are safe.
Dan Gohman17ead4f2010-11-17 21:23:15 +0000621 if (SE->isLoopInvariant(S, L)) return true;
Dan Gohman448db1c2010-04-07 22:27:08 +0000622
623 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
624 // to transform them into efficient code.
625 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
626 return AR->isAffine();
627
628 // An add is safe it all its operands are safe.
629 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
630 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
631 E = Commutative->op_end(); I != E; ++I)
Dan Gohman17ead4f2010-11-17 21:23:15 +0000632 if (!isSafe(*I, L, SE)) return false;
Dan Gohman448db1c2010-04-07 22:27:08 +0000633 return true;
634 }
Andrew Trickead71d52011-03-17 23:46:48 +0000635
Dan Gohman448db1c2010-04-07 22:27:08 +0000636 // A cast is safe if its operand is.
637 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
Dan Gohman17ead4f2010-11-17 21:23:15 +0000638 return isSafe(C->getOperand(), L, SE);
Dan Gohman448db1c2010-04-07 22:27:08 +0000639
640 // A udiv is safe if its operands are.
641 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
Dan Gohman17ead4f2010-11-17 21:23:15 +0000642 return isSafe(UD->getLHS(), L, SE) &&
643 isSafe(UD->getRHS(), L, SE);
Dan Gohman448db1c2010-04-07 22:27:08 +0000644
645 // SCEVUnknown is always safe.
646 if (isa<SCEVUnknown>(S))
647 return true;
648
649 // Nothing else is safe.
650 return false;
651}
652
Dan Gohman454d26d2010-02-22 04:11:59 +0000653void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000654 SmallVector<WeakVH, 16> DeadInsts;
655
656 // Rewrite all induction variable expressions in terms of the canonical
657 // induction variable.
658 //
659 // If there were induction variables of other sizes or offsets, manually
660 // add the offsets to the primary induction variable and cast, avoiding
661 // the need for the code evaluation methods to insert induction variables
662 // of different sizes.
Dan Gohman572645c2010-02-12 10:34:29 +0000663 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
Dan Gohman572645c2010-02-12 10:34:29 +0000664 Value *Op = UI->getOperandValToReplace();
665 const Type *UseTy = Op->getType();
666 Instruction *User = UI->getUser();
Dan Gohman81db61a2009-05-12 02:17:14 +0000667
Dan Gohman572645c2010-02-12 10:34:29 +0000668 // Compute the final addrec to expand into code.
669 const SCEV *AR = IU->getReplacementExpr(*UI);
Dan Gohman81db61a2009-05-12 02:17:14 +0000670
Dan Gohman572645c2010-02-12 10:34:29 +0000671 // Evaluate the expression out of the loop, if possible.
672 if (!L->contains(UI->getUser())) {
673 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +0000674 if (SE->isLoopInvariant(ExitVal, L))
Dan Gohman572645c2010-02-12 10:34:29 +0000675 AR = ExitVal;
Dan Gohman81db61a2009-05-12 02:17:14 +0000676 }
Dan Gohman572645c2010-02-12 10:34:29 +0000677
678 // FIXME: It is an extremely bad idea to indvar substitute anything more
679 // complex than affine induction variables. Doing so will put expensive
680 // polynomial evaluations inside of the loop, and the str reduction pass
681 // currently can only reduce affine polynomials. For now just disable
682 // indvar subst on anything more complex than an affine addrec, unless
683 // it can be expanded to a trivial value.
Dan Gohman17ead4f2010-11-17 21:23:15 +0000684 if (!isSafe(AR, L, SE))
Dan Gohman572645c2010-02-12 10:34:29 +0000685 continue;
686
687 // Determine the insertion point for this user. By default, insert
688 // immediately before the user. The SCEVExpander class will automatically
689 // hoist loop invariants out of the loop. For PHI nodes, there may be
690 // multiple uses, so compute the nearest common dominator for the
691 // incoming blocks.
692 Instruction *InsertPt = User;
693 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
694 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
695 if (PHI->getIncomingValue(i) == Op) {
696 if (InsertPt == User)
697 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
698 else
699 InsertPt =
700 DT->findNearestCommonDominator(InsertPt->getParent(),
701 PHI->getIncomingBlock(i))
702 ->getTerminator();
703 }
704
705 // Now expand it into actual Instructions and patch it into place.
706 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
707
Dan Gohmand7bfd002010-04-02 14:48:31 +0000708 // Inform ScalarEvolution that this value is changing. The change doesn't
709 // affect its value, but it does potentially affect which use lists the
710 // value will be on after the replacement, which affects ScalarEvolution's
711 // ability to walk use lists and drop dangling pointers when a value is
712 // deleted.
713 SE->forgetValue(User);
714
Dan Gohman572645c2010-02-12 10:34:29 +0000715 // Patch the new value into place.
716 if (Op->hasName())
717 NewVal->takeName(Op);
718 User->replaceUsesOfWith(Op, NewVal);
719 UI->setOperandValToReplace(NewVal);
720 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
721 << " into = " << *NewVal << "\n");
722 ++NumRemoved;
723 Changed = true;
724
725 // The old value may be dead now.
726 DeadInsts.push_back(Op);
Dan Gohman81db61a2009-05-12 02:17:14 +0000727 }
728
Torok Edwin3d431382009-05-24 20:08:21 +0000729 // Clear the rewriter cache, because values that are in the rewriter's cache
730 // can be deleted in the loop below, causing the AssertingVH in the cache to
731 // trigger.
732 Rewriter.clear();
Dan Gohman81db61a2009-05-12 02:17:14 +0000733 // Now that we're done iterating through lists, clean up any instructions
734 // which are now dead.
Dan Gohmana10756e2010-01-21 02:09:26 +0000735 while (!DeadInsts.empty())
736 if (Instruction *Inst =
Gabor Greifea4894a2010-09-18 11:53:39 +0000737 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
Dan Gohman81db61a2009-05-12 02:17:14 +0000738 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohman81db61a2009-05-12 02:17:14 +0000739}
740
741/// If there's a single exit block, sink any loop-invariant values that
742/// were defined in the preheader but not used inside the loop into the
743/// exit block to reduce register pressure in the loop.
Dan Gohman667d7872009-06-26 22:53:46 +0000744void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000745 BasicBlock *ExitBlock = L->getExitBlock();
746 if (!ExitBlock) return;
747
Dan Gohman81db61a2009-05-12 02:17:14 +0000748 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman03e896b2009-11-05 21:11:53 +0000749 if (!Preheader) return;
750
751 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
Dan Gohman81db61a2009-05-12 02:17:14 +0000752 BasicBlock::iterator I = Preheader->getTerminator();
753 while (I != Preheader->begin()) {
754 --I;
Dan Gohman667d7872009-06-26 22:53:46 +0000755 // New instructions were inserted at the end of the preheader.
756 if (isa<PHINode>(I))
Dan Gohman81db61a2009-05-12 02:17:14 +0000757 break;
Bill Wendling87a10f52010-03-23 21:15:59 +0000758
Eli Friedman0c77db32009-07-15 22:48:29 +0000759 // Don't move instructions which might have side effects, since the side
Bill Wendling87a10f52010-03-23 21:15:59 +0000760 // effects need to complete before instructions inside the loop. Also don't
761 // move instructions which might read memory, since the loop may modify
762 // memory. Note that it's okay if the instruction might have undefined
763 // behavior: LoopSimplify guarantees that the preheader dominates the exit
764 // block.
Eli Friedman0c77db32009-07-15 22:48:29 +0000765 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Dan Gohman667d7872009-06-26 22:53:46 +0000766 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000767
Devang Patel7b9f6b12010-03-15 22:23:03 +0000768 // Skip debug info intrinsics.
769 if (isa<DbgInfoIntrinsic>(I))
770 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000771
Dan Gohman76f497a2009-08-25 17:42:10 +0000772 // Don't sink static AllocaInsts out of the entry block, which would
773 // turn them into dynamic allocas!
774 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
775 if (AI->isStaticAlloca())
776 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000777
Dan Gohman81db61a2009-05-12 02:17:14 +0000778 // Determine if there is a use in or before the loop (direct or
779 // otherwise).
780 bool UsedInLoop = false;
781 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
782 UI != UE; ++UI) {
Gabor Greif76560182010-07-09 15:40:10 +0000783 User *U = *UI;
784 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
785 if (PHINode *P = dyn_cast<PHINode>(U)) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000786 unsigned i =
787 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
788 UseBB = P->getIncomingBlock(i);
789 }
790 if (UseBB == Preheader || L->contains(UseBB)) {
791 UsedInLoop = true;
792 break;
793 }
794 }
Bill Wendling87a10f52010-03-23 21:15:59 +0000795
Dan Gohman81db61a2009-05-12 02:17:14 +0000796 // If there is, the def must remain in the preheader.
797 if (UsedInLoop)
798 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000799
Dan Gohman81db61a2009-05-12 02:17:14 +0000800 // Otherwise, sink it to the exit block.
801 Instruction *ToMove = I;
802 bool Done = false;
Bill Wendling87a10f52010-03-23 21:15:59 +0000803
804 if (I != Preheader->begin()) {
805 // Skip debug info intrinsics.
806 do {
807 --I;
808 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
809
810 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
811 Done = true;
812 } else {
Dan Gohman81db61a2009-05-12 02:17:14 +0000813 Done = true;
Bill Wendling87a10f52010-03-23 21:15:59 +0000814 }
815
Dan Gohman667d7872009-06-26 22:53:46 +0000816 ToMove->moveBefore(InsertPt);
Bill Wendling87a10f52010-03-23 21:15:59 +0000817 if (Done) break;
Dan Gohman667d7872009-06-26 22:53:46 +0000818 InsertPt = ToMove;
Dan Gohman81db61a2009-05-12 02:17:14 +0000819 }
820}
821
Chris Lattnerbbb91492010-04-03 06:41:49 +0000822/// ConvertToSInt - Convert APF to an integer, if possible.
823static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
Devang Patelcd402332008-11-17 23:27:13 +0000824 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000825 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
826 return false;
Chris Lattnerbbb91492010-04-03 06:41:49 +0000827 // See if we can convert this to an int64_t
828 uint64_t UIntVal;
829 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
830 &isExact) != APFloat::opOK || !isExact)
Devang Patelcd402332008-11-17 23:27:13 +0000831 return false;
Chris Lattnerbbb91492010-04-03 06:41:49 +0000832 IntVal = UIntVal;
Devang Patelcd402332008-11-17 23:27:13 +0000833 return true;
Devang Patelcd402332008-11-17 23:27:13 +0000834}
835
Devang Patel58d43d42008-11-03 18:32:19 +0000836/// HandleFloatingPointIV - If the loop has floating induction variable
837/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000838/// For example,
839/// for(double i = 0; i < 10000; ++i)
840/// bar(i)
841/// is converted into
842/// for(int i = 0; i < 10000; ++i)
843/// bar((double)i);
844///
Chris Lattnerc91961e2010-04-03 06:17:08 +0000845void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
846 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
Devang Patel84e35152008-11-17 21:32:02 +0000847 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +0000848
Devang Patel84e35152008-11-17 21:32:02 +0000849 // Check incoming value.
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000850 ConstantFP *InitValueVal =
Chris Lattnerc91961e2010-04-03 06:17:08 +0000851 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
Chris Lattner96fd7662010-04-03 07:18:48 +0000852
Chris Lattnerbbb91492010-04-03 06:41:49 +0000853 int64_t InitValue;
Chris Lattner96fd7662010-04-03 07:18:48 +0000854 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
Devang Patelcd402332008-11-17 23:27:13 +0000855 return;
856
Chris Lattnerc91961e2010-04-03 06:17:08 +0000857 // Check IV increment. Reject this PN if increment operation is not
Devang Patelcd402332008-11-17 23:27:13 +0000858 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +0000859 BinaryOperator *Incr =
Chris Lattnerc91961e2010-04-03 06:17:08 +0000860 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
Chris Lattner07aa76a2010-04-03 05:54:59 +0000861 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
Andrew Trickead71d52011-03-17 23:46:48 +0000862
Chris Lattner07aa76a2010-04-03 05:54:59 +0000863 // If this is not an add of the PHI with a constantfp, or if the constant fp
864 // is not an integer, bail out.
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000865 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
Chris Lattner96fd7662010-04-03 07:18:48 +0000866 int64_t IncValue;
Chris Lattnerc91961e2010-04-03 06:17:08 +0000867 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
Chris Lattner96fd7662010-04-03 07:18:48 +0000868 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
Devang Patelcd402332008-11-17 23:27:13 +0000869 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000870
Chris Lattnerc91961e2010-04-03 06:17:08 +0000871 // Check Incr uses. One user is PN and the other user is an exit condition
Chris Lattner07aa76a2010-04-03 05:54:59 +0000872 // used by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000873 Value::use_iterator IncrUse = Incr->use_begin();
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000874 Instruction *U1 = cast<Instruction>(*IncrUse++);
Devang Patel84e35152008-11-17 21:32:02 +0000875 if (IncrUse == Incr->use_end()) return;
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000876 Instruction *U2 = cast<Instruction>(*IncrUse++);
Devang Patel84e35152008-11-17 21:32:02 +0000877 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000878
Chris Lattner07aa76a2010-04-03 05:54:59 +0000879 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
880 // only used by a branch, we can't transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +0000881 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
882 if (!Compare)
883 Compare = dyn_cast<FCmpInst>(U2);
884 if (Compare == 0 || !Compare->hasOneUse() ||
885 !isa<BranchInst>(Compare->use_back()))
Chris Lattner07aa76a2010-04-03 05:54:59 +0000886 return;
Andrew Trickead71d52011-03-17 23:46:48 +0000887
Chris Lattnerca703bd2010-04-03 06:11:07 +0000888 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
Devang Patel84e35152008-11-17 21:32:02 +0000889
Chris Lattnerd52c0722010-04-03 07:21:39 +0000890 // We need to verify that the branch actually controls the iteration count
891 // of the loop. If not, the new IV can overflow and no one will notice.
892 // The branch block must be in the loop and one of the successors must be out
893 // of the loop.
894 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
895 if (!L->contains(TheBr->getParent()) ||
896 (L->contains(TheBr->getSuccessor(0)) &&
897 L->contains(TheBr->getSuccessor(1))))
898 return;
Andrew Trickead71d52011-03-17 23:46:48 +0000899
900
Chris Lattner07aa76a2010-04-03 05:54:59 +0000901 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
902 // transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +0000903 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
Chris Lattnerbbb91492010-04-03 06:41:49 +0000904 int64_t ExitValue;
905 if (ExitValueVal == 0 ||
906 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
Devang Patel84e35152008-11-17 21:32:02 +0000907 return;
Andrew Trickead71d52011-03-17 23:46:48 +0000908
Devang Patel84e35152008-11-17 21:32:02 +0000909 // Find new predicate for integer comparison.
910 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerca703bd2010-04-03 06:11:07 +0000911 switch (Compare->getPredicate()) {
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000912 default: return; // Unknown comparison.
Devang Patel84e35152008-11-17 21:32:02 +0000913 case CmpInst::FCMP_OEQ:
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000914 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
Chris Lattner96fd7662010-04-03 07:18:48 +0000915 case CmpInst::FCMP_ONE:
916 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
Devang Patel84e35152008-11-17 21:32:02 +0000917 case CmpInst::FCMP_OGT:
Chris Lattnera40e4a02010-04-03 06:25:21 +0000918 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
Devang Patel84e35152008-11-17 21:32:02 +0000919 case CmpInst::FCMP_OGE:
Chris Lattnera40e4a02010-04-03 06:25:21 +0000920 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
Devang Patel84e35152008-11-17 21:32:02 +0000921 case CmpInst::FCMP_OLT:
Chris Lattner43b85272010-04-03 06:30:03 +0000922 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
Devang Patel84e35152008-11-17 21:32:02 +0000923 case CmpInst::FCMP_OLE:
Chris Lattner43b85272010-04-03 06:30:03 +0000924 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
Devang Patel58d43d42008-11-03 18:32:19 +0000925 }
Andrew Trickead71d52011-03-17 23:46:48 +0000926
Chris Lattner96fd7662010-04-03 07:18:48 +0000927 // We convert the floating point induction variable to a signed i32 value if
928 // we can. This is only safe if the comparison will not overflow in a way
929 // that won't be trapped by the integer equivalent operations. Check for this
930 // now.
931 // TODO: We could use i64 if it is native and the range requires it.
Andrew Trickead71d52011-03-17 23:46:48 +0000932
Chris Lattner96fd7662010-04-03 07:18:48 +0000933 // The start/stride/exit values must all fit in signed i32.
934 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
935 return;
936
937 // If not actually striding (add x, 0.0), avoid touching the code.
938 if (IncValue == 0)
939 return;
940
941 // Positive and negative strides have different safety conditions.
942 if (IncValue > 0) {
943 // If we have a positive stride, we require the init to be less than the
944 // exit value and an equality or less than comparison.
945 if (InitValue >= ExitValue ||
946 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
947 return;
Andrew Trickead71d52011-03-17 23:46:48 +0000948
Chris Lattner96fd7662010-04-03 07:18:48 +0000949 uint32_t Range = uint32_t(ExitValue-InitValue);
950 if (NewPred == CmpInst::ICMP_SLE) {
951 // Normalize SLE -> SLT, check for infinite loop.
952 if (++Range == 0) return; // Range overflows.
953 }
Andrew Trickead71d52011-03-17 23:46:48 +0000954
Chris Lattner96fd7662010-04-03 07:18:48 +0000955 unsigned Leftover = Range % uint32_t(IncValue);
Andrew Trickead71d52011-03-17 23:46:48 +0000956
Chris Lattner96fd7662010-04-03 07:18:48 +0000957 // If this is an equality comparison, we require that the strided value
958 // exactly land on the exit value, otherwise the IV condition will wrap
959 // around and do things the fp IV wouldn't.
960 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
961 Leftover != 0)
962 return;
Andrew Trickead71d52011-03-17 23:46:48 +0000963
Chris Lattner96fd7662010-04-03 07:18:48 +0000964 // If the stride would wrap around the i32 before exiting, we can't
965 // transform the IV.
966 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
967 return;
Andrew Trickead71d52011-03-17 23:46:48 +0000968
Chris Lattner96fd7662010-04-03 07:18:48 +0000969 } else {
970 // If we have a negative stride, we require the init to be greater than the
971 // exit value and an equality or greater than comparison.
972 if (InitValue >= ExitValue ||
973 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
974 return;
Andrew Trickead71d52011-03-17 23:46:48 +0000975
Chris Lattner96fd7662010-04-03 07:18:48 +0000976 uint32_t Range = uint32_t(InitValue-ExitValue);
977 if (NewPred == CmpInst::ICMP_SGE) {
978 // Normalize SGE -> SGT, check for infinite loop.
979 if (++Range == 0) return; // Range overflows.
980 }
Andrew Trickead71d52011-03-17 23:46:48 +0000981
Chris Lattner96fd7662010-04-03 07:18:48 +0000982 unsigned Leftover = Range % uint32_t(-IncValue);
Andrew Trickead71d52011-03-17 23:46:48 +0000983
Chris Lattner96fd7662010-04-03 07:18:48 +0000984 // If this is an equality comparison, we require that the strided value
985 // exactly land on the exit value, otherwise the IV condition will wrap
986 // around and do things the fp IV wouldn't.
987 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
988 Leftover != 0)
989 return;
Andrew Trickead71d52011-03-17 23:46:48 +0000990
Chris Lattner96fd7662010-04-03 07:18:48 +0000991 // If the stride would wrap around the i32 before exiting, we can't
992 // transform the IV.
993 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
994 return;
995 }
Andrew Trickead71d52011-03-17 23:46:48 +0000996
Chris Lattner96fd7662010-04-03 07:18:48 +0000997 const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
Dan Gohmancafb8132009-02-17 19:13:57 +0000998
Chris Lattnerbbb91492010-04-03 06:41:49 +0000999 // Insert new integer induction variable.
Chris Lattnerc91961e2010-04-03 06:17:08 +00001000 PHINode *NewPHI = PHINode::Create(Int32Ty, PN->getName()+".int", PN);
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001001 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
Chris Lattnerc91961e2010-04-03 06:17:08 +00001002 PN->getIncomingBlock(IncomingEdge));
Devang Patel84e35152008-11-17 21:32:02 +00001003
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001004 Value *NewAdd =
Chris Lattner96fd7662010-04-03 07:18:48 +00001005 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001006 Incr->getName()+".int", Incr);
Chris Lattnerc91961e2010-04-03 06:17:08 +00001007 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
Devang Patel84e35152008-11-17 21:32:02 +00001008
Chris Lattnerca703bd2010-04-03 06:11:07 +00001009 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
1010 ConstantInt::get(Int32Ty, ExitValue),
1011 Compare->getName());
Dan Gohmancafb8132009-02-17 19:13:57 +00001012
Chris Lattnerc91961e2010-04-03 06:17:08 +00001013 // In the following deletions, PN may become dead and may be deleted.
Dan Gohman81db61a2009-05-12 02:17:14 +00001014 // Use a WeakVH to observe whether this happens.
Chris Lattnerc91961e2010-04-03 06:17:08 +00001015 WeakVH WeakPH = PN;
Dan Gohman81db61a2009-05-12 02:17:14 +00001016
Chris Lattnerca703bd2010-04-03 06:11:07 +00001017 // Delete the old floating point exit comparison. The branch starts using the
1018 // new comparison.
1019 NewCompare->takeName(Compare);
1020 Compare->replaceAllUsesWith(NewCompare);
1021 RecursivelyDeleteTriviallyDeadInstructions(Compare);
Dan Gohmancafb8132009-02-17 19:13:57 +00001022
Chris Lattnerca703bd2010-04-03 06:11:07 +00001023 // Delete the old floating point increment.
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001024 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman81db61a2009-05-12 02:17:14 +00001025 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +00001026
Chris Lattner70c0d4f2010-04-03 06:16:22 +00001027 // If the FP induction variable still has uses, this is because something else
1028 // in the loop uses its value. In order to canonicalize the induction
1029 // variable, we chose to eliminate the IV and rewrite it in terms of an
1030 // int->fp cast.
1031 //
1032 // We give preference to sitofp over uitofp because it is faster on most
1033 // platforms.
1034 if (WeakPH) {
Chris Lattnera40e4a02010-04-03 06:25:21 +00001035 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
1036 PN->getParent()->getFirstNonPHI());
1037 PN->replaceAllUsesWith(Conv);
Chris Lattnerc91961e2010-04-03 06:17:08 +00001038 RecursivelyDeleteTriviallyDeadInstructions(PN);
Devang Patelcd402332008-11-17 23:27:13 +00001039 }
Devang Patel58d43d42008-11-03 18:32:19 +00001040
Dan Gohman81db61a2009-05-12 02:17:14 +00001041 // Add a new IVUsers entry for the newly-created integer PHI.
1042 IU->AddUsersIfInteresting(NewPHI);
1043}