blob: b5fdd0c4a17ab366369d8319f2ff2f373c903660 [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
80 IndVarSimplify() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000081
Dan Gohman5668cf72009-07-15 01:26:32 +000082 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman60f8a632009-02-17 20:49:49 +000083
Dan Gohman5668cf72009-07-15 01:26:32 +000084 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
85 AU.addRequired<DominatorTree>();
86 AU.addRequired<LoopInfo>();
87 AU.addRequired<ScalarEvolution>();
88 AU.addRequiredID(LoopSimplifyID);
89 AU.addRequiredID(LCSSAID);
90 AU.addRequired<IVUsers>();
91 AU.addPreserved<ScalarEvolution>();
92 AU.addPreservedID(LoopSimplifyID);
93 AU.addPreservedID(LCSSAID);
94 AU.addPreserved<IVUsers>();
95 AU.setPreservesCFG();
96 }
Chris Lattner15cad752003-12-23 07:47:09 +000097
Chris Lattner40bf8b42004-04-02 20:24:31 +000098 private:
Devang Patel5ee99972007-03-07 06:39:01 +000099
Dan Gohman60f8a632009-02-17 20:49:49 +0000100 void RewriteNonIntegerIVs(Loop *L);
101
Dan Gohman0bba49c2009-07-07 17:06:11 +0000102 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
Dan Gohmana5758712009-02-17 15:57:39 +0000103 Value *IndVar,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000104 BasicBlock *ExitingBlock,
105 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000106 SCEVExpander &Rewriter);
Dan Gohman454d26d2010-02-22 04:11:59 +0000107 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000108
Dan Gohman454d26d2010-02-22 04:11:59 +0000109 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000110
Dan Gohman667d7872009-06-26 22:53:46 +0000111 void SinkUnusedInvariants(Loop *L);
Dan Gohman81db61a2009-05-12 02:17:14 +0000112
113 void HandleFloatingPointIV(Loop *L, PHINode *PH);
Chris Lattner3324e712003-12-22 03:58:44 +0000114 };
Chris Lattner5e761402002-09-10 05:24:05 +0000115}
Chris Lattner394437f2001-12-04 04:32:29 +0000116
Dan Gohman844731a2008-05-13 00:00:25 +0000117char IndVarSimplify::ID = 0;
118static RegisterPass<IndVarSimplify>
119X("indvars", "Canonicalize Induction Variables");
120
Daniel Dunbar394f0442008-10-22 23:32:42 +0000121Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000122 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000123}
124
Chris Lattner40bf8b42004-04-02 20:24:31 +0000125/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000126/// 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 Gohman81db61a2009-05-12 02:17:14 +0000130ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
Dan Gohman0bba49c2009-07-07 17:06:11 +0000131 const SCEV *BackedgeTakenCount,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000132 Value *IndVar,
133 BasicBlock *ExitingBlock,
134 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000135 SCEVExpander &Rewriter) {
Chris Lattnerd2440572004-04-15 20:26:22 +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 Gohmanc2390b12009-02-12 22:19:27 +0000139 Value *CmpIndVar;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000140 const SCEV *RHS = BackedgeTakenCount;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000141 if (ExitingBlock == L->getLoopLatch()) {
Dan Gohman46bdfb02009-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.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000145 const SCEV *Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
146 const SCEV *N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000147 SE->getAddExpr(BackedgeTakenCount,
148 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
Dan Gohmanc2390b12009-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 Gohman46bdfb02009-02-24 18:55:53 +0000152 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000153 } else {
154 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-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 Gohmanc2390b12009-02-12 22:19:27 +0000159 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000160
Dan Gohman46bdfb02009-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 Gohmanc2390b12009-02-12 22:19:27 +0000164 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Chris Lattnerd2440572004-04-15 20:26:22 +0000165 } else {
166 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000167 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
168 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000169 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000170 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000171
Dan Gohman667d7872009-06-26 22:53:46 +0000172 // Expand the code for the iteration count.
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000173 assert(RHS->isLoopInvariant(L) &&
174 "Computed iteration count is not loop invariant!");
Dan Gohman667d7872009-06-26 22:53:46 +0000175 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000176
Reid Spencere4d87aa2006-12-23 06:05:41 +0000177 // Insert a new icmp_ne or icmp_eq instruction before the branch.
178 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000179 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000180 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000181 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000182 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000183
David Greenef67ef312010-01-05 01:27:06 +0000184 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
Chris Lattnerbdff5482009-08-23 04:37:46 +0000185 << " LHS:" << *CmpIndVar << '\n'
186 << " op:\t"
187 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
188 << " RHS:\t" << *RHS << "\n");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000189
Owen Anderson333c4002009-07-09 23:48:35 +0000190 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
Dan Gohman81db61a2009-05-12 02:17:14 +0000191
Dan Gohman24440802010-02-22 02:07:36 +0000192 Value *OrigCond = BI->getCondition();
Dan Gohman95bdbfa2009-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 Gohman81db61a2009-05-12 02:17:14 +0000199 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
200
Chris Lattner40bf8b42004-04-02 20:24:31 +0000201 ++NumLFTR;
202 Changed = true;
Dan Gohman81db61a2009-05-12 02:17:14 +0000203 return Cond;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000204}
205
Chris Lattner40bf8b42004-04-02 20:24:31 +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 Gohman81db61a2009-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 Gohman890f92b2009-04-18 17:56:28 +0000216void IndVarSimplify::RewriteLoopExitValues(Loop *L,
Dan Gohman667d7872009-06-26 22:53:46 +0000217 SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000218 // Verify the input to the pass in already in LCSSA form.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000219 assert(L->isLCSSAForm(*DT));
Dan Gohman81db61a2009-05-12 02:17:14 +0000220
Devang Patelb7211a22007-08-21 00:31:24 +0000221 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000222 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000223
Chris Lattner9f3d7382007-03-04 03:43:23 +0000224 // Find all values that are computed inside the loop, but used outside of it.
225 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
226 // the exit blocks of the loop to find them.
227 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
228 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000229
Chris Lattner9f3d7382007-03-04 03:43:23 +0000230 // If there are no PHI nodes in this exit block, then no values defined
231 // inside the loop are used on this path, skip it.
232 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
233 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000234
Chris Lattner9f3d7382007-03-04 03:43:23 +0000235 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000236
Chris Lattner9f3d7382007-03-04 03:43:23 +0000237 // Iterate over all of the PHI nodes.
238 BasicBlock::iterator BBI = ExitBB->begin();
239 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000240 if (PN->use_empty())
241 continue; // dead use, don't replace it
Dan Gohman814f2b22010-02-18 21:34:02 +0000242
243 // SCEV only supports integer expressions for now.
244 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
245 continue;
246
Dale Johannesen45a2d7d2010-02-19 07:14:22 +0000247 // It's necessary to tell ScalarEvolution about this explicitly so that
248 // it can walk the def-use list and forget all SCEVs, as it may not be
249 // watching the PHI itself. Once the new exit value is in place, there
250 // may not be a def-use connection between the loop and every instruction
251 // which got a SCEVAddRecExpr for that loop.
252 SE->forgetValue(PN);
253
Chris Lattner9f3d7382007-03-04 03:43:23 +0000254 // Iterate over all of the values in all the PHI nodes.
255 for (unsigned i = 0; i != NumPreds; ++i) {
256 // If the value being merged in is not integer or is not defined
257 // in the loop, skip it.
258 Value *InVal = PN->getIncomingValue(i);
Dan Gohman814f2b22010-02-18 21:34:02 +0000259 if (!isa<Instruction>(InVal))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000260 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000261
Chris Lattner9f3d7382007-03-04 03:43:23 +0000262 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000263 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000264 continue; // The Block is in a subloop, skip it.
265
266 // Check that InVal is defined in the loop.
267 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman92329c72009-12-18 01:24:09 +0000268 if (!L->contains(Inst))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000269 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000270
Chris Lattner9f3d7382007-03-04 03:43:23 +0000271 // Okay, this instruction has a user outside of the current loop
272 // and varies predictably *inside* the loop. Evaluate the value it
273 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000274 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +0000275 if (!ExitValue->isLoopInvariant(L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000276 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000277
Chris Lattner9f3d7382007-03-04 03:43:23 +0000278 Changed = true;
279 ++NumReplaced;
Dan Gohmancafb8132009-02-17 19:13:57 +0000280
Dan Gohman667d7872009-06-26 22:53:46 +0000281 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000282
David Greenef67ef312010-01-05 01:27:06 +0000283 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000284 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000285
286 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000287
Dan Gohman81db61a2009-05-12 02:17:14 +0000288 // If this instruction is dead now, delete it.
289 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000290
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000291 if (NumPreds == 1) {
292 // Completely replace a single-pred PHI. This is safe, because the
293 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
294 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000295 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000296 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000297 }
298 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000299 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000300 // Clone the PHI and delete the original one. This lets IVUsers and
301 // any other maps purge the original user from their records.
Devang Patel50b6e332009-10-27 22:16:29 +0000302 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohman667d7872009-06-26 22:53:46 +0000303 NewPN->takeName(PN);
304 NewPN->insertBefore(PN);
305 PN->replaceAllUsesWith(NewPN);
306 PN->eraseFromParent();
307 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000308 }
309 }
Dan Gohman472fdf72010-03-20 03:53:53 +0000310
311 // The insertion point instruction may have been deleted; clear it out
312 // so that the rewriter doesn't trip over it later.
313 Rewriter.clearInsertPoint();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000314}
315
Dan Gohman60f8a632009-02-17 20:49:49 +0000316void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000317 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000318 // If there are, change them into integer recurrences, permitting analysis by
319 // the SCEV routines.
320 //
321 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000322
Dan Gohman81db61a2009-05-12 02:17:14 +0000323 SmallVector<WeakVH, 8> PHIs;
324 for (BasicBlock::iterator I = Header->begin();
325 PHINode *PN = dyn_cast<PHINode>(I); ++I)
326 PHIs.push_back(PN);
327
328 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
329 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i]))
330 HandleFloatingPointIV(L, PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000331
Dan Gohman2d1be872009-04-16 03:18:22 +0000332 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000333 // may not have been able to compute a trip count. Now that we've done some
334 // re-writing, the trip count may be computable.
335 if (Changed)
Dan Gohman4c7279a2009-10-31 15:04:55 +0000336 SE->forgetLoop(L);
Dale Johannesenc671d892009-04-15 23:31:51 +0000337}
338
Dan Gohmanc2390b12009-02-12 22:19:27 +0000339bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000340 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +0000341 LI = &getAnalysis<LoopInfo>();
342 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +0000343 DT = &getAnalysis<DominatorTree>();
Devang Patel5ee99972007-03-07 06:39:01 +0000344 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +0000345
Dan Gohman2d1be872009-04-16 03:18:22 +0000346 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +0000347 // transform them to use integer recurrences.
348 RewriteNonIntegerIVs(L);
349
Dan Gohman81db61a2009-05-12 02:17:14 +0000350 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
Dan Gohman0bba49c2009-07-07 17:06:11 +0000351 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +0000352
Dan Gohman667d7872009-06-26 22:53:46 +0000353 // Create a rewriter object which we'll use to transform the code with.
354 SCEVExpander Rewriter(*SE);
355
Chris Lattner40bf8b42004-04-02 20:24:31 +0000356 // Check to see if this loop has a computable loop-invariant execution count.
357 // If so, this means that we can compute the final value of any expressions
358 // that are recurrent in the loop, and substitute the exit values from the
359 // loop into any instructions outside of the loop that use the final values of
360 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000361 //
Dan Gohman46bdfb02009-02-24 18:55:53 +0000362 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman454d26d2010-02-22 04:11:59 +0000363 RewriteLoopExitValues(L, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +0000364
Dan Gohman81db61a2009-05-12 02:17:14 +0000365 // Compute the type of the largest recurrence expression, and decide whether
366 // a canonical induction variable should be inserted.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000367 const Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000368 bool NeedCannIV = false;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000369 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
370 LargestType = BackedgeTakenCount->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000371 LargestType = SE->getEffectiveSCEVType(LargestType);
Dan Gohman81db61a2009-05-12 02:17:14 +0000372 // If we have a known trip count and a single exit block, we'll be
373 // rewriting the loop exit test condition below, which requires a
374 // canonical induction variable.
375 if (ExitingBlock)
376 NeedCannIV = true;
Chris Lattnerf50af082004-04-17 18:08:33 +0000377 }
Dan Gohman572645c2010-02-12 10:34:29 +0000378 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
379 const Type *Ty =
380 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000381 if (!LargestType ||
Dan Gohman81db61a2009-05-12 02:17:14 +0000382 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000383 SE->getTypeSizeInBits(LargestType))
Dan Gohman81db61a2009-05-12 02:17:14 +0000384 LargestType = Ty;
Dan Gohman572645c2010-02-12 10:34:29 +0000385 NeedCannIV = true;
Chris Lattner6148c022001-12-03 17:28:42 +0000386 }
387
Dan Gohmanf451cb82010-02-10 16:03:48 +0000388 // Now that we know the largest of the induction variable expressions
Dan Gohman81db61a2009-05-12 02:17:14 +0000389 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000390 Value *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000391 if (NeedCannIV) {
Dan Gohman85669632010-02-25 06:57:05 +0000392 // Check to see if the loop already has any canonical-looking induction
393 // variables. If any are present and wider than the planned canonical
394 // induction variable, temporarily remove them, so that the Rewriter
395 // doesn't attempt to reuse them.
396 SmallVector<PHINode *, 2> OldCannIVs;
397 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
Dan Gohman4d8414f2009-06-13 16:25:49 +0000398 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
399 SE->getTypeSizeInBits(LargestType))
400 OldCannIV->removeFromParent();
401 else
Dan Gohman85669632010-02-25 06:57:05 +0000402 break;
403 OldCannIVs.push_back(OldCannIV);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000404 }
405
Dan Gohman667d7872009-06-26 22:53:46 +0000406 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000407
Dan Gohmanc2390b12009-02-12 22:19:27 +0000408 ++NumInserted;
409 Changed = true;
David Greenef67ef312010-01-05 01:27:06 +0000410 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +0000411
412 // Now that the official induction variable is established, reinsert
Dan Gohman85669632010-02-25 06:57:05 +0000413 // any old canonical-looking variables after it so that the IR remains
414 // consistent. They will be deleted as part of the dead-PHI deletion at
Dan Gohman4d8414f2009-06-13 16:25:49 +0000415 // the end of the pass.
Dan Gohman85669632010-02-25 06:57:05 +0000416 while (!OldCannIVs.empty()) {
417 PHINode *OldCannIV = OldCannIVs.pop_back_val();
418 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
419 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000420 }
Chris Lattner15cad752003-12-23 07:47:09 +0000421
Dan Gohmanc2390b12009-02-12 22:19:27 +0000422 // If we have a trip count expression, rewrite the loop's exit condition
423 // using it. We can currently only handle loops with a single exit.
Dan Gohman81db61a2009-05-12 02:17:14 +0000424 ICmpInst *NewICmp = 0;
Dan Gohman85669632010-02-25 06:57:05 +0000425 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
426 !BackedgeTakenCount->isZero() &&
427 ExitingBlock) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000428 assert(NeedCannIV &&
429 "LinearFunctionTestReplace requires a canonical induction variable");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000430 // Can't rewrite non-branch yet.
Dan Gohman81db61a2009-05-12 02:17:14 +0000431 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
432 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
433 ExitingBlock, BI, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000434 }
435
Torok Edwin3d431382009-05-24 20:08:21 +0000436 // Rewrite IV-derived expressions. Clears the rewriter cache.
Dan Gohman454d26d2010-02-22 04:11:59 +0000437 RewriteIVExpressions(L, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000438
Dan Gohman667d7872009-06-26 22:53:46 +0000439 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +0000440
Dan Gohman81db61a2009-05-12 02:17:14 +0000441 // Loop-invariant instructions in the preheader that aren't used in the
442 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +0000443 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +0000444
445 // For completeness, inform IVUsers of the IV use in the newly-created
446 // loop exit test instruction.
447 if (NewICmp)
448 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
449
450 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +0000451 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +0000452 // Check a post-condition.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000453 assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +0000454 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000455}
Devang Pateld22a8492008-09-09 21:41:07 +0000456
Dan Gohman454d26d2010-02-22 04:11:59 +0000457void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000458 SmallVector<WeakVH, 16> DeadInsts;
459
460 // Rewrite all induction variable expressions in terms of the canonical
461 // induction variable.
462 //
463 // If there were induction variables of other sizes or offsets, manually
464 // add the offsets to the primary induction variable and cast, avoiding
465 // the need for the code evaluation methods to insert induction variables
466 // of different sizes.
Dan Gohman572645c2010-02-12 10:34:29 +0000467 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
468 const SCEV *Stride = UI->getStride();
469 Value *Op = UI->getOperandValToReplace();
470 const Type *UseTy = Op->getType();
471 Instruction *User = UI->getUser();
Dan Gohman81db61a2009-05-12 02:17:14 +0000472
Dan Gohman572645c2010-02-12 10:34:29 +0000473 // Compute the final addrec to expand into code.
474 const SCEV *AR = IU->getReplacementExpr(*UI);
Dan Gohman81db61a2009-05-12 02:17:14 +0000475
Dan Gohman572645c2010-02-12 10:34:29 +0000476 // Evaluate the expression out of the loop, if possible.
477 if (!L->contains(UI->getUser())) {
478 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
479 if (ExitVal->isLoopInvariant(L))
480 AR = ExitVal;
Dan Gohman81db61a2009-05-12 02:17:14 +0000481 }
Dan Gohman572645c2010-02-12 10:34:29 +0000482
483 // FIXME: It is an extremely bad idea to indvar substitute anything more
484 // complex than affine induction variables. Doing so will put expensive
485 // polynomial evaluations inside of the loop, and the str reduction pass
486 // currently can only reduce affine polynomials. For now just disable
487 // indvar subst on anything more complex than an affine addrec, unless
488 // it can be expanded to a trivial value.
489 if (!AR->isLoopInvariant(L) && !Stride->isLoopInvariant(L))
490 continue;
491
492 // Determine the insertion point for this user. By default, insert
493 // immediately before the user. The SCEVExpander class will automatically
494 // hoist loop invariants out of the loop. For PHI nodes, there may be
495 // multiple uses, so compute the nearest common dominator for the
496 // incoming blocks.
497 Instruction *InsertPt = User;
498 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
499 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
500 if (PHI->getIncomingValue(i) == Op) {
501 if (InsertPt == User)
502 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
503 else
504 InsertPt =
505 DT->findNearestCommonDominator(InsertPt->getParent(),
506 PHI->getIncomingBlock(i))
507 ->getTerminator();
508 }
509
510 // Now expand it into actual Instructions and patch it into place.
511 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
512
Dan Gohmand7bfd002010-04-02 14:48:31 +0000513 // Inform ScalarEvolution that this value is changing. The change doesn't
514 // affect its value, but it does potentially affect which use lists the
515 // value will be on after the replacement, which affects ScalarEvolution's
516 // ability to walk use lists and drop dangling pointers when a value is
517 // deleted.
518 SE->forgetValue(User);
519
Dan Gohman572645c2010-02-12 10:34:29 +0000520 // Patch the new value into place.
521 if (Op->hasName())
522 NewVal->takeName(Op);
523 User->replaceUsesOfWith(Op, NewVal);
524 UI->setOperandValToReplace(NewVal);
525 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
526 << " into = " << *NewVal << "\n");
527 ++NumRemoved;
528 Changed = true;
529
530 // The old value may be dead now.
531 DeadInsts.push_back(Op);
Dan Gohman81db61a2009-05-12 02:17:14 +0000532 }
533
Torok Edwin3d431382009-05-24 20:08:21 +0000534 // Clear the rewriter cache, because values that are in the rewriter's cache
535 // can be deleted in the loop below, causing the AssertingVH in the cache to
536 // trigger.
537 Rewriter.clear();
Dan Gohman81db61a2009-05-12 02:17:14 +0000538 // Now that we're done iterating through lists, clean up any instructions
539 // which are now dead.
Dan Gohmana10756e2010-01-21 02:09:26 +0000540 while (!DeadInsts.empty())
541 if (Instruction *Inst =
542 dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
Dan Gohman81db61a2009-05-12 02:17:14 +0000543 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohman81db61a2009-05-12 02:17:14 +0000544}
545
546/// If there's a single exit block, sink any loop-invariant values that
547/// were defined in the preheader but not used inside the loop into the
548/// exit block to reduce register pressure in the loop.
Dan Gohman667d7872009-06-26 22:53:46 +0000549void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000550 BasicBlock *ExitBlock = L->getExitBlock();
551 if (!ExitBlock) return;
552
Dan Gohman81db61a2009-05-12 02:17:14 +0000553 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman03e896b2009-11-05 21:11:53 +0000554 if (!Preheader) return;
555
556 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
Dan Gohman81db61a2009-05-12 02:17:14 +0000557 BasicBlock::iterator I = Preheader->getTerminator();
558 while (I != Preheader->begin()) {
559 --I;
Dan Gohman667d7872009-06-26 22:53:46 +0000560 // New instructions were inserted at the end of the preheader.
561 if (isa<PHINode>(I))
Dan Gohman81db61a2009-05-12 02:17:14 +0000562 break;
Bill Wendling87a10f52010-03-23 21:15:59 +0000563
Eli Friedman0c77db32009-07-15 22:48:29 +0000564 // Don't move instructions which might have side effects, since the side
Bill Wendling87a10f52010-03-23 21:15:59 +0000565 // effects need to complete before instructions inside the loop. Also don't
566 // move instructions which might read memory, since the loop may modify
567 // memory. Note that it's okay if the instruction might have undefined
568 // behavior: LoopSimplify guarantees that the preheader dominates the exit
569 // block.
Eli Friedman0c77db32009-07-15 22:48:29 +0000570 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Dan Gohman667d7872009-06-26 22:53:46 +0000571 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000572
Devang Patel7b9f6b12010-03-15 22:23:03 +0000573 // Skip debug info intrinsics.
574 if (isa<DbgInfoIntrinsic>(I))
575 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000576
Dan Gohman76f497a2009-08-25 17:42:10 +0000577 // Don't sink static AllocaInsts out of the entry block, which would
578 // turn them into dynamic allocas!
579 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
580 if (AI->isStaticAlloca())
581 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000582
Dan Gohman81db61a2009-05-12 02:17:14 +0000583 // Determine if there is a use in or before the loop (direct or
584 // otherwise).
585 bool UsedInLoop = false;
586 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
587 UI != UE; ++UI) {
588 BasicBlock *UseBB = cast<Instruction>(UI)->getParent();
589 if (PHINode *P = dyn_cast<PHINode>(UI)) {
590 unsigned i =
591 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
592 UseBB = P->getIncomingBlock(i);
593 }
594 if (UseBB == Preheader || L->contains(UseBB)) {
595 UsedInLoop = true;
596 break;
597 }
598 }
Bill Wendling87a10f52010-03-23 21:15:59 +0000599
Dan Gohman81db61a2009-05-12 02:17:14 +0000600 // If there is, the def must remain in the preheader.
601 if (UsedInLoop)
602 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000603
Dan Gohman81db61a2009-05-12 02:17:14 +0000604 // Otherwise, sink it to the exit block.
605 Instruction *ToMove = I;
606 bool Done = false;
Bill Wendling87a10f52010-03-23 21:15:59 +0000607
608 if (I != Preheader->begin()) {
609 // Skip debug info intrinsics.
610 do {
611 --I;
612 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
613
614 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
615 Done = true;
616 } else {
Dan Gohman81db61a2009-05-12 02:17:14 +0000617 Done = true;
Bill Wendling87a10f52010-03-23 21:15:59 +0000618 }
619
Dan Gohman667d7872009-06-26 22:53:46 +0000620 ToMove->moveBefore(InsertPt);
Bill Wendling87a10f52010-03-23 21:15:59 +0000621 if (Done) break;
Dan Gohman667d7872009-06-26 22:53:46 +0000622 InsertPt = ToMove;
Dan Gohman81db61a2009-05-12 02:17:14 +0000623 }
624}
625
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000626/// Return true if it is OK to use SIToFPInst for an induction variable
627/// with given initial and exit values.
Chris Lattnerca703bd2010-04-03 06:11:07 +0000628static bool CanUseSIToFP(ConstantFP *InitV, ConstantFP *ExitV,
629 uint64_t intIV, uint64_t intEV) {
Devang Patel13877bf2008-11-18 00:40:02 +0000630
Chris Lattner07aa76a2010-04-03 05:54:59 +0000631 if (InitV->getValueAPF().isNegative() || ExitV->getValueAPF().isNegative())
Devang Patel13877bf2008-11-18 00:40:02 +0000632 return true;
633
634 // If the iteration range can be handled by SIToFPInst then use it.
Chris Lattner9698c192010-04-03 06:13:12 +0000635 if (abs64(intEV - intIV) < INT32_MAX)
Devang Patel13877bf2008-11-18 00:40:02 +0000636 return true;
Dan Gohmancafb8132009-02-17 19:13:57 +0000637
Devang Patel13877bf2008-11-18 00:40:02 +0000638 return false;
639}
640
641/// convertToInt - Convert APF to an integer, if possible.
Chris Lattner07aa76a2010-04-03 05:54:59 +0000642static bool convertToInt(const APFloat &APF, uint64_t &intVal) {
Devang Patelcd402332008-11-17 23:27:13 +0000643 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000644 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
645 return false;
Chris Lattner07aa76a2010-04-03 05:54:59 +0000646 if (APF.convertToInteger(&intVal, 32, APF.isNegative(),
647 APFloat::rmTowardZero, &isExact) != APFloat::opOK)
Devang Patelcd402332008-11-17 23:27:13 +0000648 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000649 if (!isExact)
Devang Patelcd402332008-11-17 23:27:13 +0000650 return false;
651 return true;
Devang Patelcd402332008-11-17 23:27:13 +0000652}
653
Devang Patel58d43d42008-11-03 18:32:19 +0000654/// HandleFloatingPointIV - If the loop has floating induction variable
655/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000656/// For example,
657/// for(double i = 0; i < 10000; ++i)
658/// bar(i)
659/// is converted into
660/// for(int i = 0; i < 10000; ++i)
661/// bar((double)i);
662///
Dan Gohman81db61a2009-05-12 02:17:14 +0000663void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH) {
Devang Patel84e35152008-11-17 21:32:02 +0000664 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
665 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +0000666
Devang Patel84e35152008-11-17 21:32:02 +0000667 // Check incoming value.
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000668 ConstantFP *InitValueVal =
Chris Lattner07aa76a2010-04-03 05:54:59 +0000669 dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000670 if (!InitValueVal) return;
Chris Lattner07aa76a2010-04-03 05:54:59 +0000671
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000672 uint64_t InitValue;
673 if (!convertToInt(InitValueVal->getValueAPF(), InitValue))
Devang Patelcd402332008-11-17 23:27:13 +0000674 return;
675
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000676 // Check IV increment. Reject this PH if increment operation is not
Devang Patelcd402332008-11-17 23:27:13 +0000677 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +0000678 BinaryOperator *Incr =
Devang Patel84e35152008-11-17 21:32:02 +0000679 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
Chris Lattner07aa76a2010-04-03 05:54:59 +0000680 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
681
682 // If this is not an add of the PHI with a constantfp, or if the constant fp
683 // is not an integer, bail out.
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000684 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
685 uint64_t IntValue;
686 if (IncValueVal == 0 || Incr->getOperand(0) != PH ||
687 !convertToInt(IncValueVal->getValueAPF(), IntValue))
Devang Patelcd402332008-11-17 23:27:13 +0000688 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000689
Chris Lattner07aa76a2010-04-03 05:54:59 +0000690 // Check Incr uses. One user is PH and the other user is an exit condition
691 // used by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000692 Value::use_iterator IncrUse = Incr->use_begin();
693 Instruction *U1 = cast<Instruction>(IncrUse++);
694 if (IncrUse == Incr->use_end()) return;
695 Instruction *U2 = cast<Instruction>(IncrUse++);
696 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000697
Chris Lattner07aa76a2010-04-03 05:54:59 +0000698 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
699 // only used by a branch, we can't transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +0000700 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
701 if (!Compare)
702 Compare = dyn_cast<FCmpInst>(U2);
703 if (Compare == 0 || !Compare->hasOneUse() ||
704 !isa<BranchInst>(Compare->use_back()))
Chris Lattner07aa76a2010-04-03 05:54:59 +0000705 return;
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000706
Chris Lattnerca703bd2010-04-03 06:11:07 +0000707 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
Devang Patel84e35152008-11-17 21:32:02 +0000708
Chris Lattner07aa76a2010-04-03 05:54:59 +0000709 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
710 // transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +0000711 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
Chris Lattner07aa76a2010-04-03 05:54:59 +0000712 uint64_t ExitValue;
713 if (ExitValueVal == 0 || !convertToInt(ExitValueVal->getValueAPF(),ExitValue))
Devang Patel84e35152008-11-17 21:32:02 +0000714 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000715
Devang Patel84e35152008-11-17 21:32:02 +0000716 // Find new predicate for integer comparison.
717 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerca703bd2010-04-03 06:11:07 +0000718 switch (Compare->getPredicate()) {
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000719 default: return; // Unknown comparison.
Devang Patel84e35152008-11-17 21:32:02 +0000720 case CmpInst::FCMP_OEQ:
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000721 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
Devang Patel84e35152008-11-17 21:32:02 +0000722 case CmpInst::FCMP_OGT:
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000723 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_UGT; break;
Devang Patel84e35152008-11-17 21:32:02 +0000724 case CmpInst::FCMP_OGE:
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000725 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_UGE; break;
Devang Patel84e35152008-11-17 21:32:02 +0000726 case CmpInst::FCMP_OLT:
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000727 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_ULT; break;
Devang Patel84e35152008-11-17 21:32:02 +0000728 case CmpInst::FCMP_OLE:
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000729 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_ULE; break;
Devang Patel58d43d42008-11-03 18:32:19 +0000730 }
Dan Gohmancafb8132009-02-17 19:13:57 +0000731
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000732 const IntegerType *Int32Ty = Type::getInt32Ty(PH->getContext());
733
Chris Lattnerca703bd2010-04-03 06:11:07 +0000734 // Insert new i32 integer induction variable.
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000735 PHINode *NewPHI = PHINode::Create(Int32Ty, PH->getName()+".int", PH);
736 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
Devang Patel84e35152008-11-17 21:32:02 +0000737 PH->getIncomingBlock(IncomingEdge));
738
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000739 Value *NewAdd =
740 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IntValue),
741 Incr->getName()+".int", Incr);
Devang Patel84e35152008-11-17 21:32:02 +0000742 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
743
Chris Lattnerca703bd2010-04-03 06:11:07 +0000744 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
745 ConstantInt::get(Int32Ty, ExitValue),
746 Compare->getName());
Dan Gohmancafb8132009-02-17 19:13:57 +0000747
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000748 // In the following deletions, PH may become dead and may be deleted.
Dan Gohman81db61a2009-05-12 02:17:14 +0000749 // Use a WeakVH to observe whether this happens.
750 WeakVH WeakPH = PH;
751
Chris Lattnerca703bd2010-04-03 06:11:07 +0000752 // Delete the old floating point exit comparison. The branch starts using the
753 // new comparison.
754 NewCompare->takeName(Compare);
755 Compare->replaceAllUsesWith(NewCompare);
756 RecursivelyDeleteTriviallyDeadInstructions(Compare);
Dan Gohmancafb8132009-02-17 19:13:57 +0000757
Chris Lattnerca703bd2010-04-03 06:11:07 +0000758 // Delete the old floating point increment.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000759 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman81db61a2009-05-12 02:17:14 +0000760 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +0000761
Dan Gohman81db61a2009-05-12 02:17:14 +0000762 // Replace floating induction variable, if it isn't already deleted.
763 // Give SIToFPInst preference over UIToFPInst because it is faster on
764 // platforms that are widely used.
765 if (WeakPH && !PH->use_empty()) {
Chris Lattnerca703bd2010-04-03 06:11:07 +0000766 if (CanUseSIToFP(InitValueVal, ExitValueVal, InitValue, ExitValue)) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000767 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
768 PH->getParent()->getFirstNonPHI());
769 PH->replaceAllUsesWith(Conv);
770 } else {
771 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
772 PH->getParent()->getFirstNonPHI());
773 PH->replaceAllUsesWith(Conv);
774 }
775 RecursivelyDeleteTriviallyDeadInstructions(PH);
Devang Patelcd402332008-11-17 23:27:13 +0000776 }
Devang Patel58d43d42008-11-03 18:32:19 +0000777
Dan Gohman81db61a2009-05-12 02:17:14 +0000778 // Add a new IVUsers entry for the newly-created integer PHI.
779 IU->AddUsersIfInteresting(NewPHI);
780}