blob: f20d424724ab275d106233570a1c46a4cc3e5bed [file] [log] [blame]
Chris Lattner6148c022001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6148c022001-12-03 17:28:42 +00009//
Chris Lattner40bf8b42004-04-02 20:24:31 +000010// This transformation analyzes and transforms the induction variables (and
11// computations derived from them) into simpler forms suitable for subsequent
12// analysis and transformation.
13//
Reid Spencer47a53ac2006-08-18 09:01:07 +000014// This transformation makes the following changes to each loop with an
Chris Lattner40bf8b42004-04-02 20:24:31 +000015// identifiable induction variable:
16// 1. All loops are transformed to have a SINGLE canonical induction variable
17// which starts at zero and steps by one.
18// 2. The canonical induction variable is guaranteed to be the first PHI node
19// in the loop header block.
20// 3. Any pointer arithmetic recurrences are raised to use array subscripts.
21//
22// If the trip count of a loop is computable, this pass also makes the following
23// changes:
24// 1. The exit condition for the loop is canonicalized to compare the
25// induction value against the exit value. This turns loops like:
26// 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
27// 2. Any use outside of the loop of an expression derived from the indvar
28// is changed to compute the derived value outside of the loop, eliminating
29// the dependence on the exit value of the induction variable. If the only
30// purpose of the loop is to compute the exit value of some derived
31// expression, this transformation will make the loop dead.
32//
33// This transformation should be followed by strength reduction after all of the
Dan Gohmanc2c4cbf2009-05-19 20:38:47 +000034// desired loop transformations have been performed.
Chris Lattner6148c022001-12-03 17:28:42 +000035//
36//===----------------------------------------------------------------------===//
37
Chris Lattner0e5f4992006-12-19 21:40:18 +000038#define DEBUG_TYPE "indvars"
Chris Lattner022103b2002-05-07 20:03:00 +000039#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000040#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000041#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000042#include "llvm/Instructions.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000043#include "llvm/Type.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000044#include "llvm/Analysis/Dominators.h"
45#include "llvm/Analysis/IVUsers.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000046#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000047#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000048#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000049#include "llvm/Support/CFG.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000050#include "llvm/Support/Compiler.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000051#include "llvm/Support/Debug.h"
John Criswell47df12d2003-12-18 17:19:19 +000052#include "llvm/Transforms/Utils/Local.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000053#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000054#include "llvm/Support/CommandLine.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000055#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000056#include "llvm/ADT/Statistic.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000057#include "llvm/ADT/STLExtras.h"
John Criswell47df12d2003-12-18 17:19:19 +000058using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000059
Chris Lattner0e5f4992006-12-19 21:40:18 +000060STATISTIC(NumRemoved , "Number of aux indvars removed");
Chris Lattner0e5f4992006-12-19 21:40:18 +000061STATISTIC(NumInserted, "Number of canonical indvars added");
62STATISTIC(NumReplaced, "Number of exit values replaced");
63STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065namespace {
Devang Patel5ee99972007-03-07 06:39:01 +000066 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000067 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000068 LoopInfo *LI;
69 ScalarEvolution *SE;
Chris Lattner15cad752003-12-23 07:47:09 +000070 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000071 public:
Devang Patel794fd752007-05-01 21:15:47 +000072
Nick Lewyckyecd94c82007-05-06 13:37:16 +000073 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000074 IndVarSimplify() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000075
Dan Gohman60f8a632009-02-17 20:49:49 +000076 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
77
Devang Patel5ee99972007-03-07 06:39:01 +000078 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman81db61a2009-05-12 02:17:14 +000079 AU.addRequired<DominatorTree>();
Devang Patelbc533cd2007-09-10 18:08:23 +000080 AU.addRequired<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000081 AU.addRequiredID(LCSSAID);
82 AU.addRequiredID(LoopSimplifyID);
Devang Patel5ee99972007-03-07 06:39:01 +000083 AU.addRequired<LoopInfo>();
Dan Gohman81db61a2009-05-12 02:17:14 +000084 AU.addRequired<IVUsers>();
Dan Gohman474cecf2009-02-23 16:29:41 +000085 AU.addPreserved<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000086 AU.addPreservedID(LoopSimplifyID);
Dan Gohman81db61a2009-05-12 02:17:14 +000087 AU.addPreserved<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +000088 AU.addPreservedID(LCSSAID);
89 AU.setPreservesCFG();
90 }
Chris Lattner15cad752003-12-23 07:47:09 +000091
Chris Lattner40bf8b42004-04-02 20:24:31 +000092 private:
Devang Patel5ee99972007-03-07 06:39:01 +000093
Dan Gohman60f8a632009-02-17 20:49:49 +000094 void RewriteNonIntegerIVs(Loop *L);
95
Dan Gohman81db61a2009-05-12 02:17:14 +000096 ICmpInst *LinearFunctionTestReplace(Loop *L, SCEVHandle BackedgeTakenCount,
Dan Gohmana5758712009-02-17 15:57:39 +000097 Value *IndVar,
Dan Gohmanc2390b12009-02-12 22:19:27 +000098 BasicBlock *ExitingBlock,
99 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000100 SCEVExpander &Rewriter);
Dan Gohman890f92b2009-04-18 17:56:28 +0000101 void RewriteLoopExitValues(Loop *L, const SCEV *BackedgeTakenCount);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000102
Dan Gohman81db61a2009-05-12 02:17:14 +0000103 void RewriteIVExpressions(Loop *L, const Type *LargestType,
104 SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000105
Dan Gohman81db61a2009-05-12 02:17:14 +0000106 void SinkUnusedInvariants(Loop *L, SCEVExpander &Rewriter);
107
108 void FixUsesBeforeDefs(Loop *L, SCEVExpander &Rewriter);
109
110 void HandleFloatingPointIV(Loop *L, PHINode *PH);
Chris Lattner3324e712003-12-22 03:58:44 +0000111 };
Chris Lattner5e761402002-09-10 05:24:05 +0000112}
Chris Lattner394437f2001-12-04 04:32:29 +0000113
Dan Gohman844731a2008-05-13 00:00:25 +0000114char IndVarSimplify::ID = 0;
115static RegisterPass<IndVarSimplify>
116X("indvars", "Canonicalize Induction Variables");
117
Daniel Dunbar394f0442008-10-22 23:32:42 +0000118Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000119 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000120}
121
Chris Lattner40bf8b42004-04-02 20:24:31 +0000122/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000123/// loop to be a canonical != comparison against the incremented loop induction
124/// variable. This pass is able to rewrite the exit tests of any loop where the
125/// SCEV analysis can determine a loop-invariant trip count of the loop, which
126/// is actually a much broader range than just linear tests.
Dan Gohman81db61a2009-05-12 02:17:14 +0000127ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
Dan Gohman46bdfb02009-02-24 18:55:53 +0000128 SCEVHandle BackedgeTakenCount,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000129 Value *IndVar,
130 BasicBlock *ExitingBlock,
131 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000132 SCEVExpander &Rewriter) {
Chris Lattnerd2440572004-04-15 20:26:22 +0000133 // If the exiting block is not the same as the backedge block, we must compare
134 // against the preincremented value, otherwise we prefer to compare against
135 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000136 Value *CmpIndVar;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000137 SCEVHandle RHS = BackedgeTakenCount;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000138 if (ExitingBlock == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000139 // Add one to the "backedge-taken" count to get the trip count.
140 // If this addition may overflow, we have to be more pessimistic and
141 // cast the induction variable before doing the add.
142 SCEVHandle Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000143 SCEVHandle N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000144 SE->getAddExpr(BackedgeTakenCount,
145 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000146 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
147 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
148 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000149 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000150 } else {
151 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000152 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
153 IndVar->getType());
154 RHS = SE->getAddExpr(RHS,
155 SE->getIntegerSCEV(1, IndVar->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000156 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000157
Dan Gohman46bdfb02009-02-24 18:55:53 +0000158 // The BackedgeTaken expression contains the number of times that the
159 // backedge branches to the loop header. This is one less than the
160 // number of times the loop executes, so use the incremented indvar.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000161 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Chris Lattnerd2440572004-04-15 20:26:22 +0000162 } else {
163 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000164 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
165 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000166 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000167 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000168
Chris Lattner40bf8b42004-04-02 20:24:31 +0000169 // Expand the code for the iteration count into the preheader of the loop.
170 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman5be18e82009-05-19 02:15:55 +0000171 Value *ExitCnt = Rewriter.expandCodeFor(RHS, CmpIndVar->getType(),
Dan Gohmanc2390b12009-02-12 22:19:27 +0000172 Preheader->getTerminator());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000173
Reid Spencere4d87aa2006-12-23 06:05:41 +0000174 // Insert a new icmp_ne or icmp_eq instruction before the branch.
175 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000176 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000177 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000178 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000179 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000180
Dan Gohmanc2390b12009-02-12 22:19:27 +0000181 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
182 << " LHS:" << *CmpIndVar // includes a newline
183 << " op:\t"
Dan Gohmanf108e2e2009-02-14 02:26:50 +0000184 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
Dan Gohman46bdfb02009-02-24 18:55:53 +0000185 << " RHS:\t" << *RHS << "\n";
Dan Gohmanc2390b12009-02-12 22:19:27 +0000186
Dan Gohman81db61a2009-05-12 02:17:14 +0000187 ICmpInst *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
188
189 Instruction *OrigCond = cast<Instruction>(BI->getCondition());
190 OrigCond->replaceAllUsesWith(Cond);
191 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
192
Chris Lattner40bf8b42004-04-02 20:24:31 +0000193 ++NumLFTR;
194 Changed = true;
Dan Gohman81db61a2009-05-12 02:17:14 +0000195 return Cond;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000196}
197
Chris Lattner40bf8b42004-04-02 20:24:31 +0000198/// RewriteLoopExitValues - Check to see if this loop has a computable
199/// loop-invariant execution count. If so, this means that we can compute the
200/// final value of any expressions that are recurrent in the loop, and
201/// substitute the exit values from the loop into any instructions outside of
202/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000203///
204/// This is mostly redundant with the regular IndVarSimplify activities that
205/// happen later, except that it's more powerful in some cases, because it's
206/// able to brute-force evaluate arbitrary instructions as long as they have
207/// constant operands at the beginning of the loop.
Dan Gohman890f92b2009-04-18 17:56:28 +0000208void IndVarSimplify::RewriteLoopExitValues(Loop *L,
209 const SCEV *BackedgeTakenCount) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000210 // Verify the input to the pass in already in LCSSA form.
211 assert(L->isLCSSAForm());
212
Chris Lattner40bf8b42004-04-02 20:24:31 +0000213 BasicBlock *Preheader = L->getLoopPreheader();
214
215 // Scan all of the instructions in the loop, looking at those that have
216 // extra-loop users and which are recurrences.
Dan Gohman5be18e82009-05-19 02:15:55 +0000217 SCEVExpander Rewriter(*SE);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000218
219 // We insert the code into the preheader of the loop if the loop contains
220 // multiple exit blocks, or in the exit block if there is exactly one.
221 BasicBlock *BlockToInsertInto;
Devang Patelb7211a22007-08-21 00:31:24 +0000222 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000223 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000224 if (ExitBlocks.size() == 1)
225 BlockToInsertInto = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000226 else
227 BlockToInsertInto = Preheader;
Dan Gohman02dea8b2008-05-23 21:05:58 +0000228 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000229
Chris Lattner9f3d7382007-03-04 03:43:23 +0000230 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanfd939082005-04-21 23:48:37 +0000231
Chris Lattner9f3d7382007-03-04 03:43:23 +0000232 // Find all values that are computed inside the loop, but used outside of it.
233 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
234 // the exit blocks of the loop to find them.
235 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
236 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000237
Chris Lattner9f3d7382007-03-04 03:43:23 +0000238 // If there are no PHI nodes in this exit block, then no values defined
239 // inside the loop are used on this path, skip it.
240 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
241 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000242
Chris Lattner9f3d7382007-03-04 03:43:23 +0000243 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000244
Chris Lattner9f3d7382007-03-04 03:43:23 +0000245 // Iterate over all of the PHI nodes.
246 BasicBlock::iterator BBI = ExitBB->begin();
247 while ((PN = dyn_cast<PHINode>(BBI++))) {
Dan Gohmancafb8132009-02-17 19:13:57 +0000248
Chris Lattner9f3d7382007-03-04 03:43:23 +0000249 // Iterate over all of the values in all the PHI nodes.
250 for (unsigned i = 0; i != NumPreds; ++i) {
251 // If the value being merged in is not integer or is not defined
252 // in the loop, skip it.
253 Value *InVal = PN->getIncomingValue(i);
254 if (!isa<Instruction>(InVal) ||
255 // SCEV only supports integer expressions for now.
Dan Gohman2d1be872009-04-16 03:18:22 +0000256 (!isa<IntegerType>(InVal->getType()) &&
257 !isa<PointerType>(InVal->getType())))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000258 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000259
Chris Lattner9f3d7382007-03-04 03:43:23 +0000260 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000261 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000262 continue; // The Block is in a subloop, skip it.
263
264 // Check that InVal is defined in the loop.
265 Instruction *Inst = cast<Instruction>(InVal);
266 if (!L->contains(Inst->getParent()))
267 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000268
Chris Lattner9f3d7382007-03-04 03:43:23 +0000269 // Okay, this instruction has a user outside of the current loop
270 // and varies predictably *inside* the loop. Evaluate the value it
271 // contains when the loop exits, if possible.
Dan Gohman81db61a2009-05-12 02:17:14 +0000272 SCEVHandle SH = SE->getSCEV(Inst);
273 SCEVHandle ExitValue = SE->getSCEVAtScope(SH, L->getParentLoop());
Chris Lattner9f3d7382007-03-04 03:43:23 +0000274 if (isa<SCEVCouldNotCompute>(ExitValue) ||
275 !ExitValue->isLoopInvariant(L))
276 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
Chris Lattner9f3d7382007-03-04 03:43:23 +0000281 // See if we already computed the exit value for the instruction, if so,
282 // just reuse it.
283 Value *&ExitVal = ExitValues[Inst];
284 if (!ExitVal)
Dan Gohman2d1be872009-04-16 03:18:22 +0000285 ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), InsertPt);
Dan Gohmancafb8132009-02-17 19:13:57 +0000286
Chris Lattner9f3d7382007-03-04 03:43:23 +0000287 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
288 << " LoopVal = " << *Inst << "\n";
289
290 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000291
Dan Gohman81db61a2009-05-12 02:17:14 +0000292 // If this instruction is dead now, delete it.
293 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000294
Chris Lattner9f3d7382007-03-04 03:43:23 +0000295 // See if this is a single-entry LCSSA PHI node. If so, we can (and
296 // have to) remove
Chris Lattner9caed542007-03-04 01:00:28 +0000297 // the PHI entirely. This is safe, because the NewVal won't be variant
298 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000299 if (NumPreds == 1) {
300 PN->replaceAllUsesWith(ExitVal);
Torok Edwinb679de22009-05-24 14:23:16 +0000301 Rewriter.clear();
Dan Gohman81db61a2009-05-12 02:17:14 +0000302 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000303 break;
Chris Lattnerc9838f22007-03-03 22:48:48 +0000304 }
305 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000306 }
307 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000308}
309
Dan Gohman60f8a632009-02-17 20:49:49 +0000310void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000311 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000312 // If there are, change them into integer recurrences, permitting analysis by
313 // the SCEV routines.
314 //
315 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000316
Dan Gohman81db61a2009-05-12 02:17:14 +0000317 SmallVector<WeakVH, 8> PHIs;
318 for (BasicBlock::iterator I = Header->begin();
319 PHINode *PN = dyn_cast<PHINode>(I); ++I)
320 PHIs.push_back(PN);
321
322 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
323 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i]))
324 HandleFloatingPointIV(L, PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000325
Dan Gohman2d1be872009-04-16 03:18:22 +0000326 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000327 // may not have been able to compute a trip count. Now that we've done some
328 // re-writing, the trip count may be computable.
329 if (Changed)
Dan Gohman46bdfb02009-02-24 18:55:53 +0000330 SE->forgetLoopBackedgeTakenCount(L);
Dale Johannesenc671d892009-04-15 23:31:51 +0000331}
332
Dan Gohmanc2390b12009-02-12 22:19:27 +0000333bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000334 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +0000335 LI = &getAnalysis<LoopInfo>();
336 SE = &getAnalysis<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +0000337 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +0000338
Dan Gohman2d1be872009-04-16 03:18:22 +0000339 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +0000340 // transform them to use integer recurrences.
341 RewriteNonIntegerIVs(L);
342
Dan Gohmanc2390b12009-02-12 22:19:27 +0000343 BasicBlock *Header = L->getHeader();
Dan Gohman81db61a2009-05-12 02:17:14 +0000344 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
345 SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +0000346
Chris Lattner40bf8b42004-04-02 20:24:31 +0000347 // Check to see if this loop has a computable loop-invariant execution count.
348 // If so, this means that we can compute the final value of any expressions
349 // that are recurrent in the loop, and substitute the exit values from the
350 // loop into any instructions outside of the loop that use the final values of
351 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000352 //
Dan Gohman46bdfb02009-02-24 18:55:53 +0000353 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
354 RewriteLoopExitValues(L, BackedgeTakenCount);
Chris Lattner6148c022001-12-03 17:28:42 +0000355
Dan Gohman81db61a2009-05-12 02:17:14 +0000356 // Compute the type of the largest recurrence expression, and decide whether
357 // a canonical induction variable should be inserted.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000358 const Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000359 bool NeedCannIV = false;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000360 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
361 LargestType = BackedgeTakenCount->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000362 LargestType = SE->getEffectiveSCEVType(LargestType);
Dan Gohman81db61a2009-05-12 02:17:14 +0000363 // If we have a known trip count and a single exit block, we'll be
364 // rewriting the loop exit test condition below, which requires a
365 // canonical induction variable.
366 if (ExitingBlock)
367 NeedCannIV = true;
Chris Lattnerf50af082004-04-17 18:08:33 +0000368 }
Dan Gohman81db61a2009-05-12 02:17:14 +0000369 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
370 SCEVHandle Stride = IU->StrideOrder[i];
371 const Type *Ty = SE->getEffectiveSCEVType(Stride->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000372 if (!LargestType ||
Dan Gohman81db61a2009-05-12 02:17:14 +0000373 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000374 SE->getTypeSizeInBits(LargestType))
Dan Gohman81db61a2009-05-12 02:17:14 +0000375 LargestType = Ty;
376
377 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
378 IU->IVUsesByStride.find(IU->StrideOrder[i]);
379 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
380
381 if (!SI->second->Users.empty())
382 NeedCannIV = true;
Chris Lattner6148c022001-12-03 17:28:42 +0000383 }
384
Chris Lattner40bf8b42004-04-02 20:24:31 +0000385 // Create a rewriter object which we'll use to transform the code with.
Dan Gohman5be18e82009-05-19 02:15:55 +0000386 SCEVExpander Rewriter(*SE);
Chris Lattner15cad752003-12-23 07:47:09 +0000387
Dan Gohman81db61a2009-05-12 02:17:14 +0000388 // Now that we know the largest of of the induction variable expressions
389 // 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 Gohmanc2390b12009-02-12 22:19:27 +0000392 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
393 ++NumInserted;
394 Changed = true;
395 DOUT << "INDVARS: New CanIV: " << *IndVar;
Dan Gohmand19534a2007-06-15 14:38:12 +0000396 }
Chris Lattner15cad752003-12-23 07:47:09 +0000397
Dan Gohmanc2390b12009-02-12 22:19:27 +0000398 // If we have a trip count expression, rewrite the loop's exit condition
399 // using it. We can currently only handle loops with a single exit.
Dan Gohman81db61a2009-05-12 02:17:14 +0000400 ICmpInst *NewICmp = 0;
401 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && ExitingBlock) {
402 assert(NeedCannIV &&
403 "LinearFunctionTestReplace requires a canonical induction variable");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000404 // Can't rewrite non-branch yet.
Dan Gohman81db61a2009-05-12 02:17:14 +0000405 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
406 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
407 ExitingBlock, BI, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000408 }
409
Dan Gohman81db61a2009-05-12 02:17:14 +0000410 Rewriter.setInsertionPoint(Header->getFirstNonPHI());
Chris Lattner5d461d22004-04-21 22:22:01 +0000411
Dan Gohman81db61a2009-05-12 02:17:14 +0000412 // Rewrite IV-derived expressions.
413 RewriteIVExpressions(L, LargestType, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000414
Dan Gohman81db61a2009-05-12 02:17:14 +0000415 // Loop-invariant instructions in the preheader that aren't used in the
416 // loop may be sunk below the loop to reduce register pressure.
417 SinkUnusedInvariants(L, Rewriter);
Chris Lattner394437f2001-12-04 04:32:29 +0000418
Dan Gohman81db61a2009-05-12 02:17:14 +0000419 // Reorder instructions to avoid use-before-def conditions.
420 FixUsesBeforeDefs(L, Rewriter);
421
Torok Edwinb679de22009-05-24 14:23:16 +0000422 Rewriter.clear();
Dan Gohman81db61a2009-05-12 02:17:14 +0000423 // For completeness, inform IVUsers of the IV use in the newly-created
424 // loop exit test instruction.
425 if (NewICmp)
426 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
427
428 // Clean up dead instructions.
429 DeleteDeadPHIs(L->getHeader());
430 // Check a post-condition.
431 assert(L->isLCSSAForm() && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +0000432 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000433}
Devang Pateld22a8492008-09-09 21:41:07 +0000434
Dan Gohman81db61a2009-05-12 02:17:14 +0000435void IndVarSimplify::RewriteIVExpressions(Loop *L, const Type *LargestType,
436 SCEVExpander &Rewriter) {
437 SmallVector<WeakVH, 16> DeadInsts;
438
439 // Rewrite all induction variable expressions in terms of the canonical
440 // induction variable.
441 //
442 // If there were induction variables of other sizes or offsets, manually
443 // add the offsets to the primary induction variable and cast, avoiding
444 // the need for the code evaluation methods to insert induction variables
445 // of different sizes.
446 for (unsigned i = 0, e = IU->StrideOrder.size(); i != e; ++i) {
447 SCEVHandle Stride = IU->StrideOrder[i];
448
449 std::map<SCEVHandle, IVUsersOfOneStride *>::iterator SI =
450 IU->IVUsesByStride.find(IU->StrideOrder[i]);
451 assert(SI != IU->IVUsesByStride.end() && "Stride doesn't exist!");
452 ilist<IVStrideUse> &List = SI->second->Users;
453 for (ilist<IVStrideUse>::iterator UI = List.begin(),
454 E = List.end(); UI != E; ++UI) {
455 SCEVHandle Offset = UI->getOffset();
456 Value *Op = UI->getOperandValToReplace();
457 Instruction *User = UI->getUser();
458 bool isSigned = UI->isSigned();
459
460 // Compute the final addrec to expand into code.
461 SCEVHandle AR = IU->getReplacementExpr(*UI);
462
463 // FIXME: It is an extremely bad idea to indvar substitute anything more
464 // complex than affine induction variables. Doing so will put expensive
465 // polynomial evaluations inside of the loop, and the str reduction pass
466 // currently can only reduce affine polynomials. For now just disable
467 // indvar subst on anything more complex than an affine addrec, unless
468 // it can be expanded to a trivial value.
469 if (!Stride->isLoopInvariant(L) &&
470 !isa<SCEVConstant>(AR) &&
471 L->contains(User->getParent()))
472 continue;
473
474 Value *NewVal = 0;
475 if (AR->isLoopInvariant(L)) {
476 BasicBlock::iterator I = Rewriter.getInsertionPoint();
477 // Expand loop-invariant values in the loop preheader. They will
478 // be sunk to the exit block later, if possible.
Dan Gohman5be18e82009-05-19 02:15:55 +0000479 NewVal =
Dan Gohman81db61a2009-05-12 02:17:14 +0000480 Rewriter.expandCodeFor(AR, LargestType,
481 L->getLoopPreheader()->getTerminator());
482 Rewriter.setInsertionPoint(I);
483 ++NumReplaced;
484 } else {
485 const Type *IVTy = Offset->getType();
486 const Type *UseTy = Op->getType();
487
488 // Promote the Offset and Stride up to the canonical induction
489 // variable's bit width.
490 SCEVHandle PromotedOffset = Offset;
491 SCEVHandle PromotedStride = Stride;
492 if (SE->getTypeSizeInBits(IVTy) != SE->getTypeSizeInBits(LargestType)) {
493 // It doesn't matter for correctness whether zero or sign extension
494 // is used here, since the value is truncated away below, but if the
495 // value is signed, sign extension is more likely to be folded.
496 if (isSigned) {
497 PromotedOffset = SE->getSignExtendExpr(PromotedOffset, LargestType);
498 PromotedStride = SE->getSignExtendExpr(PromotedStride, LargestType);
499 } else {
500 PromotedOffset = SE->getZeroExtendExpr(PromotedOffset, LargestType);
501 // If the stride is obviously negative, use sign extension to
502 // produce things like x-1 instead of x+255.
503 if (isa<SCEVConstant>(PromotedStride) &&
504 cast<SCEVConstant>(PromotedStride)
505 ->getValue()->getValue().isNegative())
506 PromotedStride = SE->getSignExtendExpr(PromotedStride,
507 LargestType);
508 else
509 PromotedStride = SE->getZeroExtendExpr(PromotedStride,
510 LargestType);
511 }
512 }
513
514 // Create the SCEV representing the offset from the canonical
515 // induction variable, still in the canonical induction variable's
516 // type, so that all expanded arithmetic is done in the same type.
517 SCEVHandle NewAR = SE->getAddRecExpr(SE->getIntegerSCEV(0, LargestType),
518 PromotedStride, L);
519 // Add the PromotedOffset as a separate step, because it may not be
520 // loop-invariant.
521 NewAR = SE->getAddExpr(NewAR, PromotedOffset);
522
523 // Expand the addrec into instructions.
Dan Gohman5be18e82009-05-19 02:15:55 +0000524 Value *V = Rewriter.expandCodeFor(NewAR);
Dan Gohman81db61a2009-05-12 02:17:14 +0000525
526 // Insert an explicit cast if necessary to truncate the value
527 // down to the original stride type. This is done outside of
528 // SCEVExpander because in SCEV expressions, a truncate of an
529 // addrec is always folded.
530 if (LargestType != IVTy) {
531 if (SE->getTypeSizeInBits(IVTy) != SE->getTypeSizeInBits(LargestType))
532 NewAR = SE->getTruncateExpr(NewAR, IVTy);
533 if (Rewriter.isInsertedExpression(NewAR))
Dan Gohman5be18e82009-05-19 02:15:55 +0000534 V = Rewriter.expandCodeFor(NewAR);
Dan Gohman81db61a2009-05-12 02:17:14 +0000535 else {
536 V = Rewriter.InsertCastOfTo(CastInst::getCastOpcode(V, false,
537 IVTy, false),
538 V, IVTy);
539 assert(!isa<SExtInst>(V) && !isa<ZExtInst>(V) &&
540 "LargestType wasn't actually the largest type!");
541 // Force the rewriter to use this trunc whenever this addrec
542 // appears so that it doesn't insert new phi nodes or
543 // arithmetic in a different type.
544 Rewriter.addInsertedValue(V, NewAR);
545 }
546 }
547
548 DOUT << "INDVARS: Made offset-and-trunc IV for offset "
549 << *IVTy << " " << *Offset << ": ";
550 DEBUG(WriteAsOperand(*DOUT, V, false));
551 DOUT << "\n";
552
553 // Now expand it into actual Instructions and patch it into place.
554 NewVal = Rewriter.expandCodeFor(AR, UseTy);
555 }
556
557 // Patch the new value into place.
558 if (Op->hasName())
559 NewVal->takeName(Op);
560 User->replaceUsesOfWith(Op, NewVal);
561 UI->setOperandValToReplace(NewVal);
562 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *Op
563 << " into = " << *NewVal << "\n";
564 ++NumRemoved;
565 Changed = true;
566
567 // The old value may be dead now.
568 DeadInsts.push_back(Op);
569 }
570 }
571
572 // Now that we're done iterating through lists, clean up any instructions
573 // which are now dead.
574 while (!DeadInsts.empty()) {
575 Instruction *Inst = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
576 if (Inst)
577 RecursivelyDeleteTriviallyDeadInstructions(Inst);
578 }
579}
580
581/// If there's a single exit block, sink any loop-invariant values that
582/// were defined in the preheader but not used inside the loop into the
583/// exit block to reduce register pressure in the loop.
584void IndVarSimplify::SinkUnusedInvariants(Loop *L, SCEVExpander &Rewriter) {
585 BasicBlock *ExitBlock = L->getExitBlock();
586 if (!ExitBlock) return;
587
588 Instruction *NonPHI = ExitBlock->getFirstNonPHI();
589 BasicBlock *Preheader = L->getLoopPreheader();
590 BasicBlock::iterator I = Preheader->getTerminator();
591 while (I != Preheader->begin()) {
592 --I;
593 // New instructions were inserted at the end of the preheader. Only
594 // consider those new instructions.
595 if (!Rewriter.isInsertedInstruction(I))
596 break;
597 // Determine if there is a use in or before the loop (direct or
598 // otherwise).
599 bool UsedInLoop = false;
600 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
601 UI != UE; ++UI) {
602 BasicBlock *UseBB = cast<Instruction>(UI)->getParent();
603 if (PHINode *P = dyn_cast<PHINode>(UI)) {
604 unsigned i =
605 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
606 UseBB = P->getIncomingBlock(i);
607 }
608 if (UseBB == Preheader || L->contains(UseBB)) {
609 UsedInLoop = true;
610 break;
611 }
612 }
613 // If there is, the def must remain in the preheader.
614 if (UsedInLoop)
615 continue;
616 // Otherwise, sink it to the exit block.
617 Instruction *ToMove = I;
618 bool Done = false;
619 if (I != Preheader->begin())
620 --I;
621 else
622 Done = true;
623 ToMove->moveBefore(NonPHI);
624 if (Done)
625 break;
626 }
627}
628
629/// Re-schedule the inserted instructions to put defs before uses. This
630/// fixes problems that arrise when SCEV expressions contain loop-variant
631/// values unrelated to the induction variable which are defined inside the
632/// loop. FIXME: It would be better to insert instructions in the right
633/// place so that this step isn't needed.
634void IndVarSimplify::FixUsesBeforeDefs(Loop *L, SCEVExpander &Rewriter) {
635 // Visit all the blocks in the loop in pre-order dom-tree dfs order.
636 DominatorTree *DT = &getAnalysis<DominatorTree>();
637 std::map<Instruction *, unsigned> NumPredsLeft;
638 SmallVector<DomTreeNode *, 16> Worklist;
639 Worklist.push_back(DT->getNode(L->getHeader()));
640 do {
641 DomTreeNode *Node = Worklist.pop_back_val();
642 for (DomTreeNode::iterator I = Node->begin(), E = Node->end(); I != E; ++I)
643 if (L->contains((*I)->getBlock()))
644 Worklist.push_back(*I);
645 BasicBlock *BB = Node->getBlock();
646 // Visit all the instructions in the block top down.
647 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
648 // Count the number of operands that aren't properly dominating.
649 unsigned NumPreds = 0;
650 if (Rewriter.isInsertedInstruction(I) && !isa<PHINode>(I))
651 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
652 OI != OE; ++OI)
653 if (Instruction *Inst = dyn_cast<Instruction>(OI))
654 if (L->contains(Inst->getParent()) && !NumPredsLeft.count(Inst))
655 ++NumPreds;
656 NumPredsLeft[I] = NumPreds;
657 // Notify uses of the position of this instruction, and move the
658 // users (and their dependents, recursively) into place after this
659 // instruction if it is their last outstanding operand.
660 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
661 UI != UE; ++UI) {
662 Instruction *Inst = cast<Instruction>(UI);
663 std::map<Instruction *, unsigned>::iterator Z = NumPredsLeft.find(Inst);
664 if (Z != NumPredsLeft.end() && Z->second != 0 && --Z->second == 0) {
665 SmallVector<Instruction *, 4> UseWorkList;
666 UseWorkList.push_back(Inst);
Dan Gohmand6d02942009-05-22 16:47:11 +0000667 BasicBlock::iterator InsertPt = I;
668 if (InvokeInst *II = dyn_cast<InvokeInst>(InsertPt))
669 InsertPt = II->getNormalDest()->begin();
670 else
671 ++InsertPt;
Dan Gohman81db61a2009-05-12 02:17:14 +0000672 while (isa<PHINode>(InsertPt)) ++InsertPt;
673 do {
674 Instruction *Use = UseWorkList.pop_back_val();
675 Use->moveBefore(InsertPt);
676 NumPredsLeft.erase(Use);
677 for (Value::use_iterator IUI = Use->use_begin(),
678 IUE = Use->use_end(); IUI != IUE; ++IUI) {
679 Instruction *IUIInst = cast<Instruction>(IUI);
680 if (L->contains(IUIInst->getParent()) &&
681 Rewriter.isInsertedInstruction(IUIInst) &&
682 !isa<PHINode>(IUIInst))
683 UseWorkList.push_back(IUIInst);
684 }
685 } while (!UseWorkList.empty());
686 }
687 }
688 }
689 } while (!Worklist.empty());
690}
691
Devang Patel13877bf2008-11-18 00:40:02 +0000692/// Return true if it is OK to use SIToFPInst for an inducation variable
693/// with given inital and exit values.
694static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
695 uint64_t intIV, uint64_t intEV) {
696
Dan Gohmancafb8132009-02-17 19:13:57 +0000697 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
Devang Patel13877bf2008-11-18 00:40:02 +0000698 return true;
699
700 // If the iteration range can be handled by SIToFPInst then use it.
701 APInt Max = APInt::getSignedMaxValue(32);
Dale Johannesenbae7d6d2009-05-14 16:47:34 +0000702 if (Max.getZExtValue() > static_cast<uint64_t>(abs64(intEV - intIV)))
Devang Patel13877bf2008-11-18 00:40:02 +0000703 return true;
Dan Gohmancafb8132009-02-17 19:13:57 +0000704
Devang Patel13877bf2008-11-18 00:40:02 +0000705 return false;
706}
707
708/// convertToInt - Convert APF to an integer, if possible.
Devang Patelcd402332008-11-17 23:27:13 +0000709static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
710
711 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000712 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
713 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000714 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
Devang Patelcd402332008-11-17 23:27:13 +0000715 APFloat::rmTowardZero, &isExact)
716 != APFloat::opOK)
717 return false;
Dan Gohmancafb8132009-02-17 19:13:57 +0000718 if (!isExact)
Devang Patelcd402332008-11-17 23:27:13 +0000719 return false;
720 return true;
721
722}
723
Devang Patel58d43d42008-11-03 18:32:19 +0000724/// HandleFloatingPointIV - If the loop has floating induction variable
725/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000726/// For example,
727/// for(double i = 0; i < 10000; ++i)
728/// bar(i)
729/// is converted into
730/// for(int i = 0; i < 10000; ++i)
731/// bar((double)i);
732///
Dan Gohman81db61a2009-05-12 02:17:14 +0000733void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH) {
Devang Patel58d43d42008-11-03 18:32:19 +0000734
Devang Patel84e35152008-11-17 21:32:02 +0000735 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
736 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +0000737
Devang Patel84e35152008-11-17 21:32:02 +0000738 // Check incoming value.
Devang Patelcd402332008-11-17 23:27:13 +0000739 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
740 if (!InitValue) return;
741 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
742 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
743 return;
744
745 // Check IV increment. Reject this PH if increement operation is not
746 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +0000747 BinaryOperator *Incr =
Devang Patel84e35152008-11-17 21:32:02 +0000748 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
749 if (!Incr) return;
750 if (Incr->getOpcode() != Instruction::Add) return;
751 ConstantFP *IncrValue = NULL;
752 unsigned IncrVIndex = 1;
753 if (Incr->getOperand(1) == PH)
754 IncrVIndex = 0;
755 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
756 if (!IncrValue) return;
Devang Patelcd402332008-11-17 23:27:13 +0000757 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
758 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
759 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000760
Devang Patelcd402332008-11-17 23:27:13 +0000761 // Check Incr uses. One user is PH and the other users is exit condition used
762 // by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000763 Value::use_iterator IncrUse = Incr->use_begin();
764 Instruction *U1 = cast<Instruction>(IncrUse++);
765 if (IncrUse == Incr->use_end()) return;
766 Instruction *U2 = cast<Instruction>(IncrUse++);
767 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000768
Devang Patel84e35152008-11-17 21:32:02 +0000769 // Find exit condition.
770 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
771 if (!EC)
772 EC = dyn_cast<FCmpInst>(U2);
773 if (!EC) return;
774
775 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
776 if (!BI->isConditional()) return;
777 if (BI->getCondition() != EC) return;
Devang Patel58d43d42008-11-03 18:32:19 +0000778 }
Devang Patel58d43d42008-11-03 18:32:19 +0000779
Devang Patelcd402332008-11-17 23:27:13 +0000780 // Find exit value. If exit value can not be represented as an interger then
781 // do not handle this floating point PH.
Devang Patel84e35152008-11-17 21:32:02 +0000782 ConstantFP *EV = NULL;
783 unsigned EVIndex = 1;
784 if (EC->getOperand(1) == Incr)
785 EVIndex = 0;
786 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
787 if (!EV) return;
Devang Patel84e35152008-11-17 21:32:02 +0000788 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
Devang Patelcd402332008-11-17 23:27:13 +0000789 if (!convertToInt(EV->getValueAPF(), &intEV))
Devang Patel84e35152008-11-17 21:32:02 +0000790 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000791
Devang Patel84e35152008-11-17 21:32:02 +0000792 // Find new predicate for integer comparison.
793 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
794 switch (EC->getPredicate()) {
795 case CmpInst::FCMP_OEQ:
796 case CmpInst::FCMP_UEQ:
797 NewPred = CmpInst::ICMP_EQ;
798 break;
799 case CmpInst::FCMP_OGT:
800 case CmpInst::FCMP_UGT:
801 NewPred = CmpInst::ICMP_UGT;
802 break;
803 case CmpInst::FCMP_OGE:
804 case CmpInst::FCMP_UGE:
805 NewPred = CmpInst::ICMP_UGE;
806 break;
807 case CmpInst::FCMP_OLT:
808 case CmpInst::FCMP_ULT:
809 NewPred = CmpInst::ICMP_ULT;
810 break;
811 case CmpInst::FCMP_OLE:
812 case CmpInst::FCMP_ULE:
813 NewPred = CmpInst::ICMP_ULE;
814 break;
815 default:
816 break;
Devang Patel58d43d42008-11-03 18:32:19 +0000817 }
Devang Patel84e35152008-11-17 21:32:02 +0000818 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000819
Devang Patel84e35152008-11-17 21:32:02 +0000820 // Insert new integer induction variable.
821 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
822 PH->getName()+".int", PH);
Devang Patelcd402332008-11-17 23:27:13 +0000823 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
Devang Patel84e35152008-11-17 21:32:02 +0000824 PH->getIncomingBlock(IncomingEdge));
825
Dan Gohmancafb8132009-02-17 19:13:57 +0000826 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
827 ConstantInt::get(Type::Int32Ty,
Devang Patelcd402332008-11-17 23:27:13 +0000828 newIncrValue),
Devang Patel84e35152008-11-17 21:32:02 +0000829 Incr->getName()+".int", Incr);
830 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
831
Dale Johannesen617d1082009-04-27 21:03:15 +0000832 // The back edge is edge 1 of newPHI, whatever it may have been in the
833 // original PHI.
Devang Patel84e35152008-11-17 21:32:02 +0000834 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
Dale Johannesen617d1082009-04-27 21:03:15 +0000835 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(1) : NewEV);
836 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(1));
Dan Gohmancafb8132009-02-17 19:13:57 +0000837 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
Devang Patel84e35152008-11-17 21:32:02 +0000838 EC->getParent()->getTerminator());
Dan Gohmancafb8132009-02-17 19:13:57 +0000839
Dan Gohman81db61a2009-05-12 02:17:14 +0000840 // In the following deltions, PH may become dead and may be deleted.
841 // Use a WeakVH to observe whether this happens.
842 WeakVH WeakPH = PH;
843
Devang Patel84e35152008-11-17 21:32:02 +0000844 // Delete old, floating point, exit comparision instruction.
Dan Gohman14fba292009-05-24 18:09:01 +0000845 NewEC->takeName(EC);
Devang Patel84e35152008-11-17 21:32:02 +0000846 EC->replaceAllUsesWith(NewEC);
Dan Gohman81db61a2009-05-12 02:17:14 +0000847 RecursivelyDeleteTriviallyDeadInstructions(EC);
Dan Gohmancafb8132009-02-17 19:13:57 +0000848
Devang Patel84e35152008-11-17 21:32:02 +0000849 // Delete old, floating point, increment instruction.
850 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman81db61a2009-05-12 02:17:14 +0000851 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +0000852
Dan Gohman81db61a2009-05-12 02:17:14 +0000853 // Replace floating induction variable, if it isn't already deleted.
854 // Give SIToFPInst preference over UIToFPInst because it is faster on
855 // platforms that are widely used.
856 if (WeakPH && !PH->use_empty()) {
857 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
858 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
859 PH->getParent()->getFirstNonPHI());
860 PH->replaceAllUsesWith(Conv);
861 } else {
862 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
863 PH->getParent()->getFirstNonPHI());
864 PH->replaceAllUsesWith(Conv);
865 }
866 RecursivelyDeleteTriviallyDeadInstructions(PH);
Devang Patelcd402332008-11-17 23:27:13 +0000867 }
Devang Patel58d43d42008-11-03 18:32:19 +0000868
Dan Gohman81db61a2009-05-12 02:17:14 +0000869 // Add a new IVUsers entry for the newly-created integer PHI.
870 IU->AddUsersIfInteresting(NewPHI);
871}