blob: 577d3cc46fa8964d0b8c3a0ece4fdae5ff3ec6fb [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// 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//
14// This transformation makes the following changes to each loop with an
15// 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 Gohman024f6132009-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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Gohman211ca4a2009-05-19 20:38:47 +000037// desired loop transformations have been performed.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000038//
39//===----------------------------------------------------------------------===//
40
41#define DEBUG_TYPE "indvars"
42#include "llvm/Transforms/Scalar.h"
43#include "llvm/BasicBlock.h"
44#include "llvm/Constants.h"
45#include "llvm/Instructions.h"
46#include "llvm/Type.h"
Dan Gohman28055122009-05-12 02:17:14 +000047#include "llvm/Analysis/Dominators.h"
48#include "llvm/Analysis/IVUsers.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049#include "llvm/Analysis/ScalarEvolutionExpander.h"
50#include "llvm/Analysis/LoopInfo.h"
51#include "llvm/Analysis/LoopPass.h"
52#include "llvm/Support/CFG.h"
53#include "llvm/Support/Compiler.h"
54#include "llvm/Support/Debug.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055#include "llvm/Transforms/Utils/Local.h"
Dan Gohman28055122009-05-12 02:17:14 +000056#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000057#include "llvm/Support/CommandLine.h"
58#include "llvm/ADT/SmallVector.h"
59#include "llvm/ADT/Statistic.h"
Dan Gohman28055122009-05-12 02:17:14 +000060#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061using namespace llvm;
62
63STATISTIC(NumRemoved , "Number of aux indvars removed");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000064STATISTIC(NumInserted, "Number of canonical indvars added");
65STATISTIC(NumReplaced, "Number of exit values replaced");
66STATISTIC(NumLFTR , "Number of loop exit tests replaced");
67
68namespace {
69 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
Dan Gohman28055122009-05-12 02:17:14 +000070 IVUsers *IU;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000071 LoopInfo *LI;
72 ScalarEvolution *SE;
Dan Gohman402142e2009-06-27 05:16:57 +000073 DominatorTree *DT;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000074 bool Changed;
75 public:
76
77 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000078 IndVarSimplify() : LoopPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079
Dan Gohmanf3a060a2009-02-17 20:49:49 +000080 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
81
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman28055122009-05-12 02:17:14 +000083 AU.addRequired<DominatorTree>();
Devang Patele6a8d482007-09-10 18:08:23 +000084 AU.addRequired<ScalarEvolution>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085 AU.addRequiredID(LoopSimplifyID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086 AU.addRequired<LoopInfo>();
Dan Gohman28055122009-05-12 02:17:14 +000087 AU.addRequired<IVUsers>();
Dan Gohmancba21cb2009-07-01 23:21:38 +000088 AU.addRequiredID(LCSSAID);
Dan Gohman0d35b112009-02-23 16:29:41 +000089 AU.addPreserved<ScalarEvolution>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000090 AU.addPreservedID(LoopSimplifyID);
Dan Gohman28055122009-05-12 02:17:14 +000091 AU.addPreserved<IVUsers>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000092 AU.addPreservedID(LCSSAID);
93 AU.setPreservesCFG();
94 }
95
96 private:
97
Dan Gohmanf3a060a2009-02-17 20:49:49 +000098 void RewriteNonIntegerIVs(Loop *L);
99
Owen Andersonecd0cd72009-06-22 21:39:50 +0000100 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV* BackedgeTakenCount,
Dan Gohman1247dc32009-02-17 15:57:39 +0000101 Value *IndVar,
Dan Gohmancacd2012009-02-12 22:19:27 +0000102 BasicBlock *ExitingBlock,
103 BranchInst *BI,
Dan Gohmanebac2542009-02-23 23:20:35 +0000104 SCEVExpander &Rewriter);
Dan Gohman9a0303b2009-06-26 22:53:46 +0000105 void RewriteLoopExitValues(Loop *L, const SCEV *BackedgeTakenCount,
106 SCEVExpander &Rewriter);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107
Dan Gohman28055122009-05-12 02:17:14 +0000108 void RewriteIVExpressions(Loop *L, const Type *LargestType,
Dan Gohman9a0303b2009-06-26 22:53:46 +0000109 SCEVExpander &Rewriter);
Devang Patelbda43802008-09-09 21:41:07 +0000110
Dan Gohman9a0303b2009-06-26 22:53:46 +0000111 void SinkUnusedInvariants(Loop *L);
Dan Gohman28055122009-05-12 02:17:14 +0000112
113 void HandleFloatingPointIV(Loop *L, PHINode *PH);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000114 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000115}
116
Dan Gohman089efff2008-05-13 00:00:25 +0000117char IndVarSimplify::ID = 0;
118static RegisterPass<IndVarSimplify>
119X("indvars", "Canonicalize Induction Variables");
120
Daniel Dunbar163555a2008-10-22 23:32:42 +0000121Pass *llvm::createIndVarSimplifyPass() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122 return new IndVarSimplify();
123}
124
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125/// LinearFunctionTestReplace - This method rewrites the exit condition of the
126/// loop to be a canonical != comparison against the incremented loop induction
127/// variable. This pass is able to rewrite the exit tests of any loop where the
128/// SCEV analysis can determine a loop-invariant trip count of the loop, which
129/// is actually a much broader range than just linear tests.
Dan Gohman28055122009-05-12 02:17:14 +0000130ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
Owen Andersonecd0cd72009-06-22 21:39:50 +0000131 const SCEV* BackedgeTakenCount,
Dan Gohmancacd2012009-02-12 22:19:27 +0000132 Value *IndVar,
133 BasicBlock *ExitingBlock,
134 BranchInst *BI,
Dan Gohmanebac2542009-02-23 23:20:35 +0000135 SCEVExpander &Rewriter) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136 // If the exiting block is not the same as the backedge block, we must compare
137 // against the preincremented value, otherwise we prefer to compare against
138 // the post-incremented value.
Dan Gohmancacd2012009-02-12 22:19:27 +0000139 Value *CmpIndVar;
Owen Andersonecd0cd72009-06-22 21:39:50 +0000140 const SCEV* RHS = BackedgeTakenCount;
Dan Gohmancacd2012009-02-12 22:19:27 +0000141 if (ExitingBlock == L->getLoopLatch()) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000142 // Add one to the "backedge-taken" count to get the trip count.
143 // If this addition may overflow, we have to be more pessimistic and
144 // cast the induction variable before doing the add.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000145 const SCEV* Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
146 const SCEV* N =
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000147 SE->getAddExpr(BackedgeTakenCount,
148 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
Dan Gohmancacd2012009-02-12 22:19:27 +0000149 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
150 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
151 // No overflow. Cast the sum.
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000152 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmancacd2012009-02-12 22:19:27 +0000153 } else {
154 // Potential overflow. Cast before doing the add.
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000155 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
156 IndVar->getType());
157 RHS = SE->getAddExpr(RHS,
158 SE->getIntegerSCEV(1, IndVar->getType()));
Dan Gohmancacd2012009-02-12 22:19:27 +0000159 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000160
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000161 // The BackedgeTaken expression contains the number of times that the
162 // backedge branches to the loop header. This is one less than the
163 // number of times the loop executes, so use the incremented indvar.
Dan Gohmancacd2012009-02-12 22:19:27 +0000164 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000165 } else {
166 // We have to use the preincremented value...
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000167 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
168 IndVar->getType());
Dan Gohmancacd2012009-02-12 22:19:27 +0000169 CmpIndVar = IndVar;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171
Dan Gohman9a0303b2009-06-26 22:53:46 +0000172 // Expand the code for the iteration count.
Dan Gohman423ed6c2009-06-24 01:18:18 +0000173 assert(RHS->isLoopInvariant(L) &&
174 "Computed iteration count is not loop invariant!");
Dan Gohman9a0303b2009-06-26 22:53:46 +0000175 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176
177 // Insert a new icmp_ne or icmp_eq instruction before the branch.
178 ICmpInst::Predicate Opcode;
179 if (L->contains(BI->getSuccessor(0)))
180 Opcode = ICmpInst::ICMP_NE;
181 else
182 Opcode = ICmpInst::ICMP_EQ;
183
Dan Gohmancacd2012009-02-12 22:19:27 +0000184 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
185 << " LHS:" << *CmpIndVar // includes a newline
186 << " op:\t"
Dan Gohman8555ff72009-02-14 02:26:50 +0000187 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000188 << " RHS:\t" << *RHS << "\n";
Dan Gohmancacd2012009-02-12 22:19:27 +0000189
Dan Gohman28055122009-05-12 02:17:14 +0000190 ICmpInst *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
191
192 Instruction *OrigCond = cast<Instruction>(BI->getCondition());
Dan Gohman53cc9222009-05-24 19:11:38 +0000193 // It's tempting to use replaceAllUsesWith here to fully replace the old
194 // comparison, but that's not immediately safe, since users of the old
195 // comparison may not be dominated by the new comparison. Instead, just
196 // update the branch to use the new comparison; in the common case this
197 // will make old comparison dead.
198 BI->setCondition(Cond);
Dan Gohman28055122009-05-12 02:17:14 +0000199 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
200
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201 ++NumLFTR;
202 Changed = true;
Dan Gohman28055122009-05-12 02:17:14 +0000203 return Cond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204}
205
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206/// RewriteLoopExitValues - Check to see if this loop has a computable
207/// loop-invariant execution count. If so, this means that we can compute the
208/// final value of any expressions that are recurrent in the loop, and
209/// substitute the exit values from the loop into any instructions outside of
210/// the loop that use the final values of the current expressions.
Dan Gohman28055122009-05-12 02:17:14 +0000211///
212/// This is mostly redundant with the regular IndVarSimplify activities that
213/// happen later, except that it's more powerful in some cases, because it's
214/// able to brute-force evaluate arbitrary instructions as long as they have
215/// constant operands at the beginning of the loop.
Dan Gohman9a769972009-04-18 17:56:28 +0000216void IndVarSimplify::RewriteLoopExitValues(Loop *L,
Dan Gohman9a0303b2009-06-26 22:53:46 +0000217 const SCEV *BackedgeTakenCount,
218 SCEVExpander &Rewriter) {
Dan Gohman28055122009-05-12 02:17:14 +0000219 // Verify the input to the pass in already in LCSSA form.
220 assert(L->isLCSSAForm());
221
Devang Patel02451fa2007-08-21 00:31:24 +0000222 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223 L->getUniqueExitBlocks(ExitBlocks);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224
225 // Find all values that are computed inside the loop, but used outside of it.
226 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
227 // the exit blocks of the loop to find them.
228 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
229 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohman963fc812009-02-17 19:13:57 +0000230
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 // If there are no PHI nodes in this exit block, then no values defined
232 // inside the loop are used on this path, skip it.
233 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
234 if (!PN) continue;
Dan Gohman963fc812009-02-17 19:13:57 +0000235
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohman963fc812009-02-17 19:13:57 +0000237
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238 // Iterate over all of the PHI nodes.
239 BasicBlock::iterator BBI = ExitBB->begin();
240 while ((PN = dyn_cast<PHINode>(BBI++))) {
Edwin Törökf06a8f22009-05-24 19:36:09 +0000241 if (PN->use_empty())
242 continue; // dead use, don't replace it
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000243 // Iterate over all of the values in all the PHI nodes.
244 for (unsigned i = 0; i != NumPreds; ++i) {
245 // If the value being merged in is not integer or is not defined
246 // in the loop, skip it.
247 Value *InVal = PN->getIncomingValue(i);
248 if (!isa<Instruction>(InVal) ||
249 // SCEV only supports integer expressions for now.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000250 (!isa<IntegerType>(InVal->getType()) &&
251 !isa<PointerType>(InVal->getType())))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 continue;
253
254 // If this pred is for a subloop, not L itself, skip it.
Dan Gohman963fc812009-02-17 19:13:57 +0000255 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000256 continue; // The Block is in a subloop, skip it.
257
258 // Check that InVal is defined in the loop.
259 Instruction *Inst = cast<Instruction>(InVal);
260 if (!L->contains(Inst->getParent()))
261 continue;
Dan Gohman963fc812009-02-17 19:13:57 +0000262
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263 // Okay, this instruction has a user outside of the current loop
264 // and varies predictably *inside* the loop. Evaluate the value it
265 // contains when the loop exits, if possible.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000266 const SCEV* ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohmanaff14d62009-05-24 23:25:42 +0000267 if (!ExitValue->isLoopInvariant(L))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268 continue;
269
270 Changed = true;
271 ++NumReplaced;
Dan Gohman963fc812009-02-17 19:13:57 +0000272
Dan Gohman9a0303b2009-06-26 22:53:46 +0000273 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohman963fc812009-02-17 19:13:57 +0000274
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
276 << " LoopVal = " << *Inst << "\n";
277
278 PN->setIncomingValue(i, ExitVal);
Dan Gohman963fc812009-02-17 19:13:57 +0000279
Dan Gohman28055122009-05-12 02:17:14 +0000280 // If this instruction is dead now, delete it.
281 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohman963fc812009-02-17 19:13:57 +0000282
Dan Gohmanea999562009-06-22 00:15:15 +0000283 // If we're inserting code into the exit block rather than the
284 // preheader, we can (and have to) remove the PHI entirely.
285 // This is safe, because the NewVal won't be variant
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286 // in the loop, so we don't need an LCSSA phi node anymore.
Dan Gohmanea999562009-06-22 00:15:15 +0000287 if (ExitBlocks.size() == 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288 PN->replaceAllUsesWith(ExitVal);
Dan Gohman28055122009-05-12 02:17:14 +0000289 RecursivelyDeleteTriviallyDeadInstructions(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290 break;
291 }
292 }
Dan Gohman9a0303b2009-06-26 22:53:46 +0000293 if (ExitBlocks.size() != 1) {
294 // Clone the PHI and delete the original one. This lets IVUsers and
295 // any other maps purge the original user from their records.
296 PHINode *NewPN = PN->clone();
297 NewPN->takeName(PN);
298 NewPN->insertBefore(PN);
299 PN->replaceAllUsesWith(NewPN);
300 PN->eraseFromParent();
301 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000302 }
303 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304}
305
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000306void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000307 // First step. Check to see if there are any floating-point recurrences.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308 // If there are, change them into integer recurrences, permitting analysis by
309 // the SCEV routines.
310 //
311 BasicBlock *Header = L->getHeader();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312
Dan Gohman28055122009-05-12 02:17:14 +0000313 SmallVector<WeakVH, 8> PHIs;
314 for (BasicBlock::iterator I = Header->begin();
315 PHINode *PN = dyn_cast<PHINode>(I); ++I)
316 PHIs.push_back(PN);
317
318 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
319 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i]))
320 HandleFloatingPointIV(L, PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000321
Dan Gohman01c2ee72009-04-16 03:18:22 +0000322 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000323 // may not have been able to compute a trip count. Now that we've done some
324 // re-writing, the trip count may be computable.
325 if (Changed)
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000326 SE->forgetLoopBackedgeTakenCount(L);
Dale Johannesen3c25cb22009-04-15 23:31:51 +0000327}
328
Dan Gohmancacd2012009-02-12 22:19:27 +0000329bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohman28055122009-05-12 02:17:14 +0000330 IU = &getAnalysis<IVUsers>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331 LI = &getAnalysis<LoopInfo>();
332 SE = &getAnalysis<ScalarEvolution>();
Dan Gohman402142e2009-06-27 05:16:57 +0000333 DT = &getAnalysis<DominatorTree>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334 Changed = false;
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000335
Dan Gohman01c2ee72009-04-16 03:18:22 +0000336 // If there are any floating-point recurrences, attempt to
Dan Gohmanf3a060a2009-02-17 20:49:49 +0000337 // transform them to use integer recurrences.
338 RewriteNonIntegerIVs(L);
339
Dan Gohman28055122009-05-12 02:17:14 +0000340 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
Owen Andersonecd0cd72009-06-22 21:39:50 +0000341 const SCEV* BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342
Dan Gohman9a0303b2009-06-26 22:53:46 +0000343 // Create a rewriter object which we'll use to transform the code with.
344 SCEVExpander Rewriter(*SE);
345
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346 // Check to see if this loop has a computable loop-invariant execution count.
347 // If so, this means that we can compute the final value of any expressions
348 // that are recurrent in the loop, and substitute the exit values from the
349 // loop into any instructions outside of the loop that use the final values of
350 // the current expressions.
351 //
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000352 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman9a0303b2009-06-26 22:53:46 +0000353 RewriteLoopExitValues(L, BackedgeTakenCount, Rewriter);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000354
Dan Gohman28055122009-05-12 02:17:14 +0000355 // Compute the type of the largest recurrence expression, and decide whether
356 // a canonical induction variable should be inserted.
Dan Gohmancacd2012009-02-12 22:19:27 +0000357 const Type *LargestType = 0;
Dan Gohman28055122009-05-12 02:17:14 +0000358 bool NeedCannIV = false;
Dan Gohman76d5a0d2009-02-24 18:55:53 +0000359 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
360 LargestType = BackedgeTakenCount->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000361 LargestType = SE->getEffectiveSCEVType(LargestType);
Dan Gohman28055122009-05-12 02:17:14 +0000362 // If we have a known trip count and a single exit block, we'll be
363 // rewriting the loop exit test condition below, which requires a
364 // canonical induction variable.
365 if (ExitingBlock)
366 NeedCannIV = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000367 }
Dan Gohman28055122009-05-12 02:17:14 +0000368 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000369 const SCEV* Stride = IU->StrideOrder[i];
Dan Gohman28055122009-05-12 02:17:14 +0000370 const Type *Ty = SE->getEffectiveSCEVType(Stride->getType());
Dan Gohmancacd2012009-02-12 22:19:27 +0000371 if (!LargestType ||
Dan Gohman28055122009-05-12 02:17:14 +0000372 SE->getTypeSizeInBits(Ty) >
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000373 SE->getTypeSizeInBits(LargestType))
Dan Gohman28055122009-05-12 02:17:14 +0000374 LargestType = Ty;
375
Owen Andersonecd0cd72009-06-22 21:39:50 +0000376 std::map<const SCEV*, IVUsersOfOneStride *>::iterator SI =
Dan Gohman28055122009-05-12 02:17:14 +0000377 IU->IVUsesByStride.find(IU->StrideOrder[i]);
378 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
379
380 if (!SI->second->Users.empty())
381 NeedCannIV = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000382 }
383
Dan Gohman28055122009-05-12 02:17:14 +0000384 // Now that we know the largest of of the induction variable expressions
385 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohmancacd2012009-02-12 22:19:27 +0000386 Value *IndVar = 0;
Dan Gohman28055122009-05-12 02:17:14 +0000387 if (NeedCannIV) {
Dan Gohmanfc4d0712009-06-13 16:25:49 +0000388 // Check to see if the loop already has a canonical-looking induction
389 // variable. If one is present and it's wider than the planned canonical
390 // induction variable, temporarily remove it, so that the Rewriter
391 // doesn't attempt to reuse it.
392 PHINode *OldCannIV = L->getCanonicalInductionVariable();
393 if (OldCannIV) {
394 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
395 SE->getTypeSizeInBits(LargestType))
396 OldCannIV->removeFromParent();
397 else
398 OldCannIV = 0;
399 }
400
Dan Gohman9a0303b2009-06-26 22:53:46 +0000401 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohmanfc4d0712009-06-13 16:25:49 +0000402
Dan Gohmancacd2012009-02-12 22:19:27 +0000403 ++NumInserted;
404 Changed = true;
405 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohmanfc4d0712009-06-13 16:25:49 +0000406
407 // Now that the official induction variable is established, reinsert
408 // the old canonical-looking variable after it so that the IR remains
409 // consistent. It will be deleted as part of the dead-PHI deletion at
410 // the end of the pass.
411 if (OldCannIV)
412 OldCannIV->insertAfter(cast<Instruction>(IndVar));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000413 }
414
Dan Gohmancacd2012009-02-12 22:19:27 +0000415 // If we have a trip count expression, rewrite the loop's exit condition
416 // using it. We can currently only handle loops with a single exit.
Dan Gohman28055122009-05-12 02:17:14 +0000417 ICmpInst *NewICmp = 0;
418 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && ExitingBlock) {
419 assert(NeedCannIV &&
420 "LinearFunctionTestReplace requires a canonical induction variable");
Dan Gohmancacd2012009-02-12 22:19:27 +0000421 // Can't rewrite non-branch yet.
Dan Gohman28055122009-05-12 02:17:14 +0000422 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
423 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
424 ExitingBlock, BI, Rewriter);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000425 }
426
Edwin Törökacec1c02009-05-24 20:08:21 +0000427 // Rewrite IV-derived expressions. Clears the rewriter cache.
Dan Gohman9a0303b2009-06-26 22:53:46 +0000428 RewriteIVExpressions(L, LargestType, Rewriter);
Dan Gohmancacd2012009-02-12 22:19:27 +0000429
Dan Gohman9a0303b2009-06-26 22:53:46 +0000430 // The Rewriter may not be used from this point on.
Edwin Törökacec1c02009-05-24 20:08:21 +0000431
Dan Gohman28055122009-05-12 02:17:14 +0000432 // Loop-invariant instructions in the preheader that aren't used in the
433 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman9a0303b2009-06-26 22:53:46 +0000434 SinkUnusedInvariants(L);
Dan Gohman28055122009-05-12 02:17:14 +0000435
436 // For completeness, inform IVUsers of the IV use in the newly-created
437 // loop exit test instruction.
438 if (NewICmp)
439 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
440
441 // Clean up dead instructions.
442 DeleteDeadPHIs(L->getHeader());
443 // Check a post-condition.
444 assert(L->isLCSSAForm() && "Indvars did not leave the loop in lcssa form!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000445 return Changed;
446}
Devang Patelbda43802008-09-09 21:41:07 +0000447
Dan Gohman28055122009-05-12 02:17:14 +0000448void IndVarSimplify::RewriteIVExpressions(Loop *L, const Type *LargestType,
Dan Gohman9a0303b2009-06-26 22:53:46 +0000449 SCEVExpander &Rewriter) {
Dan Gohman28055122009-05-12 02:17:14 +0000450 SmallVector<WeakVH, 16> DeadInsts;
451
452 // Rewrite all induction variable expressions in terms of the canonical
453 // induction variable.
454 //
455 // If there were induction variables of other sizes or offsets, manually
456 // add the offsets to the primary induction variable and cast, avoiding
457 // the need for the code evaluation methods to insert induction variables
458 // of different sizes.
459 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000460 const SCEV* Stride = IU->StrideOrder[i];
Dan Gohman28055122009-05-12 02:17:14 +0000461
Owen Andersonecd0cd72009-06-22 21:39:50 +0000462 std::map<const SCEV*, IVUsersOfOneStride *>::iterator SI =
Dan Gohman28055122009-05-12 02:17:14 +0000463 IU->IVUsesByStride.find(IU->StrideOrder[i]);
464 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
465 ilist<IVStrideUse> &List = SI->second->Users;
466 for (ilist<IVStrideUse>::iterator UI = List.begin(),
467 E = List.end(); UI != E; ++UI) {
Dan Gohman28055122009-05-12 02:17:14 +0000468 Value *Op = UI->getOperandValToReplace();
Dan Gohmanfc4d0712009-06-13 16:25:49 +0000469 const Type *UseTy = Op->getType();
Dan Gohman28055122009-05-12 02:17:14 +0000470 Instruction *User = UI->getUser();
Dan Gohman28055122009-05-12 02:17:14 +0000471
472 // Compute the final addrec to expand into code.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000473 const SCEV* AR = IU->getReplacementExpr(*UI);
Dan Gohman28055122009-05-12 02:17:14 +0000474
Dan Gohman423ed6c2009-06-24 01:18:18 +0000475 // FIXME: It is an extremely bad idea to indvar substitute anything more
476 // complex than affine induction variables. Doing so will put expensive
477 // polynomial evaluations inside of the loop, and the str reduction pass
478 // currently can only reduce affine polynomials. For now just disable
479 // indvar subst on anything more complex than an affine addrec, unless
480 // it can be expanded to a trivial value.
481 if (!AR->isLoopInvariant(L) && !Stride->isLoopInvariant(L))
482 continue;
Dan Gohman17370302009-06-03 19:11:31 +0000483
Dan Gohman402142e2009-06-27 05:16:57 +0000484 // Determine the insertion point for this user. By default, insert
485 // immediately before the user. The SCEVExpander class will automatically
486 // hoist loop invariants out of the loop. For PHI nodes, there may be
487 // multiple uses, so compute the nearest common dominator for the
488 // incoming blocks.
Dan Gohman9a0303b2009-06-26 22:53:46 +0000489 Instruction *InsertPt = User;
490 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
Dan Gohman402142e2009-06-27 05:16:57 +0000491 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Dan Gohman9a0303b2009-06-26 22:53:46 +0000492 if (PHI->getIncomingValue(i) == Op) {
Dan Gohman402142e2009-06-27 05:16:57 +0000493 if (InsertPt == User)
494 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
495 else
496 InsertPt =
497 DT->findNearestCommonDominator(InsertPt->getParent(),
498 PHI->getIncomingBlock(i))
499 ->getTerminator();
Dan Gohman9a0303b2009-06-26 22:53:46 +0000500 }
501
Dan Gohman423ed6c2009-06-24 01:18:18 +0000502 // Now expand it into actual Instructions and patch it into place.
503 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
Dan Gohman28055122009-05-12 02:17:14 +0000504
505 // Patch the new value into place.
506 if (Op->hasName())
507 NewVal->takeName(Op);
508 User->replaceUsesOfWith(Op, NewVal);
509 UI->setOperandValToReplace(NewVal);
510 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *Op
511 << " into = " << *NewVal << "\n";
512 ++NumRemoved;
513 Changed = true;
514
515 // The old value may be dead now.
516 DeadInsts.push_back(Op);
517 }
518 }
519
Edwin Törökacec1c02009-05-24 20:08:21 +0000520 // Clear the rewriter cache, because values that are in the rewriter's cache
521 // can be deleted in the loop below, causing the AssertingVH in the cache to
522 // trigger.
523 Rewriter.clear();
Dan Gohman28055122009-05-12 02:17:14 +0000524 // Now that we're done iterating through lists, clean up any instructions
525 // which are now dead.
526 while (!DeadInsts.empty()) {
527 Instruction *Inst = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
528 if (Inst)
529 RecursivelyDeleteTriviallyDeadInstructions(Inst);
530 }
531}
532
533/// If there's a single exit block, sink any loop-invariant values that
534/// were defined in the preheader but not used inside the loop into the
535/// exit block to reduce register pressure in the loop.
Dan Gohman9a0303b2009-06-26 22:53:46 +0000536void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
Dan Gohman28055122009-05-12 02:17:14 +0000537 BasicBlock *ExitBlock = L->getExitBlock();
538 if (!ExitBlock) return;
539
Dan Gohman9a0303b2009-06-26 22:53:46 +0000540 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
Dan Gohman28055122009-05-12 02:17:14 +0000541 BasicBlock *Preheader = L->getLoopPreheader();
542 BasicBlock::iterator I = Preheader->getTerminator();
543 while (I != Preheader->begin()) {
544 --I;
Dan Gohman9a0303b2009-06-26 22:53:46 +0000545 // New instructions were inserted at the end of the preheader.
546 if (isa<PHINode>(I))
Dan Gohman28055122009-05-12 02:17:14 +0000547 break;
Dan Gohman9a0303b2009-06-26 22:53:46 +0000548 if (I->isTrapping())
549 continue;
Dan Gohman28055122009-05-12 02:17:14 +0000550 // Determine if there is a use in or before the loop (direct or
551 // otherwise).
552 bool UsedInLoop = false;
553 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
554 UI != UE; ++UI) {
555 BasicBlock *UseBB = cast<Instruction>(UI)->getParent();
556 if (PHINode *P = dyn_cast<PHINode>(UI)) {
557 unsigned i =
558 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
559 UseBB = P->getIncomingBlock(i);
560 }
561 if (UseBB == Preheader || L->contains(UseBB)) {
562 UsedInLoop = true;
563 break;
564 }
565 }
566 // If there is, the def must remain in the preheader.
567 if (UsedInLoop)
568 continue;
569 // Otherwise, sink it to the exit block.
570 Instruction *ToMove = I;
571 bool Done = false;
572 if (I != Preheader->begin())
573 --I;
574 else
575 Done = true;
Dan Gohman9a0303b2009-06-26 22:53:46 +0000576 ToMove->moveBefore(InsertPt);
Dan Gohman28055122009-05-12 02:17:14 +0000577 if (Done)
578 break;
Dan Gohman9a0303b2009-06-26 22:53:46 +0000579 InsertPt = ToMove;
Dan Gohman28055122009-05-12 02:17:14 +0000580 }
581}
582
Devang Patelb8ccf572008-11-18 00:40:02 +0000583/// Return true if it is OK to use SIToFPInst for an inducation variable
584/// with given inital and exit values.
585static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
586 uint64_t intIV, uint64_t intEV) {
587
Dan Gohman963fc812009-02-17 19:13:57 +0000588 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patelb8ccf572008-11-18 00:40:02 +0000589 return true;
590
591 // If the iteration range can be handled by SIToFPInst then use it.
592 APInt Max = APInt::getSignedMaxValue(32);
Dale Johannesen0a12b4c2009-05-14 16:47:34 +0000593 if (Max.getZExtValue() > static_cast<uint64_t>(abs64(intEV - intIV)))
Devang Patelb8ccf572008-11-18 00:40:02 +0000594 return true;
Dan Gohman963fc812009-02-17 19:13:57 +0000595
Devang Patelb8ccf572008-11-18 00:40:02 +0000596 return false;
597}
598
599/// convertToInt - Convert APF to an integer, if possible.
Devang Patele2ba01d2008-11-17 23:27:13 +0000600static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
601
602 bool isExact = false;
Evan Cheng30e65f62008-11-26 01:11:57 +0000603 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
604 return false;
Dan Gohman963fc812009-02-17 19:13:57 +0000605 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patele2ba01d2008-11-17 23:27:13 +0000606 APFloat::rmTowardZero, &isExact)
607 != APFloat::opOK)
608 return false;
Dan Gohman963fc812009-02-17 19:13:57 +0000609 if (!isExact)
Devang Patele2ba01d2008-11-17 23:27:13 +0000610 return false;
611 return true;
612
613}
614
Devang Patel7ca23c92008-11-03 18:32:19 +0000615/// HandleFloatingPointIV - If the loop has floating induction variable
616/// then insert corresponding integer induction variable if possible.
Devang Patelc8dac622008-11-17 21:32:02 +0000617/// For example,
618/// for(double i = 0; i < 10000; ++i)
619/// bar(i)
620/// is converted into
621/// for(int i = 0; i < 10000; ++i)
622/// bar((double)i);
623///
Dan Gohman28055122009-05-12 02:17:14 +0000624void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH) {
Devang Patel7ca23c92008-11-03 18:32:19 +0000625
Devang Patelc8dac622008-11-17 21:32:02 +0000626 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
627 unsigned BackEdge = IncomingEdge^1;
Dan Gohman963fc812009-02-17 19:13:57 +0000628
Devang Patelc8dac622008-11-17 21:32:02 +0000629 // Check incoming value.
Devang Patele2ba01d2008-11-17 23:27:13 +0000630 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
631 if (!InitValue) return;
632 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
633 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
634 return;
635
636 // Check IV increment. Reject this PH if increement operation is not
637 // an add or increment value can not be represented by an integer.
Dan Gohman963fc812009-02-17 19:13:57 +0000638 BinaryOperator *Incr =
Devang Patelc8dac622008-11-17 21:32:02 +0000639 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
640 if (!Incr) return;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000641 if (Incr->getOpcode() != Instruction::FAdd) return;
Devang Patelc8dac622008-11-17 21:32:02 +0000642 ConstantFP *IncrValue = NULL;
643 unsigned IncrVIndex = 1;
644 if (Incr->getOperand(1) == PH)
645 IncrVIndex = 0;
646 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
647 if (!IncrValue) return;
Devang Patele2ba01d2008-11-17 23:27:13 +0000648 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
649 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
650 return;
Dan Gohman963fc812009-02-17 19:13:57 +0000651
Devang Patele2ba01d2008-11-17 23:27:13 +0000652 // Check Incr uses. One user is PH and the other users is exit condition used
653 // by the conditional terminator.
Devang Patelc8dac622008-11-17 21:32:02 +0000654 Value::use_iterator IncrUse = Incr->use_begin();
655 Instruction *U1 = cast<Instruction>(IncrUse++);
656 if (IncrUse == Incr->use_end()) return;
657 Instruction *U2 = cast<Instruction>(IncrUse++);
658 if (IncrUse != Incr->use_end()) return;
Dan Gohman963fc812009-02-17 19:13:57 +0000659
Devang Patelc8dac622008-11-17 21:32:02 +0000660 // Find exit condition.
661 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
662 if (!EC)
663 EC = dyn_cast<FCmpInst>(U2);
664 if (!EC) return;
665
666 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
667 if (!BI->isConditional()) return;
668 if (BI->getCondition() != EC) return;
Devang Patel7ca23c92008-11-03 18:32:19 +0000669 }
Devang Patel7ca23c92008-11-03 18:32:19 +0000670
Devang Patele2ba01d2008-11-17 23:27:13 +0000671 // Find exit value. If exit value can not be represented as an interger then
672 // do not handle this floating point PH.
Devang Patelc8dac622008-11-17 21:32:02 +0000673 ConstantFP *EV = NULL;
674 unsigned EVIndex = 1;
675 if (EC->getOperand(1) == Incr)
676 EVIndex = 0;
677 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
678 if (!EV) return;
Devang Patelc8dac622008-11-17 21:32:02 +0000679 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patele2ba01d2008-11-17 23:27:13 +0000680 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patelc8dac622008-11-17 21:32:02 +0000681 return;
Dan Gohman963fc812009-02-17 19:13:57 +0000682
Devang Patelc8dac622008-11-17 21:32:02 +0000683 // Find new predicate for integer comparison.
684 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
685 switch (EC->getPredicate()) {
686 case CmpInst::FCMP_OEQ:
687 case CmpInst::FCMP_UEQ:
688 NewPred = CmpInst::ICMP_EQ;
689 break;
690 case CmpInst::FCMP_OGT:
691 case CmpInst::FCMP_UGT:
692 NewPred = CmpInst::ICMP_UGT;
693 break;
694 case CmpInst::FCMP_OGE:
695 case CmpInst::FCMP_UGE:
696 NewPred = CmpInst::ICMP_UGE;
697 break;
698 case CmpInst::FCMP_OLT:
699 case CmpInst::FCMP_ULT:
700 NewPred = CmpInst::ICMP_ULT;
701 break;
702 case CmpInst::FCMP_OLE:
703 case CmpInst::FCMP_ULE:
704 NewPred = CmpInst::ICMP_ULE;
705 break;
706 default:
707 break;
Devang Patel7ca23c92008-11-03 18:32:19 +0000708 }
Devang Patelc8dac622008-11-17 21:32:02 +0000709 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohman963fc812009-02-17 19:13:57 +0000710
Devang Patelc8dac622008-11-17 21:32:02 +0000711 // Insert new integer induction variable.
712 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
713 PH->getName()+".int", PH);
Devang Patele2ba01d2008-11-17 23:27:13 +0000714 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patelc8dac622008-11-17 21:32:02 +0000715 PH->getIncomingBlock(IncomingEdge));
716
Dan Gohman963fc812009-02-17 19:13:57 +0000717 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
718 ConstantInt::get(Type::Int32Ty,
Devang Patele2ba01d2008-11-17 23:27:13 +0000719 newIncrValue),
Devang Patelc8dac622008-11-17 21:32:02 +0000720 Incr->getName()+".int", Incr);
721 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
722
Dale Johannesen6cb3e262009-04-27 21:03:15 +0000723 // The back edge is edge 1 of newPHI, whatever it may have been in the
724 // original PHI.
Devang Patelc8dac622008-11-17 21:32:02 +0000725 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
Dale Johannesen6cb3e262009-04-27 21:03:15 +0000726 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(1) : NewEV);
727 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(1));
Dan Gohman963fc812009-02-17 19:13:57 +0000728 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
Devang Patelc8dac622008-11-17 21:32:02 +0000729 EC->getParent()->getTerminator());
Dan Gohman963fc812009-02-17 19:13:57 +0000730
Dan Gohman28055122009-05-12 02:17:14 +0000731 // In the following deltions, PH may become dead and may be deleted.
732 // Use a WeakVH to observe whether this happens.
733 WeakVH WeakPH = PH;
734
Devang Patelc8dac622008-11-17 21:32:02 +0000735 // Delete old, floating point, exit comparision instruction.
Dan Gohmanb8098742009-05-24 18:09:01 +0000736 NewEC->takeName(EC);
Devang Patelc8dac622008-11-17 21:32:02 +0000737 EC->replaceAllUsesWith(NewEC);
Dan Gohman28055122009-05-12 02:17:14 +0000738 RecursivelyDeleteTriviallyDeadInstructions(EC);
Dan Gohman963fc812009-02-17 19:13:57 +0000739
Devang Patelc8dac622008-11-17 21:32:02 +0000740 // Delete old, floating point, increment instruction.
741 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman28055122009-05-12 02:17:14 +0000742 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohman963fc812009-02-17 19:13:57 +0000743
Dan Gohman28055122009-05-12 02:17:14 +0000744 // Replace floating induction variable, if it isn't already deleted.
745 // Give SIToFPInst preference over UIToFPInst because it is faster on
746 // platforms that are widely used.
747 if (WeakPH && !PH->use_empty()) {
748 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
749 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
750 PH->getParent()->getFirstNonPHI());
751 PH->replaceAllUsesWith(Conv);
752 } else {
753 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
754 PH->getParent()->getFirstNonPHI());
755 PH->replaceAllUsesWith(Conv);
756 }
757 RecursivelyDeleteTriviallyDeadInstructions(PH);
Devang Patele2ba01d2008-11-17 23:27:13 +0000758 }
Devang Patel7ca23c92008-11-03 18:32:19 +0000759
Dan Gohman28055122009-05-12 02:17:14 +0000760 // Add a new IVUsers entry for the newly-created integer PHI.
761 IU->AddUsersIfInteresting(NewPHI);
762}