blob: bc3bc303ae9315e1562854cf76c6ce2edf9d73ff [file] [log] [blame]
Chris Lattner6148c022001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6148c022001-12-03 17:28:42 +00009//
Chris Lattner40bf8b42004-04-02 20:24:31 +000010// This transformation analyzes and transforms the induction variables (and
11// computations derived from them) into simpler forms suitable for subsequent
12// analysis and transformation.
13//
Reid Spencer47a53ac2006-08-18 09:01:07 +000014// This transformation makes the following changes to each loop with an
Chris Lattner40bf8b42004-04-02 20:24:31 +000015// identifiable induction variable:
16// 1. All loops are transformed to have a SINGLE canonical induction variable
17// which starts at zero and steps by one.
18// 2. The canonical induction variable is guaranteed to be the first PHI node
19// in the loop header block.
Dan Gohmanea73f3c2009-06-14 22:38:41 +000020// 3. The canonical induction variable is guaranteed to be in a wide enough
21// type so that IV expressions need not be (directly) zero-extended or
22// sign-extended.
23// 4. Any pointer arithmetic recurrences are raised to use array subscripts.
Chris Lattner40bf8b42004-04-02 20:24:31 +000024//
25// If the trip count of a loop is computable, this pass also makes the following
26// changes:
27// 1. The exit condition for the loop is canonicalized to compare the
28// induction value against the exit value. This turns loops like:
29// 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
30// 2. Any use outside of the loop of an expression derived from the indvar
31// is changed to compute the derived value outside of the loop, eliminating
32// the dependence on the exit value of the induction variable. If the only
33// purpose of the loop is to compute the exit value of some derived
34// expression, this transformation will make the loop dead.
35//
36// This transformation should be followed by strength reduction after all of the
Dan Gohmanc2c4cbf2009-05-19 20:38:47 +000037// desired loop transformations have been performed.
Chris Lattner6148c022001-12-03 17:28:42 +000038//
39//===----------------------------------------------------------------------===//
40
Chris Lattner0e5f4992006-12-19 21:40:18 +000041#define DEBUG_TYPE "indvars"
Chris Lattner022103b2002-05-07 20:03:00 +000042#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000043#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000044#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000045#include "llvm/Instructions.h"
Devang Patel7b9f6b12010-03-15 22:23:03 +000046#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000047#include "llvm/LLVMContext.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000048#include "llvm/Type.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000049#include "llvm/Analysis/Dominators.h"
50#include "llvm/Analysis/IVUsers.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000051#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000052#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000053#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000054#include "llvm/Support/CFG.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000055#include "llvm/Support/Debug.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000056#include "llvm/Support/raw_ostream.h"
John Criswell47df12d2003-12-18 17:19:19 +000057#include "llvm/Transforms/Utils/Local.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000058#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Trick37da4082011-05-04 02:10:13 +000059#include "llvm/Target/TargetData.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000060#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000061#include "llvm/ADT/Statistic.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000062#include "llvm/ADT/STLExtras.h"
John Criswell47df12d2003-12-18 17:19:19 +000063using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065STATISTIC(NumRemoved , "Number of aux indvars removed");
Andrew Trick37da4082011-05-04 02:10:13 +000066STATISTIC(NumWidened , "Number of indvars widened");
Chris Lattner0e5f4992006-12-19 21:40:18 +000067STATISTIC(NumInserted, "Number of canonical indvars added");
68STATISTIC(NumReplaced, "Number of exit values replaced");
69STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000070
Andrew Trick37da4082011-05-04 02:10:13 +000071// DisableIVRewrite mode currently affects IVUsers, so is defined in libAnalysis
72// and referenced here.
73namespace llvm {
74 extern bool DisableIVRewrite;
75}
76
Chris Lattner0e5f4992006-12-19 21:40:18 +000077namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000078 class IndVarSimplify : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000079 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000080 LoopInfo *LI;
81 ScalarEvolution *SE;
Dan Gohmande53dc02009-06-27 05:16:57 +000082 DominatorTree *DT;
Andrew Trick37da4082011-05-04 02:10:13 +000083 TargetData *TD;
Andrew Trickb12a7542011-03-17 23:51:11 +000084 SmallVector<WeakVH, 16> DeadInsts;
Chris Lattner15cad752003-12-23 07:47:09 +000085 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000086 public:
Devang Patel794fd752007-05-01 21:15:47 +000087
Dan Gohman5668cf72009-07-15 01:26:32 +000088 static char ID; // Pass identification, replacement for typeid
Andrew Trick37da4082011-05-04 02:10:13 +000089 IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0) {
Owen Anderson081c34b2010-10-19 17:21:58 +000090 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
91 }
Devang Patel794fd752007-05-01 21:15:47 +000092
Dan Gohman5668cf72009-07-15 01:26:32 +000093 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman60f8a632009-02-17 20:49:49 +000094
Dan Gohman5668cf72009-07-15 01:26:32 +000095 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
96 AU.addRequired<DominatorTree>();
97 AU.addRequired<LoopInfo>();
98 AU.addRequired<ScalarEvolution>();
99 AU.addRequiredID(LoopSimplifyID);
100 AU.addRequiredID(LCSSAID);
101 AU.addRequired<IVUsers>();
102 AU.addPreserved<ScalarEvolution>();
103 AU.addPreservedID(LoopSimplifyID);
104 AU.addPreservedID(LCSSAID);
105 AU.addPreserved<IVUsers>();
106 AU.setPreservesCFG();
107 }
Chris Lattner15cad752003-12-23 07:47:09 +0000108
Chris Lattner40bf8b42004-04-02 20:24:31 +0000109 private:
Andrew Trickb12a7542011-03-17 23:51:11 +0000110 bool isValidRewrite(Value *FromVal, Value *ToVal);
Devang Patel5ee99972007-03-07 06:39:01 +0000111
Andrew Trickf85092c2011-05-20 18:25:42 +0000112 void SimplifyIVUsers(SCEVExpander &Rewriter);
Andrew Trickaeee4612011-05-12 00:04:28 +0000113 void EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
114 void EliminateIVRemainder(BinaryOperator *Rem,
115 Value *IVOperand,
Andrew Trickf85092c2011-05-20 18:25:42 +0000116 bool IsSigned,
117 PHINode *IVPhi);
Dan Gohman60f8a632009-02-17 20:49:49 +0000118 void RewriteNonIntegerIVs(Loop *L);
119
Andrew Trick4dfdf242011-05-03 22:24:10 +0000120 bool canExpandBackedgeTakenCount(Loop *L,
121 const SCEV *BackedgeTakenCount);
122
Dan Gohman0bba49c2009-07-07 17:06:11 +0000123 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
Andrew Trick4dfdf242011-05-03 22:24:10 +0000124 PHINode *IndVar,
125 SCEVExpander &Rewriter);
Andrew Trick37da4082011-05-04 02:10:13 +0000126
Dan Gohman454d26d2010-02-22 04:11:59 +0000127 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000128
Dan Gohman454d26d2010-02-22 04:11:59 +0000129 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000130
Dan Gohman667d7872009-06-26 22:53:46 +0000131 void SinkUnusedInvariants(Loop *L);
Dan Gohman81db61a2009-05-12 02:17:14 +0000132
133 void HandleFloatingPointIV(Loop *L, PHINode *PH);
Chris Lattner3324e712003-12-22 03:58:44 +0000134 };
Chris Lattner5e761402002-09-10 05:24:05 +0000135}
Chris Lattner394437f2001-12-04 04:32:29 +0000136
Dan Gohman844731a2008-05-13 00:00:25 +0000137char IndVarSimplify::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000138INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000139 "Induction Variable Simplification", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000140INITIALIZE_PASS_DEPENDENCY(DominatorTree)
141INITIALIZE_PASS_DEPENDENCY(LoopInfo)
142INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
143INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
144INITIALIZE_PASS_DEPENDENCY(LCSSA)
145INITIALIZE_PASS_DEPENDENCY(IVUsers)
146INITIALIZE_PASS_END(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000147 "Induction Variable Simplification", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000148
Daniel Dunbar394f0442008-10-22 23:32:42 +0000149Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000150 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000151}
152
Andrew Trickb12a7542011-03-17 23:51:11 +0000153/// isValidRewrite - Return true if the SCEV expansion generated by the
154/// rewriter can replace the original value. SCEV guarantees that it
155/// produces the same value, but the way it is produced may be illegal IR.
156/// Ideally, this function will only be called for verification.
157bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
158 // If an SCEV expression subsumed multiple pointers, its expansion could
159 // reassociate the GEP changing the base pointer. This is illegal because the
160 // final address produced by a GEP chain must be inbounds relative to its
161 // underlying object. Otherwise basic alias analysis, among other things,
162 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
163 // producing an expression involving multiple pointers. Until then, we must
164 // bail out here.
165 //
166 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
167 // because it understands lcssa phis while SCEV does not.
168 Value *FromPtr = FromVal;
169 Value *ToPtr = ToVal;
170 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
171 FromPtr = GEP->getPointerOperand();
172 }
173 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
174 ToPtr = GEP->getPointerOperand();
175 }
176 if (FromPtr != FromVal || ToPtr != ToVal) {
177 // Quickly check the common case
178 if (FromPtr == ToPtr)
179 return true;
180
181 // SCEV may have rewritten an expression that produces the GEP's pointer
182 // operand. That's ok as long as the pointer operand has the same base
183 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
184 // base of a recurrence. This handles the case in which SCEV expansion
185 // converts a pointer type recurrence into a nonrecurrent pointer base
186 // indexed by an integer recurrence.
187 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
188 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
189 if (FromBase == ToBase)
190 return true;
191
192 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
193 << *FromBase << " != " << *ToBase << "\n");
194
195 return false;
196 }
197 return true;
198}
199
Andrew Trick4dfdf242011-05-03 22:24:10 +0000200/// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
201/// count expression can be safely and cheaply expanded into an instruction
202/// sequence that can be used by LinearFunctionTestReplace.
203bool IndVarSimplify::
204canExpandBackedgeTakenCount(Loop *L,
205 const SCEV *BackedgeTakenCount) {
206 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
207 BackedgeTakenCount->isZero())
208 return false;
209
210 if (!L->getExitingBlock())
211 return false;
212
213 // Can't rewrite non-branch yet.
214 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
215 if (!BI)
216 return false;
217
Dan Gohmanca9b7032010-04-12 21:13:43 +0000218 // Special case: If the backedge-taken count is a UDiv, it's very likely a
219 // UDiv that ScalarEvolution produced in order to compute a precise
220 // expression, rather than a UDiv from the user's code. If we can't find a
221 // UDiv in the code with some simple searching, assume the former and forego
222 // rewriting the loop.
223 if (isa<SCEVUDivExpr>(BackedgeTakenCount)) {
224 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
Andrew Trick37da4082011-05-04 02:10:13 +0000225 if (!OrigCond) return false;
Dan Gohmanca9b7032010-04-12 21:13:43 +0000226 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
Dan Gohmandeff6212010-05-03 22:09:21 +0000227 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
Dan Gohmanca9b7032010-04-12 21:13:43 +0000228 if (R != BackedgeTakenCount) {
229 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
Dan Gohmandeff6212010-05-03 22:09:21 +0000230 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
Dan Gohmanca9b7032010-04-12 21:13:43 +0000231 if (L != BackedgeTakenCount)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000232 return false;
Dan Gohmanca9b7032010-04-12 21:13:43 +0000233 }
234 }
Andrew Trick4dfdf242011-05-03 22:24:10 +0000235 return true;
236}
237
238/// LinearFunctionTestReplace - This method rewrites the exit condition of the
239/// loop to be a canonical != comparison against the incremented loop induction
240/// variable. This pass is able to rewrite the exit tests of any loop where the
241/// SCEV analysis can determine a loop-invariant trip count of the loop, which
242/// is actually a much broader range than just linear tests.
243ICmpInst *IndVarSimplify::
244LinearFunctionTestReplace(Loop *L,
245 const SCEV *BackedgeTakenCount,
246 PHINode *IndVar,
247 SCEVExpander &Rewriter) {
248 assert(canExpandBackedgeTakenCount(L, BackedgeTakenCount) && "precondition");
249 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
Dan Gohmanca9b7032010-04-12 21:13:43 +0000250
Chris Lattnerd2440572004-04-15 20:26:22 +0000251 // If the exiting block is not the same as the backedge block, we must compare
252 // against the preincremented value, otherwise we prefer to compare against
253 // the post-incremented value.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000254 Value *CmpIndVar;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000255 const SCEV *RHS = BackedgeTakenCount;
Andrew Trick4dfdf242011-05-03 22:24:10 +0000256 if (L->getExitingBlock() == L->getLoopLatch()) {
Dan Gohman46bdfb02009-02-24 18:55:53 +0000257 // Add one to the "backedge-taken" count to get the trip count.
258 // If this addition may overflow, we have to be more pessimistic and
259 // cast the induction variable before doing the add.
Dan Gohmandeff6212010-05-03 22:09:21 +0000260 const SCEV *Zero = SE->getConstant(BackedgeTakenCount->getType(), 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000261 const SCEV *N =
Dan Gohman46bdfb02009-02-24 18:55:53 +0000262 SE->getAddExpr(BackedgeTakenCount,
Dan Gohmandeff6212010-05-03 22:09:21 +0000263 SE->getConstant(BackedgeTakenCount->getType(), 1));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000264 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
Dan Gohman3948d0b2010-04-11 19:27:13 +0000265 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
Dan Gohmanc2390b12009-02-12 22:19:27 +0000266 // No overflow. Cast the sum.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000267 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000268 } else {
269 // Potential overflow. Cast before doing the add.
Dan Gohman46bdfb02009-02-24 18:55:53 +0000270 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
271 IndVar->getType());
272 RHS = SE->getAddExpr(RHS,
Dan Gohmandeff6212010-05-03 22:09:21 +0000273 SE->getConstant(IndVar->getType(), 1));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000274 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000275
Dan Gohman46bdfb02009-02-24 18:55:53 +0000276 // The BackedgeTaken expression contains the number of times that the
277 // backedge branches to the loop header. This is one less than the
278 // number of times the loop executes, so use the incremented indvar.
Andrew Trick4dfdf242011-05-03 22:24:10 +0000279 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
Chris Lattnerd2440572004-04-15 20:26:22 +0000280 } else {
281 // We have to use the preincremented value...
Dan Gohman46bdfb02009-02-24 18:55:53 +0000282 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
283 IndVar->getType());
Dan Gohmanc2390b12009-02-12 22:19:27 +0000284 CmpIndVar = IndVar;
Chris Lattnerd2440572004-04-15 20:26:22 +0000285 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000286
Dan Gohman667d7872009-06-26 22:53:46 +0000287 // Expand the code for the iteration count.
Dan Gohman17ead4f2010-11-17 21:23:15 +0000288 assert(SE->isLoopInvariant(RHS, L) &&
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000289 "Computed iteration count is not loop invariant!");
Dan Gohman667d7872009-06-26 22:53:46 +0000290 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000291
Reid Spencere4d87aa2006-12-23 06:05:41 +0000292 // Insert a new icmp_ne or icmp_eq instruction before the branch.
293 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000294 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000295 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000296 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000297 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000298
David Greenef67ef312010-01-05 01:27:06 +0000299 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
Chris Lattnerbdff5482009-08-23 04:37:46 +0000300 << " LHS:" << *CmpIndVar << '\n'
301 << " op:\t"
302 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
303 << " RHS:\t" << *RHS << "\n");
Dan Gohmanc2390b12009-02-12 22:19:27 +0000304
Owen Anderson333c4002009-07-09 23:48:35 +0000305 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
Dan Gohman81db61a2009-05-12 02:17:14 +0000306
Dan Gohman24440802010-02-22 02:07:36 +0000307 Value *OrigCond = BI->getCondition();
Dan Gohman95bdbfa2009-05-24 19:11:38 +0000308 // It's tempting to use replaceAllUsesWith here to fully replace the old
309 // comparison, but that's not immediately safe, since users of the old
310 // comparison may not be dominated by the new comparison. Instead, just
311 // update the branch to use the new comparison; in the common case this
312 // will make old comparison dead.
313 BI->setCondition(Cond);
Andrew Trick88e92cf2011-04-28 17:30:04 +0000314 DeadInsts.push_back(OrigCond);
Dan Gohman81db61a2009-05-12 02:17:14 +0000315
Chris Lattner40bf8b42004-04-02 20:24:31 +0000316 ++NumLFTR;
317 Changed = true;
Dan Gohman81db61a2009-05-12 02:17:14 +0000318 return Cond;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000319}
320
Chris Lattner40bf8b42004-04-02 20:24:31 +0000321/// RewriteLoopExitValues - Check to see if this loop has a computable
322/// loop-invariant execution count. If so, this means that we can compute the
323/// final value of any expressions that are recurrent in the loop, and
324/// substitute the exit values from the loop into any instructions outside of
325/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000326///
327/// This is mostly redundant with the regular IndVarSimplify activities that
328/// happen later, except that it's more powerful in some cases, because it's
329/// able to brute-force evaluate arbitrary instructions as long as they have
330/// constant operands at the beginning of the loop.
Chris Lattnerf1859892011-01-09 02:16:18 +0000331void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000332 // Verify the input to the pass in already in LCSSA form.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000333 assert(L->isLCSSAForm(*DT));
Dan Gohman81db61a2009-05-12 02:17:14 +0000334
Devang Patelb7211a22007-08-21 00:31:24 +0000335 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000336 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000337
Chris Lattner9f3d7382007-03-04 03:43:23 +0000338 // Find all values that are computed inside the loop, but used outside of it.
339 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
340 // the exit blocks of the loop to find them.
341 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
342 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000343
Chris Lattner9f3d7382007-03-04 03:43:23 +0000344 // If there are no PHI nodes in this exit block, then no values defined
345 // inside the loop are used on this path, skip it.
346 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
347 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000348
Chris Lattner9f3d7382007-03-04 03:43:23 +0000349 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000350
Chris Lattner9f3d7382007-03-04 03:43:23 +0000351 // Iterate over all of the PHI nodes.
352 BasicBlock::iterator BBI = ExitBB->begin();
353 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000354 if (PN->use_empty())
355 continue; // dead use, don't replace it
Dan Gohman814f2b22010-02-18 21:34:02 +0000356
357 // SCEV only supports integer expressions for now.
358 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
359 continue;
360
Dale Johannesen45a2d7d2010-02-19 07:14:22 +0000361 // It's necessary to tell ScalarEvolution about this explicitly so that
362 // it can walk the def-use list and forget all SCEVs, as it may not be
363 // watching the PHI itself. Once the new exit value is in place, there
364 // may not be a def-use connection between the loop and every instruction
365 // which got a SCEVAddRecExpr for that loop.
366 SE->forgetValue(PN);
367
Chris Lattner9f3d7382007-03-04 03:43:23 +0000368 // Iterate over all of the values in all the PHI nodes.
369 for (unsigned i = 0; i != NumPreds; ++i) {
370 // If the value being merged in is not integer or is not defined
371 // in the loop, skip it.
372 Value *InVal = PN->getIncomingValue(i);
Dan Gohman814f2b22010-02-18 21:34:02 +0000373 if (!isa<Instruction>(InVal))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000374 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000375
Chris Lattner9f3d7382007-03-04 03:43:23 +0000376 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000377 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000378 continue; // The Block is in a subloop, skip it.
379
380 // Check that InVal is defined in the loop.
381 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman92329c72009-12-18 01:24:09 +0000382 if (!L->contains(Inst))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000383 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000384
Chris Lattner9f3d7382007-03-04 03:43:23 +0000385 // Okay, this instruction has a user outside of the current loop
386 // and varies predictably *inside* the loop. Evaluate the value it
387 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000388 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +0000389 if (!SE->isLoopInvariant(ExitValue, L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000390 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000391
Dan Gohman667d7872009-06-26 22:53:46 +0000392 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000393
David Greenef67ef312010-01-05 01:27:06 +0000394 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000395 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000396
Andrew Trickb12a7542011-03-17 23:51:11 +0000397 if (!isValidRewrite(Inst, ExitVal)) {
398 DeadInsts.push_back(ExitVal);
399 continue;
400 }
401 Changed = true;
402 ++NumReplaced;
403
Chris Lattner9f3d7382007-03-04 03:43:23 +0000404 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000405
Dan Gohman81db61a2009-05-12 02:17:14 +0000406 // If this instruction is dead now, delete it.
407 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000408
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000409 if (NumPreds == 1) {
410 // Completely replace a single-pred PHI. This is safe, because the
411 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
412 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000413 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000414 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000415 }
416 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000417 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000418 // Clone the PHI and delete the original one. This lets IVUsers and
419 // any other maps purge the original user from their records.
Devang Patel50b6e332009-10-27 22:16:29 +0000420 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohman667d7872009-06-26 22:53:46 +0000421 NewPN->takeName(PN);
422 NewPN->insertBefore(PN);
423 PN->replaceAllUsesWith(NewPN);
424 PN->eraseFromParent();
425 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000426 }
427 }
Dan Gohman472fdf72010-03-20 03:53:53 +0000428
429 // The insertion point instruction may have been deleted; clear it out
430 // so that the rewriter doesn't trip over it later.
431 Rewriter.clearInsertPoint();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000432}
433
Dan Gohman60f8a632009-02-17 20:49:49 +0000434void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000435 // First step. Check to see if there are any floating-point recurrences.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000436 // If there are, change them into integer recurrences, permitting analysis by
437 // the SCEV routines.
438 //
Chris Lattnerf1859892011-01-09 02:16:18 +0000439 BasicBlock *Header = L->getHeader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000440
Dan Gohman81db61a2009-05-12 02:17:14 +0000441 SmallVector<WeakVH, 8> PHIs;
442 for (BasicBlock::iterator I = Header->begin();
443 PHINode *PN = dyn_cast<PHINode>(I); ++I)
444 PHIs.push_back(PN);
445
446 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
Gabor Greifea4894a2010-09-18 11:53:39 +0000447 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
Dan Gohman81db61a2009-05-12 02:17:14 +0000448 HandleFloatingPointIV(L, PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000449
Dan Gohman2d1be872009-04-16 03:18:22 +0000450 // If the loop previously had floating-point IV, ScalarEvolution
Dan Gohman60f8a632009-02-17 20:49:49 +0000451 // may not have been able to compute a trip count. Now that we've done some
452 // re-writing, the trip count may be computable.
453 if (Changed)
Dan Gohman4c7279a2009-10-31 15:04:55 +0000454 SE->forgetLoop(L);
Dale Johannesenc671d892009-04-15 23:31:51 +0000455}
456
Andrew Trickf85092c2011-05-20 18:25:42 +0000457namespace {
458 // Collect information about induction variables that are used by sign/zero
459 // extend operations. This information is recorded by CollectExtend and
460 // provides the input to WidenIV.
461 struct WideIVInfo {
462 const Type *WidestNativeType; // Widest integer type created [sz]ext
463 bool IsSigned; // Was an sext user seen before a zext?
464
465 WideIVInfo() : WidestNativeType(0), IsSigned(false) {}
466 };
467 typedef std::map<PHINode *, WideIVInfo> WideIVMap;
468}
469
470/// CollectExtend - Update information about the induction variable that is
471/// extended by this sign or zero extend operation. This is used to determine
472/// the final width of the IV before actually widening it.
473static void CollectExtend(CastInst *Cast, PHINode *Phi, bool IsSigned,
474 WideIVMap &IVMap, ScalarEvolution *SE,
475 const TargetData *TD) {
476 const Type *Ty = Cast->getType();
477 uint64_t Width = SE->getTypeSizeInBits(Ty);
478 if (TD && !TD->isLegalInteger(Width))
479 return;
480
481 WideIVInfo &IVInfo = IVMap[Phi];
482 if (!IVInfo.WidestNativeType) {
483 IVInfo.WidestNativeType = SE->getEffectiveSCEVType(Ty);
484 IVInfo.IsSigned = IsSigned;
485 return;
486 }
487
488 // We extend the IV to satisfy the sign of its first user, arbitrarily.
489 if (IVInfo.IsSigned != IsSigned)
490 return;
491
492 if (Width > SE->getTypeSizeInBits(IVInfo.WidestNativeType))
493 IVInfo.WidestNativeType = SE->getEffectiveSCEVType(Ty);
494}
495
496namespace {
497/// WidenIV - The goal of this transform is to remove sign and zero extends
498/// without creating any new induction variables. To do this, it creates a new
499/// phi of the wider type and redirects all users, either removing extends or
500/// inserting truncs whenever we stop propagating the type.
501///
502class WidenIV {
503 PHINode *OrigPhi;
504 const Type *WideType;
505 bool IsSigned;
506
507 IVUsers *IU;
508 LoopInfo *LI;
509 Loop *L;
510 ScalarEvolution *SE;
511 SmallVectorImpl<WeakVH> &DeadInsts;
512
513 PHINode *WidePhi;
514 Instruction *WideInc;
515 const SCEV *WideIncExpr;
516
517 SmallPtrSet<Instruction*,16> Processed;
518
519public:
520 WidenIV(PHINode *PN, const WideIVInfo &IVInfo, IVUsers *IUsers,
521 LoopInfo *LInfo, ScalarEvolution *SEv, SmallVectorImpl<WeakVH> &DI) :
522 OrigPhi(PN),
523 WideType(IVInfo.WidestNativeType),
524 IsSigned(IVInfo.IsSigned),
525 IU(IUsers),
526 LI(LInfo),
527 L(LI->getLoopFor(OrigPhi->getParent())),
528 SE(SEv),
529 DeadInsts(DI),
530 WidePhi(0),
531 WideInc(0),
532 WideIncExpr(0) {
533 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
534 }
535
536 bool CreateWideIV(SCEVExpander &Rewriter);
537
538protected:
539 const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
540
541 Instruction *CloneIVUser(Instruction *NarrowUse,
542 Instruction *NarrowDef,
543 Instruction *WideDef);
544
545 Instruction *WidenIVUse(Instruction *NarrowUse,
546 Instruction *NarrowDef,
547 Instruction *WideDef);
548};
549} // anonymous namespace
550
Andrew Trickaeee4612011-05-12 00:04:28 +0000551/// SimplifyIVUsers - Iteratively perform simplification on IVUsers within this
552/// loop. IVUsers is treated as a worklist. Each successive simplification may
553/// push more users which may themselves be candidates for simplification.
Andrew Trickf85092c2011-05-20 18:25:42 +0000554///
555void IndVarSimplify::SimplifyIVUsers(SCEVExpander &Rewriter) {
556 WideIVMap IVMap;
Dan Gohman931e3452010-04-12 02:21:50 +0000557
Andrew Trickf85092c2011-05-20 18:25:42 +0000558 // Each round of simplification involves a round of eliminating operations
559 // followed by a round of widening IVs. A single IVUsers worklist is used
560 // across all rounds. The inner loop advances the user. If widening exposes
561 // more uses, then another pass through the outer loop is triggered.
562 for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E;) {
563 for(; I != E; ++I) {
564 Instruction *UseInst = I->getUser();
565 Value *IVOperand = I->getOperandValToReplace();
Dan Gohman931e3452010-04-12 02:21:50 +0000566
Andrew Trickf85092c2011-05-20 18:25:42 +0000567 if (DisableIVRewrite) {
568 if (CastInst *Cast = dyn_cast<CastInst>(UseInst)) {
569 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
570 if (IsSigned || Cast->getOpcode() == Instruction::ZExt) {
571 CollectExtend(Cast, I->getPhi(), IsSigned, IVMap, SE, TD);
572 continue;
573 }
574 }
575 }
576 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
577 EliminateIVComparison(ICmp, IVOperand);
Andrew Trickaeee4612011-05-12 00:04:28 +0000578 continue;
579 }
Andrew Trickf85092c2011-05-20 18:25:42 +0000580 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
581 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
582 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
583 EliminateIVRemainder(Rem, IVOperand, IsSigned, I->getPhi());
584 continue;
585 }
586 }
587 }
588 for (WideIVMap::const_iterator I = IVMap.begin(), E = IVMap.end();
589 I != E; ++I) {
590 WidenIV Widener(I->first, I->second, IU, LI, SE, DeadInsts);
591 if (Widener.CreateWideIV(Rewriter))
592 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +0000593 }
Dan Gohman931e3452010-04-12 02:21:50 +0000594 }
595}
596
Andrew Trickf85092c2011-05-20 18:25:42 +0000597// GetWideRecurrence - Is this instruction potentially interesting from IVUsers'
598// perspective after widening it's type? In other words, can the extend be
599// safely hoisted out of the loop with SCEV reducing the value to a recurrence
600// on the same loop. If so, return the sign or zero extended
601// recurrence. Otherwise return NULL.
602const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
603 if (!SE->isSCEVable(NarrowUse->getType()))
604 return 0;
605
606 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
607 const SCEV *WideExpr = IsSigned ?
608 SE->getSignExtendExpr(NarrowExpr, WideType) :
609 SE->getZeroExtendExpr(NarrowExpr, WideType);
610 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
611 if (!AddRec || AddRec->getLoop() != L)
612 return 0;
613
614 return AddRec;
615}
616
617/// CloneIVUser - Instantiate a wide operation to replace a narrow
618/// operation. This only needs to handle operations that can evaluation to
619/// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
620Instruction *WidenIV::CloneIVUser(Instruction *NarrowUse,
621 Instruction *NarrowDef,
622 Instruction *WideDef) {
623 unsigned Opcode = NarrowUse->getOpcode();
624 switch (Opcode) {
625 default:
626 return 0;
627 case Instruction::Add:
628 case Instruction::Mul:
629 case Instruction::UDiv:
630 case Instruction::Sub:
631 case Instruction::And:
632 case Instruction::Or:
633 case Instruction::Xor:
634 case Instruction::Shl:
635 case Instruction::LShr:
636 case Instruction::AShr:
637 DEBUG(dbgs() << "Cloning IVUser: " << *NarrowUse << "\n");
638
639 BinaryOperator *NarrowBO = cast<BinaryOperator>(NarrowUse);
640 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
641 NarrowBO->getOperand(0),
642 NarrowBO->getOperand(1),
643 NarrowBO->getName());
644 IRBuilder<> Builder(NarrowUse);
645 Builder.Insert(WideBO);
646 if (NarrowBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
647 if (NarrowBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
648
649 for (unsigned i = 0; i < NarrowBO->getNumOperands(); ++i) {
650 Value *NarrowOper = NarrowBO->getOperand(i);
651 if (NarrowOper == NarrowDef) {
652 WideBO->setOperand(i, WideDef);
653 continue;
654 }
655 // We don't know anything about the other operand here so must insert a
656 // [sz]ext. It is probably loop invariant and will be folded or
657 // hoisted. If it actually comes from a widened IV, it should be removed
658 // during a future call to WidenIVUse.
659 IRBuilder<> Builder(NarrowUse);
660 Value *Extend = IsSigned ?
661 Builder.CreateSExt(NarrowOper, WideType) :
662 Builder.CreateZExt(NarrowOper, WideType);
663 WideBO->setOperand(i, Extend);
664 }
665 }
666 llvm_unreachable(0);
667}
668
669/// WidenIVUse - Determine whether an individual user of the narrow IV can be
670/// widened. If so, return the wide clone of the user.
671Instruction *WidenIV::WidenIVUse(Instruction *NarrowUse,
672 Instruction *NarrowDef,
673 Instruction *WideDef) {
674 // To be consistent with IVUsers, stop traversing the def-use chain at
675 // inner-loop phis or post-loop phis.
676 if (isa<PHINode>(NarrowUse) && LI->getLoopFor(NarrowUse->getParent()) != L)
677 return 0;
678
679 // Handle data flow merges and bizarre phi cycles.
680 if (!Processed.insert(NarrowUse))
681 return 0;
682
683 // Our raison d'etre! Eliminate sign and zero extension.
684 if (IsSigned ? isa<SExtInst>(NarrowUse) : isa<ZExtInst>(NarrowUse)) {
685 NarrowUse->replaceAllUsesWith(WideDef);
686 DeadInsts.push_back(NarrowUse);
687
688 // Now that the extend is gone, expose it's uses to IVUsers for potential
689 // further simplification within SimplifyIVUsers.
690 IU->AddUsersIfInteresting(WideDef, WidePhi);
691
692 // No further widening is needed. The deceased [sz]ext had done it for us.
693 return 0;
694 }
695 const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(NarrowUse);
696 if (!WideAddRec) {
697 // This user does not evaluate to a recurence after widening, so don't
698 // follow it. Instead insert a Trunc to kill off the original use,
699 // eventually isolating the original narrow IV so it can be removed.
700 IRBuilder<> Builder(NarrowUse);
701 Value *Trunc = Builder.CreateTrunc(WideDef, NarrowUse->getType());
702 NarrowUse->replaceUsesOfWith(NarrowDef, Trunc);
703 return 0;
704 }
705 Instruction *WideUse = 0;
706 if (WideAddRec == WideIncExpr) {
707 // Reuse the IV increment that SCEVExpander created.
708 WideUse = WideInc;
709 }
710 else {
711 WideUse = CloneIVUser(NarrowUse, NarrowDef, WideDef);
712 if (!WideUse)
713 return 0;
714 }
715 // GetWideRecurrence ensured that the narrow expression could be extended
716 // outside the loop without overflow. This suggests that the wide use
717 // evaluates to the same expression as the extended narrow use, but doesn't
718 // absolutely guarantee it. Hence the following failsafe check. In rare cases
719 // where it fails, we simple throw away the newly created wide use.
720 if (WideAddRec != SE->getSCEV(WideUse)) {
721 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
722 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
723 DeadInsts.push_back(WideUse);
724 return 0;
725 }
726
727 // Returning WideUse pushes it on the worklist.
728 return WideUse;
729}
730
731/// CreateWideIV - Process a single induction variable. First use the
732/// SCEVExpander to create a wide induction variable that evaluates to the same
733/// recurrence as the original narrow IV. Then use a worklist to forward
734/// traverse the narrow IV's def-use chain. After WidenIVUse as processed all
735/// interesting IV users, the narrow IV will be isolated for removal by
736/// DeleteDeadPHIs.
737///
738/// It would be simpler to delete uses as they are processed, but we must avoid
739/// invalidating SCEV expressions.
740///
741bool WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
742 // Is this phi an induction variable?
743 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
744 if (!AddRec)
745 return false;
746
747 // Widen the induction variable expression.
748 const SCEV *WideIVExpr = IsSigned ?
749 SE->getSignExtendExpr(AddRec, WideType) :
750 SE->getZeroExtendExpr(AddRec, WideType);
751
752 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
753 "Expect the new IV expression to preserve its type");
754
755 // Can the IV be extended outside the loop without overflow?
756 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
757 if (!AddRec || AddRec->getLoop() != L)
758 return false;
759
760 // An AddRec must have loop-invariant operands. Since this AddRec it
761 // materialized by a loop header phi, the expression cannot have any post-loop
762 // operands, so they must dominate the loop header.
763 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
764 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
765 && "Loop header phi recurrence inputs do not dominate the loop");
766
767 // The rewriter provides a value for the desired IV expression. This may
768 // either find an existing phi or materialize a new one. Either way, we
769 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
770 // of the phi-SCC dominates the loop entry.
771 Instruction *InsertPt = L->getHeader()->begin();
772 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
773
774 // Remembering the WideIV increment generated by SCEVExpander allows
775 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
776 // employ a general reuse mechanism because the call above is the only call to
777 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
778 assert(WidePhi->hasOneUse() && "New IV has multiple users");
779 WideInc = WidePhi->use_back();
780 WideIncExpr = SE->getSCEV(WideInc);
781
782 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
783 ++NumWidened;
784
785 // Traverse the def-use chain using a worklist starting at the original IV.
786 assert(Processed.empty() && "expect initial state" );
787 SmallVector<std::pair<Instruction *, Instruction *>, 8> NarrowIVUsers;
788
789 NarrowIVUsers.push_back(std::make_pair(OrigPhi, WidePhi));
790 while (!NarrowIVUsers.empty()) {
791 Instruction *NarrowInst, *WideInst;
792 tie(NarrowInst, WideInst) = NarrowIVUsers.pop_back_val();
793
794 for (Value::use_iterator UI = NarrowInst->use_begin(),
795 UE = NarrowInst->use_end(); UI != UE; ++UI) {
796 Instruction *NarrowUse = cast<Instruction>(*UI);
797 Instruction *WideUse = WidenIVUse(NarrowUse, NarrowInst, WideInst);
798 if (WideUse)
799 NarrowIVUsers.push_back(std::make_pair(NarrowUse, WideUse));
800
801 if (NarrowInst->use_empty())
802 DeadInsts.push_back(NarrowInst);
803 }
804 }
805 return true;
806}
807
Andrew Trickaeee4612011-05-12 00:04:28 +0000808void IndVarSimplify::EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
809 unsigned IVOperIdx = 0;
810 ICmpInst::Predicate Pred = ICmp->getPredicate();
811 if (IVOperand != ICmp->getOperand(0)) {
812 // Swapped
813 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
814 IVOperIdx = 1;
815 Pred = ICmpInst::getSwappedPredicate(Pred);
Dan Gohmana590b792010-04-13 01:46:36 +0000816 }
Andrew Trickaeee4612011-05-12 00:04:28 +0000817
818 // Get the SCEVs for the ICmp operands.
819 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
820 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
821
822 // Simplify unnecessary loops away.
823 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
824 S = SE->getSCEVAtScope(S, ICmpLoop);
825 X = SE->getSCEVAtScope(X, ICmpLoop);
826
827 // If the condition is always true or always false, replace it with
828 // a constant value.
829 if (SE->isKnownPredicate(Pred, S, X))
830 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
831 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
832 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
833 else
834 return;
835
836 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Andrew Trick074397d2011-05-20 03:37:48 +0000837 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +0000838 DeadInsts.push_back(ICmp);
839}
840
841void IndVarSimplify::EliminateIVRemainder(BinaryOperator *Rem,
842 Value *IVOperand,
Andrew Trickf85092c2011-05-20 18:25:42 +0000843 bool IsSigned,
844 PHINode *IVPhi) {
Andrew Trickaeee4612011-05-12 00:04:28 +0000845 // We're only interested in the case where we know something about
846 // the numerator.
847 if (IVOperand != Rem->getOperand(0))
848 return;
849
850 // Get the SCEVs for the ICmp operands.
851 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
852 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
853
854 // Simplify unnecessary loops away.
855 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
856 S = SE->getSCEVAtScope(S, ICmpLoop);
857 X = SE->getSCEVAtScope(X, ICmpLoop);
858
859 // i % n --> i if i is in [0,n).
Andrew Trick074397d2011-05-20 03:37:48 +0000860 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
861 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Andrew Trickaeee4612011-05-12 00:04:28 +0000862 S, X))
863 Rem->replaceAllUsesWith(Rem->getOperand(0));
864 else {
865 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
866 const SCEV *LessOne =
867 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
Andrew Trick074397d2011-05-20 03:37:48 +0000868 if (IsSigned && !SE->isKnownNonNegative(LessOne))
Andrew Trickaeee4612011-05-12 00:04:28 +0000869 return;
870
Andrew Trick074397d2011-05-20 03:37:48 +0000871 if (!SE->isKnownPredicate(IsSigned ?
Andrew Trickaeee4612011-05-12 00:04:28 +0000872 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
873 LessOne, X))
874 return;
875
876 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
877 Rem->getOperand(0), Rem->getOperand(1),
878 "tmp");
879 SelectInst *Sel =
880 SelectInst::Create(ICmp,
881 ConstantInt::get(Rem->getType(), 0),
882 Rem->getOperand(0), "tmp", Rem);
883 Rem->replaceAllUsesWith(Sel);
884 }
885
886 // Inform IVUsers about the new users.
887 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
Andrew Trickf85092c2011-05-20 18:25:42 +0000888 IU->AddUsersIfInteresting(I, IVPhi);
Andrew Trickaeee4612011-05-12 00:04:28 +0000889
890 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
Andrew Trick074397d2011-05-20 03:37:48 +0000891 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +0000892 DeadInsts.push_back(Rem);
Dan Gohmana590b792010-04-13 01:46:36 +0000893}
894
Dan Gohmanc2390b12009-02-12 22:19:27 +0000895bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmana5283822010-06-18 01:35:11 +0000896 // If LoopSimplify form is not available, stay out of trouble. Some notes:
897 // - LSR currently only supports LoopSimplify-form loops. Indvars'
898 // canonicalization can be a pessimization without LSR to "clean up"
899 // afterwards.
900 // - We depend on having a preheader; in particular,
901 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
902 // and we're in trouble if we can't find the induction variable even when
903 // we've manually inserted one.
904 if (!L->isLoopSimplifyForm())
905 return false;
906
Dan Gohman81db61a2009-05-12 02:17:14 +0000907 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +0000908 LI = &getAnalysis<LoopInfo>();
909 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +0000910 DT = &getAnalysis<DominatorTree>();
Andrew Trick37da4082011-05-04 02:10:13 +0000911 TD = getAnalysisIfAvailable<TargetData>();
912
Andrew Trickb12a7542011-03-17 23:51:11 +0000913 DeadInsts.clear();
Devang Patel5ee99972007-03-07 06:39:01 +0000914 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +0000915
Dan Gohman2d1be872009-04-16 03:18:22 +0000916 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +0000917 // transform them to use integer recurrences.
918 RewriteNonIntegerIVs(L);
919
Dan Gohman0bba49c2009-07-07 17:06:11 +0000920 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +0000921
Dan Gohman667d7872009-06-26 22:53:46 +0000922 // Create a rewriter object which we'll use to transform the code with.
923 SCEVExpander Rewriter(*SE);
Andrew Trick37da4082011-05-04 02:10:13 +0000924 if (DisableIVRewrite)
925 Rewriter.disableCanonicalMode();
926
Chris Lattner40bf8b42004-04-02 20:24:31 +0000927 // Check to see if this loop has a computable loop-invariant execution count.
928 // If so, this means that we can compute the final value of any expressions
929 // that are recurrent in the loop, and substitute the exit values from the
930 // loop into any instructions outside of the loop that use the final values of
931 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000932 //
Dan Gohman46bdfb02009-02-24 18:55:53 +0000933 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman454d26d2010-02-22 04:11:59 +0000934 RewriteLoopExitValues(L, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +0000935
Andrew Trickf85092c2011-05-20 18:25:42 +0000936 // Eliminate redundant IV users.
937 SimplifyIVUsers(Rewriter);
Dan Gohmana590b792010-04-13 01:46:36 +0000938
Dan Gohman81db61a2009-05-12 02:17:14 +0000939 // Compute the type of the largest recurrence expression, and decide whether
940 // a canonical induction variable should be inserted.
Andrew Trickf85092c2011-05-20 18:25:42 +0000941 const Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000942 bool NeedCannIV = false;
Andrew Trick4dfdf242011-05-03 22:24:10 +0000943 bool ExpandBECount = canExpandBackedgeTakenCount(L, BackedgeTakenCount);
944 if (ExpandBECount) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000945 // If we have a known trip count and a single exit block, we'll be
946 // rewriting the loop exit test condition below, which requires a
947 // canonical induction variable.
Andrew Trick4dfdf242011-05-03 22:24:10 +0000948 NeedCannIV = true;
949 const Type *Ty = BackedgeTakenCount->getType();
950 if (!LargestType ||
951 SE->getTypeSizeInBits(Ty) >
952 SE->getTypeSizeInBits(LargestType))
953 LargestType = SE->getEffectiveSCEVType(Ty);
Chris Lattnerf50af082004-04-17 18:08:33 +0000954 }
Andrew Trick37da4082011-05-04 02:10:13 +0000955 if (!DisableIVRewrite) {
956 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
957 NeedCannIV = true;
958 const Type *Ty =
959 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
960 if (!LargestType ||
961 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000962 SE->getTypeSizeInBits(LargestType))
Andrew Trick37da4082011-05-04 02:10:13 +0000963 LargestType = Ty;
964 }
Chris Lattner6148c022001-12-03 17:28:42 +0000965 }
966
Dan Gohmanf451cb82010-02-10 16:03:48 +0000967 // Now that we know the largest of the induction variable expressions
Dan Gohman81db61a2009-05-12 02:17:14 +0000968 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohman43ef3fb2010-07-20 17:18:52 +0000969 PHINode *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +0000970 if (NeedCannIV) {
Dan Gohman85669632010-02-25 06:57:05 +0000971 // Check to see if the loop already has any canonical-looking induction
972 // variables. If any are present and wider than the planned canonical
973 // induction variable, temporarily remove them, so that the Rewriter
974 // doesn't attempt to reuse them.
975 SmallVector<PHINode *, 2> OldCannIVs;
976 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
Dan Gohman4d8414f2009-06-13 16:25:49 +0000977 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
978 SE->getTypeSizeInBits(LargestType))
979 OldCannIV->removeFromParent();
980 else
Dan Gohman85669632010-02-25 06:57:05 +0000981 break;
982 OldCannIVs.push_back(OldCannIV);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000983 }
984
Dan Gohman667d7872009-06-26 22:53:46 +0000985 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000986
Dan Gohmanc2390b12009-02-12 22:19:27 +0000987 ++NumInserted;
988 Changed = true;
David Greenef67ef312010-01-05 01:27:06 +0000989 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +0000990
991 // Now that the official induction variable is established, reinsert
Dan Gohman85669632010-02-25 06:57:05 +0000992 // any old canonical-looking variables after it so that the IR remains
993 // consistent. They will be deleted as part of the dead-PHI deletion at
Dan Gohman4d8414f2009-06-13 16:25:49 +0000994 // the end of the pass.
Dan Gohman85669632010-02-25 06:57:05 +0000995 while (!OldCannIVs.empty()) {
996 PHINode *OldCannIV = OldCannIVs.pop_back_val();
997 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
998 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000999 }
Chris Lattner15cad752003-12-23 07:47:09 +00001000
Dan Gohmanc2390b12009-02-12 22:19:27 +00001001 // If we have a trip count expression, rewrite the loop's exit condition
1002 // using it. We can currently only handle loops with a single exit.
Dan Gohman81db61a2009-05-12 02:17:14 +00001003 ICmpInst *NewICmp = 0;
Andrew Trick4dfdf242011-05-03 22:24:10 +00001004 if (ExpandBECount) {
1005 assert(canExpandBackedgeTakenCount(L, BackedgeTakenCount) &&
1006 "canonical IV disrupted BackedgeTaken expansion");
Dan Gohman81db61a2009-05-12 02:17:14 +00001007 assert(NeedCannIV &&
1008 "LinearFunctionTestReplace requires a canonical induction variable");
Andrew Trick4dfdf242011-05-03 22:24:10 +00001009 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
1010 Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +00001011 }
Andrew Trickb12a7542011-03-17 23:51:11 +00001012 // Rewrite IV-derived expressions.
Andrew Trick37da4082011-05-04 02:10:13 +00001013 if (!DisableIVRewrite)
1014 RewriteIVExpressions(L, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +00001015
Andrew Trickb12a7542011-03-17 23:51:11 +00001016 // Clear the rewriter cache, because values that are in the rewriter's cache
1017 // can be deleted in the loop below, causing the AssertingVH in the cache to
1018 // trigger.
1019 Rewriter.clear();
1020
1021 // Now that we're done iterating through lists, clean up any instructions
1022 // which are now dead.
1023 while (!DeadInsts.empty())
1024 if (Instruction *Inst =
1025 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
1026 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1027
Dan Gohman667d7872009-06-26 22:53:46 +00001028 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +00001029
Dan Gohman81db61a2009-05-12 02:17:14 +00001030 // Loop-invariant instructions in the preheader that aren't used in the
1031 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +00001032 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +00001033
1034 // For completeness, inform IVUsers of the IV use in the newly-created
1035 // loop exit test instruction.
1036 if (NewICmp)
Andrew Trickf85092c2011-05-20 18:25:42 +00001037 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)),
1038 IndVar);
Dan Gohman81db61a2009-05-12 02:17:14 +00001039
1040 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +00001041 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +00001042 // Check a post-condition.
Dan Gohmanbbf81d82010-03-10 19:38:49 +00001043 assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +00001044 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +00001045}
Devang Pateld22a8492008-09-09 21:41:07 +00001046
Dan Gohman448db1c2010-04-07 22:27:08 +00001047// FIXME: It is an extremely bad idea to indvar substitute anything more
1048// complex than affine induction variables. Doing so will put expensive
1049// polynomial evaluations inside of the loop, and the str reduction pass
1050// currently can only reduce affine polynomials. For now just disable
1051// indvar subst on anything more complex than an affine addrec, unless
1052// it can be expanded to a trivial value.
Dan Gohman17ead4f2010-11-17 21:23:15 +00001053static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
Dan Gohman448db1c2010-04-07 22:27:08 +00001054 // Loop-invariant values are safe.
Dan Gohman17ead4f2010-11-17 21:23:15 +00001055 if (SE->isLoopInvariant(S, L)) return true;
Dan Gohman448db1c2010-04-07 22:27:08 +00001056
1057 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
1058 // to transform them into efficient code.
1059 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
1060 return AR->isAffine();
1061
1062 // An add is safe it all its operands are safe.
1063 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
1064 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
1065 E = Commutative->op_end(); I != E; ++I)
Dan Gohman17ead4f2010-11-17 21:23:15 +00001066 if (!isSafe(*I, L, SE)) return false;
Dan Gohman448db1c2010-04-07 22:27:08 +00001067 return true;
1068 }
Andrew Trickead71d52011-03-17 23:46:48 +00001069
Dan Gohman448db1c2010-04-07 22:27:08 +00001070 // A cast is safe if its operand is.
1071 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
Dan Gohman17ead4f2010-11-17 21:23:15 +00001072 return isSafe(C->getOperand(), L, SE);
Dan Gohman448db1c2010-04-07 22:27:08 +00001073
1074 // A udiv is safe if its operands are.
1075 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
Dan Gohman17ead4f2010-11-17 21:23:15 +00001076 return isSafe(UD->getLHS(), L, SE) &&
1077 isSafe(UD->getRHS(), L, SE);
Dan Gohman448db1c2010-04-07 22:27:08 +00001078
1079 // SCEVUnknown is always safe.
1080 if (isa<SCEVUnknown>(S))
1081 return true;
1082
1083 // Nothing else is safe.
1084 return false;
1085}
1086
Dan Gohman454d26d2010-02-22 04:11:59 +00001087void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001088 // Rewrite all induction variable expressions in terms of the canonical
1089 // induction variable.
1090 //
1091 // If there were induction variables of other sizes or offsets, manually
1092 // add the offsets to the primary induction variable and cast, avoiding
1093 // the need for the code evaluation methods to insert induction variables
1094 // of different sizes.
Dan Gohman572645c2010-02-12 10:34:29 +00001095 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
Dan Gohman572645c2010-02-12 10:34:29 +00001096 Value *Op = UI->getOperandValToReplace();
1097 const Type *UseTy = Op->getType();
1098 Instruction *User = UI->getUser();
Dan Gohman81db61a2009-05-12 02:17:14 +00001099
Dan Gohman572645c2010-02-12 10:34:29 +00001100 // Compute the final addrec to expand into code.
1101 const SCEV *AR = IU->getReplacementExpr(*UI);
Dan Gohman81db61a2009-05-12 02:17:14 +00001102
Dan Gohman572645c2010-02-12 10:34:29 +00001103 // Evaluate the expression out of the loop, if possible.
1104 if (!L->contains(UI->getUser())) {
1105 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +00001106 if (SE->isLoopInvariant(ExitVal, L))
Dan Gohman572645c2010-02-12 10:34:29 +00001107 AR = ExitVal;
Dan Gohman81db61a2009-05-12 02:17:14 +00001108 }
Dan Gohman572645c2010-02-12 10:34:29 +00001109
1110 // FIXME: It is an extremely bad idea to indvar substitute anything more
1111 // complex than affine induction variables. Doing so will put expensive
1112 // polynomial evaluations inside of the loop, and the str reduction pass
1113 // currently can only reduce affine polynomials. For now just disable
1114 // indvar subst on anything more complex than an affine addrec, unless
1115 // it can be expanded to a trivial value.
Dan Gohman17ead4f2010-11-17 21:23:15 +00001116 if (!isSafe(AR, L, SE))
Dan Gohman572645c2010-02-12 10:34:29 +00001117 continue;
1118
1119 // Determine the insertion point for this user. By default, insert
1120 // immediately before the user. The SCEVExpander class will automatically
1121 // hoist loop invariants out of the loop. For PHI nodes, there may be
1122 // multiple uses, so compute the nearest common dominator for the
1123 // incoming blocks.
1124 Instruction *InsertPt = User;
1125 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
1126 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
1127 if (PHI->getIncomingValue(i) == Op) {
1128 if (InsertPt == User)
1129 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
1130 else
1131 InsertPt =
1132 DT->findNearestCommonDominator(InsertPt->getParent(),
1133 PHI->getIncomingBlock(i))
1134 ->getTerminator();
1135 }
1136
1137 // Now expand it into actual Instructions and patch it into place.
1138 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
1139
Andrew Trickb12a7542011-03-17 23:51:11 +00001140 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
1141 << " into = " << *NewVal << "\n");
1142
1143 if (!isValidRewrite(Op, NewVal)) {
1144 DeadInsts.push_back(NewVal);
1145 continue;
1146 }
Dan Gohmand7bfd002010-04-02 14:48:31 +00001147 // Inform ScalarEvolution that this value is changing. The change doesn't
1148 // affect its value, but it does potentially affect which use lists the
1149 // value will be on after the replacement, which affects ScalarEvolution's
1150 // ability to walk use lists and drop dangling pointers when a value is
1151 // deleted.
1152 SE->forgetValue(User);
1153
Dan Gohman572645c2010-02-12 10:34:29 +00001154 // Patch the new value into place.
1155 if (Op->hasName())
1156 NewVal->takeName(Op);
1157 User->replaceUsesOfWith(Op, NewVal);
1158 UI->setOperandValToReplace(NewVal);
Andrew Trickb12a7542011-03-17 23:51:11 +00001159
Dan Gohman572645c2010-02-12 10:34:29 +00001160 ++NumRemoved;
1161 Changed = true;
1162
1163 // The old value may be dead now.
1164 DeadInsts.push_back(Op);
Dan Gohman81db61a2009-05-12 02:17:14 +00001165 }
Dan Gohman81db61a2009-05-12 02:17:14 +00001166}
1167
1168/// If there's a single exit block, sink any loop-invariant values that
1169/// were defined in the preheader but not used inside the loop into the
1170/// exit block to reduce register pressure in the loop.
Dan Gohman667d7872009-06-26 22:53:46 +00001171void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001172 BasicBlock *ExitBlock = L->getExitBlock();
1173 if (!ExitBlock) return;
1174
Dan Gohman81db61a2009-05-12 02:17:14 +00001175 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohman03e896b2009-11-05 21:11:53 +00001176 if (!Preheader) return;
1177
1178 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
Dan Gohman81db61a2009-05-12 02:17:14 +00001179 BasicBlock::iterator I = Preheader->getTerminator();
1180 while (I != Preheader->begin()) {
1181 --I;
Dan Gohman667d7872009-06-26 22:53:46 +00001182 // New instructions were inserted at the end of the preheader.
1183 if (isa<PHINode>(I))
Dan Gohman81db61a2009-05-12 02:17:14 +00001184 break;
Bill Wendling87a10f52010-03-23 21:15:59 +00001185
Eli Friedman0c77db32009-07-15 22:48:29 +00001186 // Don't move instructions which might have side effects, since the side
Bill Wendling87a10f52010-03-23 21:15:59 +00001187 // effects need to complete before instructions inside the loop. Also don't
1188 // move instructions which might read memory, since the loop may modify
1189 // memory. Note that it's okay if the instruction might have undefined
1190 // behavior: LoopSimplify guarantees that the preheader dominates the exit
1191 // block.
Eli Friedman0c77db32009-07-15 22:48:29 +00001192 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
Dan Gohman667d7872009-06-26 22:53:46 +00001193 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001194
Devang Patel7b9f6b12010-03-15 22:23:03 +00001195 // Skip debug info intrinsics.
1196 if (isa<DbgInfoIntrinsic>(I))
1197 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001198
Dan Gohman76f497a2009-08-25 17:42:10 +00001199 // Don't sink static AllocaInsts out of the entry block, which would
1200 // turn them into dynamic allocas!
1201 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
1202 if (AI->isStaticAlloca())
1203 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001204
Dan Gohman81db61a2009-05-12 02:17:14 +00001205 // Determine if there is a use in or before the loop (direct or
1206 // otherwise).
1207 bool UsedInLoop = false;
1208 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1209 UI != UE; ++UI) {
Gabor Greif76560182010-07-09 15:40:10 +00001210 User *U = *UI;
1211 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
1212 if (PHINode *P = dyn_cast<PHINode>(U)) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001213 unsigned i =
1214 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
1215 UseBB = P->getIncomingBlock(i);
1216 }
1217 if (UseBB == Preheader || L->contains(UseBB)) {
1218 UsedInLoop = true;
1219 break;
1220 }
1221 }
Bill Wendling87a10f52010-03-23 21:15:59 +00001222
Dan Gohman81db61a2009-05-12 02:17:14 +00001223 // If there is, the def must remain in the preheader.
1224 if (UsedInLoop)
1225 continue;
Bill Wendling87a10f52010-03-23 21:15:59 +00001226
Dan Gohman81db61a2009-05-12 02:17:14 +00001227 // Otherwise, sink it to the exit block.
1228 Instruction *ToMove = I;
1229 bool Done = false;
Bill Wendling87a10f52010-03-23 21:15:59 +00001230
1231 if (I != Preheader->begin()) {
1232 // Skip debug info intrinsics.
1233 do {
1234 --I;
1235 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
1236
1237 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
1238 Done = true;
1239 } else {
Dan Gohman81db61a2009-05-12 02:17:14 +00001240 Done = true;
Bill Wendling87a10f52010-03-23 21:15:59 +00001241 }
1242
Dan Gohman667d7872009-06-26 22:53:46 +00001243 ToMove->moveBefore(InsertPt);
Bill Wendling87a10f52010-03-23 21:15:59 +00001244 if (Done) break;
Dan Gohman667d7872009-06-26 22:53:46 +00001245 InsertPt = ToMove;
Dan Gohman81db61a2009-05-12 02:17:14 +00001246 }
1247}
1248
Chris Lattnerbbb91492010-04-03 06:41:49 +00001249/// ConvertToSInt - Convert APF to an integer, if possible.
1250static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
Devang Patelcd402332008-11-17 23:27:13 +00001251 bool isExact = false;
Evan Cheng794a7db2008-11-26 01:11:57 +00001252 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
1253 return false;
Chris Lattnerbbb91492010-04-03 06:41:49 +00001254 // See if we can convert this to an int64_t
1255 uint64_t UIntVal;
1256 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
1257 &isExact) != APFloat::opOK || !isExact)
Devang Patelcd402332008-11-17 23:27:13 +00001258 return false;
Chris Lattnerbbb91492010-04-03 06:41:49 +00001259 IntVal = UIntVal;
Devang Patelcd402332008-11-17 23:27:13 +00001260 return true;
Devang Patelcd402332008-11-17 23:27:13 +00001261}
1262
Devang Patel58d43d42008-11-03 18:32:19 +00001263/// HandleFloatingPointIV - If the loop has floating induction variable
1264/// then insert corresponding integer induction variable if possible.
Devang Patel84e35152008-11-17 21:32:02 +00001265/// For example,
1266/// for(double i = 0; i < 10000; ++i)
1267/// bar(i)
1268/// is converted into
1269/// for(int i = 0; i < 10000; ++i)
1270/// bar((double)i);
1271///
Chris Lattnerc91961e2010-04-03 06:17:08 +00001272void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
1273 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
Devang Patel84e35152008-11-17 21:32:02 +00001274 unsigned BackEdge = IncomingEdge^1;
Dan Gohmancafb8132009-02-17 19:13:57 +00001275
Devang Patel84e35152008-11-17 21:32:02 +00001276 // Check incoming value.
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001277 ConstantFP *InitValueVal =
Chris Lattnerc91961e2010-04-03 06:17:08 +00001278 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
Chris Lattner96fd7662010-04-03 07:18:48 +00001279
Chris Lattnerbbb91492010-04-03 06:41:49 +00001280 int64_t InitValue;
Chris Lattner96fd7662010-04-03 07:18:48 +00001281 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
Devang Patelcd402332008-11-17 23:27:13 +00001282 return;
1283
Chris Lattnerc91961e2010-04-03 06:17:08 +00001284 // Check IV increment. Reject this PN if increment operation is not
Devang Patelcd402332008-11-17 23:27:13 +00001285 // an add or increment value can not be represented by an integer.
Dan Gohmancafb8132009-02-17 19:13:57 +00001286 BinaryOperator *Incr =
Chris Lattnerc91961e2010-04-03 06:17:08 +00001287 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
Chris Lattner07aa76a2010-04-03 05:54:59 +00001288 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
Andrew Trickead71d52011-03-17 23:46:48 +00001289
Chris Lattner07aa76a2010-04-03 05:54:59 +00001290 // If this is not an add of the PHI with a constantfp, or if the constant fp
1291 // is not an integer, bail out.
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001292 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
Chris Lattner96fd7662010-04-03 07:18:48 +00001293 int64_t IncValue;
Chris Lattnerc91961e2010-04-03 06:17:08 +00001294 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
Chris Lattner96fd7662010-04-03 07:18:48 +00001295 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
Devang Patelcd402332008-11-17 23:27:13 +00001296 return;
Dan Gohmancafb8132009-02-17 19:13:57 +00001297
Chris Lattnerc91961e2010-04-03 06:17:08 +00001298 // Check Incr uses. One user is PN and the other user is an exit condition
Chris Lattner07aa76a2010-04-03 05:54:59 +00001299 // used by the conditional terminator.
Devang Patel84e35152008-11-17 21:32:02 +00001300 Value::use_iterator IncrUse = Incr->use_begin();
Gabor Greif96f1d8e2010-07-22 13:36:47 +00001301 Instruction *U1 = cast<Instruction>(*IncrUse++);
Devang Patel84e35152008-11-17 21:32:02 +00001302 if (IncrUse == Incr->use_end()) return;
Gabor Greif96f1d8e2010-07-22 13:36:47 +00001303 Instruction *U2 = cast<Instruction>(*IncrUse++);
Devang Patel84e35152008-11-17 21:32:02 +00001304 if (IncrUse != Incr->use_end()) return;
Dan Gohmancafb8132009-02-17 19:13:57 +00001305
Chris Lattner07aa76a2010-04-03 05:54:59 +00001306 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
1307 // only used by a branch, we can't transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +00001308 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
1309 if (!Compare)
1310 Compare = dyn_cast<FCmpInst>(U2);
1311 if (Compare == 0 || !Compare->hasOneUse() ||
1312 !isa<BranchInst>(Compare->use_back()))
Chris Lattner07aa76a2010-04-03 05:54:59 +00001313 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001314
Chris Lattnerca703bd2010-04-03 06:11:07 +00001315 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
Devang Patel84e35152008-11-17 21:32:02 +00001316
Chris Lattnerd52c0722010-04-03 07:21:39 +00001317 // We need to verify that the branch actually controls the iteration count
1318 // of the loop. If not, the new IV can overflow and no one will notice.
1319 // The branch block must be in the loop and one of the successors must be out
1320 // of the loop.
1321 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
1322 if (!L->contains(TheBr->getParent()) ||
1323 (L->contains(TheBr->getSuccessor(0)) &&
1324 L->contains(TheBr->getSuccessor(1))))
1325 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001326
1327
Chris Lattner07aa76a2010-04-03 05:54:59 +00001328 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
1329 // transform it.
Chris Lattnerca703bd2010-04-03 06:11:07 +00001330 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
Chris Lattnerbbb91492010-04-03 06:41:49 +00001331 int64_t ExitValue;
1332 if (ExitValueVal == 0 ||
1333 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
Devang Patel84e35152008-11-17 21:32:02 +00001334 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001335
Devang Patel84e35152008-11-17 21:32:02 +00001336 // Find new predicate for integer comparison.
1337 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattnerca703bd2010-04-03 06:11:07 +00001338 switch (Compare->getPredicate()) {
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001339 default: return; // Unknown comparison.
Devang Patel84e35152008-11-17 21:32:02 +00001340 case CmpInst::FCMP_OEQ:
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001341 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
Chris Lattner96fd7662010-04-03 07:18:48 +00001342 case CmpInst::FCMP_ONE:
1343 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
Devang Patel84e35152008-11-17 21:32:02 +00001344 case CmpInst::FCMP_OGT:
Chris Lattnera40e4a02010-04-03 06:25:21 +00001345 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
Devang Patel84e35152008-11-17 21:32:02 +00001346 case CmpInst::FCMP_OGE:
Chris Lattnera40e4a02010-04-03 06:25:21 +00001347 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
Devang Patel84e35152008-11-17 21:32:02 +00001348 case CmpInst::FCMP_OLT:
Chris Lattner43b85272010-04-03 06:30:03 +00001349 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
Devang Patel84e35152008-11-17 21:32:02 +00001350 case CmpInst::FCMP_OLE:
Chris Lattner43b85272010-04-03 06:30:03 +00001351 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
Devang Patel58d43d42008-11-03 18:32:19 +00001352 }
Andrew Trickead71d52011-03-17 23:46:48 +00001353
Chris Lattner96fd7662010-04-03 07:18:48 +00001354 // We convert the floating point induction variable to a signed i32 value if
1355 // we can. This is only safe if the comparison will not overflow in a way
1356 // that won't be trapped by the integer equivalent operations. Check for this
1357 // now.
1358 // TODO: We could use i64 if it is native and the range requires it.
Andrew Trickead71d52011-03-17 23:46:48 +00001359
Chris Lattner96fd7662010-04-03 07:18:48 +00001360 // The start/stride/exit values must all fit in signed i32.
1361 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
1362 return;
1363
1364 // If not actually striding (add x, 0.0), avoid touching the code.
1365 if (IncValue == 0)
1366 return;
1367
1368 // Positive and negative strides have different safety conditions.
1369 if (IncValue > 0) {
1370 // If we have a positive stride, we require the init to be less than the
1371 // exit value and an equality or less than comparison.
1372 if (InitValue >= ExitValue ||
1373 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
1374 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001375
Chris Lattner96fd7662010-04-03 07:18:48 +00001376 uint32_t Range = uint32_t(ExitValue-InitValue);
1377 if (NewPred == CmpInst::ICMP_SLE) {
1378 // Normalize SLE -> SLT, check for infinite loop.
1379 if (++Range == 0) return; // Range overflows.
1380 }
Andrew Trickead71d52011-03-17 23:46:48 +00001381
Chris Lattner96fd7662010-04-03 07:18:48 +00001382 unsigned Leftover = Range % uint32_t(IncValue);
Andrew Trickead71d52011-03-17 23:46:48 +00001383
Chris Lattner96fd7662010-04-03 07:18:48 +00001384 // If this is an equality comparison, we require that the strided value
1385 // exactly land on the exit value, otherwise the IV condition will wrap
1386 // around and do things the fp IV wouldn't.
1387 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1388 Leftover != 0)
1389 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001390
Chris Lattner96fd7662010-04-03 07:18:48 +00001391 // If the stride would wrap around the i32 before exiting, we can't
1392 // transform the IV.
1393 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
1394 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001395
Chris Lattner96fd7662010-04-03 07:18:48 +00001396 } else {
1397 // If we have a negative stride, we require the init to be greater than the
1398 // exit value and an equality or greater than comparison.
1399 if (InitValue >= ExitValue ||
1400 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
1401 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001402
Chris Lattner96fd7662010-04-03 07:18:48 +00001403 uint32_t Range = uint32_t(InitValue-ExitValue);
1404 if (NewPred == CmpInst::ICMP_SGE) {
1405 // Normalize SGE -> SGT, check for infinite loop.
1406 if (++Range == 0) return; // Range overflows.
1407 }
Andrew Trickead71d52011-03-17 23:46:48 +00001408
Chris Lattner96fd7662010-04-03 07:18:48 +00001409 unsigned Leftover = Range % uint32_t(-IncValue);
Andrew Trickead71d52011-03-17 23:46:48 +00001410
Chris Lattner96fd7662010-04-03 07:18:48 +00001411 // If this is an equality comparison, we require that the strided value
1412 // exactly land on the exit value, otherwise the IV condition will wrap
1413 // around and do things the fp IV wouldn't.
1414 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1415 Leftover != 0)
1416 return;
Andrew Trickead71d52011-03-17 23:46:48 +00001417
Chris Lattner96fd7662010-04-03 07:18:48 +00001418 // If the stride would wrap around the i32 before exiting, we can't
1419 // transform the IV.
1420 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
1421 return;
1422 }
Andrew Trickead71d52011-03-17 23:46:48 +00001423
Chris Lattner96fd7662010-04-03 07:18:48 +00001424 const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
Dan Gohmancafb8132009-02-17 19:13:57 +00001425
Chris Lattnerbbb91492010-04-03 06:41:49 +00001426 // Insert new integer induction variable.
Jay Foad3ecfc862011-03-30 11:28:46 +00001427 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001428 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
Chris Lattnerc91961e2010-04-03 06:17:08 +00001429 PN->getIncomingBlock(IncomingEdge));
Devang Patel84e35152008-11-17 21:32:02 +00001430
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001431 Value *NewAdd =
Chris Lattner96fd7662010-04-03 07:18:48 +00001432 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
Chris Lattnerc4f7e802010-04-03 06:05:10 +00001433 Incr->getName()+".int", Incr);
Chris Lattnerc91961e2010-04-03 06:17:08 +00001434 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
Devang Patel84e35152008-11-17 21:32:02 +00001435
Chris Lattnerca703bd2010-04-03 06:11:07 +00001436 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
1437 ConstantInt::get(Int32Ty, ExitValue),
1438 Compare->getName());
Dan Gohmancafb8132009-02-17 19:13:57 +00001439
Chris Lattnerc91961e2010-04-03 06:17:08 +00001440 // In the following deletions, PN may become dead and may be deleted.
Dan Gohman81db61a2009-05-12 02:17:14 +00001441 // Use a WeakVH to observe whether this happens.
Chris Lattnerc91961e2010-04-03 06:17:08 +00001442 WeakVH WeakPH = PN;
Dan Gohman81db61a2009-05-12 02:17:14 +00001443
Chris Lattnerca703bd2010-04-03 06:11:07 +00001444 // Delete the old floating point exit comparison. The branch starts using the
1445 // new comparison.
1446 NewCompare->takeName(Compare);
1447 Compare->replaceAllUsesWith(NewCompare);
1448 RecursivelyDeleteTriviallyDeadInstructions(Compare);
Dan Gohmancafb8132009-02-17 19:13:57 +00001449
Chris Lattnerca703bd2010-04-03 06:11:07 +00001450 // Delete the old floating point increment.
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001451 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
Dan Gohman81db61a2009-05-12 02:17:14 +00001452 RecursivelyDeleteTriviallyDeadInstructions(Incr);
Dan Gohmancafb8132009-02-17 19:13:57 +00001453
Chris Lattner70c0d4f2010-04-03 06:16:22 +00001454 // If the FP induction variable still has uses, this is because something else
1455 // in the loop uses its value. In order to canonicalize the induction
1456 // variable, we chose to eliminate the IV and rewrite it in terms of an
1457 // int->fp cast.
1458 //
1459 // We give preference to sitofp over uitofp because it is faster on most
1460 // platforms.
1461 if (WeakPH) {
Chris Lattnera40e4a02010-04-03 06:25:21 +00001462 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
1463 PN->getParent()->getFirstNonPHI());
1464 PN->replaceAllUsesWith(Conv);
Chris Lattnerc91961e2010-04-03 06:17:08 +00001465 RecursivelyDeleteTriviallyDeadInstructions(PN);
Devang Patelcd402332008-11-17 23:27:13 +00001466 }
Devang Patel58d43d42008-11-03 18:32:19 +00001467
Dan Gohman81db61a2009-05-12 02:17:14 +00001468 // Add a new IVUsers entry for the newly-created integer PHI.
Andrew Trickf85092c2011-05-20 18:25:42 +00001469 IU->AddUsersIfInteresting(NewPHI, NewPHI);
Dan Gohman81db61a2009-05-12 02:17:14 +00001470}