blob: 1e7df43ee8d2ea643e079ee447836dbb7b549aeb [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 Trickf85092c2011-05-20 18:25:42 +0000134 bool IsSigned,
135 PHINode *IVPhi);
Andrew Trick2fabd462011-06-21 03:22:38 +0000136 void pushIVUsers(Instruction *Def);
137 bool isSimpleIVUser(Instruction *I, const Loop *L);
Dan Gohman60f8a632009-02-17 20:49:49 +0000138 void RewriteNonIntegerIVs(Loop *L);
139
Dan Gohman0bba49c2009-07-07 17:06:11 +0000140 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
Andrew Trick4dfdf242011-05-03 22:24:10 +0000141 PHINode *IndVar,
142 SCEVExpander &Rewriter);
Andrew Trick37da4082011-05-04 02:10:13 +0000143
Dan Gohman454d26d2010-02-22 04:11:59 +0000144 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000145
Dan Gohman454d26d2010-02-22 04:11:59 +0000146 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000147
Dan Gohman667d7872009-06-26 22:53:46 +0000148 void SinkUnusedInvariants(Loop *L);
Dan Gohman81db61a2009-05-12 02:17:14 +0000149
150 void HandleFloatingPointIV(Loop *L, PHINode *PH);
Chris Lattner3324e712003-12-22 03:58:44 +0000151 };
Chris Lattner5e761402002-09-10 05:24:05 +0000152}
Chris Lattner394437f2001-12-04 04:32:29 +0000153
Dan Gohman844731a2008-05-13 00:00:25 +0000154char IndVarSimplify::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000155INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000156 "Induction Variable Simplification", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000157INITIALIZE_PASS_DEPENDENCY(DominatorTree)
158INITIALIZE_PASS_DEPENDENCY(LoopInfo)
159INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
160INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
161INITIALIZE_PASS_DEPENDENCY(LCSSA)
162INITIALIZE_PASS_DEPENDENCY(IVUsers)
163INITIALIZE_PASS_END(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000164 "Induction Variable Simplification", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000165
Daniel Dunbar394f0442008-10-22 23:32:42 +0000166Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000167 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000168}
169
Andrew Trickb12a7542011-03-17 23:51:11 +0000170/// isValidRewrite - Return true if the SCEV expansion generated by the
171/// rewriter can replace the original value. SCEV guarantees that it
172/// produces the same value, but the way it is produced may be illegal IR.
173/// Ideally, this function will only be called for verification.
174bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
175 // If an SCEV expression subsumed multiple pointers, its expansion could
176 // reassociate the GEP changing the base pointer. This is illegal because the
177 // final address produced by a GEP chain must be inbounds relative to its
178 // underlying object. Otherwise basic alias analysis, among other things,
179 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
180 // producing an expression involving multiple pointers. Until then, we must
181 // bail out here.
182 //
183 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
184 // because it understands lcssa phis while SCEV does not.
185 Value *FromPtr = FromVal;
186 Value *ToPtr = ToVal;
187 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
188 FromPtr = GEP->getPointerOperand();
189 }
190 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
191 ToPtr = GEP->getPointerOperand();
192 }
193 if (FromPtr != FromVal || ToPtr != ToVal) {
194 // Quickly check the common case
195 if (FromPtr == ToPtr)
196 return true;
197
198 // SCEV may have rewritten an expression that produces the GEP's pointer
199 // operand. That's ok as long as the pointer operand has the same base
200 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
201 // base of a recurrence. This handles the case in which SCEV expansion
202 // converts a pointer type recurrence into a nonrecurrent pointer base
203 // indexed by an integer recurrence.
204 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
205 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
206 if (FromBase == ToBase)
207 return true;
208
209 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
210 << *FromBase << " != " << *ToBase << "\n");
211
212 return false;
213 }
214 return true;
215}
216
Andrew Trick4dfdf242011-05-03 22:24:10 +0000217/// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
218/// count expression can be safely and cheaply expanded into an instruction
219/// sequence that can be used by LinearFunctionTestReplace.
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000220static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) {
221 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Andrew Trick4dfdf242011-05-03 22:24:10 +0000222 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
223 BackedgeTakenCount->isZero())
224 return false;
225
226 if (!L->getExitingBlock())
227 return false;
228
229 // Can't rewrite non-branch yet.
230 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
231 if (!BI)
232 return false;
233
Dan Gohmanca9b7032010-04-12 21:13:43 +0000234 // Special case: If the backedge-taken count is a UDiv, it's very likely a
235 // UDiv that ScalarEvolution produced in order to compute a precise
236 // expression, rather than a UDiv from the user's code. If we can't find a
237 // UDiv in the code with some simple searching, assume the former and forego
238 // rewriting the loop.
239 if (isa<SCEVUDivExpr>(BackedgeTakenCount)) {
240 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
Andrew Trick37da4082011-05-04 02:10:13 +0000241 if (!OrigCond) return false;
Dan Gohmanca9b7032010-04-12 21:13:43 +0000242 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
Dan Gohmandeff6212010-05-03 22:09:21 +0000243 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
Dan Gohmanca9b7032010-04-12 21:13:43 +0000244 if (R != BackedgeTakenCount) {
245 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
Dan Gohmandeff6212010-05-03 22:09:21 +0000246 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
Dan Gohmanca9b7032010-04-12 21:13:43 +0000247 if (L != BackedgeTakenCount)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000248 return false;
Dan Gohmanca9b7032010-04-12 21:13:43 +0000249 }
250 }
Andrew Trick4dfdf242011-05-03 22:24:10 +0000251 return true;
252}
253
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000254/// getBackedgeIVType - Get the widest type used by the loop test after peeking
255/// through Truncs.
256///
257/// TODO: Unnecessary once LinearFunctionTestReplace is removed.
258static const Type *getBackedgeIVType(Loop *L) {
259 if (!L->getExitingBlock())
260 return 0;
261
262 // Can't rewrite non-branch yet.
263 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
264 if (!BI)
265 return 0;
266
267 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
268 if (!Cond)
269 return 0;
270
271 const Type *Ty = 0;
272 for(User::op_iterator OI = Cond->op_begin(), OE = Cond->op_end();
273 OI != OE; ++OI) {
274 assert((!Ty || Ty == (*OI)->getType()) && "bad icmp operand types");
275 TruncInst *Trunc = dyn_cast<TruncInst>(*OI);
276 if (!Trunc)
277 continue;
278
279 return Trunc->getSrcTy();
280 }
281 return Ty;
282}
283
Andrew Trick4dfdf242011-05-03 22:24:10 +0000284/// LinearFunctionTestReplace - This method rewrites the exit condition of the
285/// loop to be a canonical != comparison against the incremented loop induction
286/// variable. This pass is able to rewrite the exit tests of any loop where the
287/// SCEV analysis can determine a loop-invariant trip count of the loop, which
288/// is actually a much broader range than just linear tests.
289ICmpInst *IndVarSimplify::
290LinearFunctionTestReplace(Loop *L,
291 const SCEV *BackedgeTakenCount,
292 PHINode *IndVar,
293 SCEVExpander &Rewriter) {
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000294 assert(canExpandBackedgeTakenCount(L, SE) && "precondition");
Andrew Trick4dfdf242011-05-03 22:24:10 +0000295 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
Dan Gohmanca9b7032010-04-12 21:13:43 +0000296
Chris Lattnerd2440572004-04-15 20:26:22 +0000297 // If the exiting block is not the same as the backedge block, we must compare
298 // against the preincremented value, otherwise we prefer to compare against
299 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000300 Value *CmpIndVar;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000301 const SCEV *RHS = BackedgeTakenCount;
Andrew Trick4dfdf242011-05-03 22:24:10 +0000302 if (L->getExitingBlock() == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000303 // Add one to the "backedge-taken" count to get the trip count.
304 // If this addition may overflow, we have to be more pessimistic and
305 // cast the induction variable before doing the add.
Dan Gohmandeff6212010-05-03 22:09:21 +0000306 const SCEV *Zero = SE->getConstant(BackedgeTakenCount->getType(), 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000307 const SCEV *N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000308 SE->getAddExpr(BackedgeTakenCount,
Dan Gohmandeff6212010-05-03 22:09:21 +0000309 SE->getConstant(BackedgeTakenCount->getType(), 1));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000310 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000311 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000312 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000313 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000314 } else {
315 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000316 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
317 IndVar->getType());
318 RHS = SE->getAddExpr(RHS,
Dan Gohmandeff6212010-05-03 22:09:21 +0000319 SE->getConstant(IndVar->getType(), 1));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000320 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000321
Dan Gohman46bdfb02009-02-24 18:55:53 +0000322 // The BackedgeTaken expression contains the number of times that the
323 // backedge branches to the loop header. This is one less than the
324 // number of times the loop executes, so use the incremented indvar.
Andrew Trick4dfdf242011-05-03 22:24:10 +0000325 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
Chris Lattnerd2440572004-04-15 20:26:22 +0000326 } else {
327 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000328 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
329 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000330 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000331 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000332
Dan Gohman667d7872009-06-26 22:53:46 +0000333 // Expand the code for the iteration count.
Dan Gohman17ead4f2010-11-17 21:23:15 +0000334 assert(SE->isLoopInvariant(RHS, L) &&
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000335 "Computed iteration count is not loop invariant!");
Dan Gohman667d7872009-06-26 22:53:46 +0000336 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000337
Reid Spencere4d87aa2006-12-23 06:05:41 +0000338 // Insert a new icmp_ne or icmp_eq instruction before the branch.
339 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000340 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000341 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000342 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000343 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000344
David Greenef67ef312010-01-05 01:27:06 +0000345 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
Chris Lattnerbdff5482009-08-23 04:37:46 +0000346 << " LHS:" << *CmpIndVar << '\n'
347 << " op:\t"
348 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
349 << " RHS:\t" << *RHS << "\n");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000350
Owen Anderson333c4002009-07-09 23:48:35 +0000351 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
Dan Gohman81db61a2009-05-12 02:17:14 +0000352
Dan Gohman24440802010-02-22 02:07:36 +0000353 Value *OrigCond = BI->getCondition();
Dan Gohman95bdbfa2009-05-24 19:11:38 +0000354 // It's tempting to use replaceAllUsesWith here to fully replace the old
355 // comparison, but that's not immediately safe, since users of the old
356 // comparison may not be dominated by the new comparison. Instead, just
357 // update the branch to use the new comparison; in the common case this
358 // will make old comparison dead.
359 BI->setCondition(Cond);
Andrew Trick88e92cf2011-04-28 17:30:04 +0000360 DeadInsts.push_back(OrigCond);
Dan Gohman81db61a2009-05-12 02:17:14 +0000361
Chris Lattner40bf8b42004-04-02 20:24:31 +0000362 ++NumLFTR;
363 Changed = true;
Dan Gohman81db61a2009-05-12 02:17:14 +0000364 return Cond;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000365}
366
Chris Lattner40bf8b42004-04-02 20:24:31 +0000367/// RewriteLoopExitValues - Check to see if this loop has a computable
368/// loop-invariant execution count. If so, this means that we can compute the
369/// final value of any expressions that are recurrent in the loop, and
370/// substitute the exit values from the loop into any instructions outside of
371/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000372///
373/// This is mostly redundant with the regular IndVarSimplify activities that
374/// happen later, except that it's more powerful in some cases, because it's
375/// able to brute-force evaluate arbitrary instructions as long as they have
376/// constant operands at the beginning of the loop.
Chris Lattnerf1859892011-01-09 02:16:18 +0000377void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000378 // Verify the input to the pass in already in LCSSA form.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000379 assert(L->isLCSSAForm(*DT));
Dan Gohman81db61a2009-05-12 02:17:14 +0000380
Devang Patelb7211a22007-08-21 00:31:24 +0000381 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000382 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000383
Chris Lattner9f3d7382007-03-04 03:43:23 +0000384 // Find all values that are computed inside the loop, but used outside of it.
385 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
386 // the exit blocks of the loop to find them.
387 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
388 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000389
Chris Lattner9f3d7382007-03-04 03:43:23 +0000390 // If there are no PHI nodes in this exit block, then no values defined
391 // inside the loop are used on this path, skip it.
392 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
393 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000394
Chris Lattner9f3d7382007-03-04 03:43:23 +0000395 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000396
Chris Lattner9f3d7382007-03-04 03:43:23 +0000397 // Iterate over all of the PHI nodes.
398 BasicBlock::iterator BBI = ExitBB->begin();
399 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000400 if (PN->use_empty())
401 continue; // dead use, don't replace it
Dan Gohman814f2b22010-02-18 21:34:02 +0000402
403 // SCEV only supports integer expressions for now.
404 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
405 continue;
406
Dale Johannesen45a2d7d2010-02-19 07:14:22 +0000407 // It's necessary to tell ScalarEvolution about this explicitly so that
408 // it can walk the def-use list and forget all SCEVs, as it may not be
409 // watching the PHI itself. Once the new exit value is in place, there
410 // may not be a def-use connection between the loop and every instruction
411 // which got a SCEVAddRecExpr for that loop.
412 SE->forgetValue(PN);
413
Chris Lattner9f3d7382007-03-04 03:43:23 +0000414 // Iterate over all of the values in all the PHI nodes.
415 for (unsigned i = 0; i != NumPreds; ++i) {
416 // If the value being merged in is not integer or is not defined
417 // in the loop, skip it.
418 Value *InVal = PN->getIncomingValue(i);
Dan Gohman814f2b22010-02-18 21:34:02 +0000419 if (!isa<Instruction>(InVal))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000420 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000421
Chris Lattner9f3d7382007-03-04 03:43:23 +0000422 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000423 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000424 continue; // The Block is in a subloop, skip it.
425
426 // Check that InVal is defined in the loop.
427 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman92329c72009-12-18 01:24:09 +0000428 if (!L->contains(Inst))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000429 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000430
Chris Lattner9f3d7382007-03-04 03:43:23 +0000431 // Okay, this instruction has a user outside of the current loop
432 // and varies predictably *inside* the loop. Evaluate the value it
433 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000434 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +0000435 if (!SE->isLoopInvariant(ExitValue, L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000436 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000437
Dan Gohman667d7872009-06-26 22:53:46 +0000438 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000439
David Greenef67ef312010-01-05 01:27:06 +0000440 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000441 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000442
Andrew Trickb12a7542011-03-17 23:51:11 +0000443 if (!isValidRewrite(Inst, ExitVal)) {
444 DeadInsts.push_back(ExitVal);
445 continue;
446 }
447 Changed = true;
448 ++NumReplaced;
449
Chris Lattner9f3d7382007-03-04 03:43:23 +0000450 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000451
Dan Gohman81db61a2009-05-12 02:17:14 +0000452 // If this instruction is dead now, delete it.
453 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000454
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000455 if (NumPreds == 1) {
456 // Completely replace a single-pred PHI. This is safe, because the
457 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
458 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000459 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000460 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000461 }
462 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000463 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000464 // Clone the PHI and delete the original one. This lets IVUsers and
465 // any other maps purge the original user from their records.
Devang Patel50b6e332009-10-27 22:16:29 +0000466 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohman667d7872009-06-26 22:53:46 +0000467 NewPN->takeName(PN);
468 NewPN->insertBefore(PN);
469 PN->replaceAllUsesWith(NewPN);
470 PN->eraseFromParent();
471 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000472 }
473 }
Dan Gohman472fdf72010-03-20 03:53:53 +0000474
475 // The insertion point instruction may have been deleted; clear it out
476 // so that the rewriter doesn't trip over it later.
477 Rewriter.clearInsertPoint();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000478}
479
Dan Gohman60f8a632009-02-17 20:49:49 +0000480void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000481 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000482 // If there are, change them into integer recurrences, permitting analysis by
483 // the SCEV routines.
484 //
Chris Lattnerf1859892011-01-09 02:16:18 +0000485 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000486
Dan Gohman81db61a2009-05-12 02:17:14 +0000487 SmallVector<WeakVH, 8> PHIs;
488 for (BasicBlock::iterator I = Header->begin();
489 PHINode *PN = dyn_cast<PHINode>(I); ++I)
490 PHIs.push_back(PN);
491
492 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
Gabor Greifea4894a2010-09-18 11:53:39 +0000493 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
Dan Gohman81db61a2009-05-12 02:17:14 +0000494 HandleFloatingPointIV(L, PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000495
Dan Gohman2d1be872009-04-16 03:18:22 +0000496 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000497 // may not have been able to compute a trip count. Now that we've done some
498 // re-writing, the trip count may be computable.
499 if (Changed)
Dan Gohman4c7279a2009-10-31 15:04:55 +0000500 SE->forgetLoop(L);
Dale Johannesenc671d892009-04-15 23:31:51 +0000501}
502
Andrew Trick2fabd462011-06-21 03:22:38 +0000503/// SimplifyIVUsers - Iteratively perform simplification on IVUsers within this
504/// loop. IVUsers is treated as a worklist. Each successive simplification may
505/// push more users which may themselves be candidates for simplification.
506///
507/// This is the old approach to IV simplification to be replaced by
508/// SimplifyIVUsersNoRewrite.
509///
510void IndVarSimplify::SimplifyIVUsers(SCEVExpander &Rewriter) {
511 // Each round of simplification involves a round of eliminating operations
512 // followed by a round of widening IVs. A single IVUsers worklist is used
513 // across all rounds. The inner loop advances the user. If widening exposes
514 // more uses, then another pass through the outer loop is triggered.
515 for (IVUsers::iterator I = IU->begin(); I != IU->end(); ++I) {
516 Instruction *UseInst = I->getUser();
517 Value *IVOperand = I->getOperandValToReplace();
518
519 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
520 EliminateIVComparison(ICmp, IVOperand);
521 continue;
522 }
523 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
524 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
525 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
526 EliminateIVRemainder(Rem, IVOperand, IsSigned, I->getPhi());
527 continue;
528 }
529 }
530 }
531}
532
Andrew Trickf85092c2011-05-20 18:25:42 +0000533namespace {
534 // Collect information about induction variables that are used by sign/zero
535 // extend operations. This information is recorded by CollectExtend and
536 // provides the input to WidenIV.
537 struct WideIVInfo {
538 const Type *WidestNativeType; // Widest integer type created [sz]ext
539 bool IsSigned; // Was an sext user seen before a zext?
540
541 WideIVInfo() : WidestNativeType(0), IsSigned(false) {}
542 };
Andrew Trickf85092c2011-05-20 18:25:42 +0000543}
544
545/// CollectExtend - Update information about the induction variable that is
546/// extended by this sign or zero extend operation. This is used to determine
547/// the final width of the IV before actually widening it.
Andrew Trick2fabd462011-06-21 03:22:38 +0000548static void CollectExtend(CastInst *Cast, bool IsSigned, WideIVInfo &WI,
549 ScalarEvolution *SE, const TargetData *TD) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000550 const Type *Ty = Cast->getType();
551 uint64_t Width = SE->getTypeSizeInBits(Ty);
552 if (TD && !TD->isLegalInteger(Width))
553 return;
554
Andrew Trick2fabd462011-06-21 03:22:38 +0000555 if (!WI.WidestNativeType) {
556 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
557 WI.IsSigned = IsSigned;
Andrew Trickf85092c2011-05-20 18:25:42 +0000558 return;
559 }
560
561 // We extend the IV to satisfy the sign of its first user, arbitrarily.
Andrew Trick2fabd462011-06-21 03:22:38 +0000562 if (WI.IsSigned != IsSigned)
Andrew Trickf85092c2011-05-20 18:25:42 +0000563 return;
564
Andrew Trick2fabd462011-06-21 03:22:38 +0000565 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
566 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
Andrew Trickf85092c2011-05-20 18:25:42 +0000567}
568
569namespace {
570/// WidenIV - The goal of this transform is to remove sign and zero extends
571/// without creating any new induction variables. To do this, it creates a new
572/// phi of the wider type and redirects all users, either removing extends or
573/// inserting truncs whenever we stop propagating the type.
574///
575class WidenIV {
Andrew Trick2fabd462011-06-21 03:22:38 +0000576 // Parameters
Andrew Trickf85092c2011-05-20 18:25:42 +0000577 PHINode *OrigPhi;
578 const Type *WideType;
579 bool IsSigned;
580
Andrew Trick2fabd462011-06-21 03:22:38 +0000581 // Context
582 LoopInfo *LI;
583 Loop *L;
Andrew Trickf85092c2011-05-20 18:25:42 +0000584 ScalarEvolution *SE;
Andrew Trick2fabd462011-06-21 03:22:38 +0000585 DominatorTree *DT;
Andrew Trickf85092c2011-05-20 18:25:42 +0000586
Andrew Trick2fabd462011-06-21 03:22:38 +0000587 // Result
Andrew Trickf85092c2011-05-20 18:25:42 +0000588 PHINode *WidePhi;
589 Instruction *WideInc;
590 const SCEV *WideIncExpr;
Andrew Trick2fabd462011-06-21 03:22:38 +0000591 SmallVectorImpl<WeakVH> &DeadInsts;
Andrew Trickf85092c2011-05-20 18:25:42 +0000592
Andrew Trick2fabd462011-06-21 03:22:38 +0000593 SmallPtrSet<Instruction*,16> Widened;
Andrew Trickf85092c2011-05-20 18:25:42 +0000594
595public:
Andrew Trick2fabd462011-06-21 03:22:38 +0000596 WidenIV(PHINode *PN, const WideIVInfo &WI, LoopInfo *LInfo,
597 ScalarEvolution *SEv, DominatorTree *DTree,
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000598 SmallVectorImpl<WeakVH> &DI) :
Andrew Trickf85092c2011-05-20 18:25:42 +0000599 OrigPhi(PN),
Andrew Trick2fabd462011-06-21 03:22:38 +0000600 WideType(WI.WidestNativeType),
601 IsSigned(WI.IsSigned),
Andrew Trickf85092c2011-05-20 18:25:42 +0000602 LI(LInfo),
603 L(LI->getLoopFor(OrigPhi->getParent())),
604 SE(SEv),
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000605 DT(DTree),
Andrew Trickf85092c2011-05-20 18:25:42 +0000606 WidePhi(0),
607 WideInc(0),
Andrew Trick2fabd462011-06-21 03:22:38 +0000608 WideIncExpr(0),
609 DeadInsts(DI) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000610 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
611 }
612
Andrew Trick2fabd462011-06-21 03:22:38 +0000613 PHINode *CreateWideIV(SCEVExpander &Rewriter);
Andrew Trickf85092c2011-05-20 18:25:42 +0000614
615protected:
Andrew Trickf85092c2011-05-20 18:25:42 +0000616 Instruction *CloneIVUser(Instruction *NarrowUse,
617 Instruction *NarrowDef,
618 Instruction *WideDef);
619
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000620 const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
621
Andrew Trickf85092c2011-05-20 18:25:42 +0000622 Instruction *WidenIVUse(Instruction *NarrowUse,
623 Instruction *NarrowDef,
624 Instruction *WideDef);
625};
626} // anonymous namespace
627
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000628static Value *getExtend( Value *NarrowOper, const Type *WideType,
629 bool IsSigned, IRBuilder<> &Builder) {
630 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
631 Builder.CreateZExt(NarrowOper, WideType);
Andrew Trickf85092c2011-05-20 18:25:42 +0000632}
633
634/// CloneIVUser - Instantiate a wide operation to replace a narrow
635/// operation. This only needs to handle operations that can evaluation to
636/// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
637Instruction *WidenIV::CloneIVUser(Instruction *NarrowUse,
638 Instruction *NarrowDef,
639 Instruction *WideDef) {
640 unsigned Opcode = NarrowUse->getOpcode();
641 switch (Opcode) {
642 default:
643 return 0;
644 case Instruction::Add:
645 case Instruction::Mul:
646 case Instruction::UDiv:
647 case Instruction::Sub:
648 case Instruction::And:
649 case Instruction::Or:
650 case Instruction::Xor:
651 case Instruction::Shl:
652 case Instruction::LShr:
653 case Instruction::AShr:
654 DEBUG(dbgs() << "Cloning IVUser: " << *NarrowUse << "\n");
655
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000656 IRBuilder<> Builder(NarrowUse);
657
658 // Replace NarrowDef operands with WideDef. Otherwise, we don't know
659 // anything about the narrow operand yet so must insert a [sz]ext. It is
660 // probably loop invariant and will be folded or hoisted. If it actually
661 // comes from a widened IV, it should be removed during a future call to
662 // WidenIVUse.
663 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef) ? WideDef :
664 getExtend(NarrowUse->getOperand(0), WideType, IsSigned, Builder);
665 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef) ? WideDef :
666 getExtend(NarrowUse->getOperand(1), WideType, IsSigned, Builder);
667
Andrew Trickf85092c2011-05-20 18:25:42 +0000668 BinaryOperator *NarrowBO = cast<BinaryOperator>(NarrowUse);
669 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000670 LHS, RHS,
Andrew Trickf85092c2011-05-20 18:25:42 +0000671 NarrowBO->getName());
Andrew Trickf85092c2011-05-20 18:25:42 +0000672 Builder.Insert(WideBO);
673 if (NarrowBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
674 if (NarrowBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
675
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000676 return WideBO;
Andrew Trickf85092c2011-05-20 18:25:42 +0000677 }
678 llvm_unreachable(0);
679}
680
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000681// GetWideRecurrence - Is this instruction potentially interesting from IVUsers'
682// perspective after widening it's type? In other words, can the extend be
683// safely hoisted out of the loop with SCEV reducing the value to a recurrence
684// on the same loop. If so, return the sign or zero extended
685// recurrence. Otherwise return NULL.
686const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
687 if (!SE->isSCEVable(NarrowUse->getType()))
688 return 0;
689
690 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
691 const SCEV *WideExpr = IsSigned ?
692 SE->getSignExtendExpr(NarrowExpr, WideType) :
693 SE->getZeroExtendExpr(NarrowExpr, WideType);
694 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
695 if (!AddRec || AddRec->getLoop() != L)
696 return 0;
697
698 return AddRec;
699}
700
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000701/// HoistStep - Attempt to hoist an IV increment above a potential use.
702///
703/// To successfully hoist, two criteria must be met:
704/// - IncV operands dominate InsertPos and
705/// - InsertPos dominates IncV
706///
707/// Meeting the second condition means that we don't need to check all of IncV's
708/// existing uses (it's moving up in the domtree).
709///
710/// This does not yet recursively hoist the operands, although that would
711/// not be difficult.
712static bool HoistStep(Instruction *IncV, Instruction *InsertPos,
713 const DominatorTree *DT)
714{
715 if (DT->dominates(IncV, InsertPos))
716 return true;
717
718 if (!DT->dominates(InsertPos->getParent(), IncV->getParent()))
719 return false;
720
721 if (IncV->mayHaveSideEffects())
722 return false;
723
724 // Attempt to hoist IncV
725 for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end();
726 OI != OE; ++OI) {
727 Instruction *OInst = dyn_cast<Instruction>(OI);
728 if (OInst && !DT->dominates(OInst, InsertPos))
729 return false;
730 }
731 IncV->moveBefore(InsertPos);
732 return true;
733}
734
Andrew Trickf85092c2011-05-20 18:25:42 +0000735/// WidenIVUse - Determine whether an individual user of the narrow IV can be
736/// widened. If so, return the wide clone of the user.
737Instruction *WidenIV::WidenIVUse(Instruction *NarrowUse,
738 Instruction *NarrowDef,
739 Instruction *WideDef) {
740 // To be consistent with IVUsers, stop traversing the def-use chain at
741 // inner-loop phis or post-loop phis.
742 if (isa<PHINode>(NarrowUse) && LI->getLoopFor(NarrowUse->getParent()) != L)
743 return 0;
744
745 // Handle data flow merges and bizarre phi cycles.
Andrew Trick2fabd462011-06-21 03:22:38 +0000746 if (!Widened.insert(NarrowUse))
Andrew Trickf85092c2011-05-20 18:25:42 +0000747 return 0;
748
749 // Our raison d'etre! Eliminate sign and zero extension.
750 if (IsSigned ? isa<SExtInst>(NarrowUse) : isa<ZExtInst>(NarrowUse)) {
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000751 Value *NewDef = WideDef;
752 if (NarrowUse->getType() != WideType) {
753 unsigned CastWidth = SE->getTypeSizeInBits(NarrowUse->getType());
754 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
755 if (CastWidth < IVWidth) {
756 // The cast isn't as wide as the IV, so insert a Trunc.
757 IRBuilder<> Builder(NarrowUse);
758 NewDef = Builder.CreateTrunc(WideDef, NarrowUse->getType());
759 }
760 else {
761 // A wider extend was hidden behind a narrower one. This may induce
762 // another round of IV widening in which the intermediate IV becomes
763 // dead. It should be very rare.
764 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
765 << " not wide enough to subsume " << *NarrowUse << "\n");
766 NarrowUse->replaceUsesOfWith(NarrowDef, WideDef);
767 NewDef = NarrowUse;
768 }
769 }
770 if (NewDef != NarrowUse) {
771 DEBUG(dbgs() << "INDVARS: eliminating " << *NarrowUse
772 << " replaced by " << *WideDef << "\n");
773 ++NumElimExt;
774 NarrowUse->replaceAllUsesWith(NewDef);
775 DeadInsts.push_back(NarrowUse);
776 }
Andrew Trick2fabd462011-06-21 03:22:38 +0000777 // Now that the extend is gone, we want to expose it's uses for potential
778 // further simplification. We don't need to directly inform SimplifyIVUsers
779 // of the new users, because their parent IV will be processed later as a
780 // new loop phi. If we preserved IVUsers analysis, we would also want to
781 // push the uses of WideDef here.
Andrew Trickf85092c2011-05-20 18:25:42 +0000782
783 // No further widening is needed. The deceased [sz]ext had done it for us.
784 return 0;
785 }
786 const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(NarrowUse);
787 if (!WideAddRec) {
788 // This user does not evaluate to a recurence after widening, so don't
789 // follow it. Instead insert a Trunc to kill off the original use,
790 // eventually isolating the original narrow IV so it can be removed.
791 IRBuilder<> Builder(NarrowUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000792 Value *Trunc = Builder.CreateTrunc(WideDef, NarrowDef->getType());
Andrew Trickf85092c2011-05-20 18:25:42 +0000793 NarrowUse->replaceUsesOfWith(NarrowDef, Trunc);
794 return 0;
795 }
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000796 // Reuse the IV increment that SCEVExpander created as long as it dominates
797 // NarrowUse.
Andrew Trickf85092c2011-05-20 18:25:42 +0000798 Instruction *WideUse = 0;
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000799 if (WideAddRec == WideIncExpr && HoistStep(WideInc, NarrowUse, DT)) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000800 WideUse = WideInc;
801 }
802 else {
803 WideUse = CloneIVUser(NarrowUse, NarrowDef, WideDef);
804 if (!WideUse)
805 return 0;
806 }
807 // GetWideRecurrence ensured that the narrow expression could be extended
808 // outside the loop without overflow. This suggests that the wide use
809 // evaluates to the same expression as the extended narrow use, but doesn't
810 // absolutely guarantee it. Hence the following failsafe check. In rare cases
Andrew Trick2fabd462011-06-21 03:22:38 +0000811 // where it fails, we simply throw away the newly created wide use.
Andrew Trickf85092c2011-05-20 18:25:42 +0000812 if (WideAddRec != SE->getSCEV(WideUse)) {
813 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
814 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
815 DeadInsts.push_back(WideUse);
816 return 0;
817 }
818
819 // Returning WideUse pushes it on the worklist.
820 return WideUse;
821}
822
823/// CreateWideIV - Process a single induction variable. First use the
824/// SCEVExpander to create a wide induction variable that evaluates to the same
825/// recurrence as the original narrow IV. Then use a worklist to forward
Andrew Trick2fabd462011-06-21 03:22:38 +0000826/// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
Andrew Trickf85092c2011-05-20 18:25:42 +0000827/// interesting IV users, the narrow IV will be isolated for removal by
828/// DeleteDeadPHIs.
829///
830/// It would be simpler to delete uses as they are processed, but we must avoid
831/// invalidating SCEV expressions.
832///
Andrew Trick2fabd462011-06-21 03:22:38 +0000833PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000834 // Is this phi an induction variable?
835 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
836 if (!AddRec)
Andrew Trick2fabd462011-06-21 03:22:38 +0000837 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +0000838
839 // Widen the induction variable expression.
840 const SCEV *WideIVExpr = IsSigned ?
841 SE->getSignExtendExpr(AddRec, WideType) :
842 SE->getZeroExtendExpr(AddRec, WideType);
843
844 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
845 "Expect the new IV expression to preserve its type");
846
847 // Can the IV be extended outside the loop without overflow?
848 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
849 if (!AddRec || AddRec->getLoop() != L)
Andrew Trick2fabd462011-06-21 03:22:38 +0000850 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +0000851
Andrew Trick2fabd462011-06-21 03:22:38 +0000852 // An AddRec must have loop-invariant operands. Since this AddRec is
Andrew Trickf85092c2011-05-20 18:25:42 +0000853 // materialized by a loop header phi, the expression cannot have any post-loop
854 // operands, so they must dominate the loop header.
855 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
856 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
857 && "Loop header phi recurrence inputs do not dominate the loop");
858
859 // The rewriter provides a value for the desired IV expression. This may
860 // either find an existing phi or materialize a new one. Either way, we
861 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
862 // of the phi-SCC dominates the loop entry.
863 Instruction *InsertPt = L->getHeader()->begin();
864 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
865
866 // Remembering the WideIV increment generated by SCEVExpander allows
867 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
868 // employ a general reuse mechanism because the call above is the only call to
869 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000870 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
871 WideInc =
872 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
873 WideIncExpr = SE->getSCEV(WideInc);
874 }
Andrew Trickf85092c2011-05-20 18:25:42 +0000875
876 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
877 ++NumWidened;
878
879 // Traverse the def-use chain using a worklist starting at the original IV.
Andrew Trick2fabd462011-06-21 03:22:38 +0000880 assert(Widened.empty() && "expect initial state" );
Andrew Trickf85092c2011-05-20 18:25:42 +0000881
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000882 // Each worklist entry has a Narrow def-use link and Wide def.
883 SmallVector<std::pair<Use *, Instruction *>, 8> NarrowIVUsers;
884 for (Value::use_iterator UI = OrigPhi->use_begin(),
885 UE = OrigPhi->use_end(); UI != UE; ++UI) {
886 NarrowIVUsers.push_back(std::make_pair(&UI.getUse(), WidePhi));
887 }
Andrew Trickf85092c2011-05-20 18:25:42 +0000888 while (!NarrowIVUsers.empty()) {
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000889 Use *NarrowDefUse;
890 Instruction *WideDef;
891 tie(NarrowDefUse, WideDef) = NarrowIVUsers.pop_back_val();
Andrew Trickf85092c2011-05-20 18:25:42 +0000892
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000893 // Process a def-use edge. This may replace the use, so don't hold a
894 // use_iterator across it.
895 Instruction *NarrowDef = cast<Instruction>(NarrowDefUse->get());
896 Instruction *NarrowUse = cast<Instruction>(NarrowDefUse->getUser());
897 Instruction *WideUse = WidenIVUse(NarrowUse, NarrowDef, WideDef);
Andrew Trickf85092c2011-05-20 18:25:42 +0000898
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000899 // Follow all def-use edges from the previous narrow use.
900 if (WideUse) {
901 for (Value::use_iterator UI = NarrowUse->use_begin(),
902 UE = NarrowUse->use_end(); UI != UE; ++UI) {
903 NarrowIVUsers.push_back(std::make_pair(&UI.getUse(), WideUse));
904 }
Andrew Trickf85092c2011-05-20 18:25:42 +0000905 }
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000906 // WidenIVUse may have removed the def-use edge.
907 if (NarrowDef->use_empty())
908 DeadInsts.push_back(NarrowDef);
Andrew Trickf85092c2011-05-20 18:25:42 +0000909 }
Andrew Trick2fabd462011-06-21 03:22:38 +0000910 return WidePhi;
Andrew Trickf85092c2011-05-20 18:25:42 +0000911}
912
Andrew Trickaeee4612011-05-12 00:04:28 +0000913void IndVarSimplify::EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
914 unsigned IVOperIdx = 0;
915 ICmpInst::Predicate Pred = ICmp->getPredicate();
916 if (IVOperand != ICmp->getOperand(0)) {
917 // Swapped
918 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
919 IVOperIdx = 1;
920 Pred = ICmpInst::getSwappedPredicate(Pred);
Dan Gohmana590b792010-04-13 01:46:36 +0000921 }
Andrew Trickaeee4612011-05-12 00:04:28 +0000922
923 // Get the SCEVs for the ICmp operands.
924 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
925 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
926
927 // Simplify unnecessary loops away.
928 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
929 S = SE->getSCEVAtScope(S, ICmpLoop);
930 X = SE->getSCEVAtScope(X, ICmpLoop);
931
932 // If the condition is always true or always false, replace it with
933 // a constant value.
934 if (SE->isKnownPredicate(Pred, S, X))
935 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
936 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
937 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
938 else
939 return;
940
941 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000942 ++NumElimCmp;
Andrew Trick074397d2011-05-20 03:37:48 +0000943 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +0000944 DeadInsts.push_back(ICmp);
945}
946
947void IndVarSimplify::EliminateIVRemainder(BinaryOperator *Rem,
948 Value *IVOperand,
Andrew Trickf85092c2011-05-20 18:25:42 +0000949 bool IsSigned,
950 PHINode *IVPhi) {
Andrew Trickaeee4612011-05-12 00:04:28 +0000951 // We're only interested in the case where we know something about
952 // the numerator.
953 if (IVOperand != Rem->getOperand(0))
954 return;
955
956 // Get the SCEVs for the ICmp operands.
957 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
958 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
959
960 // Simplify unnecessary loops away.
961 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
962 S = SE->getSCEVAtScope(S, ICmpLoop);
963 X = SE->getSCEVAtScope(X, ICmpLoop);
964
965 // i % n --> i if i is in [0,n).
Andrew Trick074397d2011-05-20 03:37:48 +0000966 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
967 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Andrew Trickaeee4612011-05-12 00:04:28 +0000968 S, X))
969 Rem->replaceAllUsesWith(Rem->getOperand(0));
970 else {
971 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
972 const SCEV *LessOne =
973 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
Andrew Trick074397d2011-05-20 03:37:48 +0000974 if (IsSigned && !SE->isKnownNonNegative(LessOne))
Andrew Trickaeee4612011-05-12 00:04:28 +0000975 return;
976
Andrew Trick074397d2011-05-20 03:37:48 +0000977 if (!SE->isKnownPredicate(IsSigned ?
Andrew Trickaeee4612011-05-12 00:04:28 +0000978 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
979 LessOne, X))
980 return;
981
982 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
983 Rem->getOperand(0), Rem->getOperand(1),
984 "tmp");
985 SelectInst *Sel =
986 SelectInst::Create(ICmp,
987 ConstantInt::get(Rem->getType(), 0),
988 Rem->getOperand(0), "tmp", Rem);
989 Rem->replaceAllUsesWith(Sel);
990 }
991
992 // Inform IVUsers about the new users.
Andrew Trick2fabd462011-06-21 03:22:38 +0000993 if (IU) {
994 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
995 IU->AddUsersIfInteresting(I, IVPhi);
996 }
Andrew Trickaeee4612011-05-12 00:04:28 +0000997 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000998 ++NumElimRem;
Andrew Trick074397d2011-05-20 03:37:48 +0000999 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +00001000 DeadInsts.push_back(Rem);
Dan Gohmana590b792010-04-13 01:46:36 +00001001}
1002
Andrew Trick2fabd462011-06-21 03:22:38 +00001003/// EliminateIVUser - Eliminate an operation that consumes a simple IV and has
1004/// no observable side-effect given the range of IV values.
1005bool IndVarSimplify::EliminateIVUser(Instruction *UseInst,
1006 Instruction *IVOperand) {
1007 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
1008 EliminateIVComparison(ICmp, IVOperand);
1009 return true;
1010 }
1011 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
1012 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
1013 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
1014 EliminateIVRemainder(Rem, IVOperand, IsSigned, CurrIV);
1015 return true;
1016 }
1017 }
1018
1019 // Eliminate any operation that SCEV can prove is an identity function.
1020 if (!SE->isSCEVable(UseInst->getType()) ||
1021 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
1022 return false;
1023
1024 UseInst->replaceAllUsesWith(IVOperand);
1025
1026 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
1027 ++NumElimIdentity;
1028 Changed = true;
1029 DeadInsts.push_back(UseInst);
1030 return true;
1031}
1032
1033/// pushIVUsers - Add all uses of Def to the current IV's worklist.
1034///
1035void IndVarSimplify::pushIVUsers(Instruction *Def) {
1036
1037 for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
1038 UI != E; ++UI) {
1039 Instruction *User = cast<Instruction>(*UI);
1040
1041 // Avoid infinite or exponential worklist processing.
1042 // Also ensure unique worklist users.
1043 if (Simplified.insert(User))
1044 SimpleIVUsers.push_back(std::make_pair(User, Def));
1045 }
1046}
1047
1048/// isSimpleIVUser - Return true if this instruction generates a simple SCEV
1049/// expression in terms of that IV.
1050///
1051/// This is similar to IVUsers' isInsteresting() but processes each instruction
1052/// non-recursively when the operand is already known to be a simpleIVUser.
1053///
1054bool IndVarSimplify::isSimpleIVUser(Instruction *I, const Loop *L) {
1055 if (!SE->isSCEVable(I->getType()))
1056 return false;
1057
1058 // Get the symbolic expression for this instruction.
1059 const SCEV *S = SE->getSCEV(I);
1060
1061 // Only consider affine recurrences.
1062 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
1063 if (AR && AR->getLoop() == L)
1064 return true;
1065
1066 return false;
1067}
1068
1069/// SimplifyIVUsersNoRewrite - Iteratively perform simplification on a worklist
1070/// of IV users. Each successive simplification may push more users which may
1071/// themselves be candidates for simplification.
1072///
1073/// The "NoRewrite" algorithm does not require IVUsers analysis. Instead, it
1074/// simplifies instructions in-place during analysis. Rather than rewriting
1075/// induction variables bottom-up from their users, it transforms a chain of
1076/// IVUsers top-down, updating the IR only when it encouters a clear
1077/// optimization opportunitiy. A SCEVExpander "Rewriter" instance is still
1078/// needed, but only used to generate a new IV (phi) of wider type for sign/zero
1079/// extend elimination.
1080///
1081/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
1082///
1083void IndVarSimplify::SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter) {
1084 // Simplification is performed independently for each IV, as represented by a
1085 // loop header phi. Each round of simplification first iterates through the
1086 // SimplifyIVUsers worklist, then determines whether the current IV should be
1087 // widened. Widening adds a new phi to LoopPhis, inducing another round of
1088 // simplification on the wide IV.
1089 SmallVector<PHINode*, 8> LoopPhis;
1090 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1091 LoopPhis.push_back(cast<PHINode>(I));
1092 }
1093 while (!LoopPhis.empty()) {
1094 CurrIV = LoopPhis.pop_back_val();
1095 Simplified.clear();
1096 assert(SimpleIVUsers.empty() && "expect empty IV users list");
1097
1098 WideIVInfo WI;
1099
1100 pushIVUsers(CurrIV);
1101
1102 while (!SimpleIVUsers.empty()) {
1103 Instruction *UseInst, *Operand;
1104 tie(UseInst, Operand) = SimpleIVUsers.pop_back_val();
1105
1106 if (EliminateIVUser(UseInst, Operand)) {
1107 pushIVUsers(Operand);
1108 continue;
1109 }
1110 if (CastInst *Cast = dyn_cast<CastInst>(UseInst)) {
1111 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
1112 if (IsSigned || Cast->getOpcode() == Instruction::ZExt) {
1113 CollectExtend(Cast, IsSigned, WI, SE, TD);
1114 }
1115 continue;
1116 }
1117 if (isSimpleIVUser(UseInst, L)) {
1118 pushIVUsers(UseInst);
1119 }
1120 }
1121 if (WI.WidestNativeType) {
1122 WidenIV Widener(CurrIV, WI, LI, SE, DT, DeadInsts);
1123 if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
1124 Changed = true;
1125 LoopPhis.push_back(WidePhi);
1126 }
1127 }
1128 }
1129}
1130
Dan Gohmanc2390b12009-02-12 22:19:27 +00001131bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmana5283822010-06-18 01:35:11 +00001132 // If LoopSimplify form is not available, stay out of trouble. Some notes:
1133 // - LSR currently only supports LoopSimplify-form loops. Indvars'
1134 // canonicalization can be a pessimization without LSR to "clean up"
1135 // afterwards.
1136 // - We depend on having a preheader; in particular,
1137 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
1138 // and we're in trouble if we can't find the induction variable even when
1139 // we've manually inserted one.
1140 if (!L->isLoopSimplifyForm())
1141 return false;
1142
Andrew Trick2fabd462011-06-21 03:22:38 +00001143 if (!DisableIVRewrite)
1144 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +00001145 LI = &getAnalysis<LoopInfo>();
1146 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +00001147 DT = &getAnalysis<DominatorTree>();
Andrew Trick37da4082011-05-04 02:10:13 +00001148 TD = getAnalysisIfAvailable<TargetData>();
1149
Andrew Trick2fabd462011-06-21 03:22:38 +00001150 CurrIV = NULL;
1151 Simplified.clear();
Andrew Trickb12a7542011-03-17 23:51:11 +00001152 DeadInsts.clear();
Devang Patel5ee99972007-03-07 06:39:01 +00001153 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +00001154
Dan Gohman2d1be872009-04-16 03:18:22 +00001155 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +00001156 // transform them to use integer recurrences.
1157 RewriteNonIntegerIVs(L);
1158
Dan Gohman0bba49c2009-07-07 17:06:11 +00001159 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +00001160
Dan Gohman667d7872009-06-26 22:53:46 +00001161 // Create a rewriter object which we'll use to transform the code with.
1162 SCEVExpander Rewriter(*SE);
Andrew Trick37da4082011-05-04 02:10:13 +00001163 if (DisableIVRewrite)
1164 Rewriter.disableCanonicalMode();
1165
Chris Lattner40bf8b42004-04-02 20:24:31 +00001166 // Check to see if this loop has a computable loop-invariant execution count.
1167 // If so, this means that we can compute the final value of any expressions
1168 // that are recurrent in the loop, and substitute the exit values from the
1169 // loop into any instructions outside of the loop that use the final values of
1170 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +00001171 //
Dan Gohman46bdfb02009-02-24 18:55:53 +00001172 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman454d26d2010-02-22 04:11:59 +00001173 RewriteLoopExitValues(L, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +00001174
Andrew Trickf85092c2011-05-20 18:25:42 +00001175 // Eliminate redundant IV users.
Andrew Trick2fabd462011-06-21 03:22:38 +00001176 if (DisableIVRewrite)
1177 SimplifyIVUsersNoRewrite(L, Rewriter);
1178 else
1179 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 Trickf85092c2011-05-20 18:25:42 +00001286 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)),
1287 IndVar);
Dan Gohman81db61a2009-05-12 02:17:14 +00001288
1289 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +00001290 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +00001291 // Check a post-condition.
Dan Gohmanbbf81d82010-03-10 19:38:49 +00001292 assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +00001293 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +00001294}
Devang Pateld22a8492008-09-09 21:41:07 +00001295
Dan Gohman448db1c2010-04-07 22:27:08 +00001296// FIXME: It is an extremely bad idea to indvar substitute anything more
1297// complex than affine induction variables. Doing so will put expensive
1298// polynomial evaluations inside of the loop, and the str reduction pass
1299// currently can only reduce affine polynomials. For now just disable
1300// indvar subst on anything more complex than an affine addrec, unless
1301// it can be expanded to a trivial value.
Dan Gohman17ead4f2010-11-17 21:23:15 +00001302static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
Dan Gohman448db1c2010-04-07 22:27:08 +00001303 // Loop-invariant values are safe.
Dan Gohman17ead4f2010-11-17 21:23:15 +00001304 if (SE->isLoopInvariant(S, L)) return true;
Dan Gohman448db1c2010-04-07 22:27:08 +00001305
1306 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
1307 // to transform them into efficient code.
1308 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
1309 return AR->isAffine();
1310
1311 // An add is safe it all its operands are safe.
1312 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
1313 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
1314 E = Commutative->op_end(); I != E; ++I)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001315 if (!isSafe(*I, L, SE)) return false;
Dan Gohman448db1c2010-04-07 22:27:08 +00001316 return true;
1317 }
Andrew Trickead71d52011-03-17 23:46:48 +00001318
Dan Gohman448db1c2010-04-07 22:27:08 +00001319 // A cast is safe if its operand is.
1320 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
Dan Gohman17ead4f2010-11-17 21:23:15 +00001321 return isSafe(C->getOperand(), L, SE);
Dan Gohman448db1c2010-04-07 22:27:08 +00001322
1323 // A udiv is safe if its operands are.
1324 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
Dan Gohman17ead4f2010-11-17 21:23:15 +00001325 return isSafe(UD->getLHS(), L, SE) &&
1326 isSafe(UD->getRHS(), L, SE);
Dan Gohman448db1c2010-04-07 22:27:08 +00001327
1328 // SCEVUnknown is always safe.
1329 if (isa<SCEVUnknown>(S))
1330 return true;
1331
1332 // Nothing else is safe.
1333 return false;
1334}
1335
Dan Gohman454d26d2010-02-22 04:11:59 +00001336void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001337 // Rewrite all induction variable expressions in terms of the canonical
1338 // induction variable.
1339 //
1340 // If there were induction variables of other sizes or offsets, manually
1341 // add the offsets to the primary induction variable and cast, avoiding
1342 // the need for the code evaluation methods to insert induction variables
1343 // of different sizes.
Dan Gohman572645c2010-02-12 10:34:29 +00001344 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
Dan Gohman572645c2010-02-12 10:34:29 +00001345 Value *Op = UI->getOperandValToReplace();
1346 const Type *UseTy = Op->getType();
1347 Instruction *User = UI->getUser();
Dan Gohman81db61a2009-05-12 02:17:14 +00001348
Dan Gohman572645c2010-02-12 10:34:29 +00001349 // Compute the final addrec to expand into code.
1350 const SCEV *AR = IU->getReplacementExpr(*UI);
Dan Gohman81db61a2009-05-12 02:17:14 +00001351
Dan Gohman572645c2010-02-12 10:34:29 +00001352 // Evaluate the expression out of the loop, if possible.
1353 if (!L->contains(UI->getUser())) {
1354 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +00001355 if (SE->isLoopInvariant(ExitVal, L))
Dan Gohman572645c2010-02-12 10:34:29 +00001356 AR = ExitVal;
Dan Gohman81db61a2009-05-12 02:17:14 +00001357 }
Dan Gohman572645c2010-02-12 10:34:29 +00001358
1359 // FIXME: It is an extremely bad idea to indvar substitute anything more
1360 // complex than affine induction variables. Doing so will put expensive
1361 // polynomial evaluations inside of the loop, and the str reduction pass
1362 // currently can only reduce affine polynomials. For now just disable
1363 // indvar subst on anything more complex than an affine addrec, unless
1364 // it can be expanded to a trivial value.
Dan Gohman17ead4f2010-11-17 21:23:15 +00001365 if (!isSafe(AR, L, SE))
Dan Gohman572645c2010-02-12 10:34:29 +00001366 continue;
1367
1368 // Determine the insertion point for this user. By default, insert
1369 // immediately before the user. The SCEVExpander class will automatically
1370 // hoist loop invariants out of the loop. For PHI nodes, there may be
1371 // multiple uses, so compute the nearest common dominator for the
1372 // incoming blocks.
1373 Instruction *InsertPt = User;
1374 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
1375 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
1376 if (PHI->getIncomingValue(i) == Op) {
1377 if (InsertPt == User)
1378 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
1379 else
1380 InsertPt =
1381 DT->findNearestCommonDominator(InsertPt->getParent(),
1382 PHI->getIncomingBlock(i))
1383 ->getTerminator();
1384 }
1385
1386 // Now expand it into actual Instructions and patch it into place.
1387 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
1388
Andrew Trickb12a7542011-03-17 23:51:11 +00001389 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
1390 << " into = " << *NewVal << "\n");
1391
1392 if (!isValidRewrite(Op, NewVal)) {
1393 DeadInsts.push_back(NewVal);
1394 continue;
1395 }
Dan Gohmand7bfd002010-04-02 14:48:31 +00001396 // Inform ScalarEvolution that this value is changing. The change doesn't
1397 // affect its value, but it does potentially affect which use lists the
1398 // value will be on after the replacement, which affects ScalarEvolution's
1399 // ability to walk use lists and drop dangling pointers when a value is
1400 // deleted.
1401 SE->forgetValue(User);
1402
Dan Gohman572645c2010-02-12 10:34:29 +00001403 // Patch the new value into place.
1404 if (Op->hasName())
1405 NewVal->takeName(Op);
1406 User->replaceUsesOfWith(Op, NewVal);
1407 UI->setOperandValToReplace(NewVal);
Andrew Trickb12a7542011-03-17 23:51:11 +00001408
Dan Gohman572645c2010-02-12 10:34:29 +00001409 ++NumRemoved;
1410 Changed = true;
1411
1412 // The old value may be dead now.
1413 DeadInsts.push_back(Op);
Dan Gohman81db61a2009-05-12 02:17:14 +00001414 }
Dan Gohman81db61a2009-05-12 02:17:14 +00001415}
1416
1417/// If there's a single exit block, sink any loop-invariant values that
1418/// were defined in the preheader but not used inside the loop into the
1419/// exit block to reduce register pressure in the loop.
Dan Gohman667d7872009-06-26 22:53:46 +00001420void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001421 BasicBlock *ExitBlock = L->getExitBlock();
1422 if (!ExitBlock) return;
1423
Dan Gohman81db61a2009-05-12 02:17:14 +00001424 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman03e896b2009-11-05 21:11:53 +00001425 if (!Preheader) return;
1426
1427 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
Dan Gohman81db61a2009-05-12 02:17:14 +00001428 BasicBlock::iterator I = Preheader->getTerminator();
1429 while (I != Preheader->begin()) {
1430 --I;
Dan Gohman667d7872009-06-26 22:53:46 +00001431 // New instructions were inserted at the end of the preheader.
1432 if (isa<PHINode>(I))
Dan Gohman81db61a2009-05-12 02:17:14 +00001433 break;
Bill Wendling87a10f52010-03-23 21:15:59 +00001434
Eli Friedman0c77db32009-07-15 22:48:29 +00001435 // Don't move instructions which might have side effects, since the side
Bill Wendling87a10f52010-03-23 21:15:59 +00001436 // effects need to complete before instructions inside the loop. Also don't
1437 // move instructions which might read memory, since the loop may modify
1438 // memory. Note that it's okay if the instruction might have undefined
1439 // behavior: LoopSimplify guarantees that the preheader dominates the exit
1440 // block.
Eli Friedman0c77db32009-07-15 22:48:29 +00001441 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Dan Gohman667d7872009-06-26 22:53:46 +00001442 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001443
Devang Patel7b9f6b12010-03-15 22:23:03 +00001444 // Skip debug info intrinsics.
1445 if (isa<DbgInfoIntrinsic>(I))
1446 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001447
Dan Gohman76f497a2009-08-25 17:42:10 +00001448 // Don't sink static AllocaInsts out of the entry block, which would
1449 // turn them into dynamic allocas!
1450 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
1451 if (AI->isStaticAlloca())
1452 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001453
Dan Gohman81db61a2009-05-12 02:17:14 +00001454 // Determine if there is a use in or before the loop (direct or
1455 // otherwise).
1456 bool UsedInLoop = false;
1457 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1458 UI != UE; ++UI) {
Gabor Greif76560182010-07-09 15:40:10 +00001459 User *U = *UI;
1460 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
1461 if (PHINode *P = dyn_cast<PHINode>(U)) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001462 unsigned i =
1463 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
1464 UseBB = P->getIncomingBlock(i);
1465 }
1466 if (UseBB == Preheader || L->contains(UseBB)) {
1467 UsedInLoop = true;
1468 break;
1469 }
1470 }
Bill Wendling87a10f52010-03-23 21:15:59 +00001471
Dan Gohman81db61a2009-05-12 02:17:14 +00001472 // If there is, the def must remain in the preheader.
1473 if (UsedInLoop)
1474 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001475
Dan Gohman81db61a2009-05-12 02:17:14 +00001476 // Otherwise, sink it to the exit block.
1477 Instruction *ToMove = I;
1478 bool Done = false;
Bill Wendling87a10f52010-03-23 21:15:59 +00001479
1480 if (I != Preheader->begin()) {
1481 // Skip debug info intrinsics.
1482 do {
1483 --I;
1484 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
1485
1486 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
1487 Done = true;
1488 } else {
Dan Gohman81db61a2009-05-12 02:17:14 +00001489 Done = true;
Bill Wendling87a10f52010-03-23 21:15:59 +00001490 }
1491
Dan Gohman667d7872009-06-26 22:53:46 +00001492 ToMove->moveBefore(InsertPt);
Bill Wendling87a10f52010-03-23 21:15:59 +00001493 if (Done) break;
Dan Gohman667d7872009-06-26 22:53:46 +00001494 InsertPt = ToMove;
Dan Gohman81db61a2009-05-12 02:17:14 +00001495 }
1496}
1497
Chris Lattnerbbb91492010-04-03 06:41:49 +00001498/// ConvertToSInt - Convert APF to an integer, if possible.
1499static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
Devang Patelcd402332008-11-17 23:27:13 +00001500 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +00001501 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
1502 return false;
Chris Lattnerbbb91492010-04-03 06:41:49 +00001503 // See if we can convert this to an int64_t
1504 uint64_t UIntVal;
1505 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
1506 &isExact) != APFloat::opOK || !isExact)
Devang Patelcd402332008-11-17 23:27:13 +00001507 return false;
Chris Lattnerbbb91492010-04-03 06:41:49 +00001508 IntVal = UIntVal;
Devang Patelcd402332008-11-17 23:27:13 +00001509 return true;
Devang Patelcd402332008-11-17 23:27:13 +00001510}
1511
Devang Patel58d43d42008-11-03 18:32:19 +00001512/// HandleFloatingPointIV - If the loop has floating induction variable
1513/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +00001514/// For example,
1515/// for(double i = 0; i < 10000; ++i)
1516/// bar(i)
1517/// is converted into
1518/// for(int i = 0; i < 10000; ++i)
1519/// bar((double)i);
1520///
Chris Lattnerc91961e2010-04-03 06:17:08 +00001521void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
1522 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
Devang Patel84e35152008-11-17 21:32:02 +00001523 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +00001524
Devang Patel84e35152008-11-17 21:32:02 +00001525 // Check incoming value.
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001526 ConstantFP *InitValueVal =
Chris Lattnerc91961e2010-04-03 06:17:08 +00001527 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
Chris Lattner96fd7662010-04-03 07:18:48 +00001528
Chris Lattnerbbb91492010-04-03 06:41:49 +00001529 int64_t InitValue;
Chris Lattner96fd7662010-04-03 07:18:48 +00001530 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
Devang Patelcd402332008-11-17 23:27:13 +00001531 return;
1532
Chris Lattnerc91961e2010-04-03 06:17:08 +00001533 // Check IV increment. Reject this PN if increment operation is not
Devang Patelcd402332008-11-17 23:27:13 +00001534 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +00001535 BinaryOperator *Incr =
Chris Lattnerc91961e2010-04-03 06:17:08 +00001536 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
Chris Lattner07aa76a2010-04-03 05:54:59 +00001537 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
Andrew Trickead71d52011-03-17 23:46:48 +00001538
Chris Lattner07aa76a2010-04-03 05:54:59 +00001539 // If this is not an add of the PHI with a constantfp, or if the constant fp
1540 // is not an integer, bail out.
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001541 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
Chris Lattner96fd7662010-04-03 07:18:48 +00001542 int64_t IncValue;
Chris Lattnerc91961e2010-04-03 06:17:08 +00001543 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
Chris Lattner96fd7662010-04-03 07:18:48 +00001544 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
Devang Patelcd402332008-11-17 23:27:13 +00001545 return;
Dan Gohmancafb8132009-02-17 19:13:57 +00001546
Chris Lattnerc91961e2010-04-03 06:17:08 +00001547 // Check Incr uses. One user is PN and the other user is an exit condition
Chris Lattner07aa76a2010-04-03 05:54:59 +00001548 // used by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +00001549 Value::use_iterator IncrUse = Incr->use_begin();
Gabor Greif96f1d8e2010-07-22 13:36:47 +00001550 Instruction *U1 = cast<Instruction>(*IncrUse++);
Devang Patel84e35152008-11-17 21:32:02 +00001551 if (IncrUse == Incr->use_end()) return;
Gabor Greif96f1d8e2010-07-22 13:36:47 +00001552 Instruction *U2 = cast<Instruction>(*IncrUse++);
Devang Patel84e35152008-11-17 21:32:02 +00001553 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +00001554
Chris Lattner07aa76a2010-04-03 05:54:59 +00001555 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
1556 // only used by a branch, we can't transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +00001557 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
1558 if (!Compare)
1559 Compare = dyn_cast<FCmpInst>(U2);
1560 if (Compare == 0 || !Compare->hasOneUse() ||
1561 !isa<BranchInst>(Compare->use_back()))
Chris Lattner07aa76a2010-04-03 05:54:59 +00001562 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001563
Chris Lattnerca703bd2010-04-03 06:11:07 +00001564 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
Devang Patel84e35152008-11-17 21:32:02 +00001565
Chris Lattnerd52c0722010-04-03 07:21:39 +00001566 // We need to verify that the branch actually controls the iteration count
1567 // of the loop. If not, the new IV can overflow and no one will notice.
1568 // The branch block must be in the loop and one of the successors must be out
1569 // of the loop.
1570 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
1571 if (!L->contains(TheBr->getParent()) ||
1572 (L->contains(TheBr->getSuccessor(0)) &&
1573 L->contains(TheBr->getSuccessor(1))))
1574 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001575
1576
Chris Lattner07aa76a2010-04-03 05:54:59 +00001577 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
1578 // transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +00001579 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
Chris Lattnerbbb91492010-04-03 06:41:49 +00001580 int64_t ExitValue;
1581 if (ExitValueVal == 0 ||
1582 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
Devang Patel84e35152008-11-17 21:32:02 +00001583 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001584
Devang Patel84e35152008-11-17 21:32:02 +00001585 // Find new predicate for integer comparison.
1586 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerca703bd2010-04-03 06:11:07 +00001587 switch (Compare->getPredicate()) {
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001588 default: return; // Unknown comparison.
Devang Patel84e35152008-11-17 21:32:02 +00001589 case CmpInst::FCMP_OEQ:
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001590 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
Chris Lattner96fd7662010-04-03 07:18:48 +00001591 case CmpInst::FCMP_ONE:
1592 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
Devang Patel84e35152008-11-17 21:32:02 +00001593 case CmpInst::FCMP_OGT:
Chris Lattnera40e4a02010-04-03 06:25:21 +00001594 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
Devang Patel84e35152008-11-17 21:32:02 +00001595 case CmpInst::FCMP_OGE:
Chris Lattnera40e4a02010-04-03 06:25:21 +00001596 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
Devang Patel84e35152008-11-17 21:32:02 +00001597 case CmpInst::FCMP_OLT:
Chris Lattner43b85272010-04-03 06:30:03 +00001598 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
Devang Patel84e35152008-11-17 21:32:02 +00001599 case CmpInst::FCMP_OLE:
Chris Lattner43b85272010-04-03 06:30:03 +00001600 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
Devang Patel58d43d42008-11-03 18:32:19 +00001601 }
Andrew Trickead71d52011-03-17 23:46:48 +00001602
Chris Lattner96fd7662010-04-03 07:18:48 +00001603 // We convert the floating point induction variable to a signed i32 value if
1604 // we can. This is only safe if the comparison will not overflow in a way
1605 // that won't be trapped by the integer equivalent operations. Check for this
1606 // now.
1607 // TODO: We could use i64 if it is native and the range requires it.
Andrew Trickead71d52011-03-17 23:46:48 +00001608
Chris Lattner96fd7662010-04-03 07:18:48 +00001609 // The start/stride/exit values must all fit in signed i32.
1610 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
1611 return;
1612
1613 // If not actually striding (add x, 0.0), avoid touching the code.
1614 if (IncValue == 0)
1615 return;
1616
1617 // Positive and negative strides have different safety conditions.
1618 if (IncValue > 0) {
1619 // If we have a positive stride, we require the init to be less than the
1620 // exit value and an equality or less than comparison.
1621 if (InitValue >= ExitValue ||
1622 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
1623 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001624
Chris Lattner96fd7662010-04-03 07:18:48 +00001625 uint32_t Range = uint32_t(ExitValue-InitValue);
1626 if (NewPred == CmpInst::ICMP_SLE) {
1627 // Normalize SLE -> SLT, check for infinite loop.
1628 if (++Range == 0) return; // Range overflows.
1629 }
Andrew Trickead71d52011-03-17 23:46:48 +00001630
Chris Lattner96fd7662010-04-03 07:18:48 +00001631 unsigned Leftover = Range % uint32_t(IncValue);
Andrew Trickead71d52011-03-17 23:46:48 +00001632
Chris Lattner96fd7662010-04-03 07:18:48 +00001633 // If this is an equality comparison, we require that the strided value
1634 // exactly land on the exit value, otherwise the IV condition will wrap
1635 // around and do things the fp IV wouldn't.
1636 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1637 Leftover != 0)
1638 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001639
Chris Lattner96fd7662010-04-03 07:18:48 +00001640 // If the stride would wrap around the i32 before exiting, we can't
1641 // transform the IV.
1642 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
1643 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001644
Chris Lattner96fd7662010-04-03 07:18:48 +00001645 } else {
1646 // If we have a negative stride, we require the init to be greater than the
1647 // exit value and an equality or greater than comparison.
1648 if (InitValue >= ExitValue ||
1649 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
1650 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001651
Chris Lattner96fd7662010-04-03 07:18:48 +00001652 uint32_t Range = uint32_t(InitValue-ExitValue);
1653 if (NewPred == CmpInst::ICMP_SGE) {
1654 // Normalize SGE -> SGT, check for infinite loop.
1655 if (++Range == 0) return; // Range overflows.
1656 }
Andrew Trickead71d52011-03-17 23:46:48 +00001657
Chris Lattner96fd7662010-04-03 07:18:48 +00001658 unsigned Leftover = Range % uint32_t(-IncValue);
Andrew Trickead71d52011-03-17 23:46:48 +00001659
Chris Lattner96fd7662010-04-03 07:18:48 +00001660 // If this is an equality comparison, we require that the strided value
1661 // exactly land on the exit value, otherwise the IV condition will wrap
1662 // around and do things the fp IV wouldn't.
1663 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1664 Leftover != 0)
1665 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001666
Chris Lattner96fd7662010-04-03 07:18:48 +00001667 // If the stride would wrap around the i32 before exiting, we can't
1668 // transform the IV.
1669 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
1670 return;
1671 }
Andrew Trickead71d52011-03-17 23:46:48 +00001672
Chris Lattner96fd7662010-04-03 07:18:48 +00001673 const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
Dan Gohmancafb8132009-02-17 19:13:57 +00001674
Chris Lattnerbbb91492010-04-03 06:41:49 +00001675 // Insert new integer induction variable.
Jay Foad3ecfc862011-03-30 11:28:46 +00001676 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001677 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
Chris Lattnerc91961e2010-04-03 06:17:08 +00001678 PN->getIncomingBlock(IncomingEdge));
Devang Patel84e35152008-11-17 21:32:02 +00001679
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001680 Value *NewAdd =
Chris Lattner96fd7662010-04-03 07:18:48 +00001681 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001682 Incr->getName()+".int", Incr);
Chris Lattnerc91961e2010-04-03 06:17:08 +00001683 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
Devang Patel84e35152008-11-17 21:32:02 +00001684
Chris Lattnerca703bd2010-04-03 06:11:07 +00001685 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
1686 ConstantInt::get(Int32Ty, ExitValue),
1687 Compare->getName());
Dan Gohmancafb8132009-02-17 19:13:57 +00001688
Chris Lattnerc91961e2010-04-03 06:17:08 +00001689 // In the following deletions, PN may become dead and may be deleted.
Dan Gohman81db61a2009-05-12 02:17:14 +00001690 // Use a WeakVH to observe whether this happens.
Chris Lattnerc91961e2010-04-03 06:17:08 +00001691 WeakVH WeakPH = PN;
Dan Gohman81db61a2009-05-12 02:17:14 +00001692
Chris Lattnerca703bd2010-04-03 06:11:07 +00001693 // Delete the old floating point exit comparison. The branch starts using the
1694 // new comparison.
1695 NewCompare->takeName(Compare);
1696 Compare->replaceAllUsesWith(NewCompare);
1697 RecursivelyDeleteTriviallyDeadInstructions(Compare);
Dan Gohmancafb8132009-02-17 19:13:57 +00001698
Chris Lattnerca703bd2010-04-03 06:11:07 +00001699 // Delete the old floating point increment.
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001700 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman81db61a2009-05-12 02:17:14 +00001701 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +00001702
Chris Lattner70c0d4f2010-04-03 06:16:22 +00001703 // If the FP induction variable still has uses, this is because something else
1704 // in the loop uses its value. In order to canonicalize the induction
1705 // variable, we chose to eliminate the IV and rewrite it in terms of an
1706 // int->fp cast.
1707 //
1708 // We give preference to sitofp over uitofp because it is faster on most
1709 // platforms.
1710 if (WeakPH) {
Chris Lattnera40e4a02010-04-03 06:25:21 +00001711 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
1712 PN->getParent()->getFirstNonPHI());
1713 PN->replaceAllUsesWith(Conv);
Chris Lattnerc91961e2010-04-03 06:17:08 +00001714 RecursivelyDeleteTriviallyDeadInstructions(PN);
Devang Patelcd402332008-11-17 23:27:13 +00001715 }
Devang Patel58d43d42008-11-03 18:32:19 +00001716
Dan Gohman81db61a2009-05-12 02:17:14 +00001717 // Add a new IVUsers entry for the newly-created integer PHI.
Andrew Trick2fabd462011-06-21 03:22:38 +00001718 if (IU)
1719 IU->AddUsersIfInteresting(NewPHI, NewPHI);
Dan Gohman81db61a2009-05-12 02:17:14 +00001720}