blob: 2693f3a9a9026c7cd6ff68b8b914783d88f03c2d [file] [log] [blame]
Chris Lattner6148c022001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6148c022001-12-03 17:28:42 +00009//
Chris Lattner40bf8b42004-04-02 20:24:31 +000010// This transformation analyzes and transforms the induction variables (and
11// computations derived from them) into simpler forms suitable for subsequent
12// analysis and transformation.
13//
Reid Spencer47a53ac2006-08-18 09:01:07 +000014// This transformation makes the following changes to each loop with an
Chris Lattner40bf8b42004-04-02 20:24:31 +000015// identifiable induction variable:
16// 1. All loops are transformed to have a SINGLE canonical induction variable
17// which starts at zero and steps by one.
18// 2. The canonical induction variable is guaranteed to be the first PHI node
19// in the loop header block.
Dan Gohmanea73f3c2009-06-14 22:38:41 +000020// 3. The canonical induction variable is guaranteed to be in a wide enough
21// type so that IV expressions need not be (directly) zero-extended or
22// sign-extended.
23// 4. Any pointer arithmetic recurrences are raised to use array subscripts.
Chris Lattner40bf8b42004-04-02 20:24:31 +000024//
25// If the trip count of a loop is computable, this pass also makes the following
26// changes:
27// 1. The exit condition for the loop is canonicalized to compare the
28// induction value against the exit value. This turns loops like:
29// 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
30// 2. Any use outside of the loop of an expression derived from the indvar
31// is changed to compute the derived value outside of the loop, eliminating
32// the dependence on the exit value of the induction variable. If the only
33// purpose of the loop is to compute the exit value of some derived
34// expression, this transformation will make the loop dead.
35//
36// This transformation should be followed by strength reduction after all of the
Dan Gohmanc2c4cbf2009-05-19 20:38:47 +000037// desired loop transformations have been performed.
Chris Lattner6148c022001-12-03 17:28:42 +000038//
39//===----------------------------------------------------------------------===//
40
Chris Lattner0e5f4992006-12-19 21:40:18 +000041#define DEBUG_TYPE "indvars"
Chris Lattner022103b2002-05-07 20:03:00 +000042#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000043#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000044#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000045#include "llvm/Instructions.h"
Devang Patel7b9f6b12010-03-15 22:23:03 +000046#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000047#include "llvm/LLVMContext.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000048#include "llvm/Type.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000049#include "llvm/Analysis/Dominators.h"
50#include "llvm/Analysis/IVUsers.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000051#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000052#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000053#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000054#include "llvm/Support/CFG.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000055#include "llvm/Support/CommandLine.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000056#include "llvm/Support/Debug.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000057#include "llvm/Support/raw_ostream.h"
John Criswell47df12d2003-12-18 17:19:19 +000058#include "llvm/Transforms/Utils/Local.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000059#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000060#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000061#include "llvm/ADT/Statistic.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000062#include "llvm/ADT/STLExtras.h"
John Criswell47df12d2003-12-18 17:19:19 +000063using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065STATISTIC(NumRemoved , "Number of aux indvars removed");
Chris Lattner0e5f4992006-12-19 21:40:18 +000066STATISTIC(NumInserted, "Number of canonical indvars added");
67STATISTIC(NumReplaced, "Number of exit values replaced");
68STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000071 class IndVarSimplify : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000072 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000073 LoopInfo *LI;
74 ScalarEvolution *SE;
Dan Gohmande53dc02009-06-27 05:16:57 +000075 DominatorTree *DT;
Chris Lattner15cad752003-12-23 07:47:09 +000076 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000077 public:
Devang Patel794fd752007-05-01 21:15:47 +000078
Dan Gohman5668cf72009-07-15 01:26:32 +000079 static char ID; // Pass identification, replacement for typeid
80 IndVarSimplify() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000081
Dan Gohman5668cf72009-07-15 01:26:32 +000082 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman60f8a632009-02-17 20:49:49 +000083
Dan Gohman5668cf72009-07-15 01:26:32 +000084 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
85 AU.addRequired<DominatorTree>();
86 AU.addRequired<LoopInfo>();
87 AU.addRequired<ScalarEvolution>();
88 AU.addRequiredID(LoopSimplifyID);
89 AU.addRequiredID(LCSSAID);
90 AU.addRequired<IVUsers>();
91 AU.addPreserved<ScalarEvolution>();
92 AU.addPreservedID(LoopSimplifyID);
93 AU.addPreservedID(LCSSAID);
94 AU.addPreserved<IVUsers>();
95 AU.setPreservesCFG();
96 }
Chris Lattner15cad752003-12-23 07:47:09 +000097
Chris Lattner40bf8b42004-04-02 20:24:31 +000098 private:
Devang Patel5ee99972007-03-07 06:39:01 +000099
Dan Gohman931e3452010-04-12 02:21:50 +0000100 void EliminateIVComparisons();
Dan Gohman60f8a632009-02-17 20:49:49 +0000101 void RewriteNonIntegerIVs(Loop *L);
102
Dan Gohman0bba49c2009-07-07 17:06:11 +0000103 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
Dan Gohmana5758712009-02-17 15:57:39 +0000104 Value *IndVar,
Dan Gohmanc2390b12009-02-12 22:19:27 +0000105 BasicBlock *ExitingBlock,
106 BranchInst *BI,
Dan Gohman15cab282009-02-23 23:20:35 +0000107 SCEVExpander &Rewriter);
Dan Gohman454d26d2010-02-22 04:11:59 +0000108 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000109
Dan Gohman454d26d2010-02-22 04:11:59 +0000110 void RewriteIVExpressions(Loop *L, 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) {
Dan Gohmanca9b7032010-04-12 21:13:43 +0000137 // Special case: If the backedge-taken count is a UDiv, it's very likely a
138 // UDiv that ScalarEvolution produced in order to compute a precise
139 // expression, rather than a UDiv from the user's code. If we can't find a
140 // UDiv in the code with some simple searching, assume the former and forego
141 // rewriting the loop.
142 if (isa<SCEVUDivExpr>(BackedgeTakenCount)) {
143 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
144 if (!OrigCond) return 0;
145 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
146 R = SE->getMinusSCEV(R, SE->getIntegerSCEV(1, R->getType()));
147 if (R != BackedgeTakenCount) {
148 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
149 L = SE->getMinusSCEV(L, SE->getIntegerSCEV(1, L->getType()));
150 if (L != BackedgeTakenCount)
151 return 0;
152 }
153 }
154
Chris Lattnerd2440572004-04-15 20:26:22 +0000155 // If the exiting block is not the same as the backedge block, we must compare
156 // against the preincremented value, otherwise we prefer to compare against
157 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000158 Value *CmpIndVar;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000159 const SCEV *RHS = BackedgeTakenCount;
Dan Gohmanc2390b12009-02-12 22:19:27 +0000160 if (ExitingBlock == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000161 // Add one to the "backedge-taken" count to get the trip count.
162 // If this addition may overflow, we have to be more pessimistic and
163 // cast the induction variable before doing the add.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000164 const SCEV *Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
165 const SCEV *N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000166 SE->getAddExpr(BackedgeTakenCount,
167 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000168 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000169 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000170 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000171 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000172 } else {
173 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000174 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
175 IndVar->getType());
176 RHS = SE->getAddExpr(RHS,
177 SE->getIntegerSCEV(1, IndVar->getType()));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000178 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000179
Dan Gohman46bdfb02009-02-24 18:55:53 +0000180 // The BackedgeTaken expression contains the number of times that the
181 // backedge branches to the loop header. This is one less than the
182 // number of times the loop executes, so use the incremented indvar.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000183 CmpIndVar = L->getCanonicalInductionVariableIncrement();
Chris Lattnerd2440572004-04-15 20:26:22 +0000184 } else {
185 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000186 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
187 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000188 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000189 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000190
Dan Gohman667d7872009-06-26 22:53:46 +0000191 // Expand the code for the iteration count.
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000192 assert(RHS->isLoopInvariant(L) &&
193 "Computed iteration count is not loop invariant!");
Dan Gohman667d7872009-06-26 22:53:46 +0000194 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000195
Reid Spencere4d87aa2006-12-23 06:05:41 +0000196 // Insert a new icmp_ne or icmp_eq instruction before the branch.
197 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000198 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000199 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000200 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000201 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000202
David Greenef67ef312010-01-05 01:27:06 +0000203 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
Chris Lattnerbdff5482009-08-23 04:37:46 +0000204 << " LHS:" << *CmpIndVar << '\n'
205 << " op:\t"
206 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
207 << " RHS:\t" << *RHS << "\n");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000208
Owen Anderson333c4002009-07-09 23:48:35 +0000209 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
Dan Gohman81db61a2009-05-12 02:17:14 +0000210
Dan Gohman24440802010-02-22 02:07:36 +0000211 Value *OrigCond = BI->getCondition();
Dan Gohman95bdbfa2009-05-24 19:11:38 +0000212 // It's tempting to use replaceAllUsesWith here to fully replace the old
213 // comparison, but that's not immediately safe, since users of the old
214 // comparison may not be dominated by the new comparison. Instead, just
215 // update the branch to use the new comparison; in the common case this
216 // will make old comparison dead.
217 BI->setCondition(Cond);
Dan Gohman81db61a2009-05-12 02:17:14 +0000218 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
219
Chris Lattner40bf8b42004-04-02 20:24:31 +0000220 ++NumLFTR;
221 Changed = true;
Dan Gohman81db61a2009-05-12 02:17:14 +0000222 return Cond;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000223}
224
Chris Lattner40bf8b42004-04-02 20:24:31 +0000225/// RewriteLoopExitValues - Check to see if this loop has a computable
226/// loop-invariant execution count. If so, this means that we can compute the
227/// final value of any expressions that are recurrent in the loop, and
228/// substitute the exit values from the loop into any instructions outside of
229/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000230///
231/// This is mostly redundant with the regular IndVarSimplify activities that
232/// happen later, except that it's more powerful in some cases, because it's
233/// able to brute-force evaluate arbitrary instructions as long as they have
234/// constant operands at the beginning of the loop.
Dan Gohman890f92b2009-04-18 17:56:28 +0000235void IndVarSimplify::RewriteLoopExitValues(Loop *L,
Dan Gohman667d7872009-06-26 22:53:46 +0000236 SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000237 // Verify the input to the pass in already in LCSSA form.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000238 assert(L->isLCSSAForm(*DT));
Dan Gohman81db61a2009-05-12 02:17:14 +0000239
Devang Patelb7211a22007-08-21 00:31:24 +0000240 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000241 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000242
Chris Lattner9f3d7382007-03-04 03:43:23 +0000243 // Find all values that are computed inside the loop, but used outside of it.
244 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
245 // the exit blocks of the loop to find them.
246 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
247 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000248
Chris Lattner9f3d7382007-03-04 03:43:23 +0000249 // If there are no PHI nodes in this exit block, then no values defined
250 // inside the loop are used on this path, skip it.
251 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
252 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000253
Chris Lattner9f3d7382007-03-04 03:43:23 +0000254 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000255
Chris Lattner9f3d7382007-03-04 03:43:23 +0000256 // Iterate over all of the PHI nodes.
257 BasicBlock::iterator BBI = ExitBB->begin();
258 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000259 if (PN->use_empty())
260 continue; // dead use, don't replace it
Dan Gohman814f2b22010-02-18 21:34:02 +0000261
262 // SCEV only supports integer expressions for now.
263 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
264 continue;
265
Dale Johannesen45a2d7d2010-02-19 07:14:22 +0000266 // It's necessary to tell ScalarEvolution about this explicitly so that
267 // it can walk the def-use list and forget all SCEVs, as it may not be
268 // watching the PHI itself. Once the new exit value is in place, there
269 // may not be a def-use connection between the loop and every instruction
270 // which got a SCEVAddRecExpr for that loop.
271 SE->forgetValue(PN);
272
Chris Lattner9f3d7382007-03-04 03:43:23 +0000273 // Iterate over all of the values in all the PHI nodes.
274 for (unsigned i = 0; i != NumPreds; ++i) {
275 // If the value being merged in is not integer or is not defined
276 // in the loop, skip it.
277 Value *InVal = PN->getIncomingValue(i);
Dan Gohman814f2b22010-02-18 21:34:02 +0000278 if (!isa<Instruction>(InVal))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000279 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000280
Chris Lattner9f3d7382007-03-04 03:43:23 +0000281 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000282 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000283 continue; // The Block is in a subloop, skip it.
284
285 // Check that InVal is defined in the loop.
286 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman92329c72009-12-18 01:24:09 +0000287 if (!L->contains(Inst))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000288 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000289
Chris Lattner9f3d7382007-03-04 03:43:23 +0000290 // Okay, this instruction has a user outside of the current loop
291 // and varies predictably *inside* the loop. Evaluate the value it
292 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000293 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +0000294 if (!ExitValue->isLoopInvariant(L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000295 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000296
Chris Lattner9f3d7382007-03-04 03:43:23 +0000297 Changed = true;
298 ++NumReplaced;
Dan Gohmancafb8132009-02-17 19:13:57 +0000299
Dan Gohman667d7872009-06-26 22:53:46 +0000300 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000301
David Greenef67ef312010-01-05 01:27:06 +0000302 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000303 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000304
305 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000306
Dan Gohman81db61a2009-05-12 02:17:14 +0000307 // If this instruction is dead now, delete it.
308 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000309
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000310 if (NumPreds == 1) {
311 // Completely replace a single-pred PHI. This is safe, because the
312 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
313 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000314 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000315 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000316 }
317 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000318 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000319 // Clone the PHI and delete the original one. This lets IVUsers and
320 // any other maps purge the original user from their records.
Devang Patel50b6e332009-10-27 22:16:29 +0000321 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohman667d7872009-06-26 22:53:46 +0000322 NewPN->takeName(PN);
323 NewPN->insertBefore(PN);
324 PN->replaceAllUsesWith(NewPN);
325 PN->eraseFromParent();
326 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000327 }
328 }
Dan Gohman472fdf72010-03-20 03:53:53 +0000329
330 // The insertion point instruction may have been deleted; clear it out
331 // so that the rewriter doesn't trip over it later.
332 Rewriter.clearInsertPoint();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000333}
334
Dan Gohman60f8a632009-02-17 20:49:49 +0000335void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000336 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000337 // If there are, change them into integer recurrences, permitting analysis by
338 // the SCEV routines.
339 //
340 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000341
Dan Gohman81db61a2009-05-12 02:17:14 +0000342 SmallVector<WeakVH, 8> PHIs;
343 for (BasicBlock::iterator I = Header->begin();
344 PHINode *PN = dyn_cast<PHINode>(I); ++I)
345 PHIs.push_back(PN);
346
347 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
348 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i]))
349 HandleFloatingPointIV(L, PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000350
Dan Gohman2d1be872009-04-16 03:18:22 +0000351 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000352 // may not have been able to compute a trip count. Now that we've done some
353 // re-writing, the trip count may be computable.
354 if (Changed)
Dan Gohman4c7279a2009-10-31 15:04:55 +0000355 SE->forgetLoop(L);
Dale Johannesenc671d892009-04-15 23:31:51 +0000356}
357
Dan Gohman931e3452010-04-12 02:21:50 +0000358void IndVarSimplify::EliminateIVComparisons() {
Dan Gohmandd842e32010-04-12 07:29:15 +0000359 SmallVector<WeakVH, 16> DeadInsts;
360
Dan Gohman931e3452010-04-12 02:21:50 +0000361 // Look for ICmp users.
Dan Gohmandd842e32010-04-12 07:29:15 +0000362 for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
363 IVStrideUse &UI = *I;
Dan Gohman931e3452010-04-12 02:21:50 +0000364 ICmpInst *ICmp = dyn_cast<ICmpInst>(UI.getUser());
365 if (!ICmp) continue;
366
367 bool Swapped = UI.getOperandValToReplace() == ICmp->getOperand(1);
368 ICmpInst::Predicate Pred = ICmp->getPredicate();
369 if (Swapped) Pred = ICmpInst::getSwappedPredicate(Pred);
370
371 // Get the SCEVs for the ICmp operands.
372 const SCEV *S = IU->getReplacementExpr(UI);
373 const SCEV *X = SE->getSCEV(ICmp->getOperand(!Swapped));
374
375 // Simplify unnecessary loops away.
376 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
377 S = SE->getSCEVAtScope(S, ICmpLoop);
378 X = SE->getSCEVAtScope(X, ICmpLoop);
379
380 // If the condition is always true or always false, replace it with
381 // a constant value.
382 if (SE->isKnownPredicate(Pred, S, X))
383 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
384 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
385 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
386 else
387 continue;
388
389 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Dan Gohmandd842e32010-04-12 07:29:15 +0000390 DeadInsts.push_back(ICmp);
Dan Gohman931e3452010-04-12 02:21:50 +0000391 }
Dan Gohmandd842e32010-04-12 07:29:15 +0000392
393 // Now that we're done iterating through lists, clean up any instructions
394 // which are now dead.
395 while (!DeadInsts.empty())
396 if (Instruction *Inst =
397 dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
398 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohman931e3452010-04-12 02:21:50 +0000399}
400
Dan Gohmanc2390b12009-02-12 22:19:27 +0000401bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000402 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +0000403 LI = &getAnalysis<LoopInfo>();
404 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +0000405 DT = &getAnalysis<DominatorTree>();
Devang Patel5ee99972007-03-07 06:39:01 +0000406 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +0000407
Dan Gohman2d1be872009-04-16 03:18:22 +0000408 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +0000409 // transform them to use integer recurrences.
410 RewriteNonIntegerIVs(L);
411
Dan Gohman81db61a2009-05-12 02:17:14 +0000412 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
Dan Gohman0bba49c2009-07-07 17:06:11 +0000413 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +0000414
Dan Gohman667d7872009-06-26 22:53:46 +0000415 // Create a rewriter object which we'll use to transform the code with.
416 SCEVExpander Rewriter(*SE);
417
Chris Lattner40bf8b42004-04-02 20:24:31 +0000418 // Check to see if this loop has a computable loop-invariant execution count.
419 // If so, this means that we can compute the final value of any expressions
420 // that are recurrent in the loop, and substitute the exit values from the
421 // loop into any instructions outside of the loop that use the final values of
422 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000423 //
Dan Gohman46bdfb02009-02-24 18:55:53 +0000424 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman454d26d2010-02-22 04:11:59 +0000425 RewriteLoopExitValues(L, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +0000426
Dan Gohmand890f292010-04-12 07:56:56 +0000427 // Simplify ICmp IV users.
428 EliminateIVComparisons();
429
Dan Gohman81db61a2009-05-12 02:17:14 +0000430 // Compute the type of the largest recurrence expression, and decide whether
431 // a canonical induction variable should be inserted.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000432 const Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000433 bool NeedCannIV = false;
Dan Gohman46bdfb02009-02-24 18:55:53 +0000434 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
435 LargestType = BackedgeTakenCount->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000436 LargestType = SE->getEffectiveSCEVType(LargestType);
Dan Gohman81db61a2009-05-12 02:17:14 +0000437 // If we have a known trip count and a single exit block, we'll be
438 // rewriting the loop exit test condition below, which requires a
439 // canonical induction variable.
440 if (ExitingBlock)
441 NeedCannIV = true;
Chris Lattnerf50af082004-04-17 18:08:33 +0000442 }
Dan Gohman572645c2010-02-12 10:34:29 +0000443 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
444 const Type *Ty =
445 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000446 if (!LargestType ||
Dan Gohman81db61a2009-05-12 02:17:14 +0000447 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000448 SE->getTypeSizeInBits(LargestType))
Dan Gohman81db61a2009-05-12 02:17:14 +0000449 LargestType = Ty;
Dan Gohman572645c2010-02-12 10:34:29 +0000450 NeedCannIV = true;
Chris Lattner6148c022001-12-03 17:28:42 +0000451 }
452
Dan Gohmanf451cb82010-02-10 16:03:48 +0000453 // Now that we know the largest of the induction variable expressions
Dan Gohman81db61a2009-05-12 02:17:14 +0000454 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000455 Value *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000456 if (NeedCannIV) {
Dan Gohman85669632010-02-25 06:57:05 +0000457 // Check to see if the loop already has any canonical-looking induction
458 // variables. If any are present and wider than the planned canonical
459 // induction variable, temporarily remove them, so that the Rewriter
460 // doesn't attempt to reuse them.
461 SmallVector<PHINode *, 2> OldCannIVs;
462 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
Dan Gohman4d8414f2009-06-13 16:25:49 +0000463 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
464 SE->getTypeSizeInBits(LargestType))
465 OldCannIV->removeFromParent();
466 else
Dan Gohman85669632010-02-25 06:57:05 +0000467 break;
468 OldCannIVs.push_back(OldCannIV);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000469 }
470
Dan Gohman667d7872009-06-26 22:53:46 +0000471 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000472
Dan Gohmanc2390b12009-02-12 22:19:27 +0000473 ++NumInserted;
474 Changed = true;
David Greenef67ef312010-01-05 01:27:06 +0000475 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +0000476
477 // Now that the official induction variable is established, reinsert
Dan Gohman85669632010-02-25 06:57:05 +0000478 // any old canonical-looking variables after it so that the IR remains
479 // consistent. They will be deleted as part of the dead-PHI deletion at
Dan Gohman4d8414f2009-06-13 16:25:49 +0000480 // the end of the pass.
Dan Gohman85669632010-02-25 06:57:05 +0000481 while (!OldCannIVs.empty()) {
482 PHINode *OldCannIV = OldCannIVs.pop_back_val();
483 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
484 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000485 }
Chris Lattner15cad752003-12-23 07:47:09 +0000486
Dan Gohmanc2390b12009-02-12 22:19:27 +0000487 // If we have a trip count expression, rewrite the loop's exit condition
488 // using it. We can currently only handle loops with a single exit.
Dan Gohman81db61a2009-05-12 02:17:14 +0000489 ICmpInst *NewICmp = 0;
Dan Gohman85669632010-02-25 06:57:05 +0000490 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
491 !BackedgeTakenCount->isZero() &&
492 ExitingBlock) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000493 assert(NeedCannIV &&
494 "LinearFunctionTestReplace requires a canonical induction variable");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000495 // Can't rewrite non-branch yet.
Dan Gohmand890f292010-04-12 07:56:56 +0000496 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
Dan Gohman81db61a2009-05-12 02:17:14 +0000497 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
498 ExitingBlock, BI, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000499 }
500
Torok Edwin3d431382009-05-24 20:08:21 +0000501 // Rewrite IV-derived expressions. Clears the rewriter cache.
Dan Gohman454d26d2010-02-22 04:11:59 +0000502 RewriteIVExpressions(L, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000503
Dan Gohman667d7872009-06-26 22:53:46 +0000504 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +0000505
Dan Gohman81db61a2009-05-12 02:17:14 +0000506 // Loop-invariant instructions in the preheader that aren't used in the
507 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +0000508 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +0000509
510 // For completeness, inform IVUsers of the IV use in the newly-created
511 // loop exit test instruction.
512 if (NewICmp)
513 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
514
515 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +0000516 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +0000517 // Check a post-condition.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000518 assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +0000519 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000520}
Devang Pateld22a8492008-09-09 21:41:07 +0000521
Dan Gohman448db1c2010-04-07 22:27:08 +0000522// FIXME: It is an extremely bad idea to indvar substitute anything more
523// complex than affine induction variables. Doing so will put expensive
524// polynomial evaluations inside of the loop, and the str reduction pass
525// currently can only reduce affine polynomials. For now just disable
526// indvar subst on anything more complex than an affine addrec, unless
527// it can be expanded to a trivial value.
528static bool isSafe(const SCEV *S, const Loop *L) {
529 // Loop-invariant values are safe.
530 if (S->isLoopInvariant(L)) return true;
531
532 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
533 // to transform them into efficient code.
534 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
535 return AR->isAffine();
536
537 // An add is safe it all its operands are safe.
538 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
539 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
540 E = Commutative->op_end(); I != E; ++I)
541 if (!isSafe(*I, L)) return false;
542 return true;
543 }
544
545 // A cast is safe if its operand is.
546 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
547 return isSafe(C->getOperand(), L);
548
549 // A udiv is safe if its operands are.
550 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
551 return isSafe(UD->getLHS(), L) &&
552 isSafe(UD->getRHS(), L);
553
554 // SCEVUnknown is always safe.
555 if (isa<SCEVUnknown>(S))
556 return true;
557
558 // Nothing else is safe.
559 return false;
560}
561
Dan Gohman454d26d2010-02-22 04:11:59 +0000562void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000563 SmallVector<WeakVH, 16> DeadInsts;
564
565 // Rewrite all induction variable expressions in terms of the canonical
566 // induction variable.
567 //
568 // If there were induction variables of other sizes or offsets, manually
569 // add the offsets to the primary induction variable and cast, avoiding
570 // the need for the code evaluation methods to insert induction variables
571 // of different sizes.
Dan Gohman572645c2010-02-12 10:34:29 +0000572 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
Dan Gohman572645c2010-02-12 10:34:29 +0000573 Value *Op = UI->getOperandValToReplace();
574 const Type *UseTy = Op->getType();
575 Instruction *User = UI->getUser();
Dan Gohman81db61a2009-05-12 02:17:14 +0000576
Dan Gohman572645c2010-02-12 10:34:29 +0000577 // Compute the final addrec to expand into code.
578 const SCEV *AR = IU->getReplacementExpr(*UI);
Dan Gohman81db61a2009-05-12 02:17:14 +0000579
Dan Gohman572645c2010-02-12 10:34:29 +0000580 // Evaluate the expression out of the loop, if possible.
581 if (!L->contains(UI->getUser())) {
582 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
583 if (ExitVal->isLoopInvariant(L))
584 AR = ExitVal;
Dan Gohman81db61a2009-05-12 02:17:14 +0000585 }
Dan Gohman572645c2010-02-12 10:34:29 +0000586
587 // FIXME: It is an extremely bad idea to indvar substitute anything more
588 // complex than affine induction variables. Doing so will put expensive
589 // polynomial evaluations inside of the loop, and the str reduction pass
590 // currently can only reduce affine polynomials. For now just disable
591 // indvar subst on anything more complex than an affine addrec, unless
592 // it can be expanded to a trivial value.
Dan Gohman448db1c2010-04-07 22:27:08 +0000593 if (!isSafe(AR, L))
Dan Gohman572645c2010-02-12 10:34:29 +0000594 continue;
595
596 // Determine the insertion point for this user. By default, insert
597 // immediately before the user. The SCEVExpander class will automatically
598 // hoist loop invariants out of the loop. For PHI nodes, there may be
599 // multiple uses, so compute the nearest common dominator for the
600 // incoming blocks.
601 Instruction *InsertPt = User;
602 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
603 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
604 if (PHI->getIncomingValue(i) == Op) {
605 if (InsertPt == User)
606 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
607 else
608 InsertPt =
609 DT->findNearestCommonDominator(InsertPt->getParent(),
610 PHI->getIncomingBlock(i))
611 ->getTerminator();
612 }
613
614 // Now expand it into actual Instructions and patch it into place.
615 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
616
Dan Gohmand7bfd002010-04-02 14:48:31 +0000617 // Inform ScalarEvolution that this value is changing. The change doesn't
618 // affect its value, but it does potentially affect which use lists the
619 // value will be on after the replacement, which affects ScalarEvolution's
620 // ability to walk use lists and drop dangling pointers when a value is
621 // deleted.
622 SE->forgetValue(User);
623
Dan Gohman572645c2010-02-12 10:34:29 +0000624 // Patch the new value into place.
625 if (Op->hasName())
626 NewVal->takeName(Op);
627 User->replaceUsesOfWith(Op, NewVal);
628 UI->setOperandValToReplace(NewVal);
629 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
630 << " into = " << *NewVal << "\n");
631 ++NumRemoved;
632 Changed = true;
633
634 // The old value may be dead now.
635 DeadInsts.push_back(Op);
Dan Gohman81db61a2009-05-12 02:17:14 +0000636 }
637
Torok Edwin3d431382009-05-24 20:08:21 +0000638 // Clear the rewriter cache, because values that are in the rewriter's cache
639 // can be deleted in the loop below, causing the AssertingVH in the cache to
640 // trigger.
641 Rewriter.clear();
Dan Gohman81db61a2009-05-12 02:17:14 +0000642 // Now that we're done iterating through lists, clean up any instructions
643 // which are now dead.
Dan Gohmana10756e2010-01-21 02:09:26 +0000644 while (!DeadInsts.empty())
645 if (Instruction *Inst =
646 dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
Dan Gohman81db61a2009-05-12 02:17:14 +0000647 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohman81db61a2009-05-12 02:17:14 +0000648}
649
650/// If there's a single exit block, sink any loop-invariant values that
651/// were defined in the preheader but not used inside the loop into the
652/// exit block to reduce register pressure in the loop.
Dan Gohman667d7872009-06-26 22:53:46 +0000653void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000654 BasicBlock *ExitBlock = L->getExitBlock();
655 if (!ExitBlock) return;
656
Dan Gohman81db61a2009-05-12 02:17:14 +0000657 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman03e896b2009-11-05 21:11:53 +0000658 if (!Preheader) return;
659
660 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
Dan Gohman81db61a2009-05-12 02:17:14 +0000661 BasicBlock::iterator I = Preheader->getTerminator();
662 while (I != Preheader->begin()) {
663 --I;
Dan Gohman667d7872009-06-26 22:53:46 +0000664 // New instructions were inserted at the end of the preheader.
665 if (isa<PHINode>(I))
Dan Gohman81db61a2009-05-12 02:17:14 +0000666 break;
Bill Wendling87a10f52010-03-23 21:15:59 +0000667
Eli Friedman0c77db32009-07-15 22:48:29 +0000668 // Don't move instructions which might have side effects, since the side
Bill Wendling87a10f52010-03-23 21:15:59 +0000669 // effects need to complete before instructions inside the loop. Also don't
670 // move instructions which might read memory, since the loop may modify
671 // memory. Note that it's okay if the instruction might have undefined
672 // behavior: LoopSimplify guarantees that the preheader dominates the exit
673 // block.
Eli Friedman0c77db32009-07-15 22:48:29 +0000674 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Dan Gohman667d7872009-06-26 22:53:46 +0000675 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000676
Devang Patel7b9f6b12010-03-15 22:23:03 +0000677 // Skip debug info intrinsics.
678 if (isa<DbgInfoIntrinsic>(I))
679 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000680
Dan Gohman76f497a2009-08-25 17:42:10 +0000681 // Don't sink static AllocaInsts out of the entry block, which would
682 // turn them into dynamic allocas!
683 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
684 if (AI->isStaticAlloca())
685 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000686
Dan Gohman81db61a2009-05-12 02:17:14 +0000687 // Determine if there is a use in or before the loop (direct or
688 // otherwise).
689 bool UsedInLoop = false;
690 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
691 UI != UE; ++UI) {
692 BasicBlock *UseBB = cast<Instruction>(UI)->getParent();
693 if (PHINode *P = dyn_cast<PHINode>(UI)) {
694 unsigned i =
695 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
696 UseBB = P->getIncomingBlock(i);
697 }
698 if (UseBB == Preheader || L->contains(UseBB)) {
699 UsedInLoop = true;
700 break;
701 }
702 }
Bill Wendling87a10f52010-03-23 21:15:59 +0000703
Dan Gohman81db61a2009-05-12 02:17:14 +0000704 // If there is, the def must remain in the preheader.
705 if (UsedInLoop)
706 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000707
Dan Gohman81db61a2009-05-12 02:17:14 +0000708 // Otherwise, sink it to the exit block.
709 Instruction *ToMove = I;
710 bool Done = false;
Bill Wendling87a10f52010-03-23 21:15:59 +0000711
712 if (I != Preheader->begin()) {
713 // Skip debug info intrinsics.
714 do {
715 --I;
716 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
717
718 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
719 Done = true;
720 } else {
Dan Gohman81db61a2009-05-12 02:17:14 +0000721 Done = true;
Bill Wendling87a10f52010-03-23 21:15:59 +0000722 }
723
Dan Gohman667d7872009-06-26 22:53:46 +0000724 ToMove->moveBefore(InsertPt);
Bill Wendling87a10f52010-03-23 21:15:59 +0000725 if (Done) break;
Dan Gohman667d7872009-06-26 22:53:46 +0000726 InsertPt = ToMove;
Dan Gohman81db61a2009-05-12 02:17:14 +0000727 }
728}
729
Chris Lattnerbbb91492010-04-03 06:41:49 +0000730/// ConvertToSInt - Convert APF to an integer, if possible.
731static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
Devang Patelcd402332008-11-17 23:27:13 +0000732 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000733 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
734 return false;
Chris Lattnerbbb91492010-04-03 06:41:49 +0000735 // See if we can convert this to an int64_t
736 uint64_t UIntVal;
737 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
738 &isExact) != APFloat::opOK || !isExact)
Devang Patelcd402332008-11-17 23:27:13 +0000739 return false;
Chris Lattnerbbb91492010-04-03 06:41:49 +0000740 IntVal = UIntVal;
Devang Patelcd402332008-11-17 23:27:13 +0000741 return true;
Devang Patelcd402332008-11-17 23:27:13 +0000742}
743
Devang Patel58d43d42008-11-03 18:32:19 +0000744/// HandleFloatingPointIV - If the loop has floating induction variable
745/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +0000746/// For example,
747/// for(double i = 0; i < 10000; ++i)
748/// bar(i)
749/// is converted into
750/// for(int i = 0; i < 10000; ++i)
751/// bar((double)i);
752///
Chris Lattnerc91961e2010-04-03 06:17:08 +0000753void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
754 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
Devang Patel84e35152008-11-17 21:32:02 +0000755 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +0000756
Devang Patel84e35152008-11-17 21:32:02 +0000757 // Check incoming value.
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000758 ConstantFP *InitValueVal =
Chris Lattnerc91961e2010-04-03 06:17:08 +0000759 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
Chris Lattner96fd7662010-04-03 07:18:48 +0000760
Chris Lattnerbbb91492010-04-03 06:41:49 +0000761 int64_t InitValue;
Chris Lattner96fd7662010-04-03 07:18:48 +0000762 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
Devang Patelcd402332008-11-17 23:27:13 +0000763 return;
764
Chris Lattnerc91961e2010-04-03 06:17:08 +0000765 // Check IV increment. Reject this PN if increment operation is not
Devang Patelcd402332008-11-17 23:27:13 +0000766 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +0000767 BinaryOperator *Incr =
Chris Lattnerc91961e2010-04-03 06:17:08 +0000768 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
Chris Lattner07aa76a2010-04-03 05:54:59 +0000769 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
770
771 // If this is not an add of the PHI with a constantfp, or if the constant fp
772 // is not an integer, bail out.
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000773 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
Chris Lattner96fd7662010-04-03 07:18:48 +0000774 int64_t IncValue;
Chris Lattnerc91961e2010-04-03 06:17:08 +0000775 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
Chris Lattner96fd7662010-04-03 07:18:48 +0000776 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
Devang Patelcd402332008-11-17 23:27:13 +0000777 return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000778
Chris Lattnerc91961e2010-04-03 06:17:08 +0000779 // Check Incr uses. One user is PN and the other user is an exit condition
Chris Lattner07aa76a2010-04-03 05:54:59 +0000780 // used by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +0000781 Value::use_iterator IncrUse = Incr->use_begin();
782 Instruction *U1 = cast<Instruction>(IncrUse++);
783 if (IncrUse == Incr->use_end()) return;
784 Instruction *U2 = cast<Instruction>(IncrUse++);
785 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +0000786
Chris Lattner07aa76a2010-04-03 05:54:59 +0000787 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
788 // only used by a branch, we can't transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +0000789 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
790 if (!Compare)
791 Compare = dyn_cast<FCmpInst>(U2);
792 if (Compare == 0 || !Compare->hasOneUse() ||
793 !isa<BranchInst>(Compare->use_back()))
Chris Lattner07aa76a2010-04-03 05:54:59 +0000794 return;
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000795
Chris Lattnerca703bd2010-04-03 06:11:07 +0000796 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
Devang Patel84e35152008-11-17 21:32:02 +0000797
Chris Lattnerd52c0722010-04-03 07:21:39 +0000798 // We need to verify that the branch actually controls the iteration count
799 // of the loop. If not, the new IV can overflow and no one will notice.
800 // The branch block must be in the loop and one of the successors must be out
801 // of the loop.
802 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
803 if (!L->contains(TheBr->getParent()) ||
804 (L->contains(TheBr->getSuccessor(0)) &&
805 L->contains(TheBr->getSuccessor(1))))
806 return;
Chris Lattner96fd7662010-04-03 07:18:48 +0000807
808
Chris Lattner07aa76a2010-04-03 05:54:59 +0000809 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
810 // transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +0000811 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
Chris Lattnerbbb91492010-04-03 06:41:49 +0000812 int64_t ExitValue;
813 if (ExitValueVal == 0 ||
814 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
Devang Patel84e35152008-11-17 21:32:02 +0000815 return;
Chris Lattnerbbb91492010-04-03 06:41:49 +0000816
Devang Patel84e35152008-11-17 21:32:02 +0000817 // Find new predicate for integer comparison.
818 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerca703bd2010-04-03 06:11:07 +0000819 switch (Compare->getPredicate()) {
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000820 default: return; // Unknown comparison.
Devang Patel84e35152008-11-17 21:32:02 +0000821 case CmpInst::FCMP_OEQ:
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000822 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
Chris Lattner96fd7662010-04-03 07:18:48 +0000823 case CmpInst::FCMP_ONE:
824 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
Devang Patel84e35152008-11-17 21:32:02 +0000825 case CmpInst::FCMP_OGT:
Chris Lattnera40e4a02010-04-03 06:25:21 +0000826 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
Devang Patel84e35152008-11-17 21:32:02 +0000827 case CmpInst::FCMP_OGE:
Chris Lattnera40e4a02010-04-03 06:25:21 +0000828 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
Devang Patel84e35152008-11-17 21:32:02 +0000829 case CmpInst::FCMP_OLT:
Chris Lattner43b85272010-04-03 06:30:03 +0000830 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
Devang Patel84e35152008-11-17 21:32:02 +0000831 case CmpInst::FCMP_OLE:
Chris Lattner43b85272010-04-03 06:30:03 +0000832 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
Devang Patel58d43d42008-11-03 18:32:19 +0000833 }
Chris Lattner96fd7662010-04-03 07:18:48 +0000834
835 // We convert the floating point induction variable to a signed i32 value if
836 // we can. This is only safe if the comparison will not overflow in a way
837 // that won't be trapped by the integer equivalent operations. Check for this
838 // now.
839 // TODO: We could use i64 if it is native and the range requires it.
840
841 // The start/stride/exit values must all fit in signed i32.
842 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
843 return;
844
845 // If not actually striding (add x, 0.0), avoid touching the code.
846 if (IncValue == 0)
847 return;
848
849 // Positive and negative strides have different safety conditions.
850 if (IncValue > 0) {
851 // If we have a positive stride, we require the init to be less than the
852 // exit value and an equality or less than comparison.
853 if (InitValue >= ExitValue ||
854 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
855 return;
856
857 uint32_t Range = uint32_t(ExitValue-InitValue);
858 if (NewPred == CmpInst::ICMP_SLE) {
859 // Normalize SLE -> SLT, check for infinite loop.
860 if (++Range == 0) return; // Range overflows.
861 }
862
863 unsigned Leftover = Range % uint32_t(IncValue);
864
865 // If this is an equality comparison, we require that the strided value
866 // exactly land on the exit value, otherwise the IV condition will wrap
867 // around and do things the fp IV wouldn't.
868 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
869 Leftover != 0)
870 return;
871
872 // If the stride would wrap around the i32 before exiting, we can't
873 // transform the IV.
874 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
875 return;
876
877 } else {
878 // If we have a negative stride, we require the init to be greater than the
879 // exit value and an equality or greater than comparison.
880 if (InitValue >= ExitValue ||
881 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
882 return;
883
884 uint32_t Range = uint32_t(InitValue-ExitValue);
885 if (NewPred == CmpInst::ICMP_SGE) {
886 // Normalize SGE -> SGT, check for infinite loop.
887 if (++Range == 0) return; // Range overflows.
888 }
889
890 unsigned Leftover = Range % uint32_t(-IncValue);
891
892 // If this is an equality comparison, we require that the strided value
893 // exactly land on the exit value, otherwise the IV condition will wrap
894 // around and do things the fp IV wouldn't.
895 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
896 Leftover != 0)
897 return;
898
899 // If the stride would wrap around the i32 before exiting, we can't
900 // transform the IV.
901 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
902 return;
903 }
904
905 const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
Dan Gohmancafb8132009-02-17 19:13:57 +0000906
Chris Lattnerbbb91492010-04-03 06:41:49 +0000907 // Insert new integer induction variable.
Chris Lattnerc91961e2010-04-03 06:17:08 +0000908 PHINode *NewPHI = PHINode::Create(Int32Ty, PN->getName()+".int", PN);
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000909 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
Chris Lattnerc91961e2010-04-03 06:17:08 +0000910 PN->getIncomingBlock(IncomingEdge));
Devang Patel84e35152008-11-17 21:32:02 +0000911
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000912 Value *NewAdd =
Chris Lattner96fd7662010-04-03 07:18:48 +0000913 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
Chris Lattnerc4f7e802010-04-03 06:05:10 +0000914 Incr->getName()+".int", Incr);
Chris Lattnerc91961e2010-04-03 06:17:08 +0000915 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
Devang Patel84e35152008-11-17 21:32:02 +0000916
Chris Lattnerca703bd2010-04-03 06:11:07 +0000917 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
918 ConstantInt::get(Int32Ty, ExitValue),
919 Compare->getName());
Dan Gohmancafb8132009-02-17 19:13:57 +0000920
Chris Lattnerc91961e2010-04-03 06:17:08 +0000921 // In the following deletions, PN may become dead and may be deleted.
Dan Gohman81db61a2009-05-12 02:17:14 +0000922 // Use a WeakVH to observe whether this happens.
Chris Lattnerc91961e2010-04-03 06:17:08 +0000923 WeakVH WeakPH = PN;
Dan Gohman81db61a2009-05-12 02:17:14 +0000924
Chris Lattnerca703bd2010-04-03 06:11:07 +0000925 // Delete the old floating point exit comparison. The branch starts using the
926 // new comparison.
927 NewCompare->takeName(Compare);
928 Compare->replaceAllUsesWith(NewCompare);
929 RecursivelyDeleteTriviallyDeadInstructions(Compare);
Dan Gohmancafb8132009-02-17 19:13:57 +0000930
Chris Lattnerca703bd2010-04-03 06:11:07 +0000931 // Delete the old floating point increment.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000932 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman81db61a2009-05-12 02:17:14 +0000933 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +0000934
Chris Lattner70c0d4f2010-04-03 06:16:22 +0000935 // If the FP induction variable still has uses, this is because something else
936 // in the loop uses its value. In order to canonicalize the induction
937 // variable, we chose to eliminate the IV and rewrite it in terms of an
938 // int->fp cast.
939 //
940 // We give preference to sitofp over uitofp because it is faster on most
941 // platforms.
942 if (WeakPH) {
Chris Lattnera40e4a02010-04-03 06:25:21 +0000943 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
944 PN->getParent()->getFirstNonPHI());
945 PN->replaceAllUsesWith(Conv);
Chris Lattnerc91961e2010-04-03 06:17:08 +0000946 RecursivelyDeleteTriviallyDeadInstructions(PN);
Devang Patelcd402332008-11-17 23:27:13 +0000947 }
Devang Patel58d43d42008-11-03 18:32:19 +0000948
Dan Gohman81db61a2009-05-12 02:17:14 +0000949 // Add a new IVUsers entry for the newly-created integer PHI.
950 IU->AddUsersIfInteresting(NewPHI);
951}