blob: 1a87b15e7fc382b6c8ab3a008598c63273f11c0f [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
Andrew Trick2fabd462011-06-21 03:22:38 +000065STATISTIC(NumRemoved , "Number of aux indvars removed");
66STATISTIC(NumWidened , "Number of indvars widened");
67STATISTIC(NumInserted , "Number of canonical indvars added");
68STATISTIC(NumReplaced , "Number of exit values replaced");
69STATISTIC(NumLFTR , "Number of loop exit tests replaced");
70STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
71STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");
72STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
73STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
Chris Lattner3324e712003-12-22 03:58:44 +000074
Andrew Trick37da4082011-05-04 02:10:13 +000075// DisableIVRewrite mode currently affects IVUsers, so is defined in libAnalysis
76// and referenced here.
77namespace llvm {
78 extern bool DisableIVRewrite;
79}
80
Chris Lattner0e5f4992006-12-19 21:40:18 +000081namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000082 class IndVarSimplify : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000083 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000084 LoopInfo *LI;
85 ScalarEvolution *SE;
Dan Gohmande53dc02009-06-27 05:16:57 +000086 DominatorTree *DT;
Andrew Trick37da4082011-05-04 02:10:13 +000087 TargetData *TD;
Andrew Trick2fabd462011-06-21 03:22:38 +000088
89 PHINode *CurrIV; // Current IV being simplified.
90
91 // Instructions processed by SimplifyIVUsers for CurrIV.
92 SmallPtrSet<Instruction*,16> Simplified;
93
94 // Use-def pairs if IVUsers waiting to be processed for CurrIV.
95 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
96
Andrew Trickb12a7542011-03-17 23:51:11 +000097 SmallVector<WeakVH, 16> DeadInsts;
Chris Lattner15cad752003-12-23 07:47:09 +000098 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000099 public:
Devang Patel794fd752007-05-01 21:15:47 +0000100
Dan Gohman5668cf72009-07-15 01:26:32 +0000101 static char ID; // Pass identification, replacement for typeid
Andrew Trick2fabd462011-06-21 03:22:38 +0000102 IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0),
103 CurrIV(0), Changed(false) {
Owen Anderson081c34b2010-10-19 17:21:58 +0000104 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
105 }
Devang Patel794fd752007-05-01 21:15:47 +0000106
Dan Gohman5668cf72009-07-15 01:26:32 +0000107 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman60f8a632009-02-17 20:49:49 +0000108
Dan Gohman5668cf72009-07-15 01:26:32 +0000109 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
110 AU.addRequired<DominatorTree>();
111 AU.addRequired<LoopInfo>();
112 AU.addRequired<ScalarEvolution>();
113 AU.addRequiredID(LoopSimplifyID);
114 AU.addRequiredID(LCSSAID);
115 AU.addRequired<IVUsers>();
116 AU.addPreserved<ScalarEvolution>();
117 AU.addPreservedID(LoopSimplifyID);
118 AU.addPreservedID(LCSSAID);
Andrew Trick2fabd462011-06-21 03:22:38 +0000119 if (!DisableIVRewrite)
120 AU.addPreserved<IVUsers>();
Dan Gohman5668cf72009-07-15 01:26:32 +0000121 AU.setPreservesCFG();
122 }
Chris Lattner15cad752003-12-23 07:47:09 +0000123
Chris Lattner40bf8b42004-04-02 20:24:31 +0000124 private:
Andrew Trickb12a7542011-03-17 23:51:11 +0000125 bool isValidRewrite(Value *FromVal, Value *ToVal);
Devang Patel5ee99972007-03-07 06:39:01 +0000126
Andrew Trickf85092c2011-05-20 18:25:42 +0000127 void SimplifyIVUsers(SCEVExpander &Rewriter);
Andrew Trick2fabd462011-06-21 03:22:38 +0000128 void SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter);
129
130 bool EliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trickaeee4612011-05-12 00:04:28 +0000131 void EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
132 void EliminateIVRemainder(BinaryOperator *Rem,
133 Value *IVOperand,
Andrew Trick4417e532011-06-21 15:43:52 +0000134 bool IsSigned);
Andrew Trick2fabd462011-06-21 03:22:38 +0000135 void pushIVUsers(Instruction *Def);
136 bool isSimpleIVUser(Instruction *I, const Loop *L);
Dan Gohman60f8a632009-02-17 20:49:49 +0000137 void RewriteNonIntegerIVs(Loop *L);
138
Dan Gohman0bba49c2009-07-07 17:06:11 +0000139 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
Andrew Trick4dfdf242011-05-03 22:24:10 +0000140 PHINode *IndVar,
141 SCEVExpander &Rewriter);
Andrew Trick37da4082011-05-04 02:10:13 +0000142
Dan Gohman454d26d2010-02-22 04:11:59 +0000143 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000144
Dan Gohman454d26d2010-02-22 04:11:59 +0000145 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000146
Dan Gohman667d7872009-06-26 22:53:46 +0000147 void SinkUnusedInvariants(Loop *L);
Dan Gohman81db61a2009-05-12 02:17:14 +0000148
149 void HandleFloatingPointIV(Loop *L, PHINode *PH);
Chris Lattner3324e712003-12-22 03:58:44 +0000150 };
Chris Lattner5e761402002-09-10 05:24:05 +0000151}
Chris Lattner394437f2001-12-04 04:32:29 +0000152
Dan Gohman844731a2008-05-13 00:00:25 +0000153char IndVarSimplify::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000154INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000155 "Induction Variable Simplification", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000156INITIALIZE_PASS_DEPENDENCY(DominatorTree)
157INITIALIZE_PASS_DEPENDENCY(LoopInfo)
158INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
159INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
160INITIALIZE_PASS_DEPENDENCY(LCSSA)
161INITIALIZE_PASS_DEPENDENCY(IVUsers)
162INITIALIZE_PASS_END(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000163 "Induction Variable Simplification", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000164
Daniel Dunbar394f0442008-10-22 23:32:42 +0000165Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000166 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000167}
168
Andrew Trickb12a7542011-03-17 23:51:11 +0000169/// isValidRewrite - Return true if the SCEV expansion generated by the
170/// rewriter can replace the original value. SCEV guarantees that it
171/// produces the same value, but the way it is produced may be illegal IR.
172/// Ideally, this function will only be called for verification.
173bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
174 // If an SCEV expression subsumed multiple pointers, its expansion could
175 // reassociate the GEP changing the base pointer. This is illegal because the
176 // final address produced by a GEP chain must be inbounds relative to its
177 // underlying object. Otherwise basic alias analysis, among other things,
178 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
179 // producing an expression involving multiple pointers. Until then, we must
180 // bail out here.
181 //
182 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
183 // because it understands lcssa phis while SCEV does not.
184 Value *FromPtr = FromVal;
185 Value *ToPtr = ToVal;
186 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
187 FromPtr = GEP->getPointerOperand();
188 }
189 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
190 ToPtr = GEP->getPointerOperand();
191 }
192 if (FromPtr != FromVal || ToPtr != ToVal) {
193 // Quickly check the common case
194 if (FromPtr == ToPtr)
195 return true;
196
197 // SCEV may have rewritten an expression that produces the GEP's pointer
198 // operand. That's ok as long as the pointer operand has the same base
199 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
200 // base of a recurrence. This handles the case in which SCEV expansion
201 // converts a pointer type recurrence into a nonrecurrent pointer base
202 // indexed by an integer recurrence.
203 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
204 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
205 if (FromBase == ToBase)
206 return true;
207
208 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
209 << *FromBase << " != " << *ToBase << "\n");
210
211 return false;
212 }
213 return true;
214}
215
Andrew Trick4dfdf242011-05-03 22:24:10 +0000216/// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
217/// count expression can be safely and cheaply expanded into an instruction
218/// sequence that can be used by LinearFunctionTestReplace.
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000219static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) {
220 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Andrew Trick4dfdf242011-05-03 22:24:10 +0000221 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
222 BackedgeTakenCount->isZero())
223 return false;
224
225 if (!L->getExitingBlock())
226 return false;
227
228 // Can't rewrite non-branch yet.
229 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
230 if (!BI)
231 return false;
232
Dan Gohmanca9b7032010-04-12 21:13:43 +0000233 // Special case: If the backedge-taken count is a UDiv, it's very likely a
234 // UDiv that ScalarEvolution produced in order to compute a precise
235 // expression, rather than a UDiv from the user's code. If we can't find a
236 // UDiv in the code with some simple searching, assume the former and forego
237 // rewriting the loop.
238 if (isa<SCEVUDivExpr>(BackedgeTakenCount)) {
239 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
Andrew Trick37da4082011-05-04 02:10:13 +0000240 if (!OrigCond) return false;
Dan Gohmanca9b7032010-04-12 21:13:43 +0000241 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
Dan Gohmandeff6212010-05-03 22:09:21 +0000242 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
Dan Gohmanca9b7032010-04-12 21:13:43 +0000243 if (R != BackedgeTakenCount) {
244 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
Dan Gohmandeff6212010-05-03 22:09:21 +0000245 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
Dan Gohmanca9b7032010-04-12 21:13:43 +0000246 if (L != BackedgeTakenCount)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000247 return false;
Dan Gohmanca9b7032010-04-12 21:13:43 +0000248 }
249 }
Andrew Trick4dfdf242011-05-03 22:24:10 +0000250 return true;
251}
252
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000253/// getBackedgeIVType - Get the widest type used by the loop test after peeking
254/// through Truncs.
255///
256/// TODO: Unnecessary once LinearFunctionTestReplace is removed.
257static const Type *getBackedgeIVType(Loop *L) {
258 if (!L->getExitingBlock())
259 return 0;
260
261 // Can't rewrite non-branch yet.
262 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
263 if (!BI)
264 return 0;
265
266 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
267 if (!Cond)
268 return 0;
269
270 const Type *Ty = 0;
271 for(User::op_iterator OI = Cond->op_begin(), OE = Cond->op_end();
272 OI != OE; ++OI) {
273 assert((!Ty || Ty == (*OI)->getType()) && "bad icmp operand types");
274 TruncInst *Trunc = dyn_cast<TruncInst>(*OI);
275 if (!Trunc)
276 continue;
277
278 return Trunc->getSrcTy();
279 }
280 return Ty;
281}
282
Andrew Trick4dfdf242011-05-03 22:24:10 +0000283/// LinearFunctionTestReplace - This method rewrites the exit condition of the
284/// loop to be a canonical != comparison against the incremented loop induction
285/// variable. This pass is able to rewrite the exit tests of any loop where the
286/// SCEV analysis can determine a loop-invariant trip count of the loop, which
287/// is actually a much broader range than just linear tests.
288ICmpInst *IndVarSimplify::
289LinearFunctionTestReplace(Loop *L,
290 const SCEV *BackedgeTakenCount,
291 PHINode *IndVar,
292 SCEVExpander &Rewriter) {
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000293 assert(canExpandBackedgeTakenCount(L, SE) && "precondition");
Andrew Trick4dfdf242011-05-03 22:24:10 +0000294 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
Dan Gohmanca9b7032010-04-12 21:13:43 +0000295
Chris Lattnerd2440572004-04-15 20:26:22 +0000296 // If the exiting block is not the same as the backedge block, we must compare
297 // against the preincremented value, otherwise we prefer to compare against
298 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000299 Value *CmpIndVar;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000300 const SCEV *RHS = BackedgeTakenCount;
Andrew Trick4dfdf242011-05-03 22:24:10 +0000301 if (L->getExitingBlock() == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000302 // Add one to the "backedge-taken" count to get the trip count.
303 // If this addition may overflow, we have to be more pessimistic and
304 // cast the induction variable before doing the add.
Dan Gohmandeff6212010-05-03 22:09:21 +0000305 const SCEV *Zero = SE->getConstant(BackedgeTakenCount->getType(), 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000306 const SCEV *N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000307 SE->getAddExpr(BackedgeTakenCount,
Dan Gohmandeff6212010-05-03 22:09:21 +0000308 SE->getConstant(BackedgeTakenCount->getType(), 1));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000309 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000310 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000311 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000312 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000313 } else {
314 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000315 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
316 IndVar->getType());
317 RHS = SE->getAddExpr(RHS,
Dan Gohmandeff6212010-05-03 22:09:21 +0000318 SE->getConstant(IndVar->getType(), 1));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000319 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000320
Dan Gohman46bdfb02009-02-24 18:55:53 +0000321 // The BackedgeTaken expression contains the number of times that the
322 // backedge branches to the loop header. This is one less than the
323 // number of times the loop executes, so use the incremented indvar.
Andrew Trick4dfdf242011-05-03 22:24:10 +0000324 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
Chris Lattnerd2440572004-04-15 20:26:22 +0000325 } else {
326 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000327 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
328 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000329 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000330 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000331
Dan Gohman667d7872009-06-26 22:53:46 +0000332 // Expand the code for the iteration count.
Dan Gohman17ead4f2010-11-17 21:23:15 +0000333 assert(SE->isLoopInvariant(RHS, L) &&
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000334 "Computed iteration count is not loop invariant!");
Dan Gohman667d7872009-06-26 22:53:46 +0000335 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000336
Reid Spencere4d87aa2006-12-23 06:05:41 +0000337 // Insert a new icmp_ne or icmp_eq instruction before the branch.
338 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000339 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000340 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000341 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000342 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000343
David Greenef67ef312010-01-05 01:27:06 +0000344 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
Chris Lattnerbdff5482009-08-23 04:37:46 +0000345 << " LHS:" << *CmpIndVar << '\n'
346 << " op:\t"
347 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
348 << " RHS:\t" << *RHS << "\n");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000349
Owen Anderson333c4002009-07-09 23:48:35 +0000350 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
Dan Gohman81db61a2009-05-12 02:17:14 +0000351
Dan Gohman24440802010-02-22 02:07:36 +0000352 Value *OrigCond = BI->getCondition();
Dan Gohman95bdbfa2009-05-24 19:11:38 +0000353 // It's tempting to use replaceAllUsesWith here to fully replace the old
354 // comparison, but that's not immediately safe, since users of the old
355 // comparison may not be dominated by the new comparison. Instead, just
356 // update the branch to use the new comparison; in the common case this
357 // will make old comparison dead.
358 BI->setCondition(Cond);
Andrew Trick88e92cf2011-04-28 17:30:04 +0000359 DeadInsts.push_back(OrigCond);
Dan Gohman81db61a2009-05-12 02:17:14 +0000360
Chris Lattner40bf8b42004-04-02 20:24:31 +0000361 ++NumLFTR;
362 Changed = true;
Dan Gohman81db61a2009-05-12 02:17:14 +0000363 return Cond;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000364}
365
Chris Lattner40bf8b42004-04-02 20:24:31 +0000366/// RewriteLoopExitValues - Check to see if this loop has a computable
367/// loop-invariant execution count. If so, this means that we can compute the
368/// final value of any expressions that are recurrent in the loop, and
369/// substitute the exit values from the loop into any instructions outside of
370/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000371///
372/// This is mostly redundant with the regular IndVarSimplify activities that
373/// happen later, except that it's more powerful in some cases, because it's
374/// able to brute-force evaluate arbitrary instructions as long as they have
375/// constant operands at the beginning of the loop.
Chris Lattnerf1859892011-01-09 02:16:18 +0000376void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000377 // Verify the input to the pass in already in LCSSA form.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000378 assert(L->isLCSSAForm(*DT));
Dan Gohman81db61a2009-05-12 02:17:14 +0000379
Devang Patelb7211a22007-08-21 00:31:24 +0000380 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000381 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000382
Chris Lattner9f3d7382007-03-04 03:43:23 +0000383 // Find all values that are computed inside the loop, but used outside of it.
384 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
385 // the exit blocks of the loop to find them.
386 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
387 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000388
Chris Lattner9f3d7382007-03-04 03:43:23 +0000389 // If there are no PHI nodes in this exit block, then no values defined
390 // inside the loop are used on this path, skip it.
391 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
392 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000393
Chris Lattner9f3d7382007-03-04 03:43:23 +0000394 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000395
Chris Lattner9f3d7382007-03-04 03:43:23 +0000396 // Iterate over all of the PHI nodes.
397 BasicBlock::iterator BBI = ExitBB->begin();
398 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000399 if (PN->use_empty())
400 continue; // dead use, don't replace it
Dan Gohman814f2b22010-02-18 21:34:02 +0000401
402 // SCEV only supports integer expressions for now.
403 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
404 continue;
405
Dale Johannesen45a2d7d2010-02-19 07:14:22 +0000406 // It's necessary to tell ScalarEvolution about this explicitly so that
407 // it can walk the def-use list and forget all SCEVs, as it may not be
408 // watching the PHI itself. Once the new exit value is in place, there
409 // may not be a def-use connection between the loop and every instruction
410 // which got a SCEVAddRecExpr for that loop.
411 SE->forgetValue(PN);
412
Chris Lattner9f3d7382007-03-04 03:43:23 +0000413 // Iterate over all of the values in all the PHI nodes.
414 for (unsigned i = 0; i != NumPreds; ++i) {
415 // If the value being merged in is not integer or is not defined
416 // in the loop, skip it.
417 Value *InVal = PN->getIncomingValue(i);
Dan Gohman814f2b22010-02-18 21:34:02 +0000418 if (!isa<Instruction>(InVal))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000419 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000420
Chris Lattner9f3d7382007-03-04 03:43:23 +0000421 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000422 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000423 continue; // The Block is in a subloop, skip it.
424
425 // Check that InVal is defined in the loop.
426 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman92329c72009-12-18 01:24:09 +0000427 if (!L->contains(Inst))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000428 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000429
Chris Lattner9f3d7382007-03-04 03:43:23 +0000430 // Okay, this instruction has a user outside of the current loop
431 // and varies predictably *inside* the loop. Evaluate the value it
432 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000433 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +0000434 if (!SE->isLoopInvariant(ExitValue, L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000435 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000436
Dan Gohman667d7872009-06-26 22:53:46 +0000437 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000438
David Greenef67ef312010-01-05 01:27:06 +0000439 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000440 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000441
Andrew Trickb12a7542011-03-17 23:51:11 +0000442 if (!isValidRewrite(Inst, ExitVal)) {
443 DeadInsts.push_back(ExitVal);
444 continue;
445 }
446 Changed = true;
447 ++NumReplaced;
448
Chris Lattner9f3d7382007-03-04 03:43:23 +0000449 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000450
Dan Gohman81db61a2009-05-12 02:17:14 +0000451 // If this instruction is dead now, delete it.
452 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000453
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000454 if (NumPreds == 1) {
455 // Completely replace a single-pred PHI. This is safe, because the
456 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
457 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000458 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000459 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000460 }
461 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000462 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000463 // Clone the PHI and delete the original one. This lets IVUsers and
464 // any other maps purge the original user from their records.
Devang Patel50b6e332009-10-27 22:16:29 +0000465 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohman667d7872009-06-26 22:53:46 +0000466 NewPN->takeName(PN);
467 NewPN->insertBefore(PN);
468 PN->replaceAllUsesWith(NewPN);
469 PN->eraseFromParent();
470 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000471 }
472 }
Dan Gohman472fdf72010-03-20 03:53:53 +0000473
474 // The insertion point instruction may have been deleted; clear it out
475 // so that the rewriter doesn't trip over it later.
476 Rewriter.clearInsertPoint();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000477}
478
Dan Gohman60f8a632009-02-17 20:49:49 +0000479void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000480 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000481 // If there are, change them into integer recurrences, permitting analysis by
482 // the SCEV routines.
483 //
Chris Lattnerf1859892011-01-09 02:16:18 +0000484 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000485
Dan Gohman81db61a2009-05-12 02:17:14 +0000486 SmallVector<WeakVH, 8> PHIs;
487 for (BasicBlock::iterator I = Header->begin();
488 PHINode *PN = dyn_cast<PHINode>(I); ++I)
489 PHIs.push_back(PN);
490
491 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
Gabor Greifea4894a2010-09-18 11:53:39 +0000492 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
Dan Gohman81db61a2009-05-12 02:17:14 +0000493 HandleFloatingPointIV(L, PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000494
Dan Gohman2d1be872009-04-16 03:18:22 +0000495 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000496 // may not have been able to compute a trip count. Now that we've done some
497 // re-writing, the trip count may be computable.
498 if (Changed)
Dan Gohman4c7279a2009-10-31 15:04:55 +0000499 SE->forgetLoop(L);
Dale Johannesenc671d892009-04-15 23:31:51 +0000500}
501
Andrew Trick2fabd462011-06-21 03:22:38 +0000502/// SimplifyIVUsers - Iteratively perform simplification on IVUsers within this
503/// loop. IVUsers is treated as a worklist. Each successive simplification may
504/// push more users which may themselves be candidates for simplification.
505///
506/// This is the old approach to IV simplification to be replaced by
507/// SimplifyIVUsersNoRewrite.
508///
509void IndVarSimplify::SimplifyIVUsers(SCEVExpander &Rewriter) {
510 // Each round of simplification involves a round of eliminating operations
511 // followed by a round of widening IVs. A single IVUsers worklist is used
512 // across all rounds. The inner loop advances the user. If widening exposes
513 // more uses, then another pass through the outer loop is triggered.
514 for (IVUsers::iterator I = IU->begin(); I != IU->end(); ++I) {
515 Instruction *UseInst = I->getUser();
516 Value *IVOperand = I->getOperandValToReplace();
517
518 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
519 EliminateIVComparison(ICmp, IVOperand);
520 continue;
521 }
522 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
523 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
524 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
Andrew Trick4417e532011-06-21 15:43:52 +0000525 EliminateIVRemainder(Rem, IVOperand, IsSigned);
Andrew Trick2fabd462011-06-21 03:22:38 +0000526 continue;
527 }
528 }
529 }
530}
531
Andrew Trickf85092c2011-05-20 18:25:42 +0000532namespace {
533 // Collect information about induction variables that are used by sign/zero
534 // extend operations. This information is recorded by CollectExtend and
535 // provides the input to WidenIV.
536 struct WideIVInfo {
537 const Type *WidestNativeType; // Widest integer type created [sz]ext
538 bool IsSigned; // Was an sext user seen before a zext?
539
540 WideIVInfo() : WidestNativeType(0), IsSigned(false) {}
541 };
Andrew Trickf85092c2011-05-20 18:25:42 +0000542}
543
544/// CollectExtend - Update information about the induction variable that is
545/// extended by this sign or zero extend operation. This is used to determine
546/// the final width of the IV before actually widening it.
Andrew Trick2fabd462011-06-21 03:22:38 +0000547static void CollectExtend(CastInst *Cast, bool IsSigned, WideIVInfo &WI,
548 ScalarEvolution *SE, const TargetData *TD) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000549 const Type *Ty = Cast->getType();
550 uint64_t Width = SE->getTypeSizeInBits(Ty);
551 if (TD && !TD->isLegalInteger(Width))
552 return;
553
Andrew Trick2fabd462011-06-21 03:22:38 +0000554 if (!WI.WidestNativeType) {
555 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
556 WI.IsSigned = IsSigned;
Andrew Trickf85092c2011-05-20 18:25:42 +0000557 return;
558 }
559
560 // We extend the IV to satisfy the sign of its first user, arbitrarily.
Andrew Trick2fabd462011-06-21 03:22:38 +0000561 if (WI.IsSigned != IsSigned)
Andrew Trickf85092c2011-05-20 18:25:42 +0000562 return;
563
Andrew Trick2fabd462011-06-21 03:22:38 +0000564 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
565 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
Andrew Trickf85092c2011-05-20 18:25:42 +0000566}
567
568namespace {
569/// WidenIV - The goal of this transform is to remove sign and zero extends
570/// without creating any new induction variables. To do this, it creates a new
571/// phi of the wider type and redirects all users, either removing extends or
572/// inserting truncs whenever we stop propagating the type.
573///
574class WidenIV {
Andrew Trick2fabd462011-06-21 03:22:38 +0000575 // Parameters
Andrew Trickf85092c2011-05-20 18:25:42 +0000576 PHINode *OrigPhi;
577 const Type *WideType;
578 bool IsSigned;
579
Andrew Trick2fabd462011-06-21 03:22:38 +0000580 // Context
581 LoopInfo *LI;
582 Loop *L;
Andrew Trickf85092c2011-05-20 18:25:42 +0000583 ScalarEvolution *SE;
Andrew Trick2fabd462011-06-21 03:22:38 +0000584 DominatorTree *DT;
Andrew Trickf85092c2011-05-20 18:25:42 +0000585
Andrew Trick2fabd462011-06-21 03:22:38 +0000586 // Result
Andrew Trickf85092c2011-05-20 18:25:42 +0000587 PHINode *WidePhi;
588 Instruction *WideInc;
589 const SCEV *WideIncExpr;
Andrew Trick2fabd462011-06-21 03:22:38 +0000590 SmallVectorImpl<WeakVH> &DeadInsts;
Andrew Trickf85092c2011-05-20 18:25:42 +0000591
Andrew Trick2fabd462011-06-21 03:22:38 +0000592 SmallPtrSet<Instruction*,16> Widened;
Andrew Trickf85092c2011-05-20 18:25:42 +0000593
594public:
Andrew Trick2fabd462011-06-21 03:22:38 +0000595 WidenIV(PHINode *PN, const WideIVInfo &WI, LoopInfo *LInfo,
596 ScalarEvolution *SEv, DominatorTree *DTree,
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000597 SmallVectorImpl<WeakVH> &DI) :
Andrew Trickf85092c2011-05-20 18:25:42 +0000598 OrigPhi(PN),
Andrew Trick2fabd462011-06-21 03:22:38 +0000599 WideType(WI.WidestNativeType),
600 IsSigned(WI.IsSigned),
Andrew Trickf85092c2011-05-20 18:25:42 +0000601 LI(LInfo),
602 L(LI->getLoopFor(OrigPhi->getParent())),
603 SE(SEv),
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000604 DT(DTree),
Andrew Trickf85092c2011-05-20 18:25:42 +0000605 WidePhi(0),
606 WideInc(0),
Andrew Trick2fabd462011-06-21 03:22:38 +0000607 WideIncExpr(0),
608 DeadInsts(DI) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000609 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
610 }
611
Andrew Trick2fabd462011-06-21 03:22:38 +0000612 PHINode *CreateWideIV(SCEVExpander &Rewriter);
Andrew Trickf85092c2011-05-20 18:25:42 +0000613
614protected:
Andrew Trickf85092c2011-05-20 18:25:42 +0000615 Instruction *CloneIVUser(Instruction *NarrowUse,
616 Instruction *NarrowDef,
617 Instruction *WideDef);
618
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000619 const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
620
Andrew Trickf85092c2011-05-20 18:25:42 +0000621 Instruction *WidenIVUse(Instruction *NarrowUse,
622 Instruction *NarrowDef,
623 Instruction *WideDef);
624};
625} // anonymous namespace
626
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000627static Value *getExtend( Value *NarrowOper, const Type *WideType,
628 bool IsSigned, IRBuilder<> &Builder) {
629 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
630 Builder.CreateZExt(NarrowOper, WideType);
Andrew Trickf85092c2011-05-20 18:25:42 +0000631}
632
633/// CloneIVUser - Instantiate a wide operation to replace a narrow
634/// operation. This only needs to handle operations that can evaluation to
635/// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
636Instruction *WidenIV::CloneIVUser(Instruction *NarrowUse,
637 Instruction *NarrowDef,
638 Instruction *WideDef) {
639 unsigned Opcode = NarrowUse->getOpcode();
640 switch (Opcode) {
641 default:
642 return 0;
643 case Instruction::Add:
644 case Instruction::Mul:
645 case Instruction::UDiv:
646 case Instruction::Sub:
647 case Instruction::And:
648 case Instruction::Or:
649 case Instruction::Xor:
650 case Instruction::Shl:
651 case Instruction::LShr:
652 case Instruction::AShr:
653 DEBUG(dbgs() << "Cloning IVUser: " << *NarrowUse << "\n");
654
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000655 IRBuilder<> Builder(NarrowUse);
656
657 // Replace NarrowDef operands with WideDef. Otherwise, we don't know
658 // anything about the narrow operand yet so must insert a [sz]ext. It is
659 // probably loop invariant and will be folded or hoisted. If it actually
660 // comes from a widened IV, it should be removed during a future call to
661 // WidenIVUse.
662 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef) ? WideDef :
663 getExtend(NarrowUse->getOperand(0), WideType, IsSigned, Builder);
664 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef) ? WideDef :
665 getExtend(NarrowUse->getOperand(1), WideType, IsSigned, Builder);
666
Andrew Trickf85092c2011-05-20 18:25:42 +0000667 BinaryOperator *NarrowBO = cast<BinaryOperator>(NarrowUse);
668 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000669 LHS, RHS,
Andrew Trickf85092c2011-05-20 18:25:42 +0000670 NarrowBO->getName());
Andrew Trickf85092c2011-05-20 18:25:42 +0000671 Builder.Insert(WideBO);
672 if (NarrowBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
673 if (NarrowBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
674
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000675 return WideBO;
Andrew Trickf85092c2011-05-20 18:25:42 +0000676 }
677 llvm_unreachable(0);
678}
679
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000680// GetWideRecurrence - Is this instruction potentially interesting from IVUsers'
681// perspective after widening it's type? In other words, can the extend be
682// safely hoisted out of the loop with SCEV reducing the value to a recurrence
683// on the same loop. If so, return the sign or zero extended
684// recurrence. Otherwise return NULL.
685const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
686 if (!SE->isSCEVable(NarrowUse->getType()))
687 return 0;
688
689 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
690 const SCEV *WideExpr = IsSigned ?
691 SE->getSignExtendExpr(NarrowExpr, WideType) :
692 SE->getZeroExtendExpr(NarrowExpr, WideType);
693 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
694 if (!AddRec || AddRec->getLoop() != L)
695 return 0;
696
697 return AddRec;
698}
699
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000700/// HoistStep - Attempt to hoist an IV increment above a potential use.
701///
702/// To successfully hoist, two criteria must be met:
703/// - IncV operands dominate InsertPos and
704/// - InsertPos dominates IncV
705///
706/// Meeting the second condition means that we don't need to check all of IncV's
707/// existing uses (it's moving up in the domtree).
708///
709/// This does not yet recursively hoist the operands, although that would
710/// not be difficult.
711static bool HoistStep(Instruction *IncV, Instruction *InsertPos,
712 const DominatorTree *DT)
713{
714 if (DT->dominates(IncV, InsertPos))
715 return true;
716
717 if (!DT->dominates(InsertPos->getParent(), IncV->getParent()))
718 return false;
719
720 if (IncV->mayHaveSideEffects())
721 return false;
722
723 // Attempt to hoist IncV
724 for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end();
725 OI != OE; ++OI) {
726 Instruction *OInst = dyn_cast<Instruction>(OI);
727 if (OInst && !DT->dominates(OInst, InsertPos))
728 return false;
729 }
730 IncV->moveBefore(InsertPos);
731 return true;
732}
733
Andrew Trickf85092c2011-05-20 18:25:42 +0000734/// WidenIVUse - Determine whether an individual user of the narrow IV can be
735/// widened. If so, return the wide clone of the user.
736Instruction *WidenIV::WidenIVUse(Instruction *NarrowUse,
737 Instruction *NarrowDef,
738 Instruction *WideDef) {
739 // To be consistent with IVUsers, stop traversing the def-use chain at
740 // inner-loop phis or post-loop phis.
741 if (isa<PHINode>(NarrowUse) && LI->getLoopFor(NarrowUse->getParent()) != L)
742 return 0;
743
744 // Handle data flow merges and bizarre phi cycles.
Andrew Trick2fabd462011-06-21 03:22:38 +0000745 if (!Widened.insert(NarrowUse))
Andrew Trickf85092c2011-05-20 18:25:42 +0000746 return 0;
747
748 // Our raison d'etre! Eliminate sign and zero extension.
749 if (IsSigned ? isa<SExtInst>(NarrowUse) : isa<ZExtInst>(NarrowUse)) {
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000750 Value *NewDef = WideDef;
751 if (NarrowUse->getType() != WideType) {
752 unsigned CastWidth = SE->getTypeSizeInBits(NarrowUse->getType());
753 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
754 if (CastWidth < IVWidth) {
755 // The cast isn't as wide as the IV, so insert a Trunc.
756 IRBuilder<> Builder(NarrowUse);
757 NewDef = Builder.CreateTrunc(WideDef, NarrowUse->getType());
758 }
759 else {
760 // A wider extend was hidden behind a narrower one. This may induce
761 // another round of IV widening in which the intermediate IV becomes
762 // dead. It should be very rare.
763 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
764 << " not wide enough to subsume " << *NarrowUse << "\n");
765 NarrowUse->replaceUsesOfWith(NarrowDef, WideDef);
766 NewDef = NarrowUse;
767 }
768 }
769 if (NewDef != NarrowUse) {
770 DEBUG(dbgs() << "INDVARS: eliminating " << *NarrowUse
771 << " replaced by " << *WideDef << "\n");
772 ++NumElimExt;
773 NarrowUse->replaceAllUsesWith(NewDef);
774 DeadInsts.push_back(NarrowUse);
775 }
Andrew Trick2fabd462011-06-21 03:22:38 +0000776 // Now that the extend is gone, we want to expose it's uses for potential
777 // further simplification. We don't need to directly inform SimplifyIVUsers
778 // of the new users, because their parent IV will be processed later as a
779 // new loop phi. If we preserved IVUsers analysis, we would also want to
780 // push the uses of WideDef here.
Andrew Trickf85092c2011-05-20 18:25:42 +0000781
782 // No further widening is needed. The deceased [sz]ext had done it for us.
783 return 0;
784 }
785 const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(NarrowUse);
786 if (!WideAddRec) {
787 // This user does not evaluate to a recurence after widening, so don't
788 // follow it. Instead insert a Trunc to kill off the original use,
789 // eventually isolating the original narrow IV so it can be removed.
790 IRBuilder<> Builder(NarrowUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000791 Value *Trunc = Builder.CreateTrunc(WideDef, NarrowDef->getType());
Andrew Trickf85092c2011-05-20 18:25:42 +0000792 NarrowUse->replaceUsesOfWith(NarrowDef, Trunc);
793 return 0;
794 }
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000795 // Reuse the IV increment that SCEVExpander created as long as it dominates
796 // NarrowUse.
Andrew Trickf85092c2011-05-20 18:25:42 +0000797 Instruction *WideUse = 0;
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000798 if (WideAddRec == WideIncExpr && HoistStep(WideInc, NarrowUse, DT)) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000799 WideUse = WideInc;
800 }
801 else {
802 WideUse = CloneIVUser(NarrowUse, NarrowDef, WideDef);
803 if (!WideUse)
804 return 0;
805 }
806 // GetWideRecurrence ensured that the narrow expression could be extended
807 // outside the loop without overflow. This suggests that the wide use
808 // evaluates to the same expression as the extended narrow use, but doesn't
809 // absolutely guarantee it. Hence the following failsafe check. In rare cases
Andrew Trick2fabd462011-06-21 03:22:38 +0000810 // where it fails, we simply throw away the newly created wide use.
Andrew Trickf85092c2011-05-20 18:25:42 +0000811 if (WideAddRec != SE->getSCEV(WideUse)) {
812 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
813 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
814 DeadInsts.push_back(WideUse);
815 return 0;
816 }
817
818 // Returning WideUse pushes it on the worklist.
819 return WideUse;
820}
821
822/// CreateWideIV - Process a single induction variable. First use the
823/// SCEVExpander to create a wide induction variable that evaluates to the same
824/// recurrence as the original narrow IV. Then use a worklist to forward
Andrew Trick2fabd462011-06-21 03:22:38 +0000825/// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
Andrew Trickf85092c2011-05-20 18:25:42 +0000826/// interesting IV users, the narrow IV will be isolated for removal by
827/// DeleteDeadPHIs.
828///
829/// It would be simpler to delete uses as they are processed, but we must avoid
830/// invalidating SCEV expressions.
831///
Andrew Trick2fabd462011-06-21 03:22:38 +0000832PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000833 // Is this phi an induction variable?
834 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
835 if (!AddRec)
Andrew Trick2fabd462011-06-21 03:22:38 +0000836 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +0000837
838 // Widen the induction variable expression.
839 const SCEV *WideIVExpr = IsSigned ?
840 SE->getSignExtendExpr(AddRec, WideType) :
841 SE->getZeroExtendExpr(AddRec, WideType);
842
843 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
844 "Expect the new IV expression to preserve its type");
845
846 // Can the IV be extended outside the loop without overflow?
847 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
848 if (!AddRec || AddRec->getLoop() != L)
Andrew Trick2fabd462011-06-21 03:22:38 +0000849 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +0000850
Andrew Trick2fabd462011-06-21 03:22:38 +0000851 // An AddRec must have loop-invariant operands. Since this AddRec is
Andrew Trickf85092c2011-05-20 18:25:42 +0000852 // materialized by a loop header phi, the expression cannot have any post-loop
853 // operands, so they must dominate the loop header.
854 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
855 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
856 && "Loop header phi recurrence inputs do not dominate the loop");
857
858 // The rewriter provides a value for the desired IV expression. This may
859 // either find an existing phi or materialize a new one. Either way, we
860 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
861 // of the phi-SCC dominates the loop entry.
862 Instruction *InsertPt = L->getHeader()->begin();
863 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
864
865 // Remembering the WideIV increment generated by SCEVExpander allows
866 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
867 // employ a general reuse mechanism because the call above is the only call to
868 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000869 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
870 WideInc =
871 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
872 WideIncExpr = SE->getSCEV(WideInc);
873 }
Andrew Trickf85092c2011-05-20 18:25:42 +0000874
875 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
876 ++NumWidened;
877
878 // Traverse the def-use chain using a worklist starting at the original IV.
Andrew Trick2fabd462011-06-21 03:22:38 +0000879 assert(Widened.empty() && "expect initial state" );
Andrew Trickf85092c2011-05-20 18:25:42 +0000880
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000881 // Each worklist entry has a Narrow def-use link and Wide def.
882 SmallVector<std::pair<Use *, Instruction *>, 8> NarrowIVUsers;
883 for (Value::use_iterator UI = OrigPhi->use_begin(),
884 UE = OrigPhi->use_end(); UI != UE; ++UI) {
885 NarrowIVUsers.push_back(std::make_pair(&UI.getUse(), WidePhi));
886 }
Andrew Trickf85092c2011-05-20 18:25:42 +0000887 while (!NarrowIVUsers.empty()) {
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000888 Use *NarrowDefUse;
889 Instruction *WideDef;
890 tie(NarrowDefUse, WideDef) = NarrowIVUsers.pop_back_val();
Andrew Trickf85092c2011-05-20 18:25:42 +0000891
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000892 // Process a def-use edge. This may replace the use, so don't hold a
893 // use_iterator across it.
894 Instruction *NarrowDef = cast<Instruction>(NarrowDefUse->get());
895 Instruction *NarrowUse = cast<Instruction>(NarrowDefUse->getUser());
896 Instruction *WideUse = WidenIVUse(NarrowUse, NarrowDef, WideDef);
Andrew Trickf85092c2011-05-20 18:25:42 +0000897
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000898 // Follow all def-use edges from the previous narrow use.
899 if (WideUse) {
900 for (Value::use_iterator UI = NarrowUse->use_begin(),
901 UE = NarrowUse->use_end(); UI != UE; ++UI) {
902 NarrowIVUsers.push_back(std::make_pair(&UI.getUse(), WideUse));
903 }
Andrew Trickf85092c2011-05-20 18:25:42 +0000904 }
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000905 // WidenIVUse may have removed the def-use edge.
906 if (NarrowDef->use_empty())
907 DeadInsts.push_back(NarrowDef);
Andrew Trickf85092c2011-05-20 18:25:42 +0000908 }
Andrew Trick2fabd462011-06-21 03:22:38 +0000909 return WidePhi;
Andrew Trickf85092c2011-05-20 18:25:42 +0000910}
911
Andrew Trickaeee4612011-05-12 00:04:28 +0000912void IndVarSimplify::EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
913 unsigned IVOperIdx = 0;
914 ICmpInst::Predicate Pred = ICmp->getPredicate();
915 if (IVOperand != ICmp->getOperand(0)) {
916 // Swapped
917 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
918 IVOperIdx = 1;
919 Pred = ICmpInst::getSwappedPredicate(Pred);
Dan Gohmana590b792010-04-13 01:46:36 +0000920 }
Andrew Trickaeee4612011-05-12 00:04:28 +0000921
922 // Get the SCEVs for the ICmp operands.
923 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
924 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
925
926 // Simplify unnecessary loops away.
927 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
928 S = SE->getSCEVAtScope(S, ICmpLoop);
929 X = SE->getSCEVAtScope(X, ICmpLoop);
930
931 // If the condition is always true or always false, replace it with
932 // a constant value.
933 if (SE->isKnownPredicate(Pred, S, X))
934 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
935 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
936 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
937 else
938 return;
939
940 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000941 ++NumElimCmp;
Andrew Trick074397d2011-05-20 03:37:48 +0000942 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +0000943 DeadInsts.push_back(ICmp);
944}
945
946void IndVarSimplify::EliminateIVRemainder(BinaryOperator *Rem,
947 Value *IVOperand,
Andrew Trick4417e532011-06-21 15:43:52 +0000948 bool IsSigned) {
Andrew Trickaeee4612011-05-12 00:04:28 +0000949 // We're only interested in the case where we know something about
950 // the numerator.
951 if (IVOperand != Rem->getOperand(0))
952 return;
953
954 // Get the SCEVs for the ICmp operands.
955 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
956 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
957
958 // Simplify unnecessary loops away.
959 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
960 S = SE->getSCEVAtScope(S, ICmpLoop);
961 X = SE->getSCEVAtScope(X, ICmpLoop);
962
963 // i % n --> i if i is in [0,n).
Andrew Trick074397d2011-05-20 03:37:48 +0000964 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
965 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Andrew Trickaeee4612011-05-12 00:04:28 +0000966 S, X))
967 Rem->replaceAllUsesWith(Rem->getOperand(0));
968 else {
969 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
970 const SCEV *LessOne =
971 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
Andrew Trick074397d2011-05-20 03:37:48 +0000972 if (IsSigned && !SE->isKnownNonNegative(LessOne))
Andrew Trickaeee4612011-05-12 00:04:28 +0000973 return;
974
Andrew Trick074397d2011-05-20 03:37:48 +0000975 if (!SE->isKnownPredicate(IsSigned ?
Andrew Trickaeee4612011-05-12 00:04:28 +0000976 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
977 LessOne, X))
978 return;
979
980 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
981 Rem->getOperand(0), Rem->getOperand(1),
982 "tmp");
983 SelectInst *Sel =
984 SelectInst::Create(ICmp,
985 ConstantInt::get(Rem->getType(), 0),
986 Rem->getOperand(0), "tmp", Rem);
987 Rem->replaceAllUsesWith(Sel);
988 }
989
990 // Inform IVUsers about the new users.
Andrew Trick2fabd462011-06-21 03:22:38 +0000991 if (IU) {
992 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
Andrew Trick4417e532011-06-21 15:43:52 +0000993 IU->AddUsersIfInteresting(I);
Andrew Trick2fabd462011-06-21 03:22:38 +0000994 }
Andrew Trickaeee4612011-05-12 00:04:28 +0000995 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000996 ++NumElimRem;
Andrew Trick074397d2011-05-20 03:37:48 +0000997 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +0000998 DeadInsts.push_back(Rem);
Dan Gohmana590b792010-04-13 01:46:36 +0000999}
1000
Andrew Trick2fabd462011-06-21 03:22:38 +00001001/// EliminateIVUser - Eliminate an operation that consumes a simple IV and has
1002/// no observable side-effect given the range of IV values.
1003bool IndVarSimplify::EliminateIVUser(Instruction *UseInst,
1004 Instruction *IVOperand) {
1005 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
1006 EliminateIVComparison(ICmp, IVOperand);
1007 return true;
1008 }
1009 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
1010 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
1011 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
Andrew Trick4417e532011-06-21 15:43:52 +00001012 EliminateIVRemainder(Rem, IVOperand, IsSigned);
Andrew Trick2fabd462011-06-21 03:22:38 +00001013 return true;
1014 }
1015 }
1016
1017 // Eliminate any operation that SCEV can prove is an identity function.
1018 if (!SE->isSCEVable(UseInst->getType()) ||
1019 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
1020 return false;
1021
1022 UseInst->replaceAllUsesWith(IVOperand);
1023
1024 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
1025 ++NumElimIdentity;
1026 Changed = true;
1027 DeadInsts.push_back(UseInst);
1028 return true;
1029}
1030
1031/// pushIVUsers - Add all uses of Def to the current IV's worklist.
1032///
1033void IndVarSimplify::pushIVUsers(Instruction *Def) {
1034
1035 for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
1036 UI != E; ++UI) {
1037 Instruction *User = cast<Instruction>(*UI);
1038
1039 // Avoid infinite or exponential worklist processing.
1040 // Also ensure unique worklist users.
1041 if (Simplified.insert(User))
1042 SimpleIVUsers.push_back(std::make_pair(User, Def));
1043 }
1044}
1045
1046/// isSimpleIVUser - Return true if this instruction generates a simple SCEV
1047/// expression in terms of that IV.
1048///
1049/// This is similar to IVUsers' isInsteresting() but processes each instruction
1050/// non-recursively when the operand is already known to be a simpleIVUser.
1051///
1052bool IndVarSimplify::isSimpleIVUser(Instruction *I, const Loop *L) {
1053 if (!SE->isSCEVable(I->getType()))
1054 return false;
1055
1056 // Get the symbolic expression for this instruction.
1057 const SCEV *S = SE->getSCEV(I);
1058
1059 // Only consider affine recurrences.
1060 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
1061 if (AR && AR->getLoop() == L)
1062 return true;
1063
1064 return false;
1065}
1066
1067/// SimplifyIVUsersNoRewrite - Iteratively perform simplification on a worklist
1068/// of IV users. Each successive simplification may push more users which may
1069/// themselves be candidates for simplification.
1070///
1071/// The "NoRewrite" algorithm does not require IVUsers analysis. Instead, it
1072/// simplifies instructions in-place during analysis. Rather than rewriting
1073/// induction variables bottom-up from their users, it transforms a chain of
1074/// IVUsers top-down, updating the IR only when it encouters a clear
1075/// optimization opportunitiy. A SCEVExpander "Rewriter" instance is still
1076/// needed, but only used to generate a new IV (phi) of wider type for sign/zero
1077/// extend elimination.
1078///
1079/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
1080///
1081void IndVarSimplify::SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter) {
1082 // Simplification is performed independently for each IV, as represented by a
1083 // loop header phi. Each round of simplification first iterates through the
1084 // SimplifyIVUsers worklist, then determines whether the current IV should be
1085 // widened. Widening adds a new phi to LoopPhis, inducing another round of
1086 // simplification on the wide IV.
1087 SmallVector<PHINode*, 8> LoopPhis;
1088 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1089 LoopPhis.push_back(cast<PHINode>(I));
1090 }
1091 while (!LoopPhis.empty()) {
1092 CurrIV = LoopPhis.pop_back_val();
1093 Simplified.clear();
1094 assert(SimpleIVUsers.empty() && "expect empty IV users list");
1095
1096 WideIVInfo WI;
1097
1098 pushIVUsers(CurrIV);
1099
1100 while (!SimpleIVUsers.empty()) {
1101 Instruction *UseInst, *Operand;
1102 tie(UseInst, Operand) = SimpleIVUsers.pop_back_val();
1103
1104 if (EliminateIVUser(UseInst, Operand)) {
1105 pushIVUsers(Operand);
1106 continue;
1107 }
1108 if (CastInst *Cast = dyn_cast<CastInst>(UseInst)) {
1109 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
1110 if (IsSigned || Cast->getOpcode() == Instruction::ZExt) {
1111 CollectExtend(Cast, IsSigned, WI, SE, TD);
1112 }
1113 continue;
1114 }
1115 if (isSimpleIVUser(UseInst, L)) {
1116 pushIVUsers(UseInst);
1117 }
1118 }
1119 if (WI.WidestNativeType) {
1120 WidenIV Widener(CurrIV, WI, LI, SE, DT, DeadInsts);
1121 if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
1122 Changed = true;
1123 LoopPhis.push_back(WidePhi);
1124 }
1125 }
1126 }
1127}
1128
Dan Gohmanc2390b12009-02-12 22:19:27 +00001129bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmana5283822010-06-18 01:35:11 +00001130 // If LoopSimplify form is not available, stay out of trouble. Some notes:
1131 // - LSR currently only supports LoopSimplify-form loops. Indvars'
1132 // canonicalization can be a pessimization without LSR to "clean up"
1133 // afterwards.
1134 // - We depend on having a preheader; in particular,
1135 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
1136 // and we're in trouble if we can't find the induction variable even when
1137 // we've manually inserted one.
1138 if (!L->isLoopSimplifyForm())
1139 return false;
1140
Andrew Trick2fabd462011-06-21 03:22:38 +00001141 if (!DisableIVRewrite)
1142 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +00001143 LI = &getAnalysis<LoopInfo>();
1144 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +00001145 DT = &getAnalysis<DominatorTree>();
Andrew Trick37da4082011-05-04 02:10:13 +00001146 TD = getAnalysisIfAvailable<TargetData>();
1147
Andrew Trick2fabd462011-06-21 03:22:38 +00001148 CurrIV = NULL;
1149 Simplified.clear();
Andrew Trickb12a7542011-03-17 23:51:11 +00001150 DeadInsts.clear();
Devang Patel5ee99972007-03-07 06:39:01 +00001151 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +00001152
Dan Gohman2d1be872009-04-16 03:18:22 +00001153 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +00001154 // transform them to use integer recurrences.
1155 RewriteNonIntegerIVs(L);
1156
Dan Gohman0bba49c2009-07-07 17:06:11 +00001157 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +00001158
Dan Gohman667d7872009-06-26 22:53:46 +00001159 // Create a rewriter object which we'll use to transform the code with.
1160 SCEVExpander Rewriter(*SE);
Andrew Trick156d4602011-06-27 23:17:44 +00001161
1162 // Eliminate redundant IV users.
1163 if (DisableIVRewrite) {
Andrew Trick37da4082011-05-04 02:10:13 +00001164 Rewriter.disableCanonicalMode();
Andrew Trick156d4602011-06-27 23:17:44 +00001165 SimplifyIVUsersNoRewrite(L, Rewriter);
1166 }
Andrew Trick37da4082011-05-04 02:10:13 +00001167
Chris Lattner40bf8b42004-04-02 20:24:31 +00001168 // Check to see if this loop has a computable loop-invariant execution count.
1169 // If so, this means that we can compute the final value of any expressions
1170 // that are recurrent in the loop, and substitute the exit values from the
1171 // loop into any instructions outside of the loop that use the final values of
1172 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +00001173 //
Dan Gohman46bdfb02009-02-24 18:55:53 +00001174 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman454d26d2010-02-22 04:11:59 +00001175 RewriteLoopExitValues(L, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +00001176
Andrew Trickf85092c2011-05-20 18:25:42 +00001177 // Eliminate redundant IV users.
Andrew Trick156d4602011-06-27 23:17:44 +00001178 if (!DisableIVRewrite)
Andrew Trick2fabd462011-06-21 03:22:38 +00001179 SimplifyIVUsers(Rewriter);
Dan Gohmana590b792010-04-13 01:46:36 +00001180
Dan Gohman81db61a2009-05-12 02:17:14 +00001181 // Compute the type of the largest recurrence expression, and decide whether
1182 // a canonical induction variable should be inserted.
Andrew Trickf85092c2011-05-20 18:25:42 +00001183 const Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00001184 bool NeedCannIV = false;
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001185 bool ExpandBECount = canExpandBackedgeTakenCount(L, SE);
Andrew Trick4dfdf242011-05-03 22:24:10 +00001186 if (ExpandBECount) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001187 // If we have a known trip count and a single exit block, we'll be
1188 // rewriting the loop exit test condition below, which requires a
1189 // canonical induction variable.
Andrew Trick4dfdf242011-05-03 22:24:10 +00001190 NeedCannIV = true;
1191 const Type *Ty = BackedgeTakenCount->getType();
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001192 if (DisableIVRewrite) {
1193 // In this mode, SimplifyIVUsers may have already widened the IV used by
1194 // the backedge test and inserted a Trunc on the compare's operand. Get
1195 // the wider type to avoid creating a redundant narrow IV only used by the
1196 // loop test.
1197 LargestType = getBackedgeIVType(L);
1198 }
Andrew Trick4dfdf242011-05-03 22:24:10 +00001199 if (!LargestType ||
1200 SE->getTypeSizeInBits(Ty) >
1201 SE->getTypeSizeInBits(LargestType))
1202 LargestType = SE->getEffectiveSCEVType(Ty);
Chris Lattnerf50af082004-04-17 18:08:33 +00001203 }
Andrew Trick37da4082011-05-04 02:10:13 +00001204 if (!DisableIVRewrite) {
1205 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
1206 NeedCannIV = true;
1207 const Type *Ty =
1208 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
1209 if (!LargestType ||
1210 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001211 SE->getTypeSizeInBits(LargestType))
Andrew Trick37da4082011-05-04 02:10:13 +00001212 LargestType = Ty;
1213 }
Chris Lattner6148c022001-12-03 17:28:42 +00001214 }
1215
Dan Gohmanf451cb82010-02-10 16:03:48 +00001216 // Now that we know the largest of the induction variable expressions
Dan Gohman81db61a2009-05-12 02:17:14 +00001217 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohman43ef3fb2010-07-20 17:18:52 +00001218 PHINode *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00001219 if (NeedCannIV) {
Dan Gohman85669632010-02-25 06:57:05 +00001220 // Check to see if the loop already has any canonical-looking induction
1221 // variables. If any are present and wider than the planned canonical
1222 // induction variable, temporarily remove them, so that the Rewriter
1223 // doesn't attempt to reuse them.
1224 SmallVector<PHINode *, 2> OldCannIVs;
1225 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
Dan Gohman4d8414f2009-06-13 16:25:49 +00001226 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
1227 SE->getTypeSizeInBits(LargestType))
1228 OldCannIV->removeFromParent();
1229 else
Dan Gohman85669632010-02-25 06:57:05 +00001230 break;
1231 OldCannIVs.push_back(OldCannIV);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001232 }
1233
Dan Gohman667d7872009-06-26 22:53:46 +00001234 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001235
Dan Gohmanc2390b12009-02-12 22:19:27 +00001236 ++NumInserted;
1237 Changed = true;
David Greenef67ef312010-01-05 01:27:06 +00001238 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +00001239
1240 // Now that the official induction variable is established, reinsert
Dan Gohman85669632010-02-25 06:57:05 +00001241 // any old canonical-looking variables after it so that the IR remains
1242 // consistent. They will be deleted as part of the dead-PHI deletion at
Dan Gohman4d8414f2009-06-13 16:25:49 +00001243 // the end of the pass.
Dan Gohman85669632010-02-25 06:57:05 +00001244 while (!OldCannIVs.empty()) {
1245 PHINode *OldCannIV = OldCannIVs.pop_back_val();
1246 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
1247 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001248 }
Chris Lattner15cad752003-12-23 07:47:09 +00001249
Dan Gohmanc2390b12009-02-12 22:19:27 +00001250 // If we have a trip count expression, rewrite the loop's exit condition
1251 // using it. We can currently only handle loops with a single exit.
Dan Gohman81db61a2009-05-12 02:17:14 +00001252 ICmpInst *NewICmp = 0;
Andrew Trick4dfdf242011-05-03 22:24:10 +00001253 if (ExpandBECount) {
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001254 assert(canExpandBackedgeTakenCount(L, SE) &&
Andrew Trick4dfdf242011-05-03 22:24:10 +00001255 "canonical IV disrupted BackedgeTaken expansion");
Dan Gohman81db61a2009-05-12 02:17:14 +00001256 assert(NeedCannIV &&
1257 "LinearFunctionTestReplace requires a canonical induction variable");
Andrew Trick4dfdf242011-05-03 22:24:10 +00001258 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
1259 Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +00001260 }
Andrew Trickb12a7542011-03-17 23:51:11 +00001261 // Rewrite IV-derived expressions.
Andrew Trick37da4082011-05-04 02:10:13 +00001262 if (!DisableIVRewrite)
1263 RewriteIVExpressions(L, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +00001264
Andrew Trickb12a7542011-03-17 23:51:11 +00001265 // Clear the rewriter cache, because values that are in the rewriter's cache
1266 // can be deleted in the loop below, causing the AssertingVH in the cache to
1267 // trigger.
1268 Rewriter.clear();
1269
1270 // Now that we're done iterating through lists, clean up any instructions
1271 // which are now dead.
1272 while (!DeadInsts.empty())
1273 if (Instruction *Inst =
1274 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
1275 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1276
Dan Gohman667d7872009-06-26 22:53:46 +00001277 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +00001278
Dan Gohman81db61a2009-05-12 02:17:14 +00001279 // Loop-invariant instructions in the preheader that aren't used in the
1280 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +00001281 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +00001282
1283 // For completeness, inform IVUsers of the IV use in the newly-created
1284 // loop exit test instruction.
Andrew Trick2fabd462011-06-21 03:22:38 +00001285 if (NewICmp && IU)
Andrew Trick4417e532011-06-21 15:43:52 +00001286 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
Dan Gohman81db61a2009-05-12 02:17:14 +00001287
1288 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +00001289 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +00001290 // Check a post-condition.
Dan Gohmanbbf81d82010-03-10 19:38:49 +00001291 assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +00001292 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +00001293}
Devang Pateld22a8492008-09-09 21:41:07 +00001294
Dan Gohman448db1c2010-04-07 22:27:08 +00001295// FIXME: It is an extremely bad idea to indvar substitute anything more
1296// complex than affine induction variables. Doing so will put expensive
1297// polynomial evaluations inside of the loop, and the str reduction pass
1298// currently can only reduce affine polynomials. For now just disable
1299// indvar subst on anything more complex than an affine addrec, unless
1300// it can be expanded to a trivial value.
Dan Gohman17ead4f2010-11-17 21:23:15 +00001301static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
Dan Gohman448db1c2010-04-07 22:27:08 +00001302 // Loop-invariant values are safe.
Dan Gohman17ead4f2010-11-17 21:23:15 +00001303 if (SE->isLoopInvariant(S, L)) return true;
Dan Gohman448db1c2010-04-07 22:27:08 +00001304
1305 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
1306 // to transform them into efficient code.
1307 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
1308 return AR->isAffine();
1309
1310 // An add is safe it all its operands are safe.
1311 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
1312 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
1313 E = Commutative->op_end(); I != E; ++I)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001314 if (!isSafe(*I, L, SE)) return false;
Dan Gohman448db1c2010-04-07 22:27:08 +00001315 return true;
1316 }
Andrew Trickead71d52011-03-17 23:46:48 +00001317
Dan Gohman448db1c2010-04-07 22:27:08 +00001318 // A cast is safe if its operand is.
1319 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
Dan Gohman17ead4f2010-11-17 21:23:15 +00001320 return isSafe(C->getOperand(), L, SE);
Dan Gohman448db1c2010-04-07 22:27:08 +00001321
1322 // A udiv is safe if its operands are.
1323 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
Dan Gohman17ead4f2010-11-17 21:23:15 +00001324 return isSafe(UD->getLHS(), L, SE) &&
1325 isSafe(UD->getRHS(), L, SE);
Dan Gohman448db1c2010-04-07 22:27:08 +00001326
1327 // SCEVUnknown is always safe.
1328 if (isa<SCEVUnknown>(S))
1329 return true;
1330
1331 // Nothing else is safe.
1332 return false;
1333}
1334
Dan Gohman454d26d2010-02-22 04:11:59 +00001335void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001336 // Rewrite all induction variable expressions in terms of the canonical
1337 // induction variable.
1338 //
1339 // If there were induction variables of other sizes or offsets, manually
1340 // add the offsets to the primary induction variable and cast, avoiding
1341 // the need for the code evaluation methods to insert induction variables
1342 // of different sizes.
Dan Gohman572645c2010-02-12 10:34:29 +00001343 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
Dan Gohman572645c2010-02-12 10:34:29 +00001344 Value *Op = UI->getOperandValToReplace();
1345 const Type *UseTy = Op->getType();
1346 Instruction *User = UI->getUser();
Dan Gohman81db61a2009-05-12 02:17:14 +00001347
Dan Gohman572645c2010-02-12 10:34:29 +00001348 // Compute the final addrec to expand into code.
1349 const SCEV *AR = IU->getReplacementExpr(*UI);
Dan Gohman81db61a2009-05-12 02:17:14 +00001350
Dan Gohman572645c2010-02-12 10:34:29 +00001351 // Evaluate the expression out of the loop, if possible.
1352 if (!L->contains(UI->getUser())) {
1353 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +00001354 if (SE->isLoopInvariant(ExitVal, L))
Dan Gohman572645c2010-02-12 10:34:29 +00001355 AR = ExitVal;
Dan Gohman81db61a2009-05-12 02:17:14 +00001356 }
Dan Gohman572645c2010-02-12 10:34:29 +00001357
1358 // FIXME: It is an extremely bad idea to indvar substitute anything more
1359 // complex than affine induction variables. Doing so will put expensive
1360 // polynomial evaluations inside of the loop, and the str reduction pass
1361 // currently can only reduce affine polynomials. For now just disable
1362 // indvar subst on anything more complex than an affine addrec, unless
1363 // it can be expanded to a trivial value.
Dan Gohman17ead4f2010-11-17 21:23:15 +00001364 if (!isSafe(AR, L, SE))
Dan Gohman572645c2010-02-12 10:34:29 +00001365 continue;
1366
1367 // Determine the insertion point for this user. By default, insert
1368 // immediately before the user. The SCEVExpander class will automatically
1369 // hoist loop invariants out of the loop. For PHI nodes, there may be
1370 // multiple uses, so compute the nearest common dominator for the
1371 // incoming blocks.
1372 Instruction *InsertPt = User;
1373 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
1374 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
1375 if (PHI->getIncomingValue(i) == Op) {
1376 if (InsertPt == User)
1377 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
1378 else
1379 InsertPt =
1380 DT->findNearestCommonDominator(InsertPt->getParent(),
1381 PHI->getIncomingBlock(i))
1382 ->getTerminator();
1383 }
1384
1385 // Now expand it into actual Instructions and patch it into place.
1386 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
1387
Andrew Trickb12a7542011-03-17 23:51:11 +00001388 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
1389 << " into = " << *NewVal << "\n");
1390
1391 if (!isValidRewrite(Op, NewVal)) {
1392 DeadInsts.push_back(NewVal);
1393 continue;
1394 }
Dan Gohmand7bfd002010-04-02 14:48:31 +00001395 // Inform ScalarEvolution that this value is changing. The change doesn't
1396 // affect its value, but it does potentially affect which use lists the
1397 // value will be on after the replacement, which affects ScalarEvolution's
1398 // ability to walk use lists and drop dangling pointers when a value is
1399 // deleted.
1400 SE->forgetValue(User);
1401
Dan Gohman572645c2010-02-12 10:34:29 +00001402 // Patch the new value into place.
1403 if (Op->hasName())
1404 NewVal->takeName(Op);
Devang Patela098bf12011-06-22 19:52:36 +00001405 if (Instruction *NewValI = dyn_cast<Instruction>(NewVal))
1406 NewValI->setDebugLoc(User->getDebugLoc());
Dan Gohman572645c2010-02-12 10:34:29 +00001407 User->replaceUsesOfWith(Op, NewVal);
1408 UI->setOperandValToReplace(NewVal);
Andrew Trickb12a7542011-03-17 23:51:11 +00001409
Dan Gohman572645c2010-02-12 10:34:29 +00001410 ++NumRemoved;
1411 Changed = true;
1412
1413 // The old value may be dead now.
1414 DeadInsts.push_back(Op);
Dan Gohman81db61a2009-05-12 02:17:14 +00001415 }
Dan Gohman81db61a2009-05-12 02:17:14 +00001416}
1417
1418/// If there's a single exit block, sink any loop-invariant values that
1419/// were defined in the preheader but not used inside the loop into the
1420/// exit block to reduce register pressure in the loop.
Dan Gohman667d7872009-06-26 22:53:46 +00001421void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001422 BasicBlock *ExitBlock = L->getExitBlock();
1423 if (!ExitBlock) return;
1424
Dan Gohman81db61a2009-05-12 02:17:14 +00001425 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman03e896b2009-11-05 21:11:53 +00001426 if (!Preheader) return;
1427
1428 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
Dan Gohman81db61a2009-05-12 02:17:14 +00001429 BasicBlock::iterator I = Preheader->getTerminator();
1430 while (I != Preheader->begin()) {
1431 --I;
Dan Gohman667d7872009-06-26 22:53:46 +00001432 // New instructions were inserted at the end of the preheader.
1433 if (isa<PHINode>(I))
Dan Gohman81db61a2009-05-12 02:17:14 +00001434 break;
Bill Wendling87a10f52010-03-23 21:15:59 +00001435
Eli Friedman0c77db32009-07-15 22:48:29 +00001436 // Don't move instructions which might have side effects, since the side
Bill Wendling87a10f52010-03-23 21:15:59 +00001437 // effects need to complete before instructions inside the loop. Also don't
1438 // move instructions which might read memory, since the loop may modify
1439 // memory. Note that it's okay if the instruction might have undefined
1440 // behavior: LoopSimplify guarantees that the preheader dominates the exit
1441 // block.
Eli Friedman0c77db32009-07-15 22:48:29 +00001442 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Dan Gohman667d7872009-06-26 22:53:46 +00001443 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001444
Devang Patel7b9f6b12010-03-15 22:23:03 +00001445 // Skip debug info intrinsics.
1446 if (isa<DbgInfoIntrinsic>(I))
1447 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001448
Dan Gohman76f497a2009-08-25 17:42:10 +00001449 // Don't sink static AllocaInsts out of the entry block, which would
1450 // turn them into dynamic allocas!
1451 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
1452 if (AI->isStaticAlloca())
1453 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001454
Dan Gohman81db61a2009-05-12 02:17:14 +00001455 // Determine if there is a use in or before the loop (direct or
1456 // otherwise).
1457 bool UsedInLoop = false;
1458 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1459 UI != UE; ++UI) {
Gabor Greif76560182010-07-09 15:40:10 +00001460 User *U = *UI;
1461 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
1462 if (PHINode *P = dyn_cast<PHINode>(U)) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001463 unsigned i =
1464 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
1465 UseBB = P->getIncomingBlock(i);
1466 }
1467 if (UseBB == Preheader || L->contains(UseBB)) {
1468 UsedInLoop = true;
1469 break;
1470 }
1471 }
Bill Wendling87a10f52010-03-23 21:15:59 +00001472
Dan Gohman81db61a2009-05-12 02:17:14 +00001473 // If there is, the def must remain in the preheader.
1474 if (UsedInLoop)
1475 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001476
Dan Gohman81db61a2009-05-12 02:17:14 +00001477 // Otherwise, sink it to the exit block.
1478 Instruction *ToMove = I;
1479 bool Done = false;
Bill Wendling87a10f52010-03-23 21:15:59 +00001480
1481 if (I != Preheader->begin()) {
1482 // Skip debug info intrinsics.
1483 do {
1484 --I;
1485 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
1486
1487 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
1488 Done = true;
1489 } else {
Dan Gohman81db61a2009-05-12 02:17:14 +00001490 Done = true;
Bill Wendling87a10f52010-03-23 21:15:59 +00001491 }
1492
Dan Gohman667d7872009-06-26 22:53:46 +00001493 ToMove->moveBefore(InsertPt);
Bill Wendling87a10f52010-03-23 21:15:59 +00001494 if (Done) break;
Dan Gohman667d7872009-06-26 22:53:46 +00001495 InsertPt = ToMove;
Dan Gohman81db61a2009-05-12 02:17:14 +00001496 }
1497}
1498
Chris Lattnerbbb91492010-04-03 06:41:49 +00001499/// ConvertToSInt - Convert APF to an integer, if possible.
1500static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
Devang Patelcd402332008-11-17 23:27:13 +00001501 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +00001502 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
1503 return false;
Chris Lattnerbbb91492010-04-03 06:41:49 +00001504 // See if we can convert this to an int64_t
1505 uint64_t UIntVal;
1506 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
1507 &isExact) != APFloat::opOK || !isExact)
Devang Patelcd402332008-11-17 23:27:13 +00001508 return false;
Chris Lattnerbbb91492010-04-03 06:41:49 +00001509 IntVal = UIntVal;
Devang Patelcd402332008-11-17 23:27:13 +00001510 return true;
Devang Patelcd402332008-11-17 23:27:13 +00001511}
1512
Devang Patel58d43d42008-11-03 18:32:19 +00001513/// HandleFloatingPointIV - If the loop has floating induction variable
1514/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +00001515/// For example,
1516/// for(double i = 0; i < 10000; ++i)
1517/// bar(i)
1518/// is converted into
1519/// for(int i = 0; i < 10000; ++i)
1520/// bar((double)i);
1521///
Chris Lattnerc91961e2010-04-03 06:17:08 +00001522void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
1523 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
Devang Patel84e35152008-11-17 21:32:02 +00001524 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +00001525
Devang Patel84e35152008-11-17 21:32:02 +00001526 // Check incoming value.
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001527 ConstantFP *InitValueVal =
Chris Lattnerc91961e2010-04-03 06:17:08 +00001528 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
Chris Lattner96fd7662010-04-03 07:18:48 +00001529
Chris Lattnerbbb91492010-04-03 06:41:49 +00001530 int64_t InitValue;
Chris Lattner96fd7662010-04-03 07:18:48 +00001531 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
Devang Patelcd402332008-11-17 23:27:13 +00001532 return;
1533
Chris Lattnerc91961e2010-04-03 06:17:08 +00001534 // Check IV increment. Reject this PN if increment operation is not
Devang Patelcd402332008-11-17 23:27:13 +00001535 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +00001536 BinaryOperator *Incr =
Chris Lattnerc91961e2010-04-03 06:17:08 +00001537 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
Chris Lattner07aa76a2010-04-03 05:54:59 +00001538 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
Andrew Trickead71d52011-03-17 23:46:48 +00001539
Chris Lattner07aa76a2010-04-03 05:54:59 +00001540 // If this is not an add of the PHI with a constantfp, or if the constant fp
1541 // is not an integer, bail out.
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001542 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
Chris Lattner96fd7662010-04-03 07:18:48 +00001543 int64_t IncValue;
Chris Lattnerc91961e2010-04-03 06:17:08 +00001544 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
Chris Lattner96fd7662010-04-03 07:18:48 +00001545 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
Devang Patelcd402332008-11-17 23:27:13 +00001546 return;
Dan Gohmancafb8132009-02-17 19:13:57 +00001547
Chris Lattnerc91961e2010-04-03 06:17:08 +00001548 // Check Incr uses. One user is PN and the other user is an exit condition
Chris Lattner07aa76a2010-04-03 05:54:59 +00001549 // used by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +00001550 Value::use_iterator IncrUse = Incr->use_begin();
Gabor Greif96f1d8e2010-07-22 13:36:47 +00001551 Instruction *U1 = cast<Instruction>(*IncrUse++);
Devang Patel84e35152008-11-17 21:32:02 +00001552 if (IncrUse == Incr->use_end()) return;
Gabor Greif96f1d8e2010-07-22 13:36:47 +00001553 Instruction *U2 = cast<Instruction>(*IncrUse++);
Devang Patel84e35152008-11-17 21:32:02 +00001554 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +00001555
Chris Lattner07aa76a2010-04-03 05:54:59 +00001556 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
1557 // only used by a branch, we can't transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +00001558 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
1559 if (!Compare)
1560 Compare = dyn_cast<FCmpInst>(U2);
1561 if (Compare == 0 || !Compare->hasOneUse() ||
1562 !isa<BranchInst>(Compare->use_back()))
Chris Lattner07aa76a2010-04-03 05:54:59 +00001563 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001564
Chris Lattnerca703bd2010-04-03 06:11:07 +00001565 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
Devang Patel84e35152008-11-17 21:32:02 +00001566
Chris Lattnerd52c0722010-04-03 07:21:39 +00001567 // We need to verify that the branch actually controls the iteration count
1568 // of the loop. If not, the new IV can overflow and no one will notice.
1569 // The branch block must be in the loop and one of the successors must be out
1570 // of the loop.
1571 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
1572 if (!L->contains(TheBr->getParent()) ||
1573 (L->contains(TheBr->getSuccessor(0)) &&
1574 L->contains(TheBr->getSuccessor(1))))
1575 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001576
1577
Chris Lattner07aa76a2010-04-03 05:54:59 +00001578 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
1579 // transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +00001580 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
Chris Lattnerbbb91492010-04-03 06:41:49 +00001581 int64_t ExitValue;
1582 if (ExitValueVal == 0 ||
1583 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
Devang Patel84e35152008-11-17 21:32:02 +00001584 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001585
Devang Patel84e35152008-11-17 21:32:02 +00001586 // Find new predicate for integer comparison.
1587 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerca703bd2010-04-03 06:11:07 +00001588 switch (Compare->getPredicate()) {
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001589 default: return; // Unknown comparison.
Devang Patel84e35152008-11-17 21:32:02 +00001590 case CmpInst::FCMP_OEQ:
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001591 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
Chris Lattner96fd7662010-04-03 07:18:48 +00001592 case CmpInst::FCMP_ONE:
1593 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
Devang Patel84e35152008-11-17 21:32:02 +00001594 case CmpInst::FCMP_OGT:
Chris Lattnera40e4a02010-04-03 06:25:21 +00001595 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
Devang Patel84e35152008-11-17 21:32:02 +00001596 case CmpInst::FCMP_OGE:
Chris Lattnera40e4a02010-04-03 06:25:21 +00001597 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
Devang Patel84e35152008-11-17 21:32:02 +00001598 case CmpInst::FCMP_OLT:
Chris Lattner43b85272010-04-03 06:30:03 +00001599 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
Devang Patel84e35152008-11-17 21:32:02 +00001600 case CmpInst::FCMP_OLE:
Chris Lattner43b85272010-04-03 06:30:03 +00001601 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
Devang Patel58d43d42008-11-03 18:32:19 +00001602 }
Andrew Trickead71d52011-03-17 23:46:48 +00001603
Chris Lattner96fd7662010-04-03 07:18:48 +00001604 // We convert the floating point induction variable to a signed i32 value if
1605 // we can. This is only safe if the comparison will not overflow in a way
1606 // that won't be trapped by the integer equivalent operations. Check for this
1607 // now.
1608 // TODO: We could use i64 if it is native and the range requires it.
Andrew Trickead71d52011-03-17 23:46:48 +00001609
Chris Lattner96fd7662010-04-03 07:18:48 +00001610 // The start/stride/exit values must all fit in signed i32.
1611 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
1612 return;
1613
1614 // If not actually striding (add x, 0.0), avoid touching the code.
1615 if (IncValue == 0)
1616 return;
1617
1618 // Positive and negative strides have different safety conditions.
1619 if (IncValue > 0) {
1620 // If we have a positive stride, we require the init to be less than the
1621 // exit value and an equality or less than comparison.
1622 if (InitValue >= ExitValue ||
1623 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
1624 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001625
Chris Lattner96fd7662010-04-03 07:18:48 +00001626 uint32_t Range = uint32_t(ExitValue-InitValue);
1627 if (NewPred == CmpInst::ICMP_SLE) {
1628 // Normalize SLE -> SLT, check for infinite loop.
1629 if (++Range == 0) return; // Range overflows.
1630 }
Andrew Trickead71d52011-03-17 23:46:48 +00001631
Chris Lattner96fd7662010-04-03 07:18:48 +00001632 unsigned Leftover = Range % uint32_t(IncValue);
Andrew Trickead71d52011-03-17 23:46:48 +00001633
Chris Lattner96fd7662010-04-03 07:18:48 +00001634 // If this is an equality comparison, we require that the strided value
1635 // exactly land on the exit value, otherwise the IV condition will wrap
1636 // around and do things the fp IV wouldn't.
1637 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1638 Leftover != 0)
1639 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001640
Chris Lattner96fd7662010-04-03 07:18:48 +00001641 // If the stride would wrap around the i32 before exiting, we can't
1642 // transform the IV.
1643 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
1644 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001645
Chris Lattner96fd7662010-04-03 07:18:48 +00001646 } else {
1647 // If we have a negative stride, we require the init to be greater than the
1648 // exit value and an equality or greater than comparison.
1649 if (InitValue >= ExitValue ||
1650 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
1651 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001652
Chris Lattner96fd7662010-04-03 07:18:48 +00001653 uint32_t Range = uint32_t(InitValue-ExitValue);
1654 if (NewPred == CmpInst::ICMP_SGE) {
1655 // Normalize SGE -> SGT, check for infinite loop.
1656 if (++Range == 0) return; // Range overflows.
1657 }
Andrew Trickead71d52011-03-17 23:46:48 +00001658
Chris Lattner96fd7662010-04-03 07:18:48 +00001659 unsigned Leftover = Range % uint32_t(-IncValue);
Andrew Trickead71d52011-03-17 23:46:48 +00001660
Chris Lattner96fd7662010-04-03 07:18:48 +00001661 // If this is an equality comparison, we require that the strided value
1662 // exactly land on the exit value, otherwise the IV condition will wrap
1663 // around and do things the fp IV wouldn't.
1664 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1665 Leftover != 0)
1666 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001667
Chris Lattner96fd7662010-04-03 07:18:48 +00001668 // If the stride would wrap around the i32 before exiting, we can't
1669 // transform the IV.
1670 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
1671 return;
1672 }
Andrew Trickead71d52011-03-17 23:46:48 +00001673
Chris Lattner96fd7662010-04-03 07:18:48 +00001674 const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
Dan Gohmancafb8132009-02-17 19:13:57 +00001675
Chris Lattnerbbb91492010-04-03 06:41:49 +00001676 // Insert new integer induction variable.
Jay Foad3ecfc862011-03-30 11:28:46 +00001677 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001678 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
Chris Lattnerc91961e2010-04-03 06:17:08 +00001679 PN->getIncomingBlock(IncomingEdge));
Devang Patel84e35152008-11-17 21:32:02 +00001680
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001681 Value *NewAdd =
Chris Lattner96fd7662010-04-03 07:18:48 +00001682 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001683 Incr->getName()+".int", Incr);
Chris Lattnerc91961e2010-04-03 06:17:08 +00001684 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
Devang Patel84e35152008-11-17 21:32:02 +00001685
Chris Lattnerca703bd2010-04-03 06:11:07 +00001686 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
1687 ConstantInt::get(Int32Ty, ExitValue),
1688 Compare->getName());
Dan Gohmancafb8132009-02-17 19:13:57 +00001689
Chris Lattnerc91961e2010-04-03 06:17:08 +00001690 // In the following deletions, PN may become dead and may be deleted.
Dan Gohman81db61a2009-05-12 02:17:14 +00001691 // Use a WeakVH to observe whether this happens.
Chris Lattnerc91961e2010-04-03 06:17:08 +00001692 WeakVH WeakPH = PN;
Dan Gohman81db61a2009-05-12 02:17:14 +00001693
Chris Lattnerca703bd2010-04-03 06:11:07 +00001694 // Delete the old floating point exit comparison. The branch starts using the
1695 // new comparison.
1696 NewCompare->takeName(Compare);
1697 Compare->replaceAllUsesWith(NewCompare);
1698 RecursivelyDeleteTriviallyDeadInstructions(Compare);
Dan Gohmancafb8132009-02-17 19:13:57 +00001699
Chris Lattnerca703bd2010-04-03 06:11:07 +00001700 // Delete the old floating point increment.
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001701 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman81db61a2009-05-12 02:17:14 +00001702 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +00001703
Chris Lattner70c0d4f2010-04-03 06:16:22 +00001704 // If the FP induction variable still has uses, this is because something else
1705 // in the loop uses its value. In order to canonicalize the induction
1706 // variable, we chose to eliminate the IV and rewrite it in terms of an
1707 // int->fp cast.
1708 //
1709 // We give preference to sitofp over uitofp because it is faster on most
1710 // platforms.
1711 if (WeakPH) {
Chris Lattnera40e4a02010-04-03 06:25:21 +00001712 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
1713 PN->getParent()->getFirstNonPHI());
1714 PN->replaceAllUsesWith(Conv);
Chris Lattnerc91961e2010-04-03 06:17:08 +00001715 RecursivelyDeleteTriviallyDeadInstructions(PN);
Devang Patelcd402332008-11-17 23:27:13 +00001716 }
Devang Patel58d43d42008-11-03 18:32:19 +00001717
Dan Gohman81db61a2009-05-12 02:17:14 +00001718 // Add a new IVUsers entry for the newly-created integer PHI.
Andrew Trick2fabd462011-06-21 03:22:38 +00001719 if (IU)
Andrew Trick4417e532011-06-21 15:43:52 +00001720 IU->AddUsersIfInteresting(NewPHI);
Dan Gohman81db61a2009-05-12 02:17:14 +00001721}