blob: a0e8b6e4583b76f05c9a1068d01fb3705616ae6d [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 Lattneree4f13a2007-01-07 01:14:12 +000055#include "llvm/Support/Debug.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000056#include "llvm/Support/raw_ostream.h"
John Criswell47df12d2003-12-18 17:19:19 +000057#include "llvm/Transforms/Utils/Local.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000058#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Trick37da4082011-05-04 02:10:13 +000059#include "llvm/Target/TargetData.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");
Andrew Trick37da4082011-05-04 02:10:13 +000066STATISTIC(NumWidened , "Number of indvars widened");
Chris Lattner0e5f4992006-12-19 21:40:18 +000067STATISTIC(NumInserted, "Number of canonical indvars added");
68STATISTIC(NumReplaced, "Number of exit values replaced");
69STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000070
Andrew Trick37da4082011-05-04 02:10:13 +000071// DisableIVRewrite mode currently affects IVUsers, so is defined in libAnalysis
72// and referenced here.
73namespace llvm {
74 extern bool DisableIVRewrite;
75}
76
Chris Lattner0e5f4992006-12-19 21:40:18 +000077namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000078 class IndVarSimplify : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000079 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000080 LoopInfo *LI;
81 ScalarEvolution *SE;
Dan Gohmande53dc02009-06-27 05:16:57 +000082 DominatorTree *DT;
Andrew Trick37da4082011-05-04 02:10:13 +000083 TargetData *TD;
Andrew Trickb12a7542011-03-17 23:51:11 +000084 SmallVector<WeakVH, 16> DeadInsts;
Chris Lattner15cad752003-12-23 07:47:09 +000085 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000086 public:
Devang Patel794fd752007-05-01 21:15:47 +000087
Dan Gohman5668cf72009-07-15 01:26:32 +000088 static char ID; // Pass identification, replacement for typeid
Andrew Trick37da4082011-05-04 02:10:13 +000089 IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0) {
Owen Anderson081c34b2010-10-19 17:21:58 +000090 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
91 }
Devang Patel794fd752007-05-01 21:15:47 +000092
Dan Gohman5668cf72009-07-15 01:26:32 +000093 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman60f8a632009-02-17 20:49:49 +000094
Dan Gohman5668cf72009-07-15 01:26:32 +000095 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
96 AU.addRequired<DominatorTree>();
97 AU.addRequired<LoopInfo>();
98 AU.addRequired<ScalarEvolution>();
99 AU.addRequiredID(LoopSimplifyID);
100 AU.addRequiredID(LCSSAID);
101 AU.addRequired<IVUsers>();
102 AU.addPreserved<ScalarEvolution>();
103 AU.addPreservedID(LoopSimplifyID);
104 AU.addPreservedID(LCSSAID);
105 AU.addPreserved<IVUsers>();
106 AU.setPreservesCFG();
107 }
Chris Lattner15cad752003-12-23 07:47:09 +0000108
Chris Lattner40bf8b42004-04-02 20:24:31 +0000109 private:
Andrew Trickb12a7542011-03-17 23:51:11 +0000110 bool isValidRewrite(Value *FromVal, Value *ToVal);
Devang Patel5ee99972007-03-07 06:39:01 +0000111
Dan Gohman931e3452010-04-12 02:21:50 +0000112 void EliminateIVComparisons();
Dan Gohmana590b792010-04-13 01:46:36 +0000113 void EliminateIVRemainders();
Dan Gohman60f8a632009-02-17 20:49:49 +0000114 void RewriteNonIntegerIVs(Loop *L);
Andrew Trick37da4082011-05-04 02:10:13 +0000115 const Type *WidenIVs(Loop *L, SCEVExpander &Rewriter);
Dan Gohman60f8a632009-02-17 20:49:49 +0000116
Andrew Trick4dfdf242011-05-03 22:24:10 +0000117 bool canExpandBackedgeTakenCount(Loop *L,
118 const SCEV *BackedgeTakenCount);
119
Dan Gohman0bba49c2009-07-07 17:06:11 +0000120 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
Andrew Trick4dfdf242011-05-03 22:24:10 +0000121 PHINode *IndVar,
122 SCEVExpander &Rewriter);
Andrew Trick37da4082011-05-04 02:10:13 +0000123
Dan Gohman454d26d2010-02-22 04:11:59 +0000124 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000125
Dan Gohman454d26d2010-02-22 04:11:59 +0000126 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000127
Dan Gohman667d7872009-06-26 22:53:46 +0000128 void SinkUnusedInvariants(Loop *L);
Dan Gohman81db61a2009-05-12 02:17:14 +0000129
130 void HandleFloatingPointIV(Loop *L, PHINode *PH);
Chris Lattner3324e712003-12-22 03:58:44 +0000131 };
Chris Lattner5e761402002-09-10 05:24:05 +0000132}
Chris Lattner394437f2001-12-04 04:32:29 +0000133
Dan Gohman844731a2008-05-13 00:00:25 +0000134char IndVarSimplify::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000135INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000136 "Induction Variable Simplification", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000137INITIALIZE_PASS_DEPENDENCY(DominatorTree)
138INITIALIZE_PASS_DEPENDENCY(LoopInfo)
139INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
140INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
141INITIALIZE_PASS_DEPENDENCY(LCSSA)
142INITIALIZE_PASS_DEPENDENCY(IVUsers)
143INITIALIZE_PASS_END(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000144 "Induction Variable Simplification", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000145
Daniel Dunbar394f0442008-10-22 23:32:42 +0000146Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000147 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000148}
149
Andrew Trickb12a7542011-03-17 23:51:11 +0000150/// isValidRewrite - Return true if the SCEV expansion generated by the
151/// rewriter can replace the original value. SCEV guarantees that it
152/// produces the same value, but the way it is produced may be illegal IR.
153/// Ideally, this function will only be called for verification.
154bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
155 // If an SCEV expression subsumed multiple pointers, its expansion could
156 // reassociate the GEP changing the base pointer. This is illegal because the
157 // final address produced by a GEP chain must be inbounds relative to its
158 // underlying object. Otherwise basic alias analysis, among other things,
159 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
160 // producing an expression involving multiple pointers. Until then, we must
161 // bail out here.
162 //
163 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
164 // because it understands lcssa phis while SCEV does not.
165 Value *FromPtr = FromVal;
166 Value *ToPtr = ToVal;
167 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
168 FromPtr = GEP->getPointerOperand();
169 }
170 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
171 ToPtr = GEP->getPointerOperand();
172 }
173 if (FromPtr != FromVal || ToPtr != ToVal) {
174 // Quickly check the common case
175 if (FromPtr == ToPtr)
176 return true;
177
178 // SCEV may have rewritten an expression that produces the GEP's pointer
179 // operand. That's ok as long as the pointer operand has the same base
180 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
181 // base of a recurrence. This handles the case in which SCEV expansion
182 // converts a pointer type recurrence into a nonrecurrent pointer base
183 // indexed by an integer recurrence.
184 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
185 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
186 if (FromBase == ToBase)
187 return true;
188
189 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
190 << *FromBase << " != " << *ToBase << "\n");
191
192 return false;
193 }
194 return true;
195}
196
Andrew Trick4dfdf242011-05-03 22:24:10 +0000197/// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
198/// count expression can be safely and cheaply expanded into an instruction
199/// sequence that can be used by LinearFunctionTestReplace.
200bool IndVarSimplify::
201canExpandBackedgeTakenCount(Loop *L,
202 const SCEV *BackedgeTakenCount) {
203 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
204 BackedgeTakenCount->isZero())
205 return false;
206
207 if (!L->getExitingBlock())
208 return false;
209
210 // Can't rewrite non-branch yet.
211 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
212 if (!BI)
213 return false;
214
Dan Gohmanca9b7032010-04-12 21:13:43 +0000215 // Special case: If the backedge-taken count is a UDiv, it's very likely a
216 // UDiv that ScalarEvolution produced in order to compute a precise
217 // expression, rather than a UDiv from the user's code. If we can't find a
218 // UDiv in the code with some simple searching, assume the former and forego
219 // rewriting the loop.
220 if (isa<SCEVUDivExpr>(BackedgeTakenCount)) {
221 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
Andrew Trick37da4082011-05-04 02:10:13 +0000222 if (!OrigCond) return false;
Dan Gohmanca9b7032010-04-12 21:13:43 +0000223 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
Dan Gohmandeff6212010-05-03 22:09:21 +0000224 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
Dan Gohmanca9b7032010-04-12 21:13:43 +0000225 if (R != BackedgeTakenCount) {
226 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
Dan Gohmandeff6212010-05-03 22:09:21 +0000227 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
Dan Gohmanca9b7032010-04-12 21:13:43 +0000228 if (L != BackedgeTakenCount)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000229 return false;
Dan Gohmanca9b7032010-04-12 21:13:43 +0000230 }
231 }
Andrew Trick4dfdf242011-05-03 22:24:10 +0000232 return true;
233}
234
235/// LinearFunctionTestReplace - This method rewrites the exit condition of the
236/// loop to be a canonical != comparison against the incremented loop induction
237/// variable. This pass is able to rewrite the exit tests of any loop where the
238/// SCEV analysis can determine a loop-invariant trip count of the loop, which
239/// is actually a much broader range than just linear tests.
240ICmpInst *IndVarSimplify::
241LinearFunctionTestReplace(Loop *L,
242 const SCEV *BackedgeTakenCount,
243 PHINode *IndVar,
244 SCEVExpander &Rewriter) {
245 assert(canExpandBackedgeTakenCount(L, BackedgeTakenCount) && "precondition");
246 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
Dan Gohmanca9b7032010-04-12 21:13:43 +0000247
Chris Lattnerd2440572004-04-15 20:26:22 +0000248 // If the exiting block is not the same as the backedge block, we must compare
249 // against the preincremented value, otherwise we prefer to compare against
250 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000251 Value *CmpIndVar;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000252 const SCEV *RHS = BackedgeTakenCount;
Andrew Trick4dfdf242011-05-03 22:24:10 +0000253 if (L->getExitingBlock() == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000254 // Add one to the "backedge-taken" count to get the trip count.
255 // If this addition may overflow, we have to be more pessimistic and
256 // cast the induction variable before doing the add.
Dan Gohmandeff6212010-05-03 22:09:21 +0000257 const SCEV *Zero = SE->getConstant(BackedgeTakenCount->getType(), 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000258 const SCEV *N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000259 SE->getAddExpr(BackedgeTakenCount,
Dan Gohmandeff6212010-05-03 22:09:21 +0000260 SE->getConstant(BackedgeTakenCount->getType(), 1));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000261 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000262 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000263 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000264 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000265 } else {
266 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000267 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
268 IndVar->getType());
269 RHS = SE->getAddExpr(RHS,
Dan Gohmandeff6212010-05-03 22:09:21 +0000270 SE->getConstant(IndVar->getType(), 1));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000271 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000272
Dan Gohman46bdfb02009-02-24 18:55:53 +0000273 // The BackedgeTaken expression contains the number of times that the
274 // backedge branches to the loop header. This is one less than the
275 // number of times the loop executes, so use the incremented indvar.
Andrew Trick4dfdf242011-05-03 22:24:10 +0000276 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
Chris Lattnerd2440572004-04-15 20:26:22 +0000277 } else {
278 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000279 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
280 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000281 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000282 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000283
Dan Gohman667d7872009-06-26 22:53:46 +0000284 // Expand the code for the iteration count.
Dan Gohman17ead4f2010-11-17 21:23:15 +0000285 assert(SE->isLoopInvariant(RHS, L) &&
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000286 "Computed iteration count is not loop invariant!");
Dan Gohman667d7872009-06-26 22:53:46 +0000287 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000288
Reid Spencere4d87aa2006-12-23 06:05:41 +0000289 // Insert a new icmp_ne or icmp_eq instruction before the branch.
290 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000291 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000292 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000293 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000294 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000295
David Greenef67ef312010-01-05 01:27:06 +0000296 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
Chris Lattnerbdff5482009-08-23 04:37:46 +0000297 << " LHS:" << *CmpIndVar << '\n'
298 << " op:\t"
299 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
300 << " RHS:\t" << *RHS << "\n");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000301
Owen Anderson333c4002009-07-09 23:48:35 +0000302 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
Dan Gohman81db61a2009-05-12 02:17:14 +0000303
Dan Gohman24440802010-02-22 02:07:36 +0000304 Value *OrigCond = BI->getCondition();
Dan Gohman95bdbfa2009-05-24 19:11:38 +0000305 // It's tempting to use replaceAllUsesWith here to fully replace the old
306 // comparison, but that's not immediately safe, since users of the old
307 // comparison may not be dominated by the new comparison. Instead, just
308 // update the branch to use the new comparison; in the common case this
309 // will make old comparison dead.
310 BI->setCondition(Cond);
Andrew Trick88e92cf2011-04-28 17:30:04 +0000311 DeadInsts.push_back(OrigCond);
Dan Gohman81db61a2009-05-12 02:17:14 +0000312
Chris Lattner40bf8b42004-04-02 20:24:31 +0000313 ++NumLFTR;
314 Changed = true;
Dan Gohman81db61a2009-05-12 02:17:14 +0000315 return Cond;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000316}
317
Chris Lattner40bf8b42004-04-02 20:24:31 +0000318/// RewriteLoopExitValues - Check to see if this loop has a computable
319/// loop-invariant execution count. If so, this means that we can compute the
320/// final value of any expressions that are recurrent in the loop, and
321/// substitute the exit values from the loop into any instructions outside of
322/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000323///
324/// This is mostly redundant with the regular IndVarSimplify activities that
325/// happen later, except that it's more powerful in some cases, because it's
326/// able to brute-force evaluate arbitrary instructions as long as they have
327/// constant operands at the beginning of the loop.
Chris Lattnerf1859892011-01-09 02:16:18 +0000328void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000329 // Verify the input to the pass in already in LCSSA form.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000330 assert(L->isLCSSAForm(*DT));
Dan Gohman81db61a2009-05-12 02:17:14 +0000331
Devang Patelb7211a22007-08-21 00:31:24 +0000332 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000333 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000334
Chris Lattner9f3d7382007-03-04 03:43:23 +0000335 // Find all values that are computed inside the loop, but used outside of it.
336 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
337 // the exit blocks of the loop to find them.
338 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
339 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000340
Chris Lattner9f3d7382007-03-04 03:43:23 +0000341 // If there are no PHI nodes in this exit block, then no values defined
342 // inside the loop are used on this path, skip it.
343 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
344 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000345
Chris Lattner9f3d7382007-03-04 03:43:23 +0000346 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000347
Chris Lattner9f3d7382007-03-04 03:43:23 +0000348 // Iterate over all of the PHI nodes.
349 BasicBlock::iterator BBI = ExitBB->begin();
350 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000351 if (PN->use_empty())
352 continue; // dead use, don't replace it
Dan Gohman814f2b22010-02-18 21:34:02 +0000353
354 // SCEV only supports integer expressions for now.
355 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
356 continue;
357
Dale Johannesen45a2d7d2010-02-19 07:14:22 +0000358 // It's necessary to tell ScalarEvolution about this explicitly so that
359 // it can walk the def-use list and forget all SCEVs, as it may not be
360 // watching the PHI itself. Once the new exit value is in place, there
361 // may not be a def-use connection between the loop and every instruction
362 // which got a SCEVAddRecExpr for that loop.
363 SE->forgetValue(PN);
364
Chris Lattner9f3d7382007-03-04 03:43:23 +0000365 // Iterate over all of the values in all the PHI nodes.
366 for (unsigned i = 0; i != NumPreds; ++i) {
367 // If the value being merged in is not integer or is not defined
368 // in the loop, skip it.
369 Value *InVal = PN->getIncomingValue(i);
Dan Gohman814f2b22010-02-18 21:34:02 +0000370 if (!isa<Instruction>(InVal))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000371 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000372
Chris Lattner9f3d7382007-03-04 03:43:23 +0000373 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000374 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000375 continue; // The Block is in a subloop, skip it.
376
377 // Check that InVal is defined in the loop.
378 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman92329c72009-12-18 01:24:09 +0000379 if (!L->contains(Inst))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000380 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000381
Chris Lattner9f3d7382007-03-04 03:43:23 +0000382 // Okay, this instruction has a user outside of the current loop
383 // and varies predictably *inside* the loop. Evaluate the value it
384 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000385 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +0000386 if (!SE->isLoopInvariant(ExitValue, L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000387 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000388
Dan Gohman667d7872009-06-26 22:53:46 +0000389 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000390
David Greenef67ef312010-01-05 01:27:06 +0000391 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000392 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000393
Andrew Trickb12a7542011-03-17 23:51:11 +0000394 if (!isValidRewrite(Inst, ExitVal)) {
395 DeadInsts.push_back(ExitVal);
396 continue;
397 }
398 Changed = true;
399 ++NumReplaced;
400
Chris Lattner9f3d7382007-03-04 03:43:23 +0000401 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000402
Dan Gohman81db61a2009-05-12 02:17:14 +0000403 // If this instruction is dead now, delete it.
404 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000405
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000406 if (NumPreds == 1) {
407 // Completely replace a single-pred PHI. This is safe, because the
408 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
409 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000410 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000411 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000412 }
413 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000414 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000415 // Clone the PHI and delete the original one. This lets IVUsers and
416 // any other maps purge the original user from their records.
Devang Patel50b6e332009-10-27 22:16:29 +0000417 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohman667d7872009-06-26 22:53:46 +0000418 NewPN->takeName(PN);
419 NewPN->insertBefore(PN);
420 PN->replaceAllUsesWith(NewPN);
421 PN->eraseFromParent();
422 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000423 }
424 }
Dan Gohman472fdf72010-03-20 03:53:53 +0000425
426 // The insertion point instruction may have been deleted; clear it out
427 // so that the rewriter doesn't trip over it later.
428 Rewriter.clearInsertPoint();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000429}
430
Dan Gohman60f8a632009-02-17 20:49:49 +0000431void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000432 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000433 // If there are, change them into integer recurrences, permitting analysis by
434 // the SCEV routines.
435 //
Chris Lattnerf1859892011-01-09 02:16:18 +0000436 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000437
Dan Gohman81db61a2009-05-12 02:17:14 +0000438 SmallVector<WeakVH, 8> PHIs;
439 for (BasicBlock::iterator I = Header->begin();
440 PHINode *PN = dyn_cast<PHINode>(I); ++I)
441 PHIs.push_back(PN);
442
443 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
Gabor Greifea4894a2010-09-18 11:53:39 +0000444 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
Dan Gohman81db61a2009-05-12 02:17:14 +0000445 HandleFloatingPointIV(L, PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000446
Dan Gohman2d1be872009-04-16 03:18:22 +0000447 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000448 // may not have been able to compute a trip count. Now that we've done some
449 // re-writing, the trip count may be computable.
450 if (Changed)
Dan Gohman4c7279a2009-10-31 15:04:55 +0000451 SE->forgetLoop(L);
Dale Johannesenc671d892009-04-15 23:31:51 +0000452}
453
Dan Gohman931e3452010-04-12 02:21:50 +0000454void IndVarSimplify::EliminateIVComparisons() {
455 // Look for ICmp users.
Dan Gohmandd842e32010-04-12 07:29:15 +0000456 for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
457 IVStrideUse &UI = *I;
Dan Gohman931e3452010-04-12 02:21:50 +0000458 ICmpInst *ICmp = dyn_cast<ICmpInst>(UI.getUser());
459 if (!ICmp) continue;
460
461 bool Swapped = UI.getOperandValToReplace() == ICmp->getOperand(1);
462 ICmpInst::Predicate Pred = ICmp->getPredicate();
463 if (Swapped) Pred = ICmpInst::getSwappedPredicate(Pred);
464
465 // Get the SCEVs for the ICmp operands.
466 const SCEV *S = IU->getReplacementExpr(UI);
467 const SCEV *X = SE->getSCEV(ICmp->getOperand(!Swapped));
468
469 // Simplify unnecessary loops away.
470 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
471 S = SE->getSCEVAtScope(S, ICmpLoop);
472 X = SE->getSCEVAtScope(X, ICmpLoop);
473
474 // If the condition is always true or always false, replace it with
475 // a constant value.
476 if (SE->isKnownPredicate(Pred, S, X))
477 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
478 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
479 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
480 else
481 continue;
482
483 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Dan Gohmandd842e32010-04-12 07:29:15 +0000484 DeadInsts.push_back(ICmp);
Dan Gohman931e3452010-04-12 02:21:50 +0000485 }
486}
487
Dan Gohmana590b792010-04-13 01:46:36 +0000488void IndVarSimplify::EliminateIVRemainders() {
Dan Gohmana590b792010-04-13 01:46:36 +0000489 // Look for SRem and URem users.
490 for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
491 IVStrideUse &UI = *I;
492 BinaryOperator *Rem = dyn_cast<BinaryOperator>(UI.getUser());
493 if (!Rem) continue;
494
495 bool isSigned = Rem->getOpcode() == Instruction::SRem;
496 if (!isSigned && Rem->getOpcode() != Instruction::URem)
497 continue;
498
499 // We're only interested in the case where we know something about
500 // the numerator.
501 if (UI.getOperandValToReplace() != Rem->getOperand(0))
502 continue;
503
504 // Get the SCEVs for the ICmp operands.
505 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
506 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
507
508 // Simplify unnecessary loops away.
509 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
510 S = SE->getSCEVAtScope(S, ICmpLoop);
511 X = SE->getSCEVAtScope(X, ICmpLoop);
512
513 // i % n --> i if i is in [0,n).
514 if ((!isSigned || SE->isKnownNonNegative(S)) &&
515 SE->isKnownPredicate(isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
516 S, X))
517 Rem->replaceAllUsesWith(Rem->getOperand(0));
518 else {
519 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
520 const SCEV *LessOne =
Dan Gohmandeff6212010-05-03 22:09:21 +0000521 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
Dan Gohmana590b792010-04-13 01:46:36 +0000522 if ((!isSigned || SE->isKnownNonNegative(LessOne)) &&
523 SE->isKnownPredicate(isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
524 LessOne, X)) {
525 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
526 Rem->getOperand(0), Rem->getOperand(1),
527 "tmp");
528 SelectInst *Sel =
529 SelectInst::Create(ICmp,
530 ConstantInt::get(Rem->getType(), 0),
531 Rem->getOperand(0), "tmp", Rem);
532 Rem->replaceAllUsesWith(Sel);
533 } else
534 continue;
535 }
536
537 // Inform IVUsers about the new users.
538 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
539 IU->AddUsersIfInteresting(I);
540
541 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
542 DeadInsts.push_back(Rem);
543 }
Dan Gohmana590b792010-04-13 01:46:36 +0000544}
545
Dan Gohmanc2390b12009-02-12 22:19:27 +0000546bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmana5283822010-06-18 01:35:11 +0000547 // If LoopSimplify form is not available, stay out of trouble. Some notes:
548 // - LSR currently only supports LoopSimplify-form loops. Indvars'
549 // canonicalization can be a pessimization without LSR to "clean up"
550 // afterwards.
551 // - We depend on having a preheader; in particular,
552 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
553 // and we're in trouble if we can't find the induction variable even when
554 // we've manually inserted one.
555 if (!L->isLoopSimplifyForm())
556 return false;
557
Dan Gohman81db61a2009-05-12 02:17:14 +0000558 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +0000559 LI = &getAnalysis<LoopInfo>();
560 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +0000561 DT = &getAnalysis<DominatorTree>();
Andrew Trick37da4082011-05-04 02:10:13 +0000562 TD = getAnalysisIfAvailable<TargetData>();
563
Andrew Trickb12a7542011-03-17 23:51:11 +0000564 DeadInsts.clear();
Devang Patel5ee99972007-03-07 06:39:01 +0000565 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +0000566
Dan Gohman2d1be872009-04-16 03:18:22 +0000567 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +0000568 // transform them to use integer recurrences.
569 RewriteNonIntegerIVs(L);
570
Dan Gohman0bba49c2009-07-07 17:06:11 +0000571 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +0000572
Dan Gohman667d7872009-06-26 22:53:46 +0000573 // Create a rewriter object which we'll use to transform the code with.
574 SCEVExpander Rewriter(*SE);
Andrew Trick37da4082011-05-04 02:10:13 +0000575 if (DisableIVRewrite)
576 Rewriter.disableCanonicalMode();
577
578 const Type *LargestType = 0;
579 if (DisableIVRewrite) {
580 LargestType = WidenIVs(L, Rewriter);
581 }
Dan Gohman667d7872009-06-26 22:53:46 +0000582
Chris Lattner40bf8b42004-04-02 20:24:31 +0000583 // Check to see if this loop has a computable loop-invariant execution count.
584 // If so, this means that we can compute the final value of any expressions
585 // that are recurrent in the loop, and substitute the exit values from the
586 // loop into any instructions outside of the loop that use the final values of
587 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000588 //
Dan Gohman46bdfb02009-02-24 18:55:53 +0000589 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman454d26d2010-02-22 04:11:59 +0000590 RewriteLoopExitValues(L, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +0000591
Dan Gohmand890f292010-04-12 07:56:56 +0000592 // Simplify ICmp IV users.
593 EliminateIVComparisons();
594
Dan Gohmana590b792010-04-13 01:46:36 +0000595 // Simplify SRem and URem IV users.
596 EliminateIVRemainders();
597
Dan Gohman81db61a2009-05-12 02:17:14 +0000598 // Compute the type of the largest recurrence expression, and decide whether
599 // a canonical induction variable should be inserted.
Dan Gohman81db61a2009-05-12 02:17:14 +0000600 bool NeedCannIV = false;
Andrew Trick4dfdf242011-05-03 22:24:10 +0000601 bool ExpandBECount = canExpandBackedgeTakenCount(L, BackedgeTakenCount);
602 if (ExpandBECount) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000603 // If we have a known trip count and a single exit block, we'll be
604 // rewriting the loop exit test condition below, which requires a
605 // canonical induction variable.
Andrew Trick4dfdf242011-05-03 22:24:10 +0000606 NeedCannIV = true;
607 const Type *Ty = BackedgeTakenCount->getType();
608 if (!LargestType ||
609 SE->getTypeSizeInBits(Ty) >
610 SE->getTypeSizeInBits(LargestType))
611 LargestType = SE->getEffectiveSCEVType(Ty);
Chris Lattnerf50af082004-04-17 18:08:33 +0000612 }
Dan Gohman572645c2010-02-12 10:34:29 +0000613 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
Andrew Trick4dfdf242011-05-03 22:24:10 +0000614 NeedCannIV = true;
Dan Gohman572645c2010-02-12 10:34:29 +0000615 const Type *Ty =
616 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000617 if (!LargestType ||
Dan Gohman81db61a2009-05-12 02:17:14 +0000618 SE->getTypeSizeInBits(Ty) >
Andrew Trick37da4082011-05-04 02:10:13 +0000619 SE->getTypeSizeInBits(LargestType))
620 LargestType = SE->getEffectiveSCEVType(Ty);
621 }
622 if (!DisableIVRewrite) {
623 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
624 NeedCannIV = true;
625 const Type *Ty =
626 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
627 if (!LargestType ||
628 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000629 SE->getTypeSizeInBits(LargestType))
Andrew Trick37da4082011-05-04 02:10:13 +0000630 LargestType = Ty;
631 }
Chris Lattner6148c022001-12-03 17:28:42 +0000632 }
633
Dan Gohmanf451cb82010-02-10 16:03:48 +0000634 // Now that we know the largest of the induction variable expressions
Dan Gohman81db61a2009-05-12 02:17:14 +0000635 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohman43ef3fb2010-07-20 17:18:52 +0000636 PHINode *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000637 if (NeedCannIV) {
Dan Gohman85669632010-02-25 06:57:05 +0000638 // Check to see if the loop already has any canonical-looking induction
639 // variables. If any are present and wider than the planned canonical
640 // induction variable, temporarily remove them, so that the Rewriter
641 // doesn't attempt to reuse them.
642 SmallVector<PHINode *, 2> OldCannIVs;
643 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
Dan Gohman4d8414f2009-06-13 16:25:49 +0000644 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
645 SE->getTypeSizeInBits(LargestType))
646 OldCannIV->removeFromParent();
647 else
Dan Gohman85669632010-02-25 06:57:05 +0000648 break;
649 OldCannIVs.push_back(OldCannIV);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000650 }
651
Dan Gohman667d7872009-06-26 22:53:46 +0000652 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000653
Dan Gohmanc2390b12009-02-12 22:19:27 +0000654 ++NumInserted;
655 Changed = true;
David Greenef67ef312010-01-05 01:27:06 +0000656 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +0000657
658 // Now that the official induction variable is established, reinsert
Dan Gohman85669632010-02-25 06:57:05 +0000659 // any old canonical-looking variables after it so that the IR remains
660 // consistent. They will be deleted as part of the dead-PHI deletion at
Dan Gohman4d8414f2009-06-13 16:25:49 +0000661 // the end of the pass.
Dan Gohman85669632010-02-25 06:57:05 +0000662 while (!OldCannIVs.empty()) {
663 PHINode *OldCannIV = OldCannIVs.pop_back_val();
664 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
665 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000666 }
Chris Lattner15cad752003-12-23 07:47:09 +0000667
Dan Gohmanc2390b12009-02-12 22:19:27 +0000668 // If we have a trip count expression, rewrite the loop's exit condition
669 // using it. We can currently only handle loops with a single exit.
Dan Gohman81db61a2009-05-12 02:17:14 +0000670 ICmpInst *NewICmp = 0;
Andrew Trick4dfdf242011-05-03 22:24:10 +0000671 if (ExpandBECount) {
672 assert(canExpandBackedgeTakenCount(L, BackedgeTakenCount) &&
673 "canonical IV disrupted BackedgeTaken expansion");
Dan Gohman81db61a2009-05-12 02:17:14 +0000674 assert(NeedCannIV &&
675 "LinearFunctionTestReplace requires a canonical induction variable");
Andrew Trick4dfdf242011-05-03 22:24:10 +0000676 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
677 Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000678 }
Andrew Trickb12a7542011-03-17 23:51:11 +0000679 // Rewrite IV-derived expressions.
Andrew Trick37da4082011-05-04 02:10:13 +0000680 if (!DisableIVRewrite)
681 RewriteIVExpressions(L, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +0000682
Andrew Trickb12a7542011-03-17 23:51:11 +0000683 // Clear the rewriter cache, because values that are in the rewriter's cache
684 // can be deleted in the loop below, causing the AssertingVH in the cache to
685 // trigger.
686 Rewriter.clear();
687
688 // Now that we're done iterating through lists, clean up any instructions
689 // which are now dead.
690 while (!DeadInsts.empty())
691 if (Instruction *Inst =
692 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
693 RecursivelyDeleteTriviallyDeadInstructions(Inst);
694
Dan Gohman667d7872009-06-26 22:53:46 +0000695 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +0000696
Dan Gohman81db61a2009-05-12 02:17:14 +0000697 // Loop-invariant instructions in the preheader that aren't used in the
698 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +0000699 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +0000700
701 // For completeness, inform IVUsers of the IV use in the newly-created
702 // loop exit test instruction.
703 if (NewICmp)
704 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
705
706 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +0000707 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +0000708 // Check a post-condition.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000709 assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +0000710 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000711}
Devang Pateld22a8492008-09-09 21:41:07 +0000712
Dan Gohman448db1c2010-04-07 22:27:08 +0000713// FIXME: It is an extremely bad idea to indvar substitute anything more
714// complex than affine induction variables. Doing so will put expensive
715// polynomial evaluations inside of the loop, and the str reduction pass
716// currently can only reduce affine polynomials. For now just disable
717// indvar subst on anything more complex than an affine addrec, unless
718// it can be expanded to a trivial value.
Dan Gohman17ead4f2010-11-17 21:23:15 +0000719static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
Dan Gohman448db1c2010-04-07 22:27:08 +0000720 // Loop-invariant values are safe.
Dan Gohman17ead4f2010-11-17 21:23:15 +0000721 if (SE->isLoopInvariant(S, L)) return true;
Dan Gohman448db1c2010-04-07 22:27:08 +0000722
723 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
724 // to transform them into efficient code.
725 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
726 return AR->isAffine();
727
728 // An add is safe it all its operands are safe.
729 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
730 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
731 E = Commutative->op_end(); I != E; ++I)
Dan Gohman17ead4f2010-11-17 21:23:15 +0000732 if (!isSafe(*I, L, SE)) return false;
Dan Gohman448db1c2010-04-07 22:27:08 +0000733 return true;
734 }
Andrew Trickead71d52011-03-17 23:46:48 +0000735
Dan Gohman448db1c2010-04-07 22:27:08 +0000736 // A cast is safe if its operand is.
737 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
Dan Gohman17ead4f2010-11-17 21:23:15 +0000738 return isSafe(C->getOperand(), L, SE);
Dan Gohman448db1c2010-04-07 22:27:08 +0000739
740 // A udiv is safe if its operands are.
741 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
Dan Gohman17ead4f2010-11-17 21:23:15 +0000742 return isSafe(UD->getLHS(), L, SE) &&
743 isSafe(UD->getRHS(), L, SE);
Dan Gohman448db1c2010-04-07 22:27:08 +0000744
745 // SCEVUnknown is always safe.
746 if (isa<SCEVUnknown>(S))
747 return true;
748
749 // Nothing else is safe.
750 return false;
751}
752
Andrew Trick37da4082011-05-04 02:10:13 +0000753/// Widen the type of any induction variables that are sign/zero extended and
754/// remove the [sz]ext uses.
755///
756/// FIXME: This may currently create extra IVs which could increase regpressure
757/// (without LSR to cleanup).
758///
759/// FIXME: may factor this with RewriteIVExpressions once it stabilizes.
760const Type *IndVarSimplify::WidenIVs(Loop *L, SCEVExpander &Rewriter) {
761 const Type *LargestType = 0;
762 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
763 Instruction *ExtInst = UI->getUser();
764 if (!isa<SExtInst>(ExtInst) && !isa<ZExtInst>(ExtInst))
765 continue;
766 const SCEV *AR = SE->getSCEV(ExtInst);
767 // Only widen this IV is SCEV tells us it's safe.
768 if (!isa<SCEVAddRecExpr>(AR) && !isa<SCEVAddExpr>(AR))
769 continue;
770
771 if (!L->contains(UI->getUser())) {
772 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
773 if (SE->isLoopInvariant(ExitVal, L))
774 AR = ExitVal;
775 }
776
777 // Only expand affine recurences.
778 if (!isSafe(AR, L, SE))
779 continue;
780
781 const Type *Ty =
782 SE->getEffectiveSCEVType(ExtInst->getType());
783
784 // Only remove [sz]ext if the wide IV is still a native type.
785 //
786 // FIXME: We may be able to remove the copy of this logic in
787 // IVUsers::AddUsersIfInteresting.
788 uint64_t Width = SE->getTypeSizeInBits(Ty);
789 if (Width > 64 || (TD && !TD->isLegalInteger(Width)))
790 continue;
791
792 // Now expand it into actual Instructions and patch it into place.
793 //
794 // FIXME: avoid creating a new IV.
795 Value *NewVal = Rewriter.expandCodeFor(AR, Ty, ExtInst);
796
797 DEBUG(dbgs() << "INDVARS: Widened IV '" << *AR << "' " << *ExtInst << '\n'
798 << " into = " << *NewVal << "\n");
799
800 if (!isValidRewrite(ExtInst, NewVal)) {
801 DeadInsts.push_back(NewVal);
802 continue;
803 }
804
805 ++NumWidened;
806 Changed = true;
807
808 if (!LargestType ||
809 SE->getTypeSizeInBits(Ty) >
810 SE->getTypeSizeInBits(LargestType))
811 LargestType = Ty;
812
813 SE->forgetValue(ExtInst);
814
815 // Patch the new value into place.
816 if (ExtInst->hasName())
817 NewVal->takeName(ExtInst);
818 ExtInst->replaceAllUsesWith(NewVal);
819
820 // The old value may be dead now.
821 DeadInsts.push_back(ExtInst);
822
823 // UI is a linked list iterator, so AddUsersIfInteresting effectively pushes
824 // nodes on the worklist.
825 IU->AddUsersIfInteresting(ExtInst);
826 }
827 return LargestType;
828}
829
Dan Gohman454d26d2010-02-22 04:11:59 +0000830void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000831 // Rewrite all induction variable expressions in terms of the canonical
832 // induction variable.
833 //
834 // If there were induction variables of other sizes or offsets, manually
835 // add the offsets to the primary induction variable and cast, avoiding
836 // the need for the code evaluation methods to insert induction variables
837 // of different sizes.
Dan Gohman572645c2010-02-12 10:34:29 +0000838 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
Dan Gohman572645c2010-02-12 10:34:29 +0000839 Value *Op = UI->getOperandValToReplace();
840 const Type *UseTy = Op->getType();
841 Instruction *User = UI->getUser();
Dan Gohman81db61a2009-05-12 02:17:14 +0000842
Dan Gohman572645c2010-02-12 10:34:29 +0000843 // Compute the final addrec to expand into code.
844 const SCEV *AR = IU->getReplacementExpr(*UI);
Dan Gohman81db61a2009-05-12 02:17:14 +0000845
Dan Gohman572645c2010-02-12 10:34:29 +0000846 // Evaluate the expression out of the loop, if possible.
847 if (!L->contains(UI->getUser())) {
848 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +0000849 if (SE->isLoopInvariant(ExitVal, L))
Dan Gohman572645c2010-02-12 10:34:29 +0000850 AR = ExitVal;
Dan Gohman81db61a2009-05-12 02:17:14 +0000851 }
Dan Gohman572645c2010-02-12 10:34:29 +0000852
853 // FIXME: It is an extremely bad idea to indvar substitute anything more
854 // complex than affine induction variables. Doing so will put expensive
855 // polynomial evaluations inside of the loop, and the str reduction pass
856 // currently can only reduce affine polynomials. For now just disable
857 // indvar subst on anything more complex than an affine addrec, unless
858 // it can be expanded to a trivial value.
Dan Gohman17ead4f2010-11-17 21:23:15 +0000859 if (!isSafe(AR, L, SE))
Dan Gohman572645c2010-02-12 10:34:29 +0000860 continue;
861
862 // Determine the insertion point for this user. By default, insert
863 // immediately before the user. The SCEVExpander class will automatically
864 // hoist loop invariants out of the loop. For PHI nodes, there may be
865 // multiple uses, so compute the nearest common dominator for the
866 // incoming blocks.
867 Instruction *InsertPt = User;
868 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
869 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
870 if (PHI->getIncomingValue(i) == Op) {
871 if (InsertPt == User)
872 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
873 else
874 InsertPt =
875 DT->findNearestCommonDominator(InsertPt->getParent(),
876 PHI->getIncomingBlock(i))
877 ->getTerminator();
878 }
879
880 // Now expand it into actual Instructions and patch it into place.
881 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
882
Andrew Trickb12a7542011-03-17 23:51:11 +0000883 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
884 << " into = " << *NewVal << "\n");
885
886 if (!isValidRewrite(Op, NewVal)) {
887 DeadInsts.push_back(NewVal);
888 continue;
889 }
Dan Gohmand7bfd002010-04-02 14:48:31 +0000890 // Inform ScalarEvolution that this value is changing. The change doesn't
891 // affect its value, but it does potentially affect which use lists the
892 // value will be on after the replacement, which affects ScalarEvolution's
893 // ability to walk use lists and drop dangling pointers when a value is
894 // deleted.
895 SE->forgetValue(User);
896
Dan Gohman572645c2010-02-12 10:34:29 +0000897 // Patch the new value into place.
898 if (Op->hasName())
899 NewVal->takeName(Op);
900 User->replaceUsesOfWith(Op, NewVal);
901 UI->setOperandValToReplace(NewVal);
Andrew Trickb12a7542011-03-17 23:51:11 +0000902
Dan Gohman572645c2010-02-12 10:34:29 +0000903 ++NumRemoved;
904 Changed = true;
905
906 // The old value may be dead now.
907 DeadInsts.push_back(Op);
Dan Gohman81db61a2009-05-12 02:17:14 +0000908 }
Dan Gohman81db61a2009-05-12 02:17:14 +0000909}
910
911/// If there's a single exit block, sink any loop-invariant values that
912/// were defined in the preheader but not used inside the loop into the
913/// exit block to reduce register pressure in the loop.
Dan Gohman667d7872009-06-26 22:53:46 +0000914void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000915 BasicBlock *ExitBlock = L->getExitBlock();
916 if (!ExitBlock) return;
917
Dan Gohman81db61a2009-05-12 02:17:14 +0000918 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman03e896b2009-11-05 21:11:53 +0000919 if (!Preheader) return;
920
921 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
Dan Gohman81db61a2009-05-12 02:17:14 +0000922 BasicBlock::iterator I = Preheader->getTerminator();
923 while (I != Preheader->begin()) {
924 --I;
Dan Gohman667d7872009-06-26 22:53:46 +0000925 // New instructions were inserted at the end of the preheader.
926 if (isa<PHINode>(I))
Dan Gohman81db61a2009-05-12 02:17:14 +0000927 break;
Bill Wendling87a10f52010-03-23 21:15:59 +0000928
Eli Friedman0c77db32009-07-15 22:48:29 +0000929 // Don't move instructions which might have side effects, since the side
Bill Wendling87a10f52010-03-23 21:15:59 +0000930 // effects need to complete before instructions inside the loop. Also don't
931 // move instructions which might read memory, since the loop may modify
932 // memory. Note that it's okay if the instruction might have undefined
933 // behavior: LoopSimplify guarantees that the preheader dominates the exit
934 // block.
Eli Friedman0c77db32009-07-15 22:48:29 +0000935 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Dan Gohman667d7872009-06-26 22:53:46 +0000936 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000937
Devang Patel7b9f6b12010-03-15 22:23:03 +0000938 // Skip debug info intrinsics.
939 if (isa<DbgInfoIntrinsic>(I))
940 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000941
Dan Gohman76f497a2009-08-25 17:42:10 +0000942 // Don't sink static AllocaInsts out of the entry block, which would
943 // turn them into dynamic allocas!
944 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
945 if (AI->isStaticAlloca())
946 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000947
Dan Gohman81db61a2009-05-12 02:17:14 +0000948 // Determine if there is a use in or before the loop (direct or
949 // otherwise).
950 bool UsedInLoop = false;
951 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
952 UI != UE; ++UI) {
Gabor Greif76560182010-07-09 15:40:10 +0000953 User *U = *UI;
954 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
955 if (PHINode *P = dyn_cast<PHINode>(U)) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000956 unsigned i =
957 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
958 UseBB = P->getIncomingBlock(i);
959 }
960 if (UseBB == Preheader || L->contains(UseBB)) {
961 UsedInLoop = true;
962 break;
963 }
964 }
Bill Wendling87a10f52010-03-23 21:15:59 +0000965
Dan Gohman81db61a2009-05-12 02:17:14 +0000966 // If there is, the def must remain in the preheader.
967 if (UsedInLoop)
968 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +0000969
Dan Gohman81db61a2009-05-12 02:17:14 +0000970 // Otherwise, sink it to the exit block.
971 Instruction *ToMove = I;
972 bool Done = false;
Bill Wendling87a10f52010-03-23 21:15:59 +0000973
974 if (I != Preheader->begin()) {
975 // Skip debug info intrinsics.
976 do {
977 --I;
978 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
979
980 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
981 Done = true;
982 } else {
Dan Gohman81db61a2009-05-12 02:17:14 +0000983 Done = true;
Bill Wendling87a10f52010-03-23 21:15:59 +0000984 }
985
Dan Gohman667d7872009-06-26 22:53:46 +0000986 ToMove->moveBefore(InsertPt);
Bill Wendling87a10f52010-03-23 21:15:59 +0000987 if (Done) break;
Dan Gohman667d7872009-06-26 22:53:46 +0000988 InsertPt = ToMove;
Dan Gohman81db61a2009-05-12 02:17:14 +0000989 }
990}
991
Chris Lattnerbbb91492010-04-03 06:41:49 +0000992/// ConvertToSInt - Convert APF to an integer, if possible.
993static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
Devang Patelcd402332008-11-17 23:27:13 +0000994 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +0000995 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
996 return false;
Chris Lattnerbbb91492010-04-03 06:41:49 +0000997 // See if we can convert this to an int64_t
998 uint64_t UIntVal;
999 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
1000 &isExact) != APFloat::opOK || !isExact)
Devang Patelcd402332008-11-17 23:27:13 +00001001 return false;
Chris Lattnerbbb91492010-04-03 06:41:49 +00001002 IntVal = UIntVal;
Devang Patelcd402332008-11-17 23:27:13 +00001003 return true;
Devang Patelcd402332008-11-17 23:27:13 +00001004}
1005
Devang Patel58d43d42008-11-03 18:32:19 +00001006/// HandleFloatingPointIV - If the loop has floating induction variable
1007/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +00001008/// For example,
1009/// for(double i = 0; i < 10000; ++i)
1010/// bar(i)
1011/// is converted into
1012/// for(int i = 0; i < 10000; ++i)
1013/// bar((double)i);
1014///
Chris Lattnerc91961e2010-04-03 06:17:08 +00001015void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
1016 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
Devang Patel84e35152008-11-17 21:32:02 +00001017 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +00001018
Devang Patel84e35152008-11-17 21:32:02 +00001019 // Check incoming value.
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001020 ConstantFP *InitValueVal =
Chris Lattnerc91961e2010-04-03 06:17:08 +00001021 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
Chris Lattner96fd7662010-04-03 07:18:48 +00001022
Chris Lattnerbbb91492010-04-03 06:41:49 +00001023 int64_t InitValue;
Chris Lattner96fd7662010-04-03 07:18:48 +00001024 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
Devang Patelcd402332008-11-17 23:27:13 +00001025 return;
1026
Chris Lattnerc91961e2010-04-03 06:17:08 +00001027 // Check IV increment. Reject this PN if increment operation is not
Devang Patelcd402332008-11-17 23:27:13 +00001028 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +00001029 BinaryOperator *Incr =
Chris Lattnerc91961e2010-04-03 06:17:08 +00001030 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
Chris Lattner07aa76a2010-04-03 05:54:59 +00001031 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
Andrew Trickead71d52011-03-17 23:46:48 +00001032
Chris Lattner07aa76a2010-04-03 05:54:59 +00001033 // If this is not an add of the PHI with a constantfp, or if the constant fp
1034 // is not an integer, bail out.
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001035 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
Chris Lattner96fd7662010-04-03 07:18:48 +00001036 int64_t IncValue;
Chris Lattnerc91961e2010-04-03 06:17:08 +00001037 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
Chris Lattner96fd7662010-04-03 07:18:48 +00001038 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
Devang Patelcd402332008-11-17 23:27:13 +00001039 return;
Dan Gohmancafb8132009-02-17 19:13:57 +00001040
Chris Lattnerc91961e2010-04-03 06:17:08 +00001041 // Check Incr uses. One user is PN and the other user is an exit condition
Chris Lattner07aa76a2010-04-03 05:54:59 +00001042 // used by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +00001043 Value::use_iterator IncrUse = Incr->use_begin();
Gabor Greif96f1d8e2010-07-22 13:36:47 +00001044 Instruction *U1 = cast<Instruction>(*IncrUse++);
Devang Patel84e35152008-11-17 21:32:02 +00001045 if (IncrUse == Incr->use_end()) return;
Gabor Greif96f1d8e2010-07-22 13:36:47 +00001046 Instruction *U2 = cast<Instruction>(*IncrUse++);
Devang Patel84e35152008-11-17 21:32:02 +00001047 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +00001048
Chris Lattner07aa76a2010-04-03 05:54:59 +00001049 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
1050 // only used by a branch, we can't transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +00001051 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
1052 if (!Compare)
1053 Compare = dyn_cast<FCmpInst>(U2);
1054 if (Compare == 0 || !Compare->hasOneUse() ||
1055 !isa<BranchInst>(Compare->use_back()))
Chris Lattner07aa76a2010-04-03 05:54:59 +00001056 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001057
Chris Lattnerca703bd2010-04-03 06:11:07 +00001058 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
Devang Patel84e35152008-11-17 21:32:02 +00001059
Chris Lattnerd52c0722010-04-03 07:21:39 +00001060 // We need to verify that the branch actually controls the iteration count
1061 // of the loop. If not, the new IV can overflow and no one will notice.
1062 // The branch block must be in the loop and one of the successors must be out
1063 // of the loop.
1064 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
1065 if (!L->contains(TheBr->getParent()) ||
1066 (L->contains(TheBr->getSuccessor(0)) &&
1067 L->contains(TheBr->getSuccessor(1))))
1068 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001069
1070
Chris Lattner07aa76a2010-04-03 05:54:59 +00001071 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
1072 // transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +00001073 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
Chris Lattnerbbb91492010-04-03 06:41:49 +00001074 int64_t ExitValue;
1075 if (ExitValueVal == 0 ||
1076 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
Devang Patel84e35152008-11-17 21:32:02 +00001077 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001078
Devang Patel84e35152008-11-17 21:32:02 +00001079 // Find new predicate for integer comparison.
1080 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerca703bd2010-04-03 06:11:07 +00001081 switch (Compare->getPredicate()) {
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001082 default: return; // Unknown comparison.
Devang Patel84e35152008-11-17 21:32:02 +00001083 case CmpInst::FCMP_OEQ:
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001084 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
Chris Lattner96fd7662010-04-03 07:18:48 +00001085 case CmpInst::FCMP_ONE:
1086 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
Devang Patel84e35152008-11-17 21:32:02 +00001087 case CmpInst::FCMP_OGT:
Chris Lattnera40e4a02010-04-03 06:25:21 +00001088 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
Devang Patel84e35152008-11-17 21:32:02 +00001089 case CmpInst::FCMP_OGE:
Chris Lattnera40e4a02010-04-03 06:25:21 +00001090 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
Devang Patel84e35152008-11-17 21:32:02 +00001091 case CmpInst::FCMP_OLT:
Chris Lattner43b85272010-04-03 06:30:03 +00001092 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
Devang Patel84e35152008-11-17 21:32:02 +00001093 case CmpInst::FCMP_OLE:
Chris Lattner43b85272010-04-03 06:30:03 +00001094 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
Devang Patel58d43d42008-11-03 18:32:19 +00001095 }
Andrew Trickead71d52011-03-17 23:46:48 +00001096
Chris Lattner96fd7662010-04-03 07:18:48 +00001097 // We convert the floating point induction variable to a signed i32 value if
1098 // we can. This is only safe if the comparison will not overflow in a way
1099 // that won't be trapped by the integer equivalent operations. Check for this
1100 // now.
1101 // TODO: We could use i64 if it is native and the range requires it.
Andrew Trickead71d52011-03-17 23:46:48 +00001102
Chris Lattner96fd7662010-04-03 07:18:48 +00001103 // The start/stride/exit values must all fit in signed i32.
1104 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
1105 return;
1106
1107 // If not actually striding (add x, 0.0), avoid touching the code.
1108 if (IncValue == 0)
1109 return;
1110
1111 // Positive and negative strides have different safety conditions.
1112 if (IncValue > 0) {
1113 // If we have a positive stride, we require the init to be less than the
1114 // exit value and an equality or less than comparison.
1115 if (InitValue >= ExitValue ||
1116 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
1117 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001118
Chris Lattner96fd7662010-04-03 07:18:48 +00001119 uint32_t Range = uint32_t(ExitValue-InitValue);
1120 if (NewPred == CmpInst::ICMP_SLE) {
1121 // Normalize SLE -> SLT, check for infinite loop.
1122 if (++Range == 0) return; // Range overflows.
1123 }
Andrew Trickead71d52011-03-17 23:46:48 +00001124
Chris Lattner96fd7662010-04-03 07:18:48 +00001125 unsigned Leftover = Range % uint32_t(IncValue);
Andrew Trickead71d52011-03-17 23:46:48 +00001126
Chris Lattner96fd7662010-04-03 07:18:48 +00001127 // If this is an equality comparison, we require that the strided value
1128 // exactly land on the exit value, otherwise the IV condition will wrap
1129 // around and do things the fp IV wouldn't.
1130 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1131 Leftover != 0)
1132 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001133
Chris Lattner96fd7662010-04-03 07:18:48 +00001134 // If the stride would wrap around the i32 before exiting, we can't
1135 // transform the IV.
1136 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
1137 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001138
Chris Lattner96fd7662010-04-03 07:18:48 +00001139 } else {
1140 // If we have a negative stride, we require the init to be greater than the
1141 // exit value and an equality or greater than comparison.
1142 if (InitValue >= ExitValue ||
1143 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
1144 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001145
Chris Lattner96fd7662010-04-03 07:18:48 +00001146 uint32_t Range = uint32_t(InitValue-ExitValue);
1147 if (NewPred == CmpInst::ICMP_SGE) {
1148 // Normalize SGE -> SGT, check for infinite loop.
1149 if (++Range == 0) return; // Range overflows.
1150 }
Andrew Trickead71d52011-03-17 23:46:48 +00001151
Chris Lattner96fd7662010-04-03 07:18:48 +00001152 unsigned Leftover = Range % uint32_t(-IncValue);
Andrew Trickead71d52011-03-17 23:46:48 +00001153
Chris Lattner96fd7662010-04-03 07:18:48 +00001154 // If this is an equality comparison, we require that the strided value
1155 // exactly land on the exit value, otherwise the IV condition will wrap
1156 // around and do things the fp IV wouldn't.
1157 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1158 Leftover != 0)
1159 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001160
Chris Lattner96fd7662010-04-03 07:18:48 +00001161 // If the stride would wrap around the i32 before exiting, we can't
1162 // transform the IV.
1163 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
1164 return;
1165 }
Andrew Trickead71d52011-03-17 23:46:48 +00001166
Chris Lattner96fd7662010-04-03 07:18:48 +00001167 const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
Dan Gohmancafb8132009-02-17 19:13:57 +00001168
Chris Lattnerbbb91492010-04-03 06:41:49 +00001169 // Insert new integer induction variable.
Jay Foad3ecfc862011-03-30 11:28:46 +00001170 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001171 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
Chris Lattnerc91961e2010-04-03 06:17:08 +00001172 PN->getIncomingBlock(IncomingEdge));
Devang Patel84e35152008-11-17 21:32:02 +00001173
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001174 Value *NewAdd =
Chris Lattner96fd7662010-04-03 07:18:48 +00001175 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001176 Incr->getName()+".int", Incr);
Chris Lattnerc91961e2010-04-03 06:17:08 +00001177 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
Devang Patel84e35152008-11-17 21:32:02 +00001178
Chris Lattnerca703bd2010-04-03 06:11:07 +00001179 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
1180 ConstantInt::get(Int32Ty, ExitValue),
1181 Compare->getName());
Dan Gohmancafb8132009-02-17 19:13:57 +00001182
Chris Lattnerc91961e2010-04-03 06:17:08 +00001183 // In the following deletions, PN may become dead and may be deleted.
Dan Gohman81db61a2009-05-12 02:17:14 +00001184 // Use a WeakVH to observe whether this happens.
Chris Lattnerc91961e2010-04-03 06:17:08 +00001185 WeakVH WeakPH = PN;
Dan Gohman81db61a2009-05-12 02:17:14 +00001186
Chris Lattnerca703bd2010-04-03 06:11:07 +00001187 // Delete the old floating point exit comparison. The branch starts using the
1188 // new comparison.
1189 NewCompare->takeName(Compare);
1190 Compare->replaceAllUsesWith(NewCompare);
1191 RecursivelyDeleteTriviallyDeadInstructions(Compare);
Dan Gohmancafb8132009-02-17 19:13:57 +00001192
Chris Lattnerca703bd2010-04-03 06:11:07 +00001193 // Delete the old floating point increment.
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001194 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman81db61a2009-05-12 02:17:14 +00001195 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +00001196
Chris Lattner70c0d4f2010-04-03 06:16:22 +00001197 // If the FP induction variable still has uses, this is because something else
1198 // in the loop uses its value. In order to canonicalize the induction
1199 // variable, we chose to eliminate the IV and rewrite it in terms of an
1200 // int->fp cast.
1201 //
1202 // We give preference to sitofp over uitofp because it is faster on most
1203 // platforms.
1204 if (WeakPH) {
Chris Lattnera40e4a02010-04-03 06:25:21 +00001205 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
1206 PN->getParent()->getFirstNonPHI());
1207 PN->replaceAllUsesWith(Conv);
Chris Lattnerc91961e2010-04-03 06:17:08 +00001208 RecursivelyDeleteTriviallyDeadInstructions(PN);
Devang Patelcd402332008-11-17 23:27:13 +00001209 }
Devang Patel58d43d42008-11-03 18:32:19 +00001210
Dan Gohman81db61a2009-05-12 02:17:14 +00001211 // Add a new IVUsers entry for the newly-created integer PHI.
1212 IU->AddUsersIfInteresting(NewPHI);
1213}