blob: 677e7908f5d0514d97a141f78ba179f652c5d223 [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"
Andrew Trick56caa092011-06-28 03:01:46 +000055#include "llvm/Support/CommandLine.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000056#include "llvm/Support/Debug.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000057#include "llvm/Support/raw_ostream.h"
John Criswell47df12d2003-12-18 17:19:19 +000058#include "llvm/Transforms/Utils/Local.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000059#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Trick37da4082011-05-04 02:10:13 +000060#include "llvm/Target/TargetData.h"
Andrew Trick037d1c02011-07-06 20:50:43 +000061#include "llvm/ADT/DenseMap.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000062#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000063#include "llvm/ADT/Statistic.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000064#include "llvm/ADT/STLExtras.h"
John Criswell47df12d2003-12-18 17:19:19 +000065using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000066
Andrew Trick2fabd462011-06-21 03:22:38 +000067STATISTIC(NumRemoved , "Number of aux indvars removed");
68STATISTIC(NumWidened , "Number of indvars widened");
69STATISTIC(NumInserted , "Number of canonical indvars added");
70STATISTIC(NumReplaced , "Number of exit values replaced");
71STATISTIC(NumLFTR , "Number of loop exit tests replaced");
72STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
73STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");
74STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
75STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
Andrew Trick037d1c02011-07-06 20:50:43 +000076STATISTIC(NumElimIV , "Number of congruent IVs eliminated");
Chris Lattner3324e712003-12-22 03:58:44 +000077
Andrew Trick56caa092011-06-28 03:01:46 +000078static cl::opt<bool> DisableIVRewrite(
79 "disable-iv-rewrite", cl::Hidden,
80 cl::desc("Disable canonical induction variable rewriting"));
Andrew Trick37da4082011-05-04 02:10:13 +000081
Chris Lattner0e5f4992006-12-19 21:40:18 +000082namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000083 class IndVarSimplify : public LoopPass {
Andrew Trick17f91d22011-07-06 21:07:10 +000084 typedef DenseMap< const SCEV *, AssertingVH<PHINode> > ExprToIVMapTy;
Andrew Trick037d1c02011-07-06 20:50:43 +000085
Dan Gohman81db61a2009-05-12 02:17:14 +000086 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000087 LoopInfo *LI;
88 ScalarEvolution *SE;
Dan Gohmande53dc02009-06-27 05:16:57 +000089 DominatorTree *DT;
Andrew Trick37da4082011-05-04 02:10:13 +000090 TargetData *TD;
Andrew Trick2fabd462011-06-21 03:22:38 +000091
Andrew Trick037d1c02011-07-06 20:50:43 +000092 ExprToIVMapTy ExprToIVMap;
Andrew Trickb12a7542011-03-17 23:51:11 +000093 SmallVector<WeakVH, 16> DeadInsts;
Chris Lattner15cad752003-12-23 07:47:09 +000094 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000095 public:
Devang Patel794fd752007-05-01 21:15:47 +000096
Dan Gohman5668cf72009-07-15 01:26:32 +000097 static char ID; // Pass identification, replacement for typeid
Andrew Trick2fabd462011-06-21 03:22:38 +000098 IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0),
Andrew Trick15832f62011-06-28 02:49:20 +000099 Changed(false) {
Owen Anderson081c34b2010-10-19 17:21:58 +0000100 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
101 }
Devang Patel794fd752007-05-01 21:15:47 +0000102
Dan Gohman5668cf72009-07-15 01:26:32 +0000103 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman60f8a632009-02-17 20:49:49 +0000104
Dan Gohman5668cf72009-07-15 01:26:32 +0000105 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
106 AU.addRequired<DominatorTree>();
107 AU.addRequired<LoopInfo>();
108 AU.addRequired<ScalarEvolution>();
109 AU.addRequiredID(LoopSimplifyID);
110 AU.addRequiredID(LCSSAID);
Andrew Trick56caa092011-06-28 03:01:46 +0000111 if (!DisableIVRewrite)
112 AU.addRequired<IVUsers>();
Dan Gohman5668cf72009-07-15 01:26:32 +0000113 AU.addPreserved<ScalarEvolution>();
114 AU.addPreservedID(LoopSimplifyID);
115 AU.addPreservedID(LCSSAID);
Andrew Trick2fabd462011-06-21 03:22:38 +0000116 if (!DisableIVRewrite)
117 AU.addPreserved<IVUsers>();
Dan Gohman5668cf72009-07-15 01:26:32 +0000118 AU.setPreservesCFG();
119 }
Chris Lattner15cad752003-12-23 07:47:09 +0000120
Chris Lattner40bf8b42004-04-02 20:24:31 +0000121 private:
Andrew Trick037d1c02011-07-06 20:50:43 +0000122 virtual void releaseMemory() {
123 ExprToIVMap.clear();
124 DeadInsts.clear();
125 }
126
Andrew Trickb12a7542011-03-17 23:51:11 +0000127 bool isValidRewrite(Value *FromVal, Value *ToVal);
Devang Patel5ee99972007-03-07 06:39:01 +0000128
Andrew Trick1a54bb22011-07-12 00:08:50 +0000129 void HandleFloatingPointIV(Loop *L, PHINode *PH);
130 void RewriteNonIntegerIVs(Loop *L);
131
132 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
133
Andrew Trickf85092c2011-05-20 18:25:42 +0000134 void SimplifyIVUsers(SCEVExpander &Rewriter);
Andrew Trick2fabd462011-06-21 03:22:38 +0000135 void SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter);
136
137 bool EliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trickaeee4612011-05-12 00:04:28 +0000138 void EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
139 void EliminateIVRemainder(BinaryOperator *Rem,
140 Value *IVOperand,
Andrew Trick4417e532011-06-21 15:43:52 +0000141 bool IsSigned);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000142
Andrew Trick037d1c02011-07-06 20:50:43 +0000143 void SimplifyCongruentIVs(Loop *L);
144
Dan Gohman454d26d2010-02-22 04:11:59 +0000145 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000146
Andrew Trick1a54bb22011-07-12 00:08:50 +0000147 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *IVLimit,
148 PHINode *IndVar,
149 SCEVExpander &Rewriter);
Dan Gohman81db61a2009-05-12 02:17:14 +0000150
Andrew Trick1a54bb22011-07-12 00:08:50 +0000151 void SinkUnusedInvariants(Loop *L);
Chris Lattner3324e712003-12-22 03:58:44 +0000152 };
Chris Lattner5e761402002-09-10 05:24:05 +0000153}
Chris Lattner394437f2001-12-04 04:32:29 +0000154
Dan Gohman844731a2008-05-13 00:00:25 +0000155char IndVarSimplify::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000156INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000157 "Induction Variable Simplification", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000158INITIALIZE_PASS_DEPENDENCY(DominatorTree)
159INITIALIZE_PASS_DEPENDENCY(LoopInfo)
160INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
161INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
162INITIALIZE_PASS_DEPENDENCY(LCSSA)
163INITIALIZE_PASS_DEPENDENCY(IVUsers)
164INITIALIZE_PASS_END(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000165 "Induction Variable Simplification", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000166
Daniel Dunbar394f0442008-10-22 23:32:42 +0000167Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000168 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000169}
170
Andrew Trickb12a7542011-03-17 23:51:11 +0000171/// isValidRewrite - Return true if the SCEV expansion generated by the
172/// rewriter can replace the original value. SCEV guarantees that it
173/// produces the same value, but the way it is produced may be illegal IR.
174/// Ideally, this function will only be called for verification.
175bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
176 // If an SCEV expression subsumed multiple pointers, its expansion could
177 // reassociate the GEP changing the base pointer. This is illegal because the
178 // final address produced by a GEP chain must be inbounds relative to its
179 // underlying object. Otherwise basic alias analysis, among other things,
180 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
181 // producing an expression involving multiple pointers. Until then, we must
182 // bail out here.
183 //
184 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
185 // because it understands lcssa phis while SCEV does not.
186 Value *FromPtr = FromVal;
187 Value *ToPtr = ToVal;
188 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
189 FromPtr = GEP->getPointerOperand();
190 }
191 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
192 ToPtr = GEP->getPointerOperand();
193 }
194 if (FromPtr != FromVal || ToPtr != ToVal) {
195 // Quickly check the common case
196 if (FromPtr == ToPtr)
197 return true;
198
199 // SCEV may have rewritten an expression that produces the GEP's pointer
200 // operand. That's ok as long as the pointer operand has the same base
201 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
202 // base of a recurrence. This handles the case in which SCEV expansion
203 // converts a pointer type recurrence into a nonrecurrent pointer base
204 // indexed by an integer recurrence.
205 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
206 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
207 if (FromBase == ToBase)
208 return true;
209
210 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
211 << *FromBase << " != " << *ToBase << "\n");
212
213 return false;
214 }
215 return true;
216}
217
Andrew Trick1a54bb22011-07-12 00:08:50 +0000218//===----------------------------------------------------------------------===//
219// RewriteNonIntegerIVs and helpers. Prefer integer IVs.
220//===----------------------------------------------------------------------===//
Andrew Trick4dfdf242011-05-03 22:24:10 +0000221
Andrew Trick1a54bb22011-07-12 00:08:50 +0000222/// ConvertToSInt - Convert APF to an integer, if possible.
223static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
224 bool isExact = false;
225 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000226 return false;
Andrew Trick1a54bb22011-07-12 00:08:50 +0000227 // See if we can convert this to an int64_t
228 uint64_t UIntVal;
229 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
230 &isExact) != APFloat::opOK || !isExact)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000231 return false;
Andrew Trick1a54bb22011-07-12 00:08:50 +0000232 IntVal = UIntVal;
Andrew Trick4dfdf242011-05-03 22:24:10 +0000233 return true;
234}
235
Andrew Trick1a54bb22011-07-12 00:08:50 +0000236/// HandleFloatingPointIV - If the loop has floating induction variable
237/// then insert corresponding integer induction variable if possible.
238/// For example,
239/// for(double i = 0; i < 10000; ++i)
240/// bar(i)
241/// is converted into
242/// for(int i = 0; i < 10000; ++i)
243/// bar((double)i);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000244///
Andrew Trick1a54bb22011-07-12 00:08:50 +0000245void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
246 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
247 unsigned BackEdge = IncomingEdge^1;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000248
Andrew Trick1a54bb22011-07-12 00:08:50 +0000249 // Check incoming value.
250 ConstantFP *InitValueVal =
251 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000252
Andrew Trick1a54bb22011-07-12 00:08:50 +0000253 int64_t InitValue;
254 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
255 return;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000256
Andrew Trick1a54bb22011-07-12 00:08:50 +0000257 // Check IV increment. Reject this PN if increment operation is not
258 // an add or increment value can not be represented by an integer.
259 BinaryOperator *Incr =
260 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
261 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000262
Andrew Trick1a54bb22011-07-12 00:08:50 +0000263 // If this is not an add of the PHI with a constantfp, or if the constant fp
264 // is not an integer, bail out.
265 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
266 int64_t IncValue;
267 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
268 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
269 return;
270
271 // Check Incr uses. One user is PN and the other user is an exit condition
272 // used by the conditional terminator.
273 Value::use_iterator IncrUse = Incr->use_begin();
274 Instruction *U1 = cast<Instruction>(*IncrUse++);
275 if (IncrUse == Incr->use_end()) return;
276 Instruction *U2 = cast<Instruction>(*IncrUse++);
277 if (IncrUse != Incr->use_end()) return;
278
279 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
280 // only used by a branch, we can't transform it.
281 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
282 if (!Compare)
283 Compare = dyn_cast<FCmpInst>(U2);
284 if (Compare == 0 || !Compare->hasOneUse() ||
285 !isa<BranchInst>(Compare->use_back()))
286 return;
287
288 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
289
290 // We need to verify that the branch actually controls the iteration count
291 // of the loop. If not, the new IV can overflow and no one will notice.
292 // The branch block must be in the loop and one of the successors must be out
293 // of the loop.
294 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
295 if (!L->contains(TheBr->getParent()) ||
296 (L->contains(TheBr->getSuccessor(0)) &&
297 L->contains(TheBr->getSuccessor(1))))
298 return;
299
300
301 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
302 // transform it.
303 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
304 int64_t ExitValue;
305 if (ExitValueVal == 0 ||
306 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
307 return;
308
309 // Find new predicate for integer comparison.
310 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
311 switch (Compare->getPredicate()) {
312 default: return; // Unknown comparison.
313 case CmpInst::FCMP_OEQ:
314 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
315 case CmpInst::FCMP_ONE:
316 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
317 case CmpInst::FCMP_OGT:
318 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
319 case CmpInst::FCMP_OGE:
320 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
321 case CmpInst::FCMP_OLT:
322 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
323 case CmpInst::FCMP_OLE:
324 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000325 }
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000326
Andrew Trick1a54bb22011-07-12 00:08:50 +0000327 // We convert the floating point induction variable to a signed i32 value if
328 // we can. This is only safe if the comparison will not overflow in a way
329 // that won't be trapped by the integer equivalent operations. Check for this
330 // now.
331 // TODO: We could use i64 if it is native and the range requires it.
Dan Gohmanca9b7032010-04-12 21:13:43 +0000332
Andrew Trick1a54bb22011-07-12 00:08:50 +0000333 // The start/stride/exit values must all fit in signed i32.
334 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
335 return;
336
337 // If not actually striding (add x, 0.0), avoid touching the code.
338 if (IncValue == 0)
339 return;
340
341 // Positive and negative strides have different safety conditions.
342 if (IncValue > 0) {
343 // If we have a positive stride, we require the init to be less than the
344 // exit value and an equality or less than comparison.
345 if (InitValue >= ExitValue ||
346 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
347 return;
348
349 uint32_t Range = uint32_t(ExitValue-InitValue);
350 if (NewPred == CmpInst::ICMP_SLE) {
351 // Normalize SLE -> SLT, check for infinite loop.
352 if (++Range == 0) return; // Range overflows.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000353 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000354
Andrew Trick1a54bb22011-07-12 00:08:50 +0000355 unsigned Leftover = Range % uint32_t(IncValue);
356
357 // If this is an equality comparison, we require that the strided value
358 // exactly land on the exit value, otherwise the IV condition will wrap
359 // around and do things the fp IV wouldn't.
360 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
361 Leftover != 0)
362 return;
363
364 // If the stride would wrap around the i32 before exiting, we can't
365 // transform the IV.
366 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
367 return;
368
Chris Lattnerd2440572004-04-15 20:26:22 +0000369 } else {
Andrew Trick1a54bb22011-07-12 00:08:50 +0000370 // If we have a negative stride, we require the init to be greater than the
371 // exit value and an equality or greater than comparison.
372 if (InitValue >= ExitValue ||
373 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
374 return;
375
376 uint32_t Range = uint32_t(InitValue-ExitValue);
377 if (NewPred == CmpInst::ICMP_SGE) {
378 // Normalize SGE -> SGT, check for infinite loop.
379 if (++Range == 0) return; // Range overflows.
380 }
381
382 unsigned Leftover = Range % uint32_t(-IncValue);
383
384 // If this is an equality comparison, we require that the strided value
385 // exactly land on the exit value, otherwise the IV condition will wrap
386 // around and do things the fp IV wouldn't.
387 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
388 Leftover != 0)
389 return;
390
391 // If the stride would wrap around the i32 before exiting, we can't
392 // transform the IV.
393 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
394 return;
Chris Lattnerd2440572004-04-15 20:26:22 +0000395 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000396
Andrew Trick1a54bb22011-07-12 00:08:50 +0000397 const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000398
Andrew Trick1a54bb22011-07-12 00:08:50 +0000399 // Insert new integer induction variable.
400 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
401 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
402 PN->getIncomingBlock(IncomingEdge));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000403
Andrew Trick1a54bb22011-07-12 00:08:50 +0000404 Value *NewAdd =
405 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
406 Incr->getName()+".int", Incr);
407 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000408
Andrew Trick1a54bb22011-07-12 00:08:50 +0000409 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
410 ConstantInt::get(Int32Ty, ExitValue),
411 Compare->getName());
Dan Gohman81db61a2009-05-12 02:17:14 +0000412
Andrew Trick1a54bb22011-07-12 00:08:50 +0000413 // In the following deletions, PN may become dead and may be deleted.
414 // Use a WeakVH to observe whether this happens.
415 WeakVH WeakPH = PN;
416
417 // Delete the old floating point exit comparison. The branch starts using the
418 // new comparison.
419 NewCompare->takeName(Compare);
420 Compare->replaceAllUsesWith(NewCompare);
421 RecursivelyDeleteTriviallyDeadInstructions(Compare);
422
423 // Delete the old floating point increment.
424 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
425 RecursivelyDeleteTriviallyDeadInstructions(Incr);
426
427 // If the FP induction variable still has uses, this is because something else
428 // in the loop uses its value. In order to canonicalize the induction
429 // variable, we chose to eliminate the IV and rewrite it in terms of an
430 // int->fp cast.
431 //
432 // We give preference to sitofp over uitofp because it is faster on most
433 // platforms.
434 if (WeakPH) {
435 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
436 PN->getParent()->getFirstNonPHI());
437 PN->replaceAllUsesWith(Conv);
438 RecursivelyDeleteTriviallyDeadInstructions(PN);
439 }
440
441 // Add a new IVUsers entry for the newly-created integer PHI.
442 if (IU)
443 IU->AddUsersIfInteresting(NewPHI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000444}
445
Andrew Trick1a54bb22011-07-12 00:08:50 +0000446void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
447 // First step. Check to see if there are any floating-point recurrences.
448 // If there are, change them into integer recurrences, permitting analysis by
449 // the SCEV routines.
450 //
451 BasicBlock *Header = L->getHeader();
452
453 SmallVector<WeakVH, 8> PHIs;
454 for (BasicBlock::iterator I = Header->begin();
455 PHINode *PN = dyn_cast<PHINode>(I); ++I)
456 PHIs.push_back(PN);
457
458 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
459 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
460 HandleFloatingPointIV(L, PN);
461
462 // If the loop previously had floating-point IV, ScalarEvolution
463 // may not have been able to compute a trip count. Now that we've done some
464 // re-writing, the trip count may be computable.
465 if (Changed)
466 SE->forgetLoop(L);
467}
468
469//===----------------------------------------------------------------------===//
470// RewriteLoopExitValues - Optimize IV users outside the loop.
471// As a side effect, reduces the amount of IV processing within the loop.
472//===----------------------------------------------------------------------===//
473
Chris Lattner40bf8b42004-04-02 20:24:31 +0000474/// RewriteLoopExitValues - Check to see if this loop has a computable
475/// loop-invariant execution count. If so, this means that we can compute the
476/// final value of any expressions that are recurrent in the loop, and
477/// substitute the exit values from the loop into any instructions outside of
478/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000479///
480/// This is mostly redundant with the regular IndVarSimplify activities that
481/// happen later, except that it's more powerful in some cases, because it's
482/// able to brute-force evaluate arbitrary instructions as long as they have
483/// constant operands at the beginning of the loop.
Chris Lattnerf1859892011-01-09 02:16:18 +0000484void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000485 // Verify the input to the pass in already in LCSSA form.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000486 assert(L->isLCSSAForm(*DT));
Dan Gohman81db61a2009-05-12 02:17:14 +0000487
Devang Patelb7211a22007-08-21 00:31:24 +0000488 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000489 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000490
Chris Lattner9f3d7382007-03-04 03:43:23 +0000491 // Find all values that are computed inside the loop, but used outside of it.
492 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
493 // the exit blocks of the loop to find them.
494 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
495 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000496
Chris Lattner9f3d7382007-03-04 03:43:23 +0000497 // If there are no PHI nodes in this exit block, then no values defined
498 // inside the loop are used on this path, skip it.
499 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
500 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000501
Chris Lattner9f3d7382007-03-04 03:43:23 +0000502 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000503
Chris Lattner9f3d7382007-03-04 03:43:23 +0000504 // Iterate over all of the PHI nodes.
505 BasicBlock::iterator BBI = ExitBB->begin();
506 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000507 if (PN->use_empty())
508 continue; // dead use, don't replace it
Dan Gohman814f2b22010-02-18 21:34:02 +0000509
510 // SCEV only supports integer expressions for now.
511 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
512 continue;
513
Dale Johannesen45a2d7d2010-02-19 07:14:22 +0000514 // It's necessary to tell ScalarEvolution about this explicitly so that
515 // it can walk the def-use list and forget all SCEVs, as it may not be
516 // watching the PHI itself. Once the new exit value is in place, there
517 // may not be a def-use connection between the loop and every instruction
518 // which got a SCEVAddRecExpr for that loop.
519 SE->forgetValue(PN);
520
Chris Lattner9f3d7382007-03-04 03:43:23 +0000521 // Iterate over all of the values in all the PHI nodes.
522 for (unsigned i = 0; i != NumPreds; ++i) {
523 // If the value being merged in is not integer or is not defined
524 // in the loop, skip it.
525 Value *InVal = PN->getIncomingValue(i);
Dan Gohman814f2b22010-02-18 21:34:02 +0000526 if (!isa<Instruction>(InVal))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000527 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000528
Chris Lattner9f3d7382007-03-04 03:43:23 +0000529 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000530 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000531 continue; // The Block is in a subloop, skip it.
532
533 // Check that InVal is defined in the loop.
534 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman92329c72009-12-18 01:24:09 +0000535 if (!L->contains(Inst))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000536 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000537
Chris Lattner9f3d7382007-03-04 03:43:23 +0000538 // Okay, this instruction has a user outside of the current loop
539 // and varies predictably *inside* the loop. Evaluate the value it
540 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000541 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +0000542 if (!SE->isLoopInvariant(ExitValue, L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000543 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000544
Dan Gohman667d7872009-06-26 22:53:46 +0000545 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000546
David Greenef67ef312010-01-05 01:27:06 +0000547 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000548 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000549
Andrew Trickb12a7542011-03-17 23:51:11 +0000550 if (!isValidRewrite(Inst, ExitVal)) {
551 DeadInsts.push_back(ExitVal);
552 continue;
553 }
554 Changed = true;
555 ++NumReplaced;
556
Chris Lattner9f3d7382007-03-04 03:43:23 +0000557 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000558
Dan Gohman81db61a2009-05-12 02:17:14 +0000559 // If this instruction is dead now, delete it.
560 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000561
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000562 if (NumPreds == 1) {
563 // Completely replace a single-pred PHI. This is safe, because the
564 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
565 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000566 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000567 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000568 }
569 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000570 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000571 // Clone the PHI and delete the original one. This lets IVUsers and
572 // any other maps purge the original user from their records.
Devang Patel50b6e332009-10-27 22:16:29 +0000573 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohman667d7872009-06-26 22:53:46 +0000574 NewPN->takeName(PN);
575 NewPN->insertBefore(PN);
576 PN->replaceAllUsesWith(NewPN);
577 PN->eraseFromParent();
578 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000579 }
580 }
Dan Gohman472fdf72010-03-20 03:53:53 +0000581
582 // The insertion point instruction may have been deleted; clear it out
583 // so that the rewriter doesn't trip over it later.
584 Rewriter.clearInsertPoint();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000585}
586
Andrew Trick1a54bb22011-07-12 00:08:50 +0000587//===----------------------------------------------------------------------===//
588// Rewrite IV users based on a canonical IV.
589// To be replaced by -disable-iv-rewrite.
590//===----------------------------------------------------------------------===//
Dale Johannesenc671d892009-04-15 23:31:51 +0000591
Andrew Trick2fabd462011-06-21 03:22:38 +0000592/// SimplifyIVUsers - Iteratively perform simplification on IVUsers within this
593/// loop. IVUsers is treated as a worklist. Each successive simplification may
594/// push more users which may themselves be candidates for simplification.
595///
596/// This is the old approach to IV simplification to be replaced by
597/// SimplifyIVUsersNoRewrite.
598///
599void IndVarSimplify::SimplifyIVUsers(SCEVExpander &Rewriter) {
600 // Each round of simplification involves a round of eliminating operations
601 // followed by a round of widening IVs. A single IVUsers worklist is used
602 // across all rounds. The inner loop advances the user. If widening exposes
603 // more uses, then another pass through the outer loop is triggered.
604 for (IVUsers::iterator I = IU->begin(); I != IU->end(); ++I) {
605 Instruction *UseInst = I->getUser();
606 Value *IVOperand = I->getOperandValToReplace();
607
608 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
609 EliminateIVComparison(ICmp, IVOperand);
610 continue;
611 }
612 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
613 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
614 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
Andrew Trick4417e532011-06-21 15:43:52 +0000615 EliminateIVRemainder(Rem, IVOperand, IsSigned);
Andrew Trick2fabd462011-06-21 03:22:38 +0000616 continue;
617 }
618 }
619 }
620}
621
Andrew Trick1a54bb22011-07-12 00:08:50 +0000622// FIXME: It is an extremely bad idea to indvar substitute anything more
623// complex than affine induction variables. Doing so will put expensive
624// polynomial evaluations inside of the loop, and the str reduction pass
625// currently can only reduce affine polynomials. For now just disable
626// indvar subst on anything more complex than an affine addrec, unless
627// it can be expanded to a trivial value.
628static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
629 // Loop-invariant values are safe.
630 if (SE->isLoopInvariant(S, L)) return true;
631
632 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
633 // to transform them into efficient code.
634 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
635 return AR->isAffine();
636
637 // An add is safe it all its operands are safe.
638 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
639 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
640 E = Commutative->op_end(); I != E; ++I)
641 if (!isSafe(*I, L, SE)) return false;
642 return true;
643 }
644
645 // A cast is safe if its operand is.
646 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
647 return isSafe(C->getOperand(), L, SE);
648
649 // A udiv is safe if its operands are.
650 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
651 return isSafe(UD->getLHS(), L, SE) &&
652 isSafe(UD->getRHS(), L, SE);
653
654 // SCEVUnknown is always safe.
655 if (isa<SCEVUnknown>(S))
656 return true;
657
658 // Nothing else is safe.
659 return false;
660}
661
662void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
663 // Rewrite all induction variable expressions in terms of the canonical
664 // induction variable.
665 //
666 // If there were induction variables of other sizes or offsets, manually
667 // add the offsets to the primary induction variable and cast, avoiding
668 // the need for the code evaluation methods to insert induction variables
669 // of different sizes.
670 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
671 Value *Op = UI->getOperandValToReplace();
672 const Type *UseTy = Op->getType();
673 Instruction *User = UI->getUser();
674
675 // Compute the final addrec to expand into code.
676 const SCEV *AR = IU->getReplacementExpr(*UI);
677
678 // Evaluate the expression out of the loop, if possible.
679 if (!L->contains(UI->getUser())) {
680 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
681 if (SE->isLoopInvariant(ExitVal, L))
682 AR = ExitVal;
683 }
684
685 // FIXME: It is an extremely bad idea to indvar substitute anything more
686 // complex than affine induction variables. Doing so will put expensive
687 // polynomial evaluations inside of the loop, and the str reduction pass
688 // currently can only reduce affine polynomials. For now just disable
689 // indvar subst on anything more complex than an affine addrec, unless
690 // it can be expanded to a trivial value.
691 if (!isSafe(AR, L, SE))
692 continue;
693
694 // Determine the insertion point for this user. By default, insert
695 // immediately before the user. The SCEVExpander class will automatically
696 // hoist loop invariants out of the loop. For PHI nodes, there may be
697 // multiple uses, so compute the nearest common dominator for the
698 // incoming blocks.
699 Instruction *InsertPt = User;
700 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
701 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
702 if (PHI->getIncomingValue(i) == Op) {
703 if (InsertPt == User)
704 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
705 else
706 InsertPt =
707 DT->findNearestCommonDominator(InsertPt->getParent(),
708 PHI->getIncomingBlock(i))
709 ->getTerminator();
710 }
711
712 // Now expand it into actual Instructions and patch it into place.
713 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
714
715 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
716 << " into = " << *NewVal << "\n");
717
718 if (!isValidRewrite(Op, NewVal)) {
719 DeadInsts.push_back(NewVal);
720 continue;
721 }
722 // Inform ScalarEvolution that this value is changing. The change doesn't
723 // affect its value, but it does potentially affect which use lists the
724 // value will be on after the replacement, which affects ScalarEvolution's
725 // ability to walk use lists and drop dangling pointers when a value is
726 // deleted.
727 SE->forgetValue(User);
728
729 // Patch the new value into place.
730 if (Op->hasName())
731 NewVal->takeName(Op);
732 if (Instruction *NewValI = dyn_cast<Instruction>(NewVal))
733 NewValI->setDebugLoc(User->getDebugLoc());
734 User->replaceUsesOfWith(Op, NewVal);
735 UI->setOperandValToReplace(NewVal);
736
737 ++NumRemoved;
738 Changed = true;
739
740 // The old value may be dead now.
741 DeadInsts.push_back(Op);
742 }
743}
744
745//===----------------------------------------------------------------------===//
746// IV Widening - Extend the width of an IV to cover its widest uses.
747//===----------------------------------------------------------------------===//
748
Andrew Trickf85092c2011-05-20 18:25:42 +0000749namespace {
750 // Collect information about induction variables that are used by sign/zero
751 // extend operations. This information is recorded by CollectExtend and
752 // provides the input to WidenIV.
753 struct WideIVInfo {
754 const Type *WidestNativeType; // Widest integer type created [sz]ext
755 bool IsSigned; // Was an sext user seen before a zext?
756
757 WideIVInfo() : WidestNativeType(0), IsSigned(false) {}
758 };
Andrew Trickf85092c2011-05-20 18:25:42 +0000759}
760
761/// CollectExtend - Update information about the induction variable that is
762/// extended by this sign or zero extend operation. This is used to determine
763/// the final width of the IV before actually widening it.
Andrew Trick2fabd462011-06-21 03:22:38 +0000764static void CollectExtend(CastInst *Cast, bool IsSigned, WideIVInfo &WI,
765 ScalarEvolution *SE, const TargetData *TD) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000766 const Type *Ty = Cast->getType();
767 uint64_t Width = SE->getTypeSizeInBits(Ty);
768 if (TD && !TD->isLegalInteger(Width))
769 return;
770
Andrew Trick2fabd462011-06-21 03:22:38 +0000771 if (!WI.WidestNativeType) {
772 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
773 WI.IsSigned = IsSigned;
Andrew Trickf85092c2011-05-20 18:25:42 +0000774 return;
775 }
776
777 // We extend the IV to satisfy the sign of its first user, arbitrarily.
Andrew Trick2fabd462011-06-21 03:22:38 +0000778 if (WI.IsSigned != IsSigned)
Andrew Trickf85092c2011-05-20 18:25:42 +0000779 return;
780
Andrew Trick2fabd462011-06-21 03:22:38 +0000781 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
782 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
Andrew Trickf85092c2011-05-20 18:25:42 +0000783}
784
785namespace {
786/// WidenIV - The goal of this transform is to remove sign and zero extends
787/// without creating any new induction variables. To do this, it creates a new
788/// phi of the wider type and redirects all users, either removing extends or
789/// inserting truncs whenever we stop propagating the type.
790///
791class WidenIV {
Andrew Trick2fabd462011-06-21 03:22:38 +0000792 // Parameters
Andrew Trickf85092c2011-05-20 18:25:42 +0000793 PHINode *OrigPhi;
794 const Type *WideType;
795 bool IsSigned;
796
Andrew Trick2fabd462011-06-21 03:22:38 +0000797 // Context
798 LoopInfo *LI;
799 Loop *L;
Andrew Trickf85092c2011-05-20 18:25:42 +0000800 ScalarEvolution *SE;
Andrew Trick2fabd462011-06-21 03:22:38 +0000801 DominatorTree *DT;
Andrew Trickf85092c2011-05-20 18:25:42 +0000802
Andrew Trick2fabd462011-06-21 03:22:38 +0000803 // Result
Andrew Trickf85092c2011-05-20 18:25:42 +0000804 PHINode *WidePhi;
805 Instruction *WideInc;
806 const SCEV *WideIncExpr;
Andrew Trick2fabd462011-06-21 03:22:38 +0000807 SmallVectorImpl<WeakVH> &DeadInsts;
Andrew Trickf85092c2011-05-20 18:25:42 +0000808
Andrew Trick2fabd462011-06-21 03:22:38 +0000809 SmallPtrSet<Instruction*,16> Widened;
Andrew Trick4b029152011-07-02 02:34:25 +0000810 SmallVector<std::pair<Use *, Instruction *>, 8> NarrowIVUsers;
Andrew Trickf85092c2011-05-20 18:25:42 +0000811
812public:
Andrew Trick2fabd462011-06-21 03:22:38 +0000813 WidenIV(PHINode *PN, const WideIVInfo &WI, LoopInfo *LInfo,
814 ScalarEvolution *SEv, DominatorTree *DTree,
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000815 SmallVectorImpl<WeakVH> &DI) :
Andrew Trickf85092c2011-05-20 18:25:42 +0000816 OrigPhi(PN),
Andrew Trick2fabd462011-06-21 03:22:38 +0000817 WideType(WI.WidestNativeType),
818 IsSigned(WI.IsSigned),
Andrew Trickf85092c2011-05-20 18:25:42 +0000819 LI(LInfo),
820 L(LI->getLoopFor(OrigPhi->getParent())),
821 SE(SEv),
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000822 DT(DTree),
Andrew Trickf85092c2011-05-20 18:25:42 +0000823 WidePhi(0),
824 WideInc(0),
Andrew Trick2fabd462011-06-21 03:22:38 +0000825 WideIncExpr(0),
826 DeadInsts(DI) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000827 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
828 }
829
Andrew Trick2fabd462011-06-21 03:22:38 +0000830 PHINode *CreateWideIV(SCEVExpander &Rewriter);
Andrew Trickf85092c2011-05-20 18:25:42 +0000831
832protected:
Andrew Trickf85092c2011-05-20 18:25:42 +0000833 Instruction *CloneIVUser(Instruction *NarrowUse,
834 Instruction *NarrowDef,
835 Instruction *WideDef);
836
Andrew Tricke0dc2fa2011-07-05 18:19:39 +0000837 const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
838
Andrew Trickcc359d92011-06-29 23:03:57 +0000839 Instruction *WidenIVUse(Use &NarrowDefUse, Instruction *NarrowDef,
Andrew Trickf85092c2011-05-20 18:25:42 +0000840 Instruction *WideDef);
Andrew Trick4b029152011-07-02 02:34:25 +0000841
842 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
Andrew Trickf85092c2011-05-20 18:25:42 +0000843};
844} // anonymous namespace
845
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000846static Value *getExtend( Value *NarrowOper, const Type *WideType,
847 bool IsSigned, IRBuilder<> &Builder) {
848 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
849 Builder.CreateZExt(NarrowOper, WideType);
Andrew Trickf85092c2011-05-20 18:25:42 +0000850}
851
852/// CloneIVUser - Instantiate a wide operation to replace a narrow
853/// operation. This only needs to handle operations that can evaluation to
854/// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
855Instruction *WidenIV::CloneIVUser(Instruction *NarrowUse,
856 Instruction *NarrowDef,
857 Instruction *WideDef) {
858 unsigned Opcode = NarrowUse->getOpcode();
859 switch (Opcode) {
860 default:
861 return 0;
862 case Instruction::Add:
863 case Instruction::Mul:
864 case Instruction::UDiv:
865 case Instruction::Sub:
866 case Instruction::And:
867 case Instruction::Or:
868 case Instruction::Xor:
869 case Instruction::Shl:
870 case Instruction::LShr:
871 case Instruction::AShr:
872 DEBUG(dbgs() << "Cloning IVUser: " << *NarrowUse << "\n");
873
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000874 IRBuilder<> Builder(NarrowUse);
875
876 // Replace NarrowDef operands with WideDef. Otherwise, we don't know
877 // anything about the narrow operand yet so must insert a [sz]ext. It is
878 // probably loop invariant and will be folded or hoisted. If it actually
879 // comes from a widened IV, it should be removed during a future call to
880 // WidenIVUse.
881 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef) ? WideDef :
882 getExtend(NarrowUse->getOperand(0), WideType, IsSigned, Builder);
883 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef) ? WideDef :
884 getExtend(NarrowUse->getOperand(1), WideType, IsSigned, Builder);
885
Andrew Trickf85092c2011-05-20 18:25:42 +0000886 BinaryOperator *NarrowBO = cast<BinaryOperator>(NarrowUse);
887 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000888 LHS, RHS,
Andrew Trickf85092c2011-05-20 18:25:42 +0000889 NarrowBO->getName());
Andrew Trickf85092c2011-05-20 18:25:42 +0000890 Builder.Insert(WideBO);
Andrew Trick6e0ce242011-06-30 19:02:17 +0000891 if (const OverflowingBinaryOperator *OBO =
892 dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
893 if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
894 if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
895 }
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000896 return WideBO;
Andrew Trickf85092c2011-05-20 18:25:42 +0000897 }
898 llvm_unreachable(0);
899}
900
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000901/// HoistStep - Attempt to hoist an IV increment above a potential use.
902///
903/// To successfully hoist, two criteria must be met:
904/// - IncV operands dominate InsertPos and
905/// - InsertPos dominates IncV
906///
907/// Meeting the second condition means that we don't need to check all of IncV's
908/// existing uses (it's moving up in the domtree).
909///
910/// This does not yet recursively hoist the operands, although that would
911/// not be difficult.
912static bool HoistStep(Instruction *IncV, Instruction *InsertPos,
913 const DominatorTree *DT)
914{
915 if (DT->dominates(IncV, InsertPos))
916 return true;
917
918 if (!DT->dominates(InsertPos->getParent(), IncV->getParent()))
919 return false;
920
921 if (IncV->mayHaveSideEffects())
922 return false;
923
924 // Attempt to hoist IncV
925 for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end();
926 OI != OE; ++OI) {
927 Instruction *OInst = dyn_cast<Instruction>(OI);
928 if (OInst && !DT->dominates(OInst, InsertPos))
929 return false;
930 }
931 IncV->moveBefore(InsertPos);
932 return true;
933}
934
Andrew Tricke0dc2fa2011-07-05 18:19:39 +0000935// GetWideRecurrence - Is this instruction potentially interesting from IVUsers'
936// perspective after widening it's type? In other words, can the extend be
937// safely hoisted out of the loop with SCEV reducing the value to a recurrence
938// on the same loop. If so, return the sign or zero extended
939// recurrence. Otherwise return NULL.
940const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
941 if (!SE->isSCEVable(NarrowUse->getType()))
942 return 0;
943
944 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
945 if (SE->getTypeSizeInBits(NarrowExpr->getType())
946 >= SE->getTypeSizeInBits(WideType)) {
947 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
948 // index. So don't follow this use.
949 return 0;
950 }
951
952 const SCEV *WideExpr = IsSigned ?
953 SE->getSignExtendExpr(NarrowExpr, WideType) :
954 SE->getZeroExtendExpr(NarrowExpr, WideType);
955 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
956 if (!AddRec || AddRec->getLoop() != L)
957 return 0;
958
959 return AddRec;
960}
961
Andrew Trickf85092c2011-05-20 18:25:42 +0000962/// WidenIVUse - Determine whether an individual user of the narrow IV can be
963/// widened. If so, return the wide clone of the user.
Andrew Trickcc359d92011-06-29 23:03:57 +0000964Instruction *WidenIV::WidenIVUse(Use &NarrowDefUse, Instruction *NarrowDef,
Andrew Trickf85092c2011-05-20 18:25:42 +0000965 Instruction *WideDef) {
Andrew Trickcc359d92011-06-29 23:03:57 +0000966 Instruction *NarrowUse = cast<Instruction>(NarrowDefUse.getUser());
967
Andrew Trick4b029152011-07-02 02:34:25 +0000968 // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
Andrew Trickf85092c2011-05-20 18:25:42 +0000969 if (isa<PHINode>(NarrowUse) && LI->getLoopFor(NarrowUse->getParent()) != L)
970 return 0;
971
Andrew Trickf85092c2011-05-20 18:25:42 +0000972 // Our raison d'etre! Eliminate sign and zero extension.
973 if (IsSigned ? isa<SExtInst>(NarrowUse) : isa<ZExtInst>(NarrowUse)) {
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000974 Value *NewDef = WideDef;
975 if (NarrowUse->getType() != WideType) {
976 unsigned CastWidth = SE->getTypeSizeInBits(NarrowUse->getType());
977 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
978 if (CastWidth < IVWidth) {
979 // The cast isn't as wide as the IV, so insert a Trunc.
Andrew Trickcc359d92011-06-29 23:03:57 +0000980 IRBuilder<> Builder(NarrowDefUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000981 NewDef = Builder.CreateTrunc(WideDef, NarrowUse->getType());
982 }
983 else {
984 // A wider extend was hidden behind a narrower one. This may induce
985 // another round of IV widening in which the intermediate IV becomes
986 // dead. It should be very rare.
987 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
988 << " not wide enough to subsume " << *NarrowUse << "\n");
989 NarrowUse->replaceUsesOfWith(NarrowDef, WideDef);
990 NewDef = NarrowUse;
991 }
992 }
993 if (NewDef != NarrowUse) {
994 DEBUG(dbgs() << "INDVARS: eliminating " << *NarrowUse
995 << " replaced by " << *WideDef << "\n");
996 ++NumElimExt;
997 NarrowUse->replaceAllUsesWith(NewDef);
998 DeadInsts.push_back(NarrowUse);
999 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001000 // Now that the extend is gone, we want to expose it's uses for potential
1001 // further simplification. We don't need to directly inform SimplifyIVUsers
1002 // of the new users, because their parent IV will be processed later as a
1003 // new loop phi. If we preserved IVUsers analysis, we would also want to
1004 // push the uses of WideDef here.
Andrew Trickf85092c2011-05-20 18:25:42 +00001005
1006 // No further widening is needed. The deceased [sz]ext had done it for us.
1007 return 0;
1008 }
Andrew Trick4b029152011-07-02 02:34:25 +00001009
1010 // Does this user itself evaluate to a recurrence after widening?
Andrew Tricke0dc2fa2011-07-05 18:19:39 +00001011 const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(NarrowUse);
Andrew Trickf85092c2011-05-20 18:25:42 +00001012 if (!WideAddRec) {
1013 // This user does not evaluate to a recurence after widening, so don't
1014 // follow it. Instead insert a Trunc to kill off the original use,
1015 // eventually isolating the original narrow IV so it can be removed.
Andrew Trickcc359d92011-06-29 23:03:57 +00001016 IRBuilder<> Builder(NarrowDefUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001017 Value *Trunc = Builder.CreateTrunc(WideDef, NarrowDef->getType());
Andrew Trickf85092c2011-05-20 18:25:42 +00001018 NarrowUse->replaceUsesOfWith(NarrowDef, Trunc);
1019 return 0;
1020 }
Andrew Trick4b029152011-07-02 02:34:25 +00001021 // We assume that block terminators are not SCEVable. We wouldn't want to
1022 // insert a Trunc after a terminator if there happens to be a critical edge.
Andrew Trickcc359d92011-06-29 23:03:57 +00001023 assert(NarrowUse != NarrowUse->getParent()->getTerminator() &&
Andrew Trick4b029152011-07-02 02:34:25 +00001024 "SCEV is not expected to evaluate a block terminator");
Andrew Trickcc359d92011-06-29 23:03:57 +00001025
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001026 // Reuse the IV increment that SCEVExpander created as long as it dominates
1027 // NarrowUse.
Andrew Trickf85092c2011-05-20 18:25:42 +00001028 Instruction *WideUse = 0;
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001029 if (WideAddRec == WideIncExpr && HoistStep(WideInc, NarrowUse, DT)) {
Andrew Trickf85092c2011-05-20 18:25:42 +00001030 WideUse = WideInc;
1031 }
1032 else {
1033 WideUse = CloneIVUser(NarrowUse, NarrowDef, WideDef);
1034 if (!WideUse)
1035 return 0;
1036 }
Andrew Trick4b029152011-07-02 02:34:25 +00001037 // Evaluation of WideAddRec ensured that the narrow expression could be
1038 // extended outside the loop without overflow. This suggests that the wide use
Andrew Trickf85092c2011-05-20 18:25:42 +00001039 // evaluates to the same expression as the extended narrow use, but doesn't
1040 // absolutely guarantee it. Hence the following failsafe check. In rare cases
Andrew Trick2fabd462011-06-21 03:22:38 +00001041 // where it fails, we simply throw away the newly created wide use.
Andrew Trickf85092c2011-05-20 18:25:42 +00001042 if (WideAddRec != SE->getSCEV(WideUse)) {
1043 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
1044 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
1045 DeadInsts.push_back(WideUse);
1046 return 0;
1047 }
1048
1049 // Returning WideUse pushes it on the worklist.
1050 return WideUse;
1051}
1052
Andrew Trick4b029152011-07-02 02:34:25 +00001053/// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers.
1054///
1055void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1056 for (Value::use_iterator UI = NarrowDef->use_begin(),
1057 UE = NarrowDef->use_end(); UI != UE; ++UI) {
1058 Use &U = UI.getUse();
1059
1060 // Handle data flow merges and bizarre phi cycles.
1061 if (!Widened.insert(cast<Instruction>(U.getUser())))
1062 continue;
1063
1064 NarrowIVUsers.push_back(std::make_pair(&UI.getUse(), WideDef));
1065 }
1066}
1067
Andrew Trickf85092c2011-05-20 18:25:42 +00001068/// CreateWideIV - Process a single induction variable. First use the
1069/// SCEVExpander to create a wide induction variable that evaluates to the same
1070/// recurrence as the original narrow IV. Then use a worklist to forward
Andrew Trick2fabd462011-06-21 03:22:38 +00001071/// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
Andrew Trickf85092c2011-05-20 18:25:42 +00001072/// interesting IV users, the narrow IV will be isolated for removal by
1073/// DeleteDeadPHIs.
1074///
1075/// It would be simpler to delete uses as they are processed, but we must avoid
1076/// invalidating SCEV expressions.
1077///
Andrew Trick2fabd462011-06-21 03:22:38 +00001078PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
Andrew Trickf85092c2011-05-20 18:25:42 +00001079 // Is this phi an induction variable?
1080 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1081 if (!AddRec)
Andrew Trick2fabd462011-06-21 03:22:38 +00001082 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +00001083
1084 // Widen the induction variable expression.
1085 const SCEV *WideIVExpr = IsSigned ?
1086 SE->getSignExtendExpr(AddRec, WideType) :
1087 SE->getZeroExtendExpr(AddRec, WideType);
1088
1089 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1090 "Expect the new IV expression to preserve its type");
1091
1092 // Can the IV be extended outside the loop without overflow?
1093 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1094 if (!AddRec || AddRec->getLoop() != L)
Andrew Trick2fabd462011-06-21 03:22:38 +00001095 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +00001096
Andrew Trick2fabd462011-06-21 03:22:38 +00001097 // An AddRec must have loop-invariant operands. Since this AddRec is
Andrew Trickf85092c2011-05-20 18:25:42 +00001098 // materialized by a loop header phi, the expression cannot have any post-loop
1099 // operands, so they must dominate the loop header.
1100 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1101 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
1102 && "Loop header phi recurrence inputs do not dominate the loop");
1103
1104 // The rewriter provides a value for the desired IV expression. This may
1105 // either find an existing phi or materialize a new one. Either way, we
1106 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1107 // of the phi-SCC dominates the loop entry.
1108 Instruction *InsertPt = L->getHeader()->begin();
1109 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
1110
1111 // Remembering the WideIV increment generated by SCEVExpander allows
1112 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
1113 // employ a general reuse mechanism because the call above is the only call to
1114 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001115 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1116 WideInc =
1117 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1118 WideIncExpr = SE->getSCEV(WideInc);
1119 }
Andrew Trickf85092c2011-05-20 18:25:42 +00001120
1121 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1122 ++NumWidened;
1123
1124 // Traverse the def-use chain using a worklist starting at the original IV.
Andrew Trick4b029152011-07-02 02:34:25 +00001125 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
Andrew Trickf85092c2011-05-20 18:25:42 +00001126
Andrew Trick4b029152011-07-02 02:34:25 +00001127 Widened.insert(OrigPhi);
1128 pushNarrowIVUsers(OrigPhi, WidePhi);
1129
Andrew Trickf85092c2011-05-20 18:25:42 +00001130 while (!NarrowIVUsers.empty()) {
Andrew Trickcc359d92011-06-29 23:03:57 +00001131 Use *UsePtr;
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001132 Instruction *WideDef;
Andrew Trickcc359d92011-06-29 23:03:57 +00001133 tie(UsePtr, WideDef) = NarrowIVUsers.pop_back_val();
1134 Use &NarrowDefUse = *UsePtr;
Andrew Trickf85092c2011-05-20 18:25:42 +00001135
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001136 // Process a def-use edge. This may replace the use, so don't hold a
1137 // use_iterator across it.
Andrew Trickcc359d92011-06-29 23:03:57 +00001138 Instruction *NarrowDef = cast<Instruction>(NarrowDefUse.get());
1139 Instruction *WideUse = WidenIVUse(NarrowDefUse, NarrowDef, WideDef);
Andrew Trickf85092c2011-05-20 18:25:42 +00001140
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001141 // Follow all def-use edges from the previous narrow use.
Andrew Trick4b029152011-07-02 02:34:25 +00001142 if (WideUse)
1143 pushNarrowIVUsers(cast<Instruction>(NarrowDefUse.getUser()), WideUse);
1144
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001145 // WidenIVUse may have removed the def-use edge.
1146 if (NarrowDef->use_empty())
1147 DeadInsts.push_back(NarrowDef);
Andrew Trickf85092c2011-05-20 18:25:42 +00001148 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001149 return WidePhi;
Andrew Trickf85092c2011-05-20 18:25:42 +00001150}
1151
Andrew Trick1a54bb22011-07-12 00:08:50 +00001152//===----------------------------------------------------------------------===//
1153// Simplification of IV users based on SCEV evaluation.
1154//===----------------------------------------------------------------------===//
1155
Andrew Trickaeee4612011-05-12 00:04:28 +00001156void IndVarSimplify::EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
1157 unsigned IVOperIdx = 0;
1158 ICmpInst::Predicate Pred = ICmp->getPredicate();
1159 if (IVOperand != ICmp->getOperand(0)) {
1160 // Swapped
1161 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
1162 IVOperIdx = 1;
1163 Pred = ICmpInst::getSwappedPredicate(Pred);
Dan Gohmana590b792010-04-13 01:46:36 +00001164 }
Andrew Trickaeee4612011-05-12 00:04:28 +00001165
1166 // Get the SCEVs for the ICmp operands.
1167 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
1168 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
1169
1170 // Simplify unnecessary loops away.
1171 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
1172 S = SE->getSCEVAtScope(S, ICmpLoop);
1173 X = SE->getSCEVAtScope(X, ICmpLoop);
1174
1175 // If the condition is always true or always false, replace it with
1176 // a constant value.
1177 if (SE->isKnownPredicate(Pred, S, X))
1178 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
1179 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
1180 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
1181 else
1182 return;
1183
1184 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001185 ++NumElimCmp;
Andrew Trick074397d2011-05-20 03:37:48 +00001186 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +00001187 DeadInsts.push_back(ICmp);
1188}
1189
1190void IndVarSimplify::EliminateIVRemainder(BinaryOperator *Rem,
1191 Value *IVOperand,
Andrew Trick4417e532011-06-21 15:43:52 +00001192 bool IsSigned) {
Andrew Trickaeee4612011-05-12 00:04:28 +00001193 // We're only interested in the case where we know something about
1194 // the numerator.
1195 if (IVOperand != Rem->getOperand(0))
1196 return;
1197
1198 // Get the SCEVs for the ICmp operands.
1199 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
1200 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
1201
1202 // Simplify unnecessary loops away.
1203 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
1204 S = SE->getSCEVAtScope(S, ICmpLoop);
1205 X = SE->getSCEVAtScope(X, ICmpLoop);
1206
1207 // i % n --> i if i is in [0,n).
Andrew Trick074397d2011-05-20 03:37:48 +00001208 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
1209 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Andrew Trickaeee4612011-05-12 00:04:28 +00001210 S, X))
1211 Rem->replaceAllUsesWith(Rem->getOperand(0));
1212 else {
1213 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
1214 const SCEV *LessOne =
1215 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
Andrew Trick074397d2011-05-20 03:37:48 +00001216 if (IsSigned && !SE->isKnownNonNegative(LessOne))
Andrew Trickaeee4612011-05-12 00:04:28 +00001217 return;
1218
Andrew Trick074397d2011-05-20 03:37:48 +00001219 if (!SE->isKnownPredicate(IsSigned ?
Andrew Trickaeee4612011-05-12 00:04:28 +00001220 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1221 LessOne, X))
1222 return;
1223
1224 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
1225 Rem->getOperand(0), Rem->getOperand(1),
1226 "tmp");
1227 SelectInst *Sel =
1228 SelectInst::Create(ICmp,
1229 ConstantInt::get(Rem->getType(), 0),
1230 Rem->getOperand(0), "tmp", Rem);
1231 Rem->replaceAllUsesWith(Sel);
1232 }
1233
1234 // Inform IVUsers about the new users.
Andrew Trick2fabd462011-06-21 03:22:38 +00001235 if (IU) {
1236 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
Andrew Trick4417e532011-06-21 15:43:52 +00001237 IU->AddUsersIfInteresting(I);
Andrew Trick2fabd462011-06-21 03:22:38 +00001238 }
Andrew Trickaeee4612011-05-12 00:04:28 +00001239 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001240 ++NumElimRem;
Andrew Trick074397d2011-05-20 03:37:48 +00001241 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +00001242 DeadInsts.push_back(Rem);
Dan Gohmana590b792010-04-13 01:46:36 +00001243}
1244
Andrew Trick2fabd462011-06-21 03:22:38 +00001245/// EliminateIVUser - Eliminate an operation that consumes a simple IV and has
1246/// no observable side-effect given the range of IV values.
1247bool IndVarSimplify::EliminateIVUser(Instruction *UseInst,
1248 Instruction *IVOperand) {
1249 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
1250 EliminateIVComparison(ICmp, IVOperand);
1251 return true;
1252 }
1253 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
1254 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
1255 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
Andrew Trick4417e532011-06-21 15:43:52 +00001256 EliminateIVRemainder(Rem, IVOperand, IsSigned);
Andrew Trick2fabd462011-06-21 03:22:38 +00001257 return true;
1258 }
1259 }
1260
1261 // Eliminate any operation that SCEV can prove is an identity function.
1262 if (!SE->isSCEVable(UseInst->getType()) ||
Andrew Trick11745d42011-06-29 03:13:40 +00001263 (UseInst->getType() != IVOperand->getType()) ||
Andrew Trick2fabd462011-06-21 03:22:38 +00001264 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
1265 return false;
1266
Andrew Trick2fabd462011-06-21 03:22:38 +00001267 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
Andrew Trick60ac7192011-06-30 01:27:23 +00001268
1269 UseInst->replaceAllUsesWith(IVOperand);
Andrew Trick2fabd462011-06-21 03:22:38 +00001270 ++NumElimIdentity;
1271 Changed = true;
1272 DeadInsts.push_back(UseInst);
1273 return true;
1274}
1275
1276/// pushIVUsers - Add all uses of Def to the current IV's worklist.
1277///
Andrew Trick15832f62011-06-28 02:49:20 +00001278static void pushIVUsers(
1279 Instruction *Def,
1280 SmallPtrSet<Instruction*,16> &Simplified,
1281 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
Andrew Trick2fabd462011-06-21 03:22:38 +00001282
1283 for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
1284 UI != E; ++UI) {
1285 Instruction *User = cast<Instruction>(*UI);
1286
1287 // Avoid infinite or exponential worklist processing.
1288 // Also ensure unique worklist users.
Andrew Trick60ac7192011-06-30 01:27:23 +00001289 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
1290 // self edges first.
1291 if (User != Def && Simplified.insert(User))
Andrew Trick2fabd462011-06-21 03:22:38 +00001292 SimpleIVUsers.push_back(std::make_pair(User, Def));
1293 }
1294}
1295
1296/// isSimpleIVUser - Return true if this instruction generates a simple SCEV
1297/// expression in terms of that IV.
1298///
1299/// This is similar to IVUsers' isInsteresting() but processes each instruction
1300/// non-recursively when the operand is already known to be a simpleIVUser.
1301///
Andrew Trick1a54bb22011-07-12 00:08:50 +00001302static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
Andrew Trick2fabd462011-06-21 03:22:38 +00001303 if (!SE->isSCEVable(I->getType()))
1304 return false;
1305
1306 // Get the symbolic expression for this instruction.
1307 const SCEV *S = SE->getSCEV(I);
1308
Andrew Trickcc359d92011-06-29 23:03:57 +00001309 // We assume that terminators are not SCEVable.
1310 assert((!S || I != I->getParent()->getTerminator()) &&
1311 "can't fold terminators");
1312
Andrew Trick2fabd462011-06-21 03:22:38 +00001313 // Only consider affine recurrences.
1314 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
1315 if (AR && AR->getLoop() == L)
1316 return true;
1317
1318 return false;
1319}
1320
1321/// SimplifyIVUsersNoRewrite - Iteratively perform simplification on a worklist
1322/// of IV users. Each successive simplification may push more users which may
1323/// themselves be candidates for simplification.
1324///
1325/// The "NoRewrite" algorithm does not require IVUsers analysis. Instead, it
1326/// simplifies instructions in-place during analysis. Rather than rewriting
1327/// induction variables bottom-up from their users, it transforms a chain of
1328/// IVUsers top-down, updating the IR only when it encouters a clear
1329/// optimization opportunitiy. A SCEVExpander "Rewriter" instance is still
1330/// needed, but only used to generate a new IV (phi) of wider type for sign/zero
1331/// extend elimination.
1332///
1333/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
1334///
1335void IndVarSimplify::SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter) {
Andrew Trick15832f62011-06-28 02:49:20 +00001336 std::map<PHINode *, WideIVInfo> WideIVMap;
1337
Andrew Trick2fabd462011-06-21 03:22:38 +00001338 SmallVector<PHINode*, 8> LoopPhis;
1339 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1340 LoopPhis.push_back(cast<PHINode>(I));
1341 }
Andrew Trick15832f62011-06-28 02:49:20 +00001342 // Each round of simplification iterates through the SimplifyIVUsers worklist
1343 // for all current phis, then determines whether any IVs can be
1344 // widened. Widening adds new phis to LoopPhis, inducing another round of
1345 // simplification on the wide IVs.
Andrew Trick2fabd462011-06-21 03:22:38 +00001346 while (!LoopPhis.empty()) {
Andrew Trick15832f62011-06-28 02:49:20 +00001347 // Evaluate as many IV expressions as possible before widening any IVs. This
Andrew Trick99a92f62011-06-28 16:45:04 +00001348 // forces SCEV to set no-wrap flags before evaluating sign/zero
Andrew Trick15832f62011-06-28 02:49:20 +00001349 // extension. The first time SCEV attempts to normalize sign/zero extension,
1350 // the result becomes final. So for the most predictable results, we delay
1351 // evaluation of sign/zero extend evaluation until needed, and avoid running
1352 // other SCEV based analysis prior to SimplifyIVUsersNoRewrite.
1353 do {
1354 PHINode *CurrIV = LoopPhis.pop_back_val();
Andrew Trick2fabd462011-06-21 03:22:38 +00001355
Andrew Trick15832f62011-06-28 02:49:20 +00001356 // Information about sign/zero extensions of CurrIV.
1357 WideIVInfo WI;
Andrew Trick2fabd462011-06-21 03:22:38 +00001358
Andrew Trick15832f62011-06-28 02:49:20 +00001359 // Instructions processed by SimplifyIVUsers for CurrIV.
1360 SmallPtrSet<Instruction*,16> Simplified;
Andrew Trick2fabd462011-06-21 03:22:38 +00001361
Andrew Trick037d1c02011-07-06 20:50:43 +00001362 // Use-def pairs if IV users waiting to be processed for CurrIV.
Andrew Trick15832f62011-06-28 02:49:20 +00001363 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
Andrew Trick2fabd462011-06-21 03:22:38 +00001364
Andrew Trick60ac7192011-06-30 01:27:23 +00001365 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
1366 // called multiple times for the same LoopPhi. This is the proper thing to
1367 // do for loop header phis that use each other.
Andrew Trick15832f62011-06-28 02:49:20 +00001368 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
1369
1370 while (!SimpleIVUsers.empty()) {
1371 Instruction *UseInst, *Operand;
1372 tie(UseInst, Operand) = SimpleIVUsers.pop_back_val();
Andrew Trick6e0ce242011-06-30 19:02:17 +00001373 // Bypass back edges to avoid extra work.
1374 if (UseInst == CurrIV) continue;
Andrew Trick15832f62011-06-28 02:49:20 +00001375
1376 if (EliminateIVUser(UseInst, Operand)) {
1377 pushIVUsers(Operand, Simplified, SimpleIVUsers);
1378 continue;
Andrew Trick2fabd462011-06-21 03:22:38 +00001379 }
Andrew Trick15832f62011-06-28 02:49:20 +00001380 if (CastInst *Cast = dyn_cast<CastInst>(UseInst)) {
1381 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
1382 if (IsSigned || Cast->getOpcode() == Instruction::ZExt) {
1383 CollectExtend(Cast, IsSigned, WI, SE, TD);
1384 }
1385 continue;
1386 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001387 if (isSimpleIVUser(UseInst, L, SE)) {
Andrew Trick15832f62011-06-28 02:49:20 +00001388 pushIVUsers(UseInst, Simplified, SimpleIVUsers);
1389 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001390 }
Andrew Trick15832f62011-06-28 02:49:20 +00001391 if (WI.WidestNativeType) {
1392 WideIVMap[CurrIV] = WI;
Andrew Trick2fabd462011-06-21 03:22:38 +00001393 }
Andrew Trick15832f62011-06-28 02:49:20 +00001394 } while(!LoopPhis.empty());
1395
1396 for (std::map<PHINode *, WideIVInfo>::const_iterator I = WideIVMap.begin(),
1397 E = WideIVMap.end(); I != E; ++I) {
1398 WidenIV Widener(I->first, I->second, LI, SE, DT, DeadInsts);
Andrew Trick2fabd462011-06-21 03:22:38 +00001399 if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
1400 Changed = true;
1401 LoopPhis.push_back(WidePhi);
1402 }
1403 }
Andrew Trick15832f62011-06-28 02:49:20 +00001404 WideIVMap.clear();
Andrew Trick2fabd462011-06-21 03:22:38 +00001405 }
1406}
1407
Andrew Trick037d1c02011-07-06 20:50:43 +00001408/// SimplifyCongruentIVs - Check for congruent phis in this loop header and
1409/// populate ExprToIVMap for use later.
1410///
1411void IndVarSimplify::SimplifyCongruentIVs(Loop *L) {
1412 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1413 PHINode *Phi = cast<PHINode>(I);
Andrew Trick1a54bb22011-07-12 00:08:50 +00001414 if (!SE->isSCEVable(Phi->getType()))
1415 continue;
1416
Andrew Trick037d1c02011-07-06 20:50:43 +00001417 const SCEV *S = SE->getSCEV(Phi);
1418 ExprToIVMapTy::const_iterator Pos;
1419 bool Inserted;
1420 tie(Pos, Inserted) = ExprToIVMap.insert(std::make_pair(S, Phi));
1421 if (Inserted)
1422 continue;
1423 PHINode *OrigPhi = Pos->second;
1424 // Replacing the congruent phi is sufficient because acyclic redundancy
1425 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1426 // that a phi is congruent, it's almost certain to be the head of an IV
1427 // user cycle that is isomorphic with the original phi. So it's worth
1428 // eagerly cleaning up the common case of a single IV increment.
1429 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1430 Instruction *OrigInc =
1431 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1432 Instruction *IsomorphicInc =
1433 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1434 if (OrigInc != IsomorphicInc &&
1435 SE->getSCEV(OrigInc) == SE->getSCEV(IsomorphicInc) &&
1436 HoistStep(OrigInc, IsomorphicInc, DT)) {
1437 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1438 << *IsomorphicInc << '\n');
1439 IsomorphicInc->replaceAllUsesWith(OrigInc);
1440 DeadInsts.push_back(IsomorphicInc);
1441 }
1442 }
1443 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1444 ++NumElimIV;
1445 Phi->replaceAllUsesWith(OrigPhi);
1446 DeadInsts.push_back(Phi);
1447 }
1448}
1449
Andrew Trick1a54bb22011-07-12 00:08:50 +00001450//===----------------------------------------------------------------------===//
1451// LinearFunctionTestReplace and its kin. Rewrite the loop exit condition.
1452//===----------------------------------------------------------------------===//
1453
1454/// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
1455/// count expression can be safely and cheaply expanded into an instruction
1456/// sequence that can be used by LinearFunctionTestReplace.
1457static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) {
1458 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1459 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1460 BackedgeTakenCount->isZero())
1461 return false;
1462
1463 if (!L->getExitingBlock())
1464 return false;
1465
1466 // Can't rewrite non-branch yet.
1467 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1468 if (!BI)
1469 return false;
1470
1471 // Special case: If the backedge-taken count is a UDiv, it's very likely a
1472 // UDiv that ScalarEvolution produced in order to compute a precise
1473 // expression, rather than a UDiv from the user's code. If we can't find a
1474 // UDiv in the code with some simple searching, assume the former and forego
1475 // rewriting the loop.
1476 if (isa<SCEVUDivExpr>(BackedgeTakenCount)) {
1477 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
1478 if (!OrigCond) return false;
1479 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
1480 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
1481 if (R != BackedgeTakenCount) {
1482 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
1483 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
1484 if (L != BackedgeTakenCount)
1485 return false;
1486 }
1487 }
1488 return true;
1489}
1490
1491/// getBackedgeIVType - Get the widest type used by the loop test after peeking
1492/// through Truncs.
1493///
1494/// TODO: Unnecessary if LFTR does not force a canonical IV.
1495static const Type *getBackedgeIVType(Loop *L) {
1496 if (!L->getExitingBlock())
1497 return 0;
1498
1499 // Can't rewrite non-branch yet.
1500 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1501 if (!BI)
1502 return 0;
1503
1504 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1505 if (!Cond)
1506 return 0;
1507
1508 const Type *Ty = 0;
1509 for(User::op_iterator OI = Cond->op_begin(), OE = Cond->op_end();
1510 OI != OE; ++OI) {
1511 assert((!Ty || Ty == (*OI)->getType()) && "bad icmp operand types");
1512 TruncInst *Trunc = dyn_cast<TruncInst>(*OI);
1513 if (!Trunc)
1514 continue;
1515
1516 return Trunc->getSrcTy();
1517 }
1518 return Ty;
1519}
1520
1521/// LinearFunctionTestReplace - This method rewrites the exit condition of the
1522/// loop to be a canonical != comparison against the incremented loop induction
1523/// variable. This pass is able to rewrite the exit tests of any loop where the
1524/// SCEV analysis can determine a loop-invariant trip count of the loop, which
1525/// is actually a much broader range than just linear tests.
1526ICmpInst *IndVarSimplify::
1527LinearFunctionTestReplace(Loop *L,
1528 const SCEV *BackedgeTakenCount,
1529 PHINode *IndVar,
1530 SCEVExpander &Rewriter) {
1531 assert(canExpandBackedgeTakenCount(L, SE) && "precondition");
1532 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1533
1534 // If the exiting block is not the same as the backedge block, we must compare
1535 // against the preincremented value, otherwise we prefer to compare against
1536 // the post-incremented value.
1537 Value *CmpIndVar;
1538 const SCEV *RHS = BackedgeTakenCount;
1539 if (L->getExitingBlock() == L->getLoopLatch()) {
1540 // Add one to the "backedge-taken" count to get the trip count.
1541 // If this addition may overflow, we have to be more pessimistic and
1542 // cast the induction variable before doing the add.
1543 const SCEV *Zero = SE->getConstant(BackedgeTakenCount->getType(), 0);
1544 const SCEV *N =
1545 SE->getAddExpr(BackedgeTakenCount,
1546 SE->getConstant(BackedgeTakenCount->getType(), 1));
1547 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
1548 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
1549 // No overflow. Cast the sum.
1550 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
1551 } else {
1552 // Potential overflow. Cast before doing the add.
1553 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
1554 IndVar->getType());
1555 RHS = SE->getAddExpr(RHS,
1556 SE->getConstant(IndVar->getType(), 1));
1557 }
1558
1559 // The BackedgeTaken expression contains the number of times that the
1560 // backedge branches to the loop header. This is one less than the
1561 // number of times the loop executes, so use the incremented indvar.
1562 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
1563 } else {
1564 // We have to use the preincremented value...
1565 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
1566 IndVar->getType());
1567 CmpIndVar = IndVar;
1568 }
1569
1570 // Expand the code for the iteration count.
1571 assert(SE->isLoopInvariant(RHS, L) &&
1572 "Computed iteration count is not loop invariant!");
1573 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
1574
1575 // Insert a new icmp_ne or icmp_eq instruction before the branch.
1576 ICmpInst::Predicate Opcode;
1577 if (L->contains(BI->getSuccessor(0)))
1578 Opcode = ICmpInst::ICMP_NE;
1579 else
1580 Opcode = ICmpInst::ICMP_EQ;
1581
1582 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
1583 << " LHS:" << *CmpIndVar << '\n'
1584 << " op:\t"
1585 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
1586 << " RHS:\t" << *RHS << "\n");
1587
1588 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
1589 Cond->setDebugLoc(BI->getDebugLoc());
1590 Value *OrigCond = BI->getCondition();
1591 // It's tempting to use replaceAllUsesWith here to fully replace the old
1592 // comparison, but that's not immediately safe, since users of the old
1593 // comparison may not be dominated by the new comparison. Instead, just
1594 // update the branch to use the new comparison; in the common case this
1595 // will make old comparison dead.
1596 BI->setCondition(Cond);
1597 DeadInsts.push_back(OrigCond);
1598
1599 ++NumLFTR;
1600 Changed = true;
1601 return Cond;
1602}
1603
1604//===----------------------------------------------------------------------===//
1605// SinkUnusedInvariants. A late subpass to cleanup loop preheaders.
1606//===----------------------------------------------------------------------===//
1607
1608/// If there's a single exit block, sink any loop-invariant values that
1609/// were defined in the preheader but not used inside the loop into the
1610/// exit block to reduce register pressure in the loop.
1611void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
1612 BasicBlock *ExitBlock = L->getExitBlock();
1613 if (!ExitBlock) return;
1614
1615 BasicBlock *Preheader = L->getLoopPreheader();
1616 if (!Preheader) return;
1617
1618 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
1619 BasicBlock::iterator I = Preheader->getTerminator();
1620 while (I != Preheader->begin()) {
1621 --I;
1622 // New instructions were inserted at the end of the preheader.
1623 if (isa<PHINode>(I))
1624 break;
1625
1626 // Don't move instructions which might have side effects, since the side
1627 // effects need to complete before instructions inside the loop. Also don't
1628 // move instructions which might read memory, since the loop may modify
1629 // memory. Note that it's okay if the instruction might have undefined
1630 // behavior: LoopSimplify guarantees that the preheader dominates the exit
1631 // block.
1632 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
1633 continue;
1634
1635 // Skip debug info intrinsics.
1636 if (isa<DbgInfoIntrinsic>(I))
1637 continue;
1638
1639 // Don't sink static AllocaInsts out of the entry block, which would
1640 // turn them into dynamic allocas!
1641 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
1642 if (AI->isStaticAlloca())
1643 continue;
1644
1645 // Determine if there is a use in or before the loop (direct or
1646 // otherwise).
1647 bool UsedInLoop = false;
1648 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1649 UI != UE; ++UI) {
1650 User *U = *UI;
1651 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
1652 if (PHINode *P = dyn_cast<PHINode>(U)) {
1653 unsigned i =
1654 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
1655 UseBB = P->getIncomingBlock(i);
1656 }
1657 if (UseBB == Preheader || L->contains(UseBB)) {
1658 UsedInLoop = true;
1659 break;
1660 }
1661 }
1662
1663 // If there is, the def must remain in the preheader.
1664 if (UsedInLoop)
1665 continue;
1666
1667 // Otherwise, sink it to the exit block.
1668 Instruction *ToMove = I;
1669 bool Done = false;
1670
1671 if (I != Preheader->begin()) {
1672 // Skip debug info intrinsics.
1673 do {
1674 --I;
1675 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
1676
1677 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
1678 Done = true;
1679 } else {
1680 Done = true;
1681 }
1682
1683 ToMove->moveBefore(InsertPt);
1684 if (Done) break;
1685 InsertPt = ToMove;
1686 }
1687}
1688
1689//===----------------------------------------------------------------------===//
1690// IndVarSimplify driver. Manage several subpasses of IV simplification.
1691//===----------------------------------------------------------------------===//
1692
Dan Gohmanc2390b12009-02-12 22:19:27 +00001693bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmana5283822010-06-18 01:35:11 +00001694 // If LoopSimplify form is not available, stay out of trouble. Some notes:
1695 // - LSR currently only supports LoopSimplify-form loops. Indvars'
1696 // canonicalization can be a pessimization without LSR to "clean up"
1697 // afterwards.
1698 // - We depend on having a preheader; in particular,
1699 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
1700 // and we're in trouble if we can't find the induction variable even when
1701 // we've manually inserted one.
1702 if (!L->isLoopSimplifyForm())
1703 return false;
1704
Andrew Trick2fabd462011-06-21 03:22:38 +00001705 if (!DisableIVRewrite)
1706 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +00001707 LI = &getAnalysis<LoopInfo>();
1708 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +00001709 DT = &getAnalysis<DominatorTree>();
Andrew Trick37da4082011-05-04 02:10:13 +00001710 TD = getAnalysisIfAvailable<TargetData>();
1711
Andrew Trick037d1c02011-07-06 20:50:43 +00001712 ExprToIVMap.clear();
Andrew Trickb12a7542011-03-17 23:51:11 +00001713 DeadInsts.clear();
Devang Patel5ee99972007-03-07 06:39:01 +00001714 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +00001715
Dan Gohman2d1be872009-04-16 03:18:22 +00001716 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +00001717 // transform them to use integer recurrences.
1718 RewriteNonIntegerIVs(L);
1719
Dan Gohman0bba49c2009-07-07 17:06:11 +00001720 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +00001721
Dan Gohman667d7872009-06-26 22:53:46 +00001722 // Create a rewriter object which we'll use to transform the code with.
Andrew Trick5e7645b2011-06-28 05:07:32 +00001723 SCEVExpander Rewriter(*SE, "indvars");
Andrew Trick156d4602011-06-27 23:17:44 +00001724
1725 // Eliminate redundant IV users.
Andrew Trick15832f62011-06-28 02:49:20 +00001726 //
1727 // Simplification works best when run before other consumers of SCEV. We
1728 // attempt to avoid evaluating SCEVs for sign/zero extend operations until
1729 // other expressions involving loop IVs have been evaluated. This helps SCEV
Andrew Trick99a92f62011-06-28 16:45:04 +00001730 // set no-wrap flags before normalizing sign/zero extension.
Andrew Trick156d4602011-06-27 23:17:44 +00001731 if (DisableIVRewrite) {
Andrew Trick37da4082011-05-04 02:10:13 +00001732 Rewriter.disableCanonicalMode();
Andrew Trick156d4602011-06-27 23:17:44 +00001733 SimplifyIVUsersNoRewrite(L, Rewriter);
1734 }
Andrew Trick37da4082011-05-04 02:10:13 +00001735
Chris Lattner40bf8b42004-04-02 20:24:31 +00001736 // Check to see if this loop has a computable loop-invariant execution count.
1737 // If so, this means that we can compute the final value of any expressions
1738 // that are recurrent in the loop, and substitute the exit values from the
1739 // loop into any instructions outside of the loop that use the final values of
1740 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +00001741 //
Dan Gohman46bdfb02009-02-24 18:55:53 +00001742 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman454d26d2010-02-22 04:11:59 +00001743 RewriteLoopExitValues(L, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +00001744
Andrew Trickf85092c2011-05-20 18:25:42 +00001745 // Eliminate redundant IV users.
Andrew Trick156d4602011-06-27 23:17:44 +00001746 if (!DisableIVRewrite)
Andrew Trick2fabd462011-06-21 03:22:38 +00001747 SimplifyIVUsers(Rewriter);
Dan Gohmana590b792010-04-13 01:46:36 +00001748
Andrew Trick037d1c02011-07-06 20:50:43 +00001749 // Eliminate redundant IV cycles and populate ExprToIVMap.
1750 // TODO: use ExprToIVMap to allow LFTR without canonical IVs
1751 if (DisableIVRewrite)
1752 SimplifyCongruentIVs(L);
1753
Dan Gohman81db61a2009-05-12 02:17:14 +00001754 // Compute the type of the largest recurrence expression, and decide whether
1755 // a canonical induction variable should be inserted.
Andrew Trickf85092c2011-05-20 18:25:42 +00001756 const Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00001757 bool NeedCannIV = false;
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001758 bool ExpandBECount = canExpandBackedgeTakenCount(L, SE);
Andrew Trick4dfdf242011-05-03 22:24:10 +00001759 if (ExpandBECount) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001760 // If we have a known trip count and a single exit block, we'll be
1761 // rewriting the loop exit test condition below, which requires a
1762 // canonical induction variable.
Andrew Trick4dfdf242011-05-03 22:24:10 +00001763 NeedCannIV = true;
1764 const Type *Ty = BackedgeTakenCount->getType();
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001765 if (DisableIVRewrite) {
1766 // In this mode, SimplifyIVUsers may have already widened the IV used by
1767 // the backedge test and inserted a Trunc on the compare's operand. Get
1768 // the wider type to avoid creating a redundant narrow IV only used by the
1769 // loop test.
1770 LargestType = getBackedgeIVType(L);
1771 }
Andrew Trick4dfdf242011-05-03 22:24:10 +00001772 if (!LargestType ||
1773 SE->getTypeSizeInBits(Ty) >
1774 SE->getTypeSizeInBits(LargestType))
1775 LargestType = SE->getEffectiveSCEVType(Ty);
Chris Lattnerf50af082004-04-17 18:08:33 +00001776 }
Andrew Trick37da4082011-05-04 02:10:13 +00001777 if (!DisableIVRewrite) {
1778 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
1779 NeedCannIV = true;
1780 const Type *Ty =
1781 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
1782 if (!LargestType ||
1783 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001784 SE->getTypeSizeInBits(LargestType))
Andrew Trick37da4082011-05-04 02:10:13 +00001785 LargestType = Ty;
1786 }
Chris Lattner6148c022001-12-03 17:28:42 +00001787 }
1788
Dan Gohmanf451cb82010-02-10 16:03:48 +00001789 // Now that we know the largest of the induction variable expressions
Dan Gohman81db61a2009-05-12 02:17:14 +00001790 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohman43ef3fb2010-07-20 17:18:52 +00001791 PHINode *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00001792 if (NeedCannIV) {
Dan Gohman85669632010-02-25 06:57:05 +00001793 // Check to see if the loop already has any canonical-looking induction
1794 // variables. If any are present and wider than the planned canonical
1795 // induction variable, temporarily remove them, so that the Rewriter
1796 // doesn't attempt to reuse them.
1797 SmallVector<PHINode *, 2> OldCannIVs;
1798 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
Dan Gohman4d8414f2009-06-13 16:25:49 +00001799 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
1800 SE->getTypeSizeInBits(LargestType))
1801 OldCannIV->removeFromParent();
1802 else
Dan Gohman85669632010-02-25 06:57:05 +00001803 break;
1804 OldCannIVs.push_back(OldCannIV);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001805 }
1806
Dan Gohman667d7872009-06-26 22:53:46 +00001807 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001808
Dan Gohmanc2390b12009-02-12 22:19:27 +00001809 ++NumInserted;
1810 Changed = true;
David Greenef67ef312010-01-05 01:27:06 +00001811 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +00001812
1813 // Now that the official induction variable is established, reinsert
Dan Gohman85669632010-02-25 06:57:05 +00001814 // any old canonical-looking variables after it so that the IR remains
1815 // consistent. They will be deleted as part of the dead-PHI deletion at
Dan Gohman4d8414f2009-06-13 16:25:49 +00001816 // the end of the pass.
Dan Gohman85669632010-02-25 06:57:05 +00001817 while (!OldCannIVs.empty()) {
1818 PHINode *OldCannIV = OldCannIVs.pop_back_val();
1819 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
1820 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001821 }
Chris Lattner15cad752003-12-23 07:47:09 +00001822
Dan Gohmanc2390b12009-02-12 22:19:27 +00001823 // If we have a trip count expression, rewrite the loop's exit condition
1824 // using it. We can currently only handle loops with a single exit.
Dan Gohman81db61a2009-05-12 02:17:14 +00001825 ICmpInst *NewICmp = 0;
Andrew Trick4dfdf242011-05-03 22:24:10 +00001826 if (ExpandBECount) {
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001827 assert(canExpandBackedgeTakenCount(L, SE) &&
Andrew Trick4dfdf242011-05-03 22:24:10 +00001828 "canonical IV disrupted BackedgeTaken expansion");
Dan Gohman81db61a2009-05-12 02:17:14 +00001829 assert(NeedCannIV &&
1830 "LinearFunctionTestReplace requires a canonical induction variable");
Andrew Trick1a54bb22011-07-12 00:08:50 +00001831 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +00001832 }
Andrew Trickb12a7542011-03-17 23:51:11 +00001833 // Rewrite IV-derived expressions.
Andrew Trick37da4082011-05-04 02:10:13 +00001834 if (!DisableIVRewrite)
1835 RewriteIVExpressions(L, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +00001836
Andrew Trickb12a7542011-03-17 23:51:11 +00001837 // Clear the rewriter cache, because values that are in the rewriter's cache
1838 // can be deleted in the loop below, causing the AssertingVH in the cache to
1839 // trigger.
1840 Rewriter.clear();
Andrew Trick17f91d22011-07-06 21:07:10 +00001841 ExprToIVMap.clear();
Andrew Trickb12a7542011-03-17 23:51:11 +00001842
1843 // Now that we're done iterating through lists, clean up any instructions
1844 // which are now dead.
1845 while (!DeadInsts.empty())
1846 if (Instruction *Inst =
1847 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
1848 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1849
Dan Gohman667d7872009-06-26 22:53:46 +00001850 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +00001851
Dan Gohman81db61a2009-05-12 02:17:14 +00001852 // Loop-invariant instructions in the preheader that aren't used in the
1853 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +00001854 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +00001855
1856 // For completeness, inform IVUsers of the IV use in the newly-created
1857 // loop exit test instruction.
Andrew Trick2fabd462011-06-21 03:22:38 +00001858 if (NewICmp && IU)
Andrew Trick4417e532011-06-21 15:43:52 +00001859 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
Dan Gohman81db61a2009-05-12 02:17:14 +00001860
1861 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +00001862 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +00001863 // Check a post-condition.
Dan Gohmanbbf81d82010-03-10 19:38:49 +00001864 assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +00001865 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +00001866}