blob: ce1307c8df3b40e7907e6b46da1737c4abe56261 [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"
Owen Andersond672ecb2009-07-03 00:17:18 +000046#include "llvm/LLVMContext.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000047#include "llvm/Type.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000048#include "llvm/Analysis/Dominators.h"
49#include "llvm/Analysis/IVUsers.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000050#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000051#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000052#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000053#include "llvm/Support/CFG.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000054#include "llvm/Support/CommandLine.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000055#include "llvm/Support/Debug.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000056#include "llvm/Support/raw_ostream.h"
John Criswell47df12d2003-12-18 17:19:19 +000057#include "llvm/Transforms/Utils/Local.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000058#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000059#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000060#include "llvm/ADT/Statistic.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000061#include "llvm/ADT/STLExtras.h"
John Criswell47df12d2003-12-18 17:19:19 +000062using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000063
Chris Lattner0e5f4992006-12-19 21:40:18 +000064STATISTIC(NumRemoved , "Number of aux indvars removed");
Chris Lattner0e5f4992006-12-19 21:40:18 +000065STATISTIC(NumInserted, "Number of canonical indvars added");
66STATISTIC(NumReplaced, "Number of exit values replaced");
67STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000068
Chris Lattner0e5f4992006-12-19 21:40:18 +000069namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000070 class IndVarSimplify : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000071 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000072 LoopInfo *LI;
73 ScalarEvolution *SE;
Dan Gohmande53dc02009-06-27 05:16:57 +000074 DominatorTree *DT;
Chris Lattner15cad752003-12-23 07:47:09 +000075 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000076 public:
Devang Patel794fd752007-05-01 21:15:47 +000077
Dan Gohman5668cf72009-07-15 01:26:32 +000078 static char ID; // Pass identification, replacement for typeid
79 IndVarSimplify() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000080
Dan Gohman5668cf72009-07-15 01:26:32 +000081 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman60f8a632009-02-17 20:49:49 +000082
Dan Gohman5668cf72009-07-15 01:26:32 +000083 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
84 AU.addRequired<DominatorTree>();
85 AU.addRequired<LoopInfo>();
86 AU.addRequired<ScalarEvolution>();
87 AU.addRequiredID(LoopSimplifyID);
88 AU.addRequiredID(LCSSAID);
89 AU.addRequired<IVUsers>();
90 AU.addPreserved<ScalarEvolution>();
91 AU.addPreservedID(LoopSimplifyID);
92 AU.addPreservedID(LCSSAID);
93 AU.addPreserved<IVUsers>();
94 AU.setPreservesCFG();
95 }
Chris Lattner15cad752003-12-23 07:47:09 +000096
Chris Lattner40bf8b42004-04-02 20:24:31 +000097 private:
Devang Patel5ee99972007-03-07 06:39:01 +000098
Dan Gohman60f8a632009-02-17 20:49:49 +000099 void RewriteNonIntegerIVs(Loop *L);
100
Dan Gohman0bba49c2009-07-07 17:06:11 +0000101 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
Dan Gohmana5758712009-02-17 15:57:39 +0000102 Value *IndVar,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000103 BasicBlock *ExitingBlock,
104 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000105 SCEVExpander &Rewriter);
Dan Gohman667d7872009-06-26 22:53:46 +0000106 void RewriteLoopExitValues(Loop *L, const SCEV *BackedgeTakenCount,
107 SCEVExpander &Rewriter);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000108
Dan Gohman81db61a2009-05-12 02:17:14 +0000109 void RewriteIVExpressions(Loop *L, const Type *LargestType,
Dan Gohman667d7872009-06-26 22:53:46 +0000110 SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000111
Dan Gohman667d7872009-06-26 22:53:46 +0000112 void SinkUnusedInvariants(Loop *L);
Dan Gohman81db61a2009-05-12 02:17:14 +0000113
114 void HandleFloatingPointIV(Loop *L, PHINode *PH);
Chris Lattner3324e712003-12-22 03:58:44 +0000115 };
Chris Lattner5e761402002-09-10 05:24:05 +0000116}
Chris Lattner394437f2001-12-04 04:32:29 +0000117
Dan Gohman844731a2008-05-13 00:00:25 +0000118char IndVarSimplify::ID = 0;
119static RegisterPass<IndVarSimplify>
120X("indvars", "Canonicalize Induction Variables");
121
Daniel Dunbar394f0442008-10-22 23:32:42 +0000122Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000123 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000124}
125
Chris Lattner40bf8b42004-04-02 20:24:31 +0000126/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000127/// loop to be a canonical != comparison against the incremented loop induction
128/// variable. This pass is able to rewrite the exit tests of any loop where the
129/// SCEV analysis can determine a loop-invariant trip count of the loop, which
130/// is actually a much broader range than just linear tests.
Dan Gohman81db61a2009-05-12 02:17:14 +0000131ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
Dan Gohman0bba49c2009-07-07 17:06:11 +0000132 const SCEV *BackedgeTakenCount,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000133 Value *IndVar,
134 BasicBlock *ExitingBlock,
135 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000136 SCEVExpander &Rewriter) {
Chris Lattnerd2440572004-04-15 20:26:22 +0000137 // If the exiting block is not the same as the backedge block, we must compare
138 // against the preincremented value, otherwise we prefer to compare against
139 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000140 Value *CmpIndVar;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000141 const SCEV *RHS = BackedgeTakenCount;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000142 if (ExitingBlock == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000143 // Add one to the "backedge-taken" count to get the trip count.
144 // If this addition may overflow, we have to be more pessimistic and
145 // cast the induction variable before doing the add.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000146 const SCEV *Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
147 const SCEV *N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000148 SE->getAddExpr(BackedgeTakenCount,
149 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000150 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
151 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
152 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000153 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000154 } else {
155 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000156 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
157 IndVar->getType());
158 RHS = SE->getAddExpr(RHS,
159 SE->getIntegerSCEV(1, IndVar->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000160 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000161
Dan Gohman46bdfb02009-02-24 18:55:53 +0000162 // The BackedgeTaken expression contains the number of times that the
163 // backedge branches to the loop header. This is one less than the
164 // number of times the loop executes, so use the incremented indvar.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000165 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Chris Lattnerd2440572004-04-15 20:26:22 +0000166 } else {
167 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000168 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
169 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000170 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000171 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000172
Dan Gohman667d7872009-06-26 22:53:46 +0000173 // Expand the code for the iteration count.
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000174 assert(RHS->isLoopInvariant(L) &&
175 "Computed iteration count is not loop invariant!");
Dan Gohman667d7872009-06-26 22:53:46 +0000176 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000177
Reid Spencere4d87aa2006-12-23 06:05:41 +0000178 // Insert a new icmp_ne or icmp_eq instruction before the branch.
179 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000180 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000181 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000182 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000183 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000184
David Greenef67ef312010-01-05 01:27:06 +0000185 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
Chris Lattnerbdff5482009-08-23 04:37:46 +0000186 << " LHS:" << *CmpIndVar << '\n'
187 << " op:\t"
188 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
189 << " RHS:\t" << *RHS << "\n");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000190
Owen Anderson333c4002009-07-09 23:48:35 +0000191 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
Dan Gohman81db61a2009-05-12 02:17:14 +0000192
193 Instruction *OrigCond = cast<Instruction>(BI->getCondition());
Dan Gohman95bdbfa2009-05-24 19:11:38 +0000194 // It's tempting to use replaceAllUsesWith here to fully replace the old
195 // comparison, but that's not immediately safe, since users of the old
196 // comparison may not be dominated by the new comparison. Instead, just
197 // update the branch to use the new comparison; in the common case this
198 // will make old comparison dead.
199 BI->setCondition(Cond);
Dan Gohman81db61a2009-05-12 02:17:14 +0000200 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
201
Chris Lattner40bf8b42004-04-02 20:24:31 +0000202 ++NumLFTR;
203 Changed = true;
Dan Gohman81db61a2009-05-12 02:17:14 +0000204 return Cond;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000205}
206
Chris Lattner40bf8b42004-04-02 20:24:31 +0000207/// RewriteLoopExitValues - Check to see if this loop has a computable
208/// loop-invariant execution count. If so, this means that we can compute the
209/// final value of any expressions that are recurrent in the loop, and
210/// substitute the exit values from the loop into any instructions outside of
211/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000212///
213/// This is mostly redundant with the regular IndVarSimplify activities that
214/// happen later, except that it's more powerful in some cases, because it's
215/// able to brute-force evaluate arbitrary instructions as long as they have
216/// constant operands at the beginning of the loop.
Dan Gohman890f92b2009-04-18 17:56:28 +0000217void IndVarSimplify::RewriteLoopExitValues(Loop *L,
Dan Gohman667d7872009-06-26 22:53:46 +0000218 const SCEV *BackedgeTakenCount,
219 SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000220 // Verify the input to the pass in already in LCSSA form.
221 assert(L->isLCSSAForm());
222
Devang Patelb7211a22007-08-21 00:31:24 +0000223 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000224 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000225
Chris Lattner9f3d7382007-03-04 03:43:23 +0000226 // Find all values that are computed inside the loop, but used outside of it.
227 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
228 // the exit blocks of the loop to find them.
229 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
230 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000231
Chris Lattner9f3d7382007-03-04 03:43:23 +0000232 // If there are no PHI nodes in this exit block, then no values defined
233 // inside the loop are used on this path, skip it.
234 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
235 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000236
Chris Lattner9f3d7382007-03-04 03:43:23 +0000237 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000238
Chris Lattner9f3d7382007-03-04 03:43:23 +0000239 // Iterate over all of the PHI nodes.
240 BasicBlock::iterator BBI = ExitBB->begin();
241 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000242 if (PN->use_empty())
243 continue; // dead use, don't replace it
Chris Lattner9f3d7382007-03-04 03:43:23 +0000244 // Iterate over all of the values in all the PHI nodes.
245 for (unsigned i = 0; i != NumPreds; ++i) {
246 // If the value being merged in is not integer or is not defined
247 // in the loop, skip it.
248 Value *InVal = PN->getIncomingValue(i);
249 if (!isa<Instruction>(InVal) ||
250 // SCEV only supports integer expressions for now.
Dan Gohman2d1be872009-04-16 03:18:22 +0000251 (!isa<IntegerType>(InVal->getType()) &&
252 !isa<PointerType>(InVal->getType())))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000253 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000254
Chris Lattner9f3d7382007-03-04 03:43:23 +0000255 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000256 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000257 continue; // The Block is in a subloop, skip it.
258
259 // Check that InVal is defined in the loop.
260 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman92329c72009-12-18 01:24:09 +0000261 if (!L->contains(Inst))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000262 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000263
Chris Lattner9f3d7382007-03-04 03:43:23 +0000264 // Okay, this instruction has a user outside of the current loop
265 // and varies predictably *inside* the loop. Evaluate the value it
266 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000267 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +0000268 if (!ExitValue->isLoopInvariant(L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000269 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000270
Chris Lattner9f3d7382007-03-04 03:43:23 +0000271 Changed = true;
272 ++NumReplaced;
Dan Gohmancafb8132009-02-17 19:13:57 +0000273
Dan Gohman667d7872009-06-26 22:53:46 +0000274 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000275
David Greenef67ef312010-01-05 01:27:06 +0000276 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000277 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000278
279 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000280
Dan Gohman81db61a2009-05-12 02:17:14 +0000281 // If this instruction is dead now, delete it.
282 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000283
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000284 if (NumPreds == 1) {
285 // Completely replace a single-pred PHI. This is safe, because the
286 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
287 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000288 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000289 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000290 }
291 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000292 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000293 // Clone the PHI and delete the original one. This lets IVUsers and
294 // any other maps purge the original user from their records.
Devang Patel50b6e332009-10-27 22:16:29 +0000295 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohman667d7872009-06-26 22:53:46 +0000296 NewPN->takeName(PN);
297 NewPN->insertBefore(PN);
298 PN->replaceAllUsesWith(NewPN);
299 PN->eraseFromParent();
300 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000301 }
302 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000303}
304
Dan Gohman60f8a632009-02-17 20:49:49 +0000305void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000306 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000307 // If there are, change them into integer recurrences, permitting analysis by
308 // the SCEV routines.
309 //
310 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000311
Dan Gohman81db61a2009-05-12 02:17:14 +0000312 SmallVector<WeakVH, 8> PHIs;
313 for (BasicBlock::iterator I = Header->begin();
314 PHINode *PN = dyn_cast<PHINode>(I); ++I)
315 PHIs.push_back(PN);
316
317 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
318 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i]))
319 HandleFloatingPointIV(L, PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000320
Dan Gohman2d1be872009-04-16 03:18:22 +0000321 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000322 // may not have been able to compute a trip count. Now that we've done some
323 // re-writing, the trip count may be computable.
324 if (Changed)
Dan Gohman4c7279a2009-10-31 15:04:55 +0000325 SE->forgetLoop(L);
Dale Johannesenc671d892009-04-15 23:31:51 +0000326}
327
Dan Gohmanc2390b12009-02-12 22:19:27 +0000328bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000329 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +0000330 LI = &getAnalysis<LoopInfo>();
331 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +0000332 DT = &getAnalysis<DominatorTree>();
Devang Patel5ee99972007-03-07 06:39:01 +0000333 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +0000334
Dan Gohman2d1be872009-04-16 03:18:22 +0000335 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +0000336 // transform them to use integer recurrences.
337 RewriteNonIntegerIVs(L);
338
Dan Gohman81db61a2009-05-12 02:17:14 +0000339 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
Dan Gohman0bba49c2009-07-07 17:06:11 +0000340 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +0000341
Dan Gohman667d7872009-06-26 22:53:46 +0000342 // Create a rewriter object which we'll use to transform the code with.
343 SCEVExpander Rewriter(*SE);
344
Chris Lattner40bf8b42004-04-02 20:24:31 +0000345 // Check to see if this loop has a computable loop-invariant execution count.
346 // If so, this means that we can compute the final value of any expressions
347 // that are recurrent in the loop, and substitute the exit values from the
348 // loop into any instructions outside of the loop that use the final values of
349 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000350 //
Dan Gohman46bdfb02009-02-24 18:55:53 +0000351 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman667d7872009-06-26 22:53:46 +0000352 RewriteLoopExitValues(L, BackedgeTakenCount, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +0000353
Dan Gohman81db61a2009-05-12 02:17:14 +0000354 // Compute the type of the largest recurrence expression, and decide whether
355 // a canonical induction variable should be inserted.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000356 const Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000357 bool NeedCannIV = false;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000358 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
359 LargestType = BackedgeTakenCount->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000360 LargestType = SE->getEffectiveSCEVType(LargestType);
Dan Gohman81db61a2009-05-12 02:17:14 +0000361 // If we have a known trip count and a single exit block, we'll be
362 // rewriting the loop exit test condition below, which requires a
363 // canonical induction variable.
364 if (ExitingBlock)
365 NeedCannIV = true;
Chris Lattnerf50af082004-04-17 18:08:33 +0000366 }
Dan Gohman81db61a2009-05-12 02:17:14 +0000367 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000368 const SCEV *Stride = IU->StrideOrder[i];
Dan Gohman81db61a2009-05-12 02:17:14 +0000369 const Type *Ty = SE->getEffectiveSCEVType(Stride->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000370 if (!LargestType ||
Dan Gohman81db61a2009-05-12 02:17:14 +0000371 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000372 SE->getTypeSizeInBits(LargestType))
Dan Gohman81db61a2009-05-12 02:17:14 +0000373 LargestType = Ty;
374
Dan Gohman0bba49c2009-07-07 17:06:11 +0000375 std::map<const SCEV *, IVUsersOfOneStride *>::iterator SI =
Dan Gohman81db61a2009-05-12 02:17:14 +0000376 IU->IVUsesByStride.find(IU->StrideOrder[i]);
377 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
378
379 if (!SI->second->Users.empty())
380 NeedCannIV = true;
Chris Lattner6148c022001-12-03 17:28:42 +0000381 }
382
Dan Gohman81db61a2009-05-12 02:17:14 +0000383 // Now that we know the largest of of the induction variable expressions
384 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000385 Value *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000386 if (NeedCannIV) {
Dan Gohman4d8414f2009-06-13 16:25:49 +0000387 // Check to see if the loop already has a canonical-looking induction
388 // variable. If one is present and it's wider than the planned canonical
389 // induction variable, temporarily remove it, so that the Rewriter
390 // doesn't attempt to reuse it.
391 PHINode *OldCannIV = L->getCanonicalInductionVariable();
392 if (OldCannIV) {
393 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
394 SE->getTypeSizeInBits(LargestType))
395 OldCannIV->removeFromParent();
396 else
397 OldCannIV = 0;
398 }
399
Dan Gohman667d7872009-06-26 22:53:46 +0000400 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000401
Dan Gohmanc2390b12009-02-12 22:19:27 +0000402 ++NumInserted;
403 Changed = true;
David Greenef67ef312010-01-05 01:27:06 +0000404 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +0000405
406 // Now that the official induction variable is established, reinsert
407 // the old canonical-looking variable after it so that the IR remains
408 // consistent. It will be deleted as part of the dead-PHI deletion at
409 // the end of the pass.
410 if (OldCannIV)
411 OldCannIV->insertAfter(cast<Instruction>(IndVar));
Dan Gohmand19534a2007-06-15 14:38:12 +0000412 }
Chris Lattner15cad752003-12-23 07:47:09 +0000413
Dan Gohmanc2390b12009-02-12 22:19:27 +0000414 // If we have a trip count expression, rewrite the loop's exit condition
415 // using it. We can currently only handle loops with a single exit.
Dan Gohman81db61a2009-05-12 02:17:14 +0000416 ICmpInst *NewICmp = 0;
417 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && ExitingBlock) {
418 assert(NeedCannIV &&
419 "LinearFunctionTestReplace requires a canonical induction variable");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000420 // Can't rewrite non-branch yet.
Dan Gohman81db61a2009-05-12 02:17:14 +0000421 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
422 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
423 ExitingBlock, BI, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000424 }
425
Torok Edwin3d431382009-05-24 20:08:21 +0000426 // Rewrite IV-derived expressions. Clears the rewriter cache.
Dan Gohman667d7872009-06-26 22:53:46 +0000427 RewriteIVExpressions(L, LargestType, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000428
Dan Gohman667d7872009-06-26 22:53:46 +0000429 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +0000430
Dan Gohman81db61a2009-05-12 02:17:14 +0000431 // Loop-invariant instructions in the preheader that aren't used in the
432 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +0000433 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +0000434
435 // For completeness, inform IVUsers of the IV use in the newly-created
436 // loop exit test instruction.
437 if (NewICmp)
438 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
439
440 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +0000441 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +0000442 // Check a post-condition.
443 assert(L->isLCSSAForm() && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +0000444 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000445}
Devang Pateld22a8492008-09-09 21:41:07 +0000446
Dan Gohman81db61a2009-05-12 02:17:14 +0000447void IndVarSimplify::RewriteIVExpressions(Loop *L, const Type *LargestType,
Dan Gohman667d7872009-06-26 22:53:46 +0000448 SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000449 SmallVector<WeakVH, 16> DeadInsts;
450
451 // Rewrite all induction variable expressions in terms of the canonical
452 // induction variable.
453 //
454 // If there were induction variables of other sizes or offsets, manually
455 // add the offsets to the primary induction variable and cast, avoiding
456 // the need for the code evaluation methods to insert induction variables
457 // of different sizes.
458 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000459 const SCEV *Stride = IU->StrideOrder[i];
Dan Gohman81db61a2009-05-12 02:17:14 +0000460
Dan Gohman0bba49c2009-07-07 17:06:11 +0000461 std::map<const SCEV *, IVUsersOfOneStride *>::iterator SI =
Dan Gohman81db61a2009-05-12 02:17:14 +0000462 IU->IVUsesByStride.find(IU->StrideOrder[i]);
463 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
464 ilist<IVStrideUse> &List = SI->second->Users;
465 for (ilist<IVStrideUse>::iterator UI = List.begin(),
466 E = List.end(); UI != E; ++UI) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000467 Value *Op = UI->getOperandValToReplace();
Dan Gohman4d8414f2009-06-13 16:25:49 +0000468 const Type *UseTy = Op->getType();
Dan Gohman81db61a2009-05-12 02:17:14 +0000469 Instruction *User = UI->getUser();
Dan Gohman81db61a2009-05-12 02:17:14 +0000470
471 // Compute the final addrec to expand into code.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000472 const SCEV *AR = IU->getReplacementExpr(*UI);
Dan Gohman81db61a2009-05-12 02:17:14 +0000473
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000474 // FIXME: It is an extremely bad idea to indvar substitute anything more
475 // complex than affine induction variables. Doing so will put expensive
476 // polynomial evaluations inside of the loop, and the str reduction pass
477 // currently can only reduce affine polynomials. For now just disable
478 // indvar subst on anything more complex than an affine addrec, unless
479 // it can be expanded to a trivial value.
480 if (!AR->isLoopInvariant(L) && !Stride->isLoopInvariant(L))
481 continue;
Dan Gohman68c93442009-06-03 19:11:31 +0000482
Dan Gohmande53dc02009-06-27 05:16:57 +0000483 // Determine the insertion point for this user. By default, insert
484 // immediately before the user. The SCEVExpander class will automatically
485 // hoist loop invariants out of the loop. For PHI nodes, there may be
486 // multiple uses, so compute the nearest common dominator for the
487 // incoming blocks.
Dan Gohman667d7872009-06-26 22:53:46 +0000488 Instruction *InsertPt = User;
489 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
Dan Gohmande53dc02009-06-27 05:16:57 +0000490 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Dan Gohman667d7872009-06-26 22:53:46 +0000491 if (PHI->getIncomingValue(i) == Op) {
Dan Gohmande53dc02009-06-27 05:16:57 +0000492 if (InsertPt == User)
493 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
494 else
495 InsertPt =
496 DT->findNearestCommonDominator(InsertPt->getParent(),
497 PHI->getIncomingBlock(i))
498 ->getTerminator();
Dan Gohman667d7872009-06-26 22:53:46 +0000499 }
500
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000501 // Now expand it into actual Instructions and patch it into place.
502 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
Dan Gohman81db61a2009-05-12 02:17:14 +0000503
504 // Patch the new value into place.
505 if (Op->hasName())
506 NewVal->takeName(Op);
507 User->replaceUsesOfWith(Op, NewVal);
508 UI->setOperandValToReplace(NewVal);
David Greenef67ef312010-01-05 01:27:06 +0000509 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000510 << " into = " << *NewVal << "\n");
Dan Gohman81db61a2009-05-12 02:17:14 +0000511 ++NumRemoved;
512 Changed = true;
513
514 // The old value may be dead now.
515 DeadInsts.push_back(Op);
516 }
517 }
518
Torok Edwin3d431382009-05-24 20:08:21 +0000519 // Clear the rewriter cache, because values that are in the rewriter's cache
520 // can be deleted in the loop below, causing the AssertingVH in the cache to
521 // trigger.
522 Rewriter.clear();
Dan Gohman81db61a2009-05-12 02:17:14 +0000523 // Now that we're done iterating through lists, clean up any instructions
524 // which are now dead.
525 while (!DeadInsts.empty()) {
526 Instruction *Inst = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
527 if (Inst)
528 RecursivelyDeleteTriviallyDeadInstructions(Inst);
529 }
530}
531
532/// If there's a single exit block, sink any loop-invariant values that
533/// were defined in the preheader but not used inside the loop into the
534/// exit block to reduce register pressure in the loop.
Dan Gohman667d7872009-06-26 22:53:46 +0000535void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000536 BasicBlock *ExitBlock = L->getExitBlock();
537 if (!ExitBlock) return;
538
Dan Gohman81db61a2009-05-12 02:17:14 +0000539 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman03e896b2009-11-05 21:11:53 +0000540 if (!Preheader) return;
541
542 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
Dan Gohman81db61a2009-05-12 02:17:14 +0000543 BasicBlock::iterator I = Preheader->getTerminator();
544 while (I != Preheader->begin()) {
545 --I;
Dan Gohman667d7872009-06-26 22:53:46 +0000546 // New instructions were inserted at the end of the preheader.
547 if (isa<PHINode>(I))
Dan Gohman81db61a2009-05-12 02:17:14 +0000548 break;
Eli Friedman0c77db32009-07-15 22:48:29 +0000549 // Don't move instructions which might have side effects, since the side
550 // effects need to complete before instructions inside the loop. Also
551 // don't move instructions which might read memory, since the loop may
552 // modify memory. Note that it's okay if the instruction might have
553 // undefined behavior: LoopSimplify guarantees that the preheader
554 // dominates the exit block.
555 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Dan Gohman667d7872009-06-26 22:53:46 +0000556 continue;
Dan Gohman76f497a2009-08-25 17:42:10 +0000557 // Don't sink static AllocaInsts out of the entry block, which would
558 // turn them into dynamic allocas!
559 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
560 if (AI->isStaticAlloca())
561 continue;
Dan Gohman81db61a2009-05-12 02:17:14 +0000562 // Determine if there is a use in or before the loop (direct or
563 // otherwise).
564 bool UsedInLoop = false;
565 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
566 UI != UE; ++UI) {
567 BasicBlock *UseBB = cast<Instruction>(UI)->getParent();
568 if (PHINode *P = dyn_cast<PHINode>(UI)) {
569 unsigned i =
570 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
571 UseBB = P->getIncomingBlock(i);
572 }
573 if (UseBB == Preheader || L->contains(UseBB)) {
574 UsedInLoop = true;
575 break;
576 }
577 }
578 // If there is, the def must remain in the preheader.
579 if (UsedInLoop)
580 continue;
581 // Otherwise, sink it to the exit block.
582 Instruction *ToMove = I;
583 bool Done = false;
584 if (I != Preheader->begin())
585 --I;
586 else
587 Done = true;
Dan Gohman667d7872009-06-26 22:53:46 +0000588 ToMove->moveBefore(InsertPt);
Dan Gohman81db61a2009-05-12 02:17:14 +0000589 if (Done)
590 break;
Dan Gohman667d7872009-06-26 22:53:46 +0000591 InsertPt = ToMove;
Dan Gohman81db61a2009-05-12 02:17:14 +0000592 }
593}
594
Devang Patel13877bf2008-11-18 00:40:02 +0000595/// Return true if it is OK to use SIToFPInst for an inducation variable
596/// with given inital and exit values.
597static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
598 uint64_t intIV, uint64_t intEV) {
599
Dan Gohmancafb8132009-02-17 19:13:57 +0000600 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patel13877bf2008-11-18 00:40:02 +0000601 return true;
602
603 // If the iteration range can be handled by SIToFPInst then use it.
604 APInt Max = APInt::getSignedMaxValue(32);
Dale Johannesenbae7d6d2009-05-14 16:47:34 +0000605 if (Max.getZExtValue() > static_cast<uint64_t>(abs64(intEV - intIV)))
Devang Patel13877bf2008-11-18 00:40:02 +0000606 return true;
Dan Gohmancafb8132009-02-17 19:13:57 +0000607
Devang Patel13877bf2008-11-18 00:40:02 +0000608 return false;
609}
610
611/// convertToInt - Convert APF to an integer, if possible.
Devang Patelcd402332008-11-17 23:27:13 +0000612static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
613
614 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000615 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
616 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000617 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patelcd402332008-11-17 23:27:13 +0000618 APFloat::rmTowardZero, &isExact)
619 != APFloat::opOK)
620 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000621 if (!isExact)
Devang Patelcd402332008-11-17 23:27:13 +0000622 return false;
623 return true;
624
625}
626
Devang Patel58d43d42008-11-03 18:32:19 +0000627/// HandleFloatingPointIV - If the loop has floating induction variable
628/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000629/// For example,
630/// for(double i = 0; i < 10000; ++i)
631/// bar(i)
632/// is converted into
633/// for(int i = 0; i < 10000; ++i)
634/// bar((double)i);
635///
Dan Gohman81db61a2009-05-12 02:17:14 +0000636void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH) {
Devang Patel58d43d42008-11-03 18:32:19 +0000637
Devang Patel84e35152008-11-17 21:32:02 +0000638 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
639 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +0000640
Devang Patel84e35152008-11-17 21:32:02 +0000641 // Check incoming value.
Devang Patelcd402332008-11-17 23:27:13 +0000642 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
643 if (!InitValue) return;
Owen Anderson1d0be152009-08-13 21:58:54 +0000644 uint64_t newInitValue =
645 Type::getInt32Ty(PH->getContext())->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000646 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
647 return;
648
649 // Check IV increment. Reject this PH if increement operation is not
650 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +0000651 BinaryOperator *Incr =
Devang Patel84e35152008-11-17 21:32:02 +0000652 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
653 if (!Incr) return;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000654 if (Incr->getOpcode() != Instruction::FAdd) return;
Devang Patel84e35152008-11-17 21:32:02 +0000655 ConstantFP *IncrValue = NULL;
656 unsigned IncrVIndex = 1;
657 if (Incr->getOperand(1) == PH)
658 IncrVIndex = 0;
659 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
660 if (!IncrValue) return;
Owen Anderson1d0be152009-08-13 21:58:54 +0000661 uint64_t newIncrValue =
662 Type::getInt32Ty(PH->getContext())->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000663 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
664 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000665
Devang Patelcd402332008-11-17 23:27:13 +0000666 // Check Incr uses. One user is PH and the other users is exit condition used
667 // by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000668 Value::use_iterator IncrUse = Incr->use_begin();
669 Instruction *U1 = cast<Instruction>(IncrUse++);
670 if (IncrUse == Incr->use_end()) return;
671 Instruction *U2 = cast<Instruction>(IncrUse++);
672 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000673
Devang Patel84e35152008-11-17 21:32:02 +0000674 // Find exit condition.
675 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
676 if (!EC)
677 EC = dyn_cast<FCmpInst>(U2);
678 if (!EC) return;
679
680 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
681 if (!BI->isConditional()) return;
682 if (BI->getCondition() != EC) return;
Devang Patel58d43d42008-11-03 18:32:19 +0000683 }
Devang Patel58d43d42008-11-03 18:32:19 +0000684
Devang Patelcd402332008-11-17 23:27:13 +0000685 // Find exit value. If exit value can not be represented as an interger then
686 // do not handle this floating point PH.
Devang Patel84e35152008-11-17 21:32:02 +0000687 ConstantFP *EV = NULL;
688 unsigned EVIndex = 1;
689 if (EC->getOperand(1) == Incr)
690 EVIndex = 0;
691 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
692 if (!EV) return;
Owen Anderson1d0be152009-08-13 21:58:54 +0000693 uint64_t intEV = Type::getInt32Ty(PH->getContext())->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000694 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patel84e35152008-11-17 21:32:02 +0000695 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000696
Devang Patel84e35152008-11-17 21:32:02 +0000697 // Find new predicate for integer comparison.
698 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
699 switch (EC->getPredicate()) {
700 case CmpInst::FCMP_OEQ:
701 case CmpInst::FCMP_UEQ:
702 NewPred = CmpInst::ICMP_EQ;
703 break;
704 case CmpInst::FCMP_OGT:
705 case CmpInst::FCMP_UGT:
706 NewPred = CmpInst::ICMP_UGT;
707 break;
708 case CmpInst::FCMP_OGE:
709 case CmpInst::FCMP_UGE:
710 NewPred = CmpInst::ICMP_UGE;
711 break;
712 case CmpInst::FCMP_OLT:
713 case CmpInst::FCMP_ULT:
714 NewPred = CmpInst::ICMP_ULT;
715 break;
716 case CmpInst::FCMP_OLE:
717 case CmpInst::FCMP_ULE:
718 NewPred = CmpInst::ICMP_ULE;
719 break;
720 default:
721 break;
Devang Patel58d43d42008-11-03 18:32:19 +0000722 }
Devang Patel84e35152008-11-17 21:32:02 +0000723 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000724
Devang Patel84e35152008-11-17 21:32:02 +0000725 // Insert new integer induction variable.
Owen Anderson1d0be152009-08-13 21:58:54 +0000726 PHINode *NewPHI = PHINode::Create(Type::getInt32Ty(PH->getContext()),
Devang Patel84e35152008-11-17 21:32:02 +0000727 PH->getName()+".int", PH);
Owen Anderson1d0be152009-08-13 21:58:54 +0000728 NewPHI->addIncoming(ConstantInt::get(Type::getInt32Ty(PH->getContext()),
729 newInitValue),
Devang Patel84e35152008-11-17 21:32:02 +0000730 PH->getIncomingBlock(IncomingEdge));
731
Dan Gohmancafb8132009-02-17 19:13:57 +0000732 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
Owen Anderson1d0be152009-08-13 21:58:54 +0000733 ConstantInt::get(Type::getInt32Ty(PH->getContext()),
Devang Patelcd402332008-11-17 23:27:13 +0000734 newIncrValue),
Devang Patel84e35152008-11-17 21:32:02 +0000735 Incr->getName()+".int", Incr);
736 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
737
Dale Johannesen617d1082009-04-27 21:03:15 +0000738 // The back edge is edge 1 of newPHI, whatever it may have been in the
739 // original PHI.
Owen Anderson1d0be152009-08-13 21:58:54 +0000740 ConstantInt *NewEV = ConstantInt::get(Type::getInt32Ty(PH->getContext()),
741 intEV);
Dale Johannesen617d1082009-04-27 21:03:15 +0000742 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(1) : NewEV);
743 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(1));
Owen Anderson333c4002009-07-09 23:48:35 +0000744 ICmpInst *NewEC = new ICmpInst(EC->getParent()->getTerminator(),
Daniel Dunbar460f6562009-07-26 09:48:23 +0000745 NewPred, LHS, RHS, EC->getName());
Dan Gohmancafb8132009-02-17 19:13:57 +0000746
Dan Gohman81db61a2009-05-12 02:17:14 +0000747 // In the following deltions, PH may become dead and may be deleted.
748 // Use a WeakVH to observe whether this happens.
749 WeakVH WeakPH = PH;
750
Devang Patel84e35152008-11-17 21:32:02 +0000751 // Delete old, floating point, exit comparision instruction.
Dan Gohman14fba292009-05-24 18:09:01 +0000752 NewEC->takeName(EC);
Devang Patel84e35152008-11-17 21:32:02 +0000753 EC->replaceAllUsesWith(NewEC);
Dan Gohman81db61a2009-05-12 02:17:14 +0000754 RecursivelyDeleteTriviallyDeadInstructions(EC);
Dan Gohmancafb8132009-02-17 19:13:57 +0000755
Devang Patel84e35152008-11-17 21:32:02 +0000756 // Delete old, floating point, increment instruction.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000757 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman81db61a2009-05-12 02:17:14 +0000758 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +0000759
Dan Gohman81db61a2009-05-12 02:17:14 +0000760 // Replace floating induction variable, if it isn't already deleted.
761 // Give SIToFPInst preference over UIToFPInst because it is faster on
762 // platforms that are widely used.
763 if (WeakPH && !PH->use_empty()) {
764 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
765 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
766 PH->getParent()->getFirstNonPHI());
767 PH->replaceAllUsesWith(Conv);
768 } else {
769 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
770 PH->getParent()->getFirstNonPHI());
771 PH->replaceAllUsesWith(Conv);
772 }
773 RecursivelyDeleteTriviallyDeadInstructions(PH);
Devang Patelcd402332008-11-17 23:27:13 +0000774 }
Devang Patel58d43d42008-11-03 18:32:19 +0000775
Dan Gohman81db61a2009-05-12 02:17:14 +0000776 // Add a new IVUsers entry for the newly-created integer PHI.
777 IU->AddUsersIfInteresting(NewPHI);
778}