blob: cf75448aa27822e5b23b599972406a7a4c09a8c8 [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 {
Dan Gohman81db61a2009-05-12 02:17:14 +000084 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000085 LoopInfo *LI;
86 ScalarEvolution *SE;
Dan Gohmande53dc02009-06-27 05:16:57 +000087 DominatorTree *DT;
Andrew Trick37da4082011-05-04 02:10:13 +000088 TargetData *TD;
Andrew Trick2fabd462011-06-21 03:22:38 +000089
Andrew Trickb12a7542011-03-17 23:51:11 +000090 SmallVector<WeakVH, 16> DeadInsts;
Chris Lattner15cad752003-12-23 07:47:09 +000091 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000092 public:
Devang Patel794fd752007-05-01 21:15:47 +000093
Dan Gohman5668cf72009-07-15 01:26:32 +000094 static char ID; // Pass identification, replacement for typeid
Andrew Trick2fabd462011-06-21 03:22:38 +000095 IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0),
Andrew Trick15832f62011-06-28 02:49:20 +000096 Changed(false) {
Owen Anderson081c34b2010-10-19 17:21:58 +000097 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
98 }
Devang Patel794fd752007-05-01 21:15:47 +000099
Dan Gohman5668cf72009-07-15 01:26:32 +0000100 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman60f8a632009-02-17 20:49:49 +0000101
Dan Gohman5668cf72009-07-15 01:26:32 +0000102 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
103 AU.addRequired<DominatorTree>();
104 AU.addRequired<LoopInfo>();
105 AU.addRequired<ScalarEvolution>();
106 AU.addRequiredID(LoopSimplifyID);
107 AU.addRequiredID(LCSSAID);
Andrew Trick56caa092011-06-28 03:01:46 +0000108 if (!DisableIVRewrite)
109 AU.addRequired<IVUsers>();
Dan Gohman5668cf72009-07-15 01:26:32 +0000110 AU.addPreserved<ScalarEvolution>();
111 AU.addPreservedID(LoopSimplifyID);
112 AU.addPreservedID(LCSSAID);
Andrew Trick2fabd462011-06-21 03:22:38 +0000113 if (!DisableIVRewrite)
114 AU.addPreserved<IVUsers>();
Dan Gohman5668cf72009-07-15 01:26:32 +0000115 AU.setPreservesCFG();
116 }
Chris Lattner15cad752003-12-23 07:47:09 +0000117
Chris Lattner40bf8b42004-04-02 20:24:31 +0000118 private:
Andrew Trick037d1c02011-07-06 20:50:43 +0000119 virtual void releaseMemory() {
Andrew Trick037d1c02011-07-06 20:50:43 +0000120 DeadInsts.clear();
121 }
122
Andrew Trickb12a7542011-03-17 23:51:11 +0000123 bool isValidRewrite(Value *FromVal, Value *ToVal);
Devang Patel5ee99972007-03-07 06:39:01 +0000124
Andrew Trick1a54bb22011-07-12 00:08:50 +0000125 void HandleFloatingPointIV(Loop *L, PHINode *PH);
126 void RewriteNonIntegerIVs(Loop *L);
127
128 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
129
Andrew Trickf85092c2011-05-20 18:25:42 +0000130 void SimplifyIVUsers(SCEVExpander &Rewriter);
Andrew Trick2fabd462011-06-21 03:22:38 +0000131 void SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter);
132
133 bool EliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trickaeee4612011-05-12 00:04:28 +0000134 void EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
135 void EliminateIVRemainder(BinaryOperator *Rem,
136 Value *IVOperand,
Andrew Trick4417e532011-06-21 15:43:52 +0000137 bool IsSigned);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000138
Andrew Trick037d1c02011-07-06 20:50:43 +0000139 void SimplifyCongruentIVs(Loop *L);
140
Dan Gohman454d26d2010-02-22 04:11:59 +0000141 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000142
Andrew Trick56147692011-07-16 01:18:53 +0000143 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
Andrew Trick1a54bb22011-07-12 00:08:50 +0000144 PHINode *IndVar,
145 SCEVExpander &Rewriter);
Dan Gohman81db61a2009-05-12 02:17:14 +0000146
Andrew Trick1a54bb22011-07-12 00:08:50 +0000147 void SinkUnusedInvariants(Loop *L);
Chris Lattner3324e712003-12-22 03:58:44 +0000148 };
Chris Lattner5e761402002-09-10 05:24:05 +0000149}
Chris Lattner394437f2001-12-04 04:32:29 +0000150
Dan Gohman844731a2008-05-13 00:00:25 +0000151char IndVarSimplify::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000152INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000153 "Induction Variable Simplification", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000154INITIALIZE_PASS_DEPENDENCY(DominatorTree)
155INITIALIZE_PASS_DEPENDENCY(LoopInfo)
156INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
157INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
158INITIALIZE_PASS_DEPENDENCY(LCSSA)
159INITIALIZE_PASS_DEPENDENCY(IVUsers)
160INITIALIZE_PASS_END(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000161 "Induction Variable Simplification", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000162
Daniel Dunbar394f0442008-10-22 23:32:42 +0000163Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000164 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000165}
166
Andrew Trickb12a7542011-03-17 23:51:11 +0000167/// isValidRewrite - Return true if the SCEV expansion generated by the
168/// rewriter can replace the original value. SCEV guarantees that it
169/// produces the same value, but the way it is produced may be illegal IR.
170/// Ideally, this function will only be called for verification.
171bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
172 // If an SCEV expression subsumed multiple pointers, its expansion could
173 // reassociate the GEP changing the base pointer. This is illegal because the
174 // final address produced by a GEP chain must be inbounds relative to its
175 // underlying object. Otherwise basic alias analysis, among other things,
176 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
177 // producing an expression involving multiple pointers. Until then, we must
178 // bail out here.
179 //
180 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
181 // because it understands lcssa phis while SCEV does not.
182 Value *FromPtr = FromVal;
183 Value *ToPtr = ToVal;
184 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
185 FromPtr = GEP->getPointerOperand();
186 }
187 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
188 ToPtr = GEP->getPointerOperand();
189 }
190 if (FromPtr != FromVal || ToPtr != ToVal) {
191 // Quickly check the common case
192 if (FromPtr == ToPtr)
193 return true;
194
195 // SCEV may have rewritten an expression that produces the GEP's pointer
196 // operand. That's ok as long as the pointer operand has the same base
197 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
198 // base of a recurrence. This handles the case in which SCEV expansion
199 // converts a pointer type recurrence into a nonrecurrent pointer base
200 // indexed by an integer recurrence.
201 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
202 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
203 if (FromBase == ToBase)
204 return true;
205
206 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
207 << *FromBase << " != " << *ToBase << "\n");
208
209 return false;
210 }
211 return true;
212}
213
Andrew Trick1a54bb22011-07-12 00:08:50 +0000214//===----------------------------------------------------------------------===//
215// RewriteNonIntegerIVs and helpers. Prefer integer IVs.
216//===----------------------------------------------------------------------===//
Andrew Trick4dfdf242011-05-03 22:24:10 +0000217
Andrew Trick1a54bb22011-07-12 00:08:50 +0000218/// ConvertToSInt - Convert APF to an integer, if possible.
219static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
220 bool isExact = false;
221 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000222 return false;
Andrew Trick1a54bb22011-07-12 00:08:50 +0000223 // See if we can convert this to an int64_t
224 uint64_t UIntVal;
225 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
226 &isExact) != APFloat::opOK || !isExact)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000227 return false;
Andrew Trick1a54bb22011-07-12 00:08:50 +0000228 IntVal = UIntVal;
Andrew Trick4dfdf242011-05-03 22:24:10 +0000229 return true;
230}
231
Andrew Trick1a54bb22011-07-12 00:08:50 +0000232/// HandleFloatingPointIV - If the loop has floating induction variable
233/// then insert corresponding integer induction variable if possible.
234/// For example,
235/// for(double i = 0; i < 10000; ++i)
236/// bar(i)
237/// is converted into
238/// for(int i = 0; i < 10000; ++i)
239/// bar((double)i);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000240///
Andrew Trick1a54bb22011-07-12 00:08:50 +0000241void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
242 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
243 unsigned BackEdge = IncomingEdge^1;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000244
Andrew Trick1a54bb22011-07-12 00:08:50 +0000245 // Check incoming value.
246 ConstantFP *InitValueVal =
247 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000248
Andrew Trick1a54bb22011-07-12 00:08:50 +0000249 int64_t InitValue;
250 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
251 return;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000252
Andrew Trick1a54bb22011-07-12 00:08:50 +0000253 // Check IV increment. Reject this PN if increment operation is not
254 // an add or increment value can not be represented by an integer.
255 BinaryOperator *Incr =
256 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
257 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000258
Andrew Trick1a54bb22011-07-12 00:08:50 +0000259 // If this is not an add of the PHI with a constantfp, or if the constant fp
260 // is not an integer, bail out.
261 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
262 int64_t IncValue;
263 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
264 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
265 return;
266
267 // Check Incr uses. One user is PN and the other user is an exit condition
268 // used by the conditional terminator.
269 Value::use_iterator IncrUse = Incr->use_begin();
270 Instruction *U1 = cast<Instruction>(*IncrUse++);
271 if (IncrUse == Incr->use_end()) return;
272 Instruction *U2 = cast<Instruction>(*IncrUse++);
273 if (IncrUse != Incr->use_end()) return;
274
275 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
276 // only used by a branch, we can't transform it.
277 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
278 if (!Compare)
279 Compare = dyn_cast<FCmpInst>(U2);
280 if (Compare == 0 || !Compare->hasOneUse() ||
281 !isa<BranchInst>(Compare->use_back()))
282 return;
283
284 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
285
286 // We need to verify that the branch actually controls the iteration count
287 // of the loop. If not, the new IV can overflow and no one will notice.
288 // The branch block must be in the loop and one of the successors must be out
289 // of the loop.
290 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
291 if (!L->contains(TheBr->getParent()) ||
292 (L->contains(TheBr->getSuccessor(0)) &&
293 L->contains(TheBr->getSuccessor(1))))
294 return;
295
296
297 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
298 // transform it.
299 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
300 int64_t ExitValue;
301 if (ExitValueVal == 0 ||
302 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
303 return;
304
305 // Find new predicate for integer comparison.
306 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
307 switch (Compare->getPredicate()) {
308 default: return; // Unknown comparison.
309 case CmpInst::FCMP_OEQ:
310 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
311 case CmpInst::FCMP_ONE:
312 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
313 case CmpInst::FCMP_OGT:
314 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
315 case CmpInst::FCMP_OGE:
316 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
317 case CmpInst::FCMP_OLT:
318 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
319 case CmpInst::FCMP_OLE:
320 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000321 }
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000322
Andrew Trick1a54bb22011-07-12 00:08:50 +0000323 // We convert the floating point induction variable to a signed i32 value if
324 // we can. This is only safe if the comparison will not overflow in a way
325 // that won't be trapped by the integer equivalent operations. Check for this
326 // now.
327 // TODO: We could use i64 if it is native and the range requires it.
Dan Gohmanca9b7032010-04-12 21:13:43 +0000328
Andrew Trick1a54bb22011-07-12 00:08:50 +0000329 // The start/stride/exit values must all fit in signed i32.
330 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
331 return;
332
333 // If not actually striding (add x, 0.0), avoid touching the code.
334 if (IncValue == 0)
335 return;
336
337 // Positive and negative strides have different safety conditions.
338 if (IncValue > 0) {
339 // If we have a positive stride, we require the init to be less than the
340 // exit value and an equality or less than comparison.
341 if (InitValue >= ExitValue ||
342 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
343 return;
344
345 uint32_t Range = uint32_t(ExitValue-InitValue);
346 if (NewPred == CmpInst::ICMP_SLE) {
347 // Normalize SLE -> SLT, check for infinite loop.
348 if (++Range == 0) return; // Range overflows.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000349 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000350
Andrew Trick1a54bb22011-07-12 00:08:50 +0000351 unsigned Leftover = Range % uint32_t(IncValue);
352
353 // If this is an equality comparison, we require that the strided value
354 // exactly land on the exit value, otherwise the IV condition will wrap
355 // around and do things the fp IV wouldn't.
356 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
357 Leftover != 0)
358 return;
359
360 // If the stride would wrap around the i32 before exiting, we can't
361 // transform the IV.
362 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
363 return;
364
Chris Lattnerd2440572004-04-15 20:26:22 +0000365 } else {
Andrew Trick1a54bb22011-07-12 00:08:50 +0000366 // If we have a negative stride, we require the init to be greater than the
367 // exit value and an equality or greater than comparison.
368 if (InitValue >= ExitValue ||
369 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
370 return;
371
372 uint32_t Range = uint32_t(InitValue-ExitValue);
373 if (NewPred == CmpInst::ICMP_SGE) {
374 // Normalize SGE -> SGT, check for infinite loop.
375 if (++Range == 0) return; // Range overflows.
376 }
377
378 unsigned Leftover = Range % uint32_t(-IncValue);
379
380 // If this is an equality comparison, we require that the strided value
381 // exactly land on the exit value, otherwise the IV condition will wrap
382 // around and do things the fp IV wouldn't.
383 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
384 Leftover != 0)
385 return;
386
387 // If the stride would wrap around the i32 before exiting, we can't
388 // transform the IV.
389 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
390 return;
Chris Lattnerd2440572004-04-15 20:26:22 +0000391 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000392
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000393 IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000394
Andrew Trick1a54bb22011-07-12 00:08:50 +0000395 // Insert new integer induction variable.
396 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
397 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
398 PN->getIncomingBlock(IncomingEdge));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000399
Andrew Trick1a54bb22011-07-12 00:08:50 +0000400 Value *NewAdd =
401 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
402 Incr->getName()+".int", Incr);
403 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000404
Andrew Trick1a54bb22011-07-12 00:08:50 +0000405 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
406 ConstantInt::get(Int32Ty, ExitValue),
407 Compare->getName());
Dan Gohman81db61a2009-05-12 02:17:14 +0000408
Andrew Trick1a54bb22011-07-12 00:08:50 +0000409 // In the following deletions, PN may become dead and may be deleted.
410 // Use a WeakVH to observe whether this happens.
411 WeakVH WeakPH = PN;
412
413 // Delete the old floating point exit comparison. The branch starts using the
414 // new comparison.
415 NewCompare->takeName(Compare);
416 Compare->replaceAllUsesWith(NewCompare);
417 RecursivelyDeleteTriviallyDeadInstructions(Compare);
418
419 // Delete the old floating point increment.
420 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
421 RecursivelyDeleteTriviallyDeadInstructions(Incr);
422
423 // If the FP induction variable still has uses, this is because something else
424 // in the loop uses its value. In order to canonicalize the induction
425 // variable, we chose to eliminate the IV and rewrite it in terms of an
426 // int->fp cast.
427 //
428 // We give preference to sitofp over uitofp because it is faster on most
429 // platforms.
430 if (WeakPH) {
431 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
432 PN->getParent()->getFirstNonPHI());
433 PN->replaceAllUsesWith(Conv);
434 RecursivelyDeleteTriviallyDeadInstructions(PN);
435 }
436
437 // Add a new IVUsers entry for the newly-created integer PHI.
438 if (IU)
439 IU->AddUsersIfInteresting(NewPHI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000440}
441
Andrew Trick1a54bb22011-07-12 00:08:50 +0000442void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
443 // First step. Check to see if there are any floating-point recurrences.
444 // If there are, change them into integer recurrences, permitting analysis by
445 // the SCEV routines.
446 //
447 BasicBlock *Header = L->getHeader();
448
449 SmallVector<WeakVH, 8> PHIs;
450 for (BasicBlock::iterator I = Header->begin();
451 PHINode *PN = dyn_cast<PHINode>(I); ++I)
452 PHIs.push_back(PN);
453
454 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
455 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
456 HandleFloatingPointIV(L, PN);
457
458 // If the loop previously had floating-point IV, ScalarEvolution
459 // may not have been able to compute a trip count. Now that we've done some
460 // re-writing, the trip count may be computable.
461 if (Changed)
462 SE->forgetLoop(L);
463}
464
465//===----------------------------------------------------------------------===//
466// RewriteLoopExitValues - Optimize IV users outside the loop.
467// As a side effect, reduces the amount of IV processing within the loop.
468//===----------------------------------------------------------------------===//
469
Chris Lattner40bf8b42004-04-02 20:24:31 +0000470/// RewriteLoopExitValues - Check to see if this loop has a computable
471/// loop-invariant execution count. If so, this means that we can compute the
472/// final value of any expressions that are recurrent in the loop, and
473/// substitute the exit values from the loop into any instructions outside of
474/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000475///
476/// This is mostly redundant with the regular IndVarSimplify activities that
477/// happen later, except that it's more powerful in some cases, because it's
478/// able to brute-force evaluate arbitrary instructions as long as they have
479/// constant operands at the beginning of the loop.
Chris Lattnerf1859892011-01-09 02:16:18 +0000480void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000481 // Verify the input to the pass in already in LCSSA form.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000482 assert(L->isLCSSAForm(*DT));
Dan Gohman81db61a2009-05-12 02:17:14 +0000483
Devang Patelb7211a22007-08-21 00:31:24 +0000484 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000485 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000486
Chris Lattner9f3d7382007-03-04 03:43:23 +0000487 // Find all values that are computed inside the loop, but used outside of it.
488 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
489 // the exit blocks of the loop to find them.
490 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
491 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000492
Chris Lattner9f3d7382007-03-04 03:43:23 +0000493 // If there are no PHI nodes in this exit block, then no values defined
494 // inside the loop are used on this path, skip it.
495 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
496 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000497
Chris Lattner9f3d7382007-03-04 03:43:23 +0000498 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000499
Chris Lattner9f3d7382007-03-04 03:43:23 +0000500 // Iterate over all of the PHI nodes.
501 BasicBlock::iterator BBI = ExitBB->begin();
502 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000503 if (PN->use_empty())
504 continue; // dead use, don't replace it
Dan Gohman814f2b22010-02-18 21:34:02 +0000505
506 // SCEV only supports integer expressions for now.
507 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
508 continue;
509
Dale Johannesen45a2d7d2010-02-19 07:14:22 +0000510 // It's necessary to tell ScalarEvolution about this explicitly so that
511 // it can walk the def-use list and forget all SCEVs, as it may not be
512 // watching the PHI itself. Once the new exit value is in place, there
513 // may not be a def-use connection between the loop and every instruction
514 // which got a SCEVAddRecExpr for that loop.
515 SE->forgetValue(PN);
516
Chris Lattner9f3d7382007-03-04 03:43:23 +0000517 // Iterate over all of the values in all the PHI nodes.
518 for (unsigned i = 0; i != NumPreds; ++i) {
519 // If the value being merged in is not integer or is not defined
520 // in the loop, skip it.
521 Value *InVal = PN->getIncomingValue(i);
Dan Gohman814f2b22010-02-18 21:34:02 +0000522 if (!isa<Instruction>(InVal))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000523 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000524
Chris Lattner9f3d7382007-03-04 03:43:23 +0000525 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000526 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000527 continue; // The Block is in a subloop, skip it.
528
529 // Check that InVal is defined in the loop.
530 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman92329c72009-12-18 01:24:09 +0000531 if (!L->contains(Inst))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000532 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000533
Chris Lattner9f3d7382007-03-04 03:43:23 +0000534 // Okay, this instruction has a user outside of the current loop
535 // and varies predictably *inside* the loop. Evaluate the value it
536 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000537 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +0000538 if (!SE->isLoopInvariant(ExitValue, L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000539 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000540
Dan Gohman667d7872009-06-26 22:53:46 +0000541 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000542
David Greenef67ef312010-01-05 01:27:06 +0000543 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000544 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000545
Andrew Trickb12a7542011-03-17 23:51:11 +0000546 if (!isValidRewrite(Inst, ExitVal)) {
547 DeadInsts.push_back(ExitVal);
548 continue;
549 }
550 Changed = true;
551 ++NumReplaced;
552
Chris Lattner9f3d7382007-03-04 03:43:23 +0000553 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000554
Dan Gohman81db61a2009-05-12 02:17:14 +0000555 // If this instruction is dead now, delete it.
556 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000557
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000558 if (NumPreds == 1) {
559 // Completely replace a single-pred PHI. This is safe, because the
560 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
561 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000562 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000563 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000564 }
565 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000566 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000567 // Clone the PHI and delete the original one. This lets IVUsers and
568 // any other maps purge the original user from their records.
Devang Patel50b6e332009-10-27 22:16:29 +0000569 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohman667d7872009-06-26 22:53:46 +0000570 NewPN->takeName(PN);
571 NewPN->insertBefore(PN);
572 PN->replaceAllUsesWith(NewPN);
573 PN->eraseFromParent();
574 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000575 }
576 }
Dan Gohman472fdf72010-03-20 03:53:53 +0000577
578 // The insertion point instruction may have been deleted; clear it out
579 // so that the rewriter doesn't trip over it later.
580 Rewriter.clearInsertPoint();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000581}
582
Andrew Trick1a54bb22011-07-12 00:08:50 +0000583//===----------------------------------------------------------------------===//
584// Rewrite IV users based on a canonical IV.
585// To be replaced by -disable-iv-rewrite.
586//===----------------------------------------------------------------------===//
Dale Johannesenc671d892009-04-15 23:31:51 +0000587
Andrew Trick2fabd462011-06-21 03:22:38 +0000588/// SimplifyIVUsers - Iteratively perform simplification on IVUsers within this
589/// loop. IVUsers is treated as a worklist. Each successive simplification may
590/// push more users which may themselves be candidates for simplification.
591///
592/// This is the old approach to IV simplification to be replaced by
593/// SimplifyIVUsersNoRewrite.
594///
595void IndVarSimplify::SimplifyIVUsers(SCEVExpander &Rewriter) {
596 // Each round of simplification involves a round of eliminating operations
597 // followed by a round of widening IVs. A single IVUsers worklist is used
598 // across all rounds. The inner loop advances the user. If widening exposes
599 // more uses, then another pass through the outer loop is triggered.
600 for (IVUsers::iterator I = IU->begin(); I != IU->end(); ++I) {
601 Instruction *UseInst = I->getUser();
602 Value *IVOperand = I->getOperandValToReplace();
603
604 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
605 EliminateIVComparison(ICmp, IVOperand);
606 continue;
607 }
608 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
609 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
610 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
Andrew Trick4417e532011-06-21 15:43:52 +0000611 EliminateIVRemainder(Rem, IVOperand, IsSigned);
Andrew Trick2fabd462011-06-21 03:22:38 +0000612 continue;
613 }
614 }
615 }
616}
617
Andrew Trick1a54bb22011-07-12 00:08:50 +0000618// FIXME: It is an extremely bad idea to indvar substitute anything more
619// complex than affine induction variables. Doing so will put expensive
620// polynomial evaluations inside of the loop, and the str reduction pass
621// currently can only reduce affine polynomials. For now just disable
622// indvar subst on anything more complex than an affine addrec, unless
623// it can be expanded to a trivial value.
624static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
625 // Loop-invariant values are safe.
626 if (SE->isLoopInvariant(S, L)) return true;
627
628 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
629 // to transform them into efficient code.
630 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
631 return AR->isAffine();
632
633 // An add is safe it all its operands are safe.
634 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
635 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
636 E = Commutative->op_end(); I != E; ++I)
637 if (!isSafe(*I, L, SE)) return false;
638 return true;
639 }
640
641 // A cast is safe if its operand is.
642 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
643 return isSafe(C->getOperand(), L, SE);
644
645 // A udiv is safe if its operands are.
646 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
647 return isSafe(UD->getLHS(), L, SE) &&
648 isSafe(UD->getRHS(), L, SE);
649
650 // SCEVUnknown is always safe.
651 if (isa<SCEVUnknown>(S))
652 return true;
653
654 // Nothing else is safe.
655 return false;
656}
657
658void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
659 // Rewrite all induction variable expressions in terms of the canonical
660 // induction variable.
661 //
662 // If there were induction variables of other sizes or offsets, manually
663 // add the offsets to the primary induction variable and cast, avoiding
664 // the need for the code evaluation methods to insert induction variables
665 // of different sizes.
666 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
667 Value *Op = UI->getOperandValToReplace();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000668 Type *UseTy = Op->getType();
Andrew Trick1a54bb22011-07-12 00:08:50 +0000669 Instruction *User = UI->getUser();
670
671 // Compute the final addrec to expand into code.
672 const SCEV *AR = IU->getReplacementExpr(*UI);
673
674 // Evaluate the expression out of the loop, if possible.
675 if (!L->contains(UI->getUser())) {
676 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
677 if (SE->isLoopInvariant(ExitVal, L))
678 AR = ExitVal;
679 }
680
681 // FIXME: It is an extremely bad idea to indvar substitute anything more
682 // complex than affine induction variables. Doing so will put expensive
683 // polynomial evaluations inside of the loop, and the str reduction pass
684 // currently can only reduce affine polynomials. For now just disable
685 // indvar subst on anything more complex than an affine addrec, unless
686 // it can be expanded to a trivial value.
687 if (!isSafe(AR, L, SE))
688 continue;
689
690 // Determine the insertion point for this user. By default, insert
691 // immediately before the user. The SCEVExpander class will automatically
692 // hoist loop invariants out of the loop. For PHI nodes, there may be
693 // multiple uses, so compute the nearest common dominator for the
694 // incoming blocks.
695 Instruction *InsertPt = User;
696 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
697 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
698 if (PHI->getIncomingValue(i) == Op) {
699 if (InsertPt == User)
700 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
701 else
702 InsertPt =
703 DT->findNearestCommonDominator(InsertPt->getParent(),
704 PHI->getIncomingBlock(i))
705 ->getTerminator();
706 }
707
708 // Now expand it into actual Instructions and patch it into place.
709 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
710
711 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
712 << " into = " << *NewVal << "\n");
713
714 if (!isValidRewrite(Op, NewVal)) {
715 DeadInsts.push_back(NewVal);
716 continue;
717 }
718 // Inform ScalarEvolution that this value is changing. The change doesn't
719 // affect its value, but it does potentially affect which use lists the
720 // value will be on after the replacement, which affects ScalarEvolution's
721 // ability to walk use lists and drop dangling pointers when a value is
722 // deleted.
723 SE->forgetValue(User);
724
725 // Patch the new value into place.
726 if (Op->hasName())
727 NewVal->takeName(Op);
728 if (Instruction *NewValI = dyn_cast<Instruction>(NewVal))
729 NewValI->setDebugLoc(User->getDebugLoc());
730 User->replaceUsesOfWith(Op, NewVal);
731 UI->setOperandValToReplace(NewVal);
732
733 ++NumRemoved;
734 Changed = true;
735
736 // The old value may be dead now.
737 DeadInsts.push_back(Op);
738 }
739}
740
741//===----------------------------------------------------------------------===//
742// IV Widening - Extend the width of an IV to cover its widest uses.
743//===----------------------------------------------------------------------===//
744
Andrew Trickf85092c2011-05-20 18:25:42 +0000745namespace {
746 // Collect information about induction variables that are used by sign/zero
747 // extend operations. This information is recorded by CollectExtend and
748 // provides the input to WidenIV.
749 struct WideIVInfo {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000750 Type *WidestNativeType; // Widest integer type created [sz]ext
Andrew Trickf85092c2011-05-20 18:25:42 +0000751 bool IsSigned; // Was an sext user seen before a zext?
752
753 WideIVInfo() : WidestNativeType(0), IsSigned(false) {}
754 };
Andrew Trickf85092c2011-05-20 18:25:42 +0000755}
756
757/// CollectExtend - Update information about the induction variable that is
758/// extended by this sign or zero extend operation. This is used to determine
759/// the final width of the IV before actually widening it.
Andrew Trick2fabd462011-06-21 03:22:38 +0000760static void CollectExtend(CastInst *Cast, bool IsSigned, WideIVInfo &WI,
761 ScalarEvolution *SE, const TargetData *TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000762 Type *Ty = Cast->getType();
Andrew Trickf85092c2011-05-20 18:25:42 +0000763 uint64_t Width = SE->getTypeSizeInBits(Ty);
764 if (TD && !TD->isLegalInteger(Width))
765 return;
766
Andrew Trick2fabd462011-06-21 03:22:38 +0000767 if (!WI.WidestNativeType) {
768 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
769 WI.IsSigned = IsSigned;
Andrew Trickf85092c2011-05-20 18:25:42 +0000770 return;
771 }
772
773 // We extend the IV to satisfy the sign of its first user, arbitrarily.
Andrew Trick2fabd462011-06-21 03:22:38 +0000774 if (WI.IsSigned != IsSigned)
Andrew Trickf85092c2011-05-20 18:25:42 +0000775 return;
776
Andrew Trick2fabd462011-06-21 03:22:38 +0000777 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
778 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
Andrew Trickf85092c2011-05-20 18:25:42 +0000779}
780
781namespace {
782/// WidenIV - The goal of this transform is to remove sign and zero extends
783/// without creating any new induction variables. To do this, it creates a new
784/// phi of the wider type and redirects all users, either removing extends or
785/// inserting truncs whenever we stop propagating the type.
786///
787class WidenIV {
Andrew Trick2fabd462011-06-21 03:22:38 +0000788 // Parameters
Andrew Trickf85092c2011-05-20 18:25:42 +0000789 PHINode *OrigPhi;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000790 Type *WideType;
Andrew Trickf85092c2011-05-20 18:25:42 +0000791 bool IsSigned;
792
Andrew Trick2fabd462011-06-21 03:22:38 +0000793 // Context
794 LoopInfo *LI;
795 Loop *L;
Andrew Trickf85092c2011-05-20 18:25:42 +0000796 ScalarEvolution *SE;
Andrew Trick2fabd462011-06-21 03:22:38 +0000797 DominatorTree *DT;
Andrew Trickf85092c2011-05-20 18:25:42 +0000798
Andrew Trick2fabd462011-06-21 03:22:38 +0000799 // Result
Andrew Trickf85092c2011-05-20 18:25:42 +0000800 PHINode *WidePhi;
801 Instruction *WideInc;
802 const SCEV *WideIncExpr;
Andrew Trick2fabd462011-06-21 03:22:38 +0000803 SmallVectorImpl<WeakVH> &DeadInsts;
Andrew Trickf85092c2011-05-20 18:25:42 +0000804
Andrew Trick2fabd462011-06-21 03:22:38 +0000805 SmallPtrSet<Instruction*,16> Widened;
Andrew Trick4b029152011-07-02 02:34:25 +0000806 SmallVector<std::pair<Use *, Instruction *>, 8> NarrowIVUsers;
Andrew Trickf85092c2011-05-20 18:25:42 +0000807
808public:
Andrew Trick2fabd462011-06-21 03:22:38 +0000809 WidenIV(PHINode *PN, const WideIVInfo &WI, LoopInfo *LInfo,
810 ScalarEvolution *SEv, DominatorTree *DTree,
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000811 SmallVectorImpl<WeakVH> &DI) :
Andrew Trickf85092c2011-05-20 18:25:42 +0000812 OrigPhi(PN),
Andrew Trick2fabd462011-06-21 03:22:38 +0000813 WideType(WI.WidestNativeType),
814 IsSigned(WI.IsSigned),
Andrew Trickf85092c2011-05-20 18:25:42 +0000815 LI(LInfo),
816 L(LI->getLoopFor(OrigPhi->getParent())),
817 SE(SEv),
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000818 DT(DTree),
Andrew Trickf85092c2011-05-20 18:25:42 +0000819 WidePhi(0),
820 WideInc(0),
Andrew Trick2fabd462011-06-21 03:22:38 +0000821 WideIncExpr(0),
822 DeadInsts(DI) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000823 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
824 }
825
Andrew Trick2fabd462011-06-21 03:22:38 +0000826 PHINode *CreateWideIV(SCEVExpander &Rewriter);
Andrew Trickf85092c2011-05-20 18:25:42 +0000827
828protected:
Andrew Trickf85092c2011-05-20 18:25:42 +0000829 Instruction *CloneIVUser(Instruction *NarrowUse,
830 Instruction *NarrowDef,
831 Instruction *WideDef);
832
Andrew Tricke0dc2fa2011-07-05 18:19:39 +0000833 const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
834
Andrew Trickcc359d92011-06-29 23:03:57 +0000835 Instruction *WidenIVUse(Use &NarrowDefUse, Instruction *NarrowDef,
Andrew Trickf85092c2011-05-20 18:25:42 +0000836 Instruction *WideDef);
Andrew Trick4b029152011-07-02 02:34:25 +0000837
838 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
Andrew Trickf85092c2011-05-20 18:25:42 +0000839};
840} // anonymous namespace
841
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000842static Value *getExtend( Value *NarrowOper, Type *WideType,
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000843 bool IsSigned, IRBuilder<> &Builder) {
844 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
845 Builder.CreateZExt(NarrowOper, WideType);
Andrew Trickf85092c2011-05-20 18:25:42 +0000846}
847
848/// CloneIVUser - Instantiate a wide operation to replace a narrow
849/// operation. This only needs to handle operations that can evaluation to
850/// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
851Instruction *WidenIV::CloneIVUser(Instruction *NarrowUse,
852 Instruction *NarrowDef,
853 Instruction *WideDef) {
854 unsigned Opcode = NarrowUse->getOpcode();
855 switch (Opcode) {
856 default:
857 return 0;
858 case Instruction::Add:
859 case Instruction::Mul:
860 case Instruction::UDiv:
861 case Instruction::Sub:
862 case Instruction::And:
863 case Instruction::Or:
864 case Instruction::Xor:
865 case Instruction::Shl:
866 case Instruction::LShr:
867 case Instruction::AShr:
868 DEBUG(dbgs() << "Cloning IVUser: " << *NarrowUse << "\n");
869
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000870 IRBuilder<> Builder(NarrowUse);
871
872 // Replace NarrowDef operands with WideDef. Otherwise, we don't know
873 // anything about the narrow operand yet so must insert a [sz]ext. It is
874 // probably loop invariant and will be folded or hoisted. If it actually
875 // comes from a widened IV, it should be removed during a future call to
876 // WidenIVUse.
877 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef) ? WideDef :
878 getExtend(NarrowUse->getOperand(0), WideType, IsSigned, Builder);
879 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef) ? WideDef :
880 getExtend(NarrowUse->getOperand(1), WideType, IsSigned, Builder);
881
Andrew Trickf85092c2011-05-20 18:25:42 +0000882 BinaryOperator *NarrowBO = cast<BinaryOperator>(NarrowUse);
883 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000884 LHS, RHS,
Andrew Trickf85092c2011-05-20 18:25:42 +0000885 NarrowBO->getName());
Andrew Trickf85092c2011-05-20 18:25:42 +0000886 Builder.Insert(WideBO);
Andrew Trick6e0ce242011-06-30 19:02:17 +0000887 if (const OverflowingBinaryOperator *OBO =
888 dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
889 if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
890 if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
891 }
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000892 return WideBO;
Andrew Trickf85092c2011-05-20 18:25:42 +0000893 }
894 llvm_unreachable(0);
895}
896
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000897/// HoistStep - Attempt to hoist an IV increment above a potential use.
898///
899/// To successfully hoist, two criteria must be met:
900/// - IncV operands dominate InsertPos and
901/// - InsertPos dominates IncV
902///
903/// Meeting the second condition means that we don't need to check all of IncV's
904/// existing uses (it's moving up in the domtree).
905///
906/// This does not yet recursively hoist the operands, although that would
907/// not be difficult.
908static bool HoistStep(Instruction *IncV, Instruction *InsertPos,
909 const DominatorTree *DT)
910{
911 if (DT->dominates(IncV, InsertPos))
912 return true;
913
914 if (!DT->dominates(InsertPos->getParent(), IncV->getParent()))
915 return false;
916
917 if (IncV->mayHaveSideEffects())
918 return false;
919
920 // Attempt to hoist IncV
921 for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end();
922 OI != OE; ++OI) {
923 Instruction *OInst = dyn_cast<Instruction>(OI);
924 if (OInst && !DT->dominates(OInst, InsertPos))
925 return false;
926 }
927 IncV->moveBefore(InsertPos);
928 return true;
929}
930
Andrew Tricke0dc2fa2011-07-05 18:19:39 +0000931// GetWideRecurrence - Is this instruction potentially interesting from IVUsers'
932// perspective after widening it's type? In other words, can the extend be
933// safely hoisted out of the loop with SCEV reducing the value to a recurrence
934// on the same loop. If so, return the sign or zero extended
935// recurrence. Otherwise return NULL.
936const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
937 if (!SE->isSCEVable(NarrowUse->getType()))
938 return 0;
939
940 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
941 if (SE->getTypeSizeInBits(NarrowExpr->getType())
942 >= SE->getTypeSizeInBits(WideType)) {
943 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
944 // index. So don't follow this use.
945 return 0;
946 }
947
948 const SCEV *WideExpr = IsSigned ?
949 SE->getSignExtendExpr(NarrowExpr, WideType) :
950 SE->getZeroExtendExpr(NarrowExpr, WideType);
951 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
952 if (!AddRec || AddRec->getLoop() != L)
953 return 0;
954
955 return AddRec;
956}
957
Andrew Trickf85092c2011-05-20 18:25:42 +0000958/// WidenIVUse - Determine whether an individual user of the narrow IV can be
959/// widened. If so, return the wide clone of the user.
Andrew Trickcc359d92011-06-29 23:03:57 +0000960Instruction *WidenIV::WidenIVUse(Use &NarrowDefUse, Instruction *NarrowDef,
Andrew Trickf85092c2011-05-20 18:25:42 +0000961 Instruction *WideDef) {
Andrew Trickcc359d92011-06-29 23:03:57 +0000962 Instruction *NarrowUse = cast<Instruction>(NarrowDefUse.getUser());
963
Andrew Trick4b029152011-07-02 02:34:25 +0000964 // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
Andrew Trickf85092c2011-05-20 18:25:42 +0000965 if (isa<PHINode>(NarrowUse) && LI->getLoopFor(NarrowUse->getParent()) != L)
966 return 0;
967
Andrew Trickf85092c2011-05-20 18:25:42 +0000968 // Our raison d'etre! Eliminate sign and zero extension.
969 if (IsSigned ? isa<SExtInst>(NarrowUse) : isa<ZExtInst>(NarrowUse)) {
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000970 Value *NewDef = WideDef;
971 if (NarrowUse->getType() != WideType) {
972 unsigned CastWidth = SE->getTypeSizeInBits(NarrowUse->getType());
973 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
974 if (CastWidth < IVWidth) {
975 // The cast isn't as wide as the IV, so insert a Trunc.
Andrew Trickcc359d92011-06-29 23:03:57 +0000976 IRBuilder<> Builder(NarrowDefUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000977 NewDef = Builder.CreateTrunc(WideDef, NarrowUse->getType());
978 }
979 else {
980 // A wider extend was hidden behind a narrower one. This may induce
981 // another round of IV widening in which the intermediate IV becomes
982 // dead. It should be very rare.
983 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
984 << " not wide enough to subsume " << *NarrowUse << "\n");
985 NarrowUse->replaceUsesOfWith(NarrowDef, WideDef);
986 NewDef = NarrowUse;
987 }
988 }
989 if (NewDef != NarrowUse) {
990 DEBUG(dbgs() << "INDVARS: eliminating " << *NarrowUse
991 << " replaced by " << *WideDef << "\n");
992 ++NumElimExt;
993 NarrowUse->replaceAllUsesWith(NewDef);
994 DeadInsts.push_back(NarrowUse);
995 }
Andrew Trick2fabd462011-06-21 03:22:38 +0000996 // Now that the extend is gone, we want to expose it's uses for potential
997 // further simplification. We don't need to directly inform SimplifyIVUsers
998 // of the new users, because their parent IV will be processed later as a
999 // new loop phi. If we preserved IVUsers analysis, we would also want to
1000 // push the uses of WideDef here.
Andrew Trickf85092c2011-05-20 18:25:42 +00001001
1002 // No further widening is needed. The deceased [sz]ext had done it for us.
1003 return 0;
1004 }
Andrew Trick4b029152011-07-02 02:34:25 +00001005
1006 // Does this user itself evaluate to a recurrence after widening?
Andrew Tricke0dc2fa2011-07-05 18:19:39 +00001007 const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(NarrowUse);
Andrew Trickf85092c2011-05-20 18:25:42 +00001008 if (!WideAddRec) {
1009 // This user does not evaluate to a recurence after widening, so don't
1010 // follow it. Instead insert a Trunc to kill off the original use,
1011 // eventually isolating the original narrow IV so it can be removed.
Andrew Trickcc359d92011-06-29 23:03:57 +00001012 IRBuilder<> Builder(NarrowDefUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001013 Value *Trunc = Builder.CreateTrunc(WideDef, NarrowDef->getType());
Andrew Trickf85092c2011-05-20 18:25:42 +00001014 NarrowUse->replaceUsesOfWith(NarrowDef, Trunc);
1015 return 0;
1016 }
Andrew Trick4b029152011-07-02 02:34:25 +00001017 // We assume that block terminators are not SCEVable. We wouldn't want to
1018 // insert a Trunc after a terminator if there happens to be a critical edge.
Andrew Trickcc359d92011-06-29 23:03:57 +00001019 assert(NarrowUse != NarrowUse->getParent()->getTerminator() &&
Andrew Trick4b029152011-07-02 02:34:25 +00001020 "SCEV is not expected to evaluate a block terminator");
Andrew Trickcc359d92011-06-29 23:03:57 +00001021
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001022 // Reuse the IV increment that SCEVExpander created as long as it dominates
1023 // NarrowUse.
Andrew Trickf85092c2011-05-20 18:25:42 +00001024 Instruction *WideUse = 0;
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001025 if (WideAddRec == WideIncExpr && HoistStep(WideInc, NarrowUse, DT)) {
Andrew Trickf85092c2011-05-20 18:25:42 +00001026 WideUse = WideInc;
1027 }
1028 else {
1029 WideUse = CloneIVUser(NarrowUse, NarrowDef, WideDef);
1030 if (!WideUse)
1031 return 0;
1032 }
Andrew Trick4b029152011-07-02 02:34:25 +00001033 // Evaluation of WideAddRec ensured that the narrow expression could be
1034 // extended outside the loop without overflow. This suggests that the wide use
Andrew Trickf85092c2011-05-20 18:25:42 +00001035 // evaluates to the same expression as the extended narrow use, but doesn't
1036 // absolutely guarantee it. Hence the following failsafe check. In rare cases
Andrew Trick2fabd462011-06-21 03:22:38 +00001037 // where it fails, we simply throw away the newly created wide use.
Andrew Trickf85092c2011-05-20 18:25:42 +00001038 if (WideAddRec != SE->getSCEV(WideUse)) {
1039 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
1040 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
1041 DeadInsts.push_back(WideUse);
1042 return 0;
1043 }
1044
1045 // Returning WideUse pushes it on the worklist.
1046 return WideUse;
1047}
1048
Andrew Trick4b029152011-07-02 02:34:25 +00001049/// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers.
1050///
1051void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1052 for (Value::use_iterator UI = NarrowDef->use_begin(),
1053 UE = NarrowDef->use_end(); UI != UE; ++UI) {
1054 Use &U = UI.getUse();
1055
1056 // Handle data flow merges and bizarre phi cycles.
1057 if (!Widened.insert(cast<Instruction>(U.getUser())))
1058 continue;
1059
1060 NarrowIVUsers.push_back(std::make_pair(&UI.getUse(), WideDef));
1061 }
1062}
1063
Andrew Trickf85092c2011-05-20 18:25:42 +00001064/// CreateWideIV - Process a single induction variable. First use the
1065/// SCEVExpander to create a wide induction variable that evaluates to the same
1066/// recurrence as the original narrow IV. Then use a worklist to forward
Andrew Trick2fabd462011-06-21 03:22:38 +00001067/// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
Andrew Trickf85092c2011-05-20 18:25:42 +00001068/// interesting IV users, the narrow IV will be isolated for removal by
1069/// DeleteDeadPHIs.
1070///
1071/// It would be simpler to delete uses as they are processed, but we must avoid
1072/// invalidating SCEV expressions.
1073///
Andrew Trick2fabd462011-06-21 03:22:38 +00001074PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
Andrew Trickf85092c2011-05-20 18:25:42 +00001075 // Is this phi an induction variable?
1076 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1077 if (!AddRec)
Andrew Trick2fabd462011-06-21 03:22:38 +00001078 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +00001079
1080 // Widen the induction variable expression.
1081 const SCEV *WideIVExpr = IsSigned ?
1082 SE->getSignExtendExpr(AddRec, WideType) :
1083 SE->getZeroExtendExpr(AddRec, WideType);
1084
1085 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1086 "Expect the new IV expression to preserve its type");
1087
1088 // Can the IV be extended outside the loop without overflow?
1089 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1090 if (!AddRec || AddRec->getLoop() != L)
Andrew Trick2fabd462011-06-21 03:22:38 +00001091 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +00001092
Andrew Trick2fabd462011-06-21 03:22:38 +00001093 // An AddRec must have loop-invariant operands. Since this AddRec is
Andrew Trickf85092c2011-05-20 18:25:42 +00001094 // materialized by a loop header phi, the expression cannot have any post-loop
1095 // operands, so they must dominate the loop header.
1096 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1097 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
1098 && "Loop header phi recurrence inputs do not dominate the loop");
1099
1100 // The rewriter provides a value for the desired IV expression. This may
1101 // either find an existing phi or materialize a new one. Either way, we
1102 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1103 // of the phi-SCC dominates the loop entry.
1104 Instruction *InsertPt = L->getHeader()->begin();
1105 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
1106
1107 // Remembering the WideIV increment generated by SCEVExpander allows
1108 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
1109 // employ a general reuse mechanism because the call above is the only call to
1110 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001111 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1112 WideInc =
1113 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1114 WideIncExpr = SE->getSCEV(WideInc);
1115 }
Andrew Trickf85092c2011-05-20 18:25:42 +00001116
1117 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1118 ++NumWidened;
1119
1120 // Traverse the def-use chain using a worklist starting at the original IV.
Andrew Trick4b029152011-07-02 02:34:25 +00001121 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
Andrew Trickf85092c2011-05-20 18:25:42 +00001122
Andrew Trick4b029152011-07-02 02:34:25 +00001123 Widened.insert(OrigPhi);
1124 pushNarrowIVUsers(OrigPhi, WidePhi);
1125
Andrew Trickf85092c2011-05-20 18:25:42 +00001126 while (!NarrowIVUsers.empty()) {
Andrew Trickcc359d92011-06-29 23:03:57 +00001127 Use *UsePtr;
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001128 Instruction *WideDef;
Andrew Trickcc359d92011-06-29 23:03:57 +00001129 tie(UsePtr, WideDef) = NarrowIVUsers.pop_back_val();
1130 Use &NarrowDefUse = *UsePtr;
Andrew Trickf85092c2011-05-20 18:25:42 +00001131
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001132 // Process a def-use edge. This may replace the use, so don't hold a
1133 // use_iterator across it.
Andrew Trickcc359d92011-06-29 23:03:57 +00001134 Instruction *NarrowDef = cast<Instruction>(NarrowDefUse.get());
1135 Instruction *WideUse = WidenIVUse(NarrowDefUse, NarrowDef, WideDef);
Andrew Trickf85092c2011-05-20 18:25:42 +00001136
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001137 // Follow all def-use edges from the previous narrow use.
Andrew Trick4b029152011-07-02 02:34:25 +00001138 if (WideUse)
1139 pushNarrowIVUsers(cast<Instruction>(NarrowDefUse.getUser()), WideUse);
1140
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001141 // WidenIVUse may have removed the def-use edge.
1142 if (NarrowDef->use_empty())
1143 DeadInsts.push_back(NarrowDef);
Andrew Trickf85092c2011-05-20 18:25:42 +00001144 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001145 return WidePhi;
Andrew Trickf85092c2011-05-20 18:25:42 +00001146}
1147
Andrew Trick1a54bb22011-07-12 00:08:50 +00001148//===----------------------------------------------------------------------===//
1149// Simplification of IV users based on SCEV evaluation.
1150//===----------------------------------------------------------------------===//
1151
Andrew Trickaeee4612011-05-12 00:04:28 +00001152void IndVarSimplify::EliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
1153 unsigned IVOperIdx = 0;
1154 ICmpInst::Predicate Pred = ICmp->getPredicate();
1155 if (IVOperand != ICmp->getOperand(0)) {
1156 // Swapped
1157 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
1158 IVOperIdx = 1;
1159 Pred = ICmpInst::getSwappedPredicate(Pred);
Dan Gohmana590b792010-04-13 01:46:36 +00001160 }
Andrew Trickaeee4612011-05-12 00:04:28 +00001161
1162 // Get the SCEVs for the ICmp operands.
1163 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
1164 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
1165
1166 // Simplify unnecessary loops away.
1167 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
1168 S = SE->getSCEVAtScope(S, ICmpLoop);
1169 X = SE->getSCEVAtScope(X, ICmpLoop);
1170
1171 // If the condition is always true or always false, replace it with
1172 // a constant value.
1173 if (SE->isKnownPredicate(Pred, S, X))
1174 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
1175 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
1176 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
1177 else
1178 return;
1179
1180 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001181 ++NumElimCmp;
Andrew Trick074397d2011-05-20 03:37:48 +00001182 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +00001183 DeadInsts.push_back(ICmp);
1184}
1185
1186void IndVarSimplify::EliminateIVRemainder(BinaryOperator *Rem,
1187 Value *IVOperand,
Andrew Trick4417e532011-06-21 15:43:52 +00001188 bool IsSigned) {
Andrew Trickaeee4612011-05-12 00:04:28 +00001189 // We're only interested in the case where we know something about
1190 // the numerator.
1191 if (IVOperand != Rem->getOperand(0))
1192 return;
1193
1194 // Get the SCEVs for the ICmp operands.
1195 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
1196 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
1197
1198 // Simplify unnecessary loops away.
1199 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
1200 S = SE->getSCEVAtScope(S, ICmpLoop);
1201 X = SE->getSCEVAtScope(X, ICmpLoop);
1202
1203 // i % n --> i if i is in [0,n).
Andrew Trick074397d2011-05-20 03:37:48 +00001204 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
1205 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Andrew Trickaeee4612011-05-12 00:04:28 +00001206 S, X))
1207 Rem->replaceAllUsesWith(Rem->getOperand(0));
1208 else {
1209 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
1210 const SCEV *LessOne =
1211 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
Andrew Trick074397d2011-05-20 03:37:48 +00001212 if (IsSigned && !SE->isKnownNonNegative(LessOne))
Andrew Trickaeee4612011-05-12 00:04:28 +00001213 return;
1214
Andrew Trick074397d2011-05-20 03:37:48 +00001215 if (!SE->isKnownPredicate(IsSigned ?
Andrew Trickaeee4612011-05-12 00:04:28 +00001216 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1217 LessOne, X))
1218 return;
1219
1220 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
1221 Rem->getOperand(0), Rem->getOperand(1),
1222 "tmp");
1223 SelectInst *Sel =
1224 SelectInst::Create(ICmp,
1225 ConstantInt::get(Rem->getType(), 0),
1226 Rem->getOperand(0), "tmp", Rem);
1227 Rem->replaceAllUsesWith(Sel);
1228 }
1229
1230 // Inform IVUsers about the new users.
Andrew Trick2fabd462011-06-21 03:22:38 +00001231 if (IU) {
1232 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
Andrew Trick4417e532011-06-21 15:43:52 +00001233 IU->AddUsersIfInteresting(I);
Andrew Trick2fabd462011-06-21 03:22:38 +00001234 }
Andrew Trickaeee4612011-05-12 00:04:28 +00001235 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001236 ++NumElimRem;
Andrew Trick074397d2011-05-20 03:37:48 +00001237 Changed = true;
Andrew Trickaeee4612011-05-12 00:04:28 +00001238 DeadInsts.push_back(Rem);
Dan Gohmana590b792010-04-13 01:46:36 +00001239}
1240
Andrew Trick2fabd462011-06-21 03:22:38 +00001241/// EliminateIVUser - Eliminate an operation that consumes a simple IV and has
1242/// no observable side-effect given the range of IV values.
1243bool IndVarSimplify::EliminateIVUser(Instruction *UseInst,
1244 Instruction *IVOperand) {
1245 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
1246 EliminateIVComparison(ICmp, IVOperand);
1247 return true;
1248 }
1249 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
1250 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
1251 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
Andrew Trick4417e532011-06-21 15:43:52 +00001252 EliminateIVRemainder(Rem, IVOperand, IsSigned);
Andrew Trick2fabd462011-06-21 03:22:38 +00001253 return true;
1254 }
1255 }
1256
1257 // Eliminate any operation that SCEV can prove is an identity function.
1258 if (!SE->isSCEVable(UseInst->getType()) ||
Andrew Trick11745d42011-06-29 03:13:40 +00001259 (UseInst->getType() != IVOperand->getType()) ||
Andrew Trick2fabd462011-06-21 03:22:38 +00001260 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
1261 return false;
1262
Andrew Trick2fabd462011-06-21 03:22:38 +00001263 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
Andrew Trick60ac7192011-06-30 01:27:23 +00001264
1265 UseInst->replaceAllUsesWith(IVOperand);
Andrew Trick2fabd462011-06-21 03:22:38 +00001266 ++NumElimIdentity;
1267 Changed = true;
1268 DeadInsts.push_back(UseInst);
1269 return true;
1270}
1271
1272/// pushIVUsers - Add all uses of Def to the current IV's worklist.
1273///
Andrew Trick15832f62011-06-28 02:49:20 +00001274static void pushIVUsers(
1275 Instruction *Def,
1276 SmallPtrSet<Instruction*,16> &Simplified,
1277 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
Andrew Trick2fabd462011-06-21 03:22:38 +00001278
1279 for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
1280 UI != E; ++UI) {
1281 Instruction *User = cast<Instruction>(*UI);
1282
1283 // Avoid infinite or exponential worklist processing.
1284 // Also ensure unique worklist users.
Andrew Trick60ac7192011-06-30 01:27:23 +00001285 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
1286 // self edges first.
1287 if (User != Def && Simplified.insert(User))
Andrew Trick2fabd462011-06-21 03:22:38 +00001288 SimpleIVUsers.push_back(std::make_pair(User, Def));
1289 }
1290}
1291
1292/// isSimpleIVUser - Return true if this instruction generates a simple SCEV
1293/// expression in terms of that IV.
1294///
1295/// This is similar to IVUsers' isInsteresting() but processes each instruction
1296/// non-recursively when the operand is already known to be a simpleIVUser.
1297///
Andrew Trick1a54bb22011-07-12 00:08:50 +00001298static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
Andrew Trick2fabd462011-06-21 03:22:38 +00001299 if (!SE->isSCEVable(I->getType()))
1300 return false;
1301
1302 // Get the symbolic expression for this instruction.
1303 const SCEV *S = SE->getSCEV(I);
1304
Andrew Trickcc359d92011-06-29 23:03:57 +00001305 // We assume that terminators are not SCEVable.
1306 assert((!S || I != I->getParent()->getTerminator()) &&
1307 "can't fold terminators");
1308
Andrew Trick2fabd462011-06-21 03:22:38 +00001309 // Only consider affine recurrences.
1310 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
1311 if (AR && AR->getLoop() == L)
1312 return true;
1313
1314 return false;
1315}
1316
1317/// SimplifyIVUsersNoRewrite - Iteratively perform simplification on a worklist
1318/// of IV users. Each successive simplification may push more users which may
1319/// themselves be candidates for simplification.
1320///
1321/// The "NoRewrite" algorithm does not require IVUsers analysis. Instead, it
1322/// simplifies instructions in-place during analysis. Rather than rewriting
1323/// induction variables bottom-up from their users, it transforms a chain of
1324/// IVUsers top-down, updating the IR only when it encouters a clear
1325/// optimization opportunitiy. A SCEVExpander "Rewriter" instance is still
1326/// needed, but only used to generate a new IV (phi) of wider type for sign/zero
1327/// extend elimination.
1328///
1329/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
1330///
1331void IndVarSimplify::SimplifyIVUsersNoRewrite(Loop *L, SCEVExpander &Rewriter) {
Andrew Trick15832f62011-06-28 02:49:20 +00001332 std::map<PHINode *, WideIVInfo> WideIVMap;
1333
Andrew Trick2fabd462011-06-21 03:22:38 +00001334 SmallVector<PHINode*, 8> LoopPhis;
1335 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1336 LoopPhis.push_back(cast<PHINode>(I));
1337 }
Andrew Trick15832f62011-06-28 02:49:20 +00001338 // Each round of simplification iterates through the SimplifyIVUsers worklist
1339 // for all current phis, then determines whether any IVs can be
1340 // widened. Widening adds new phis to LoopPhis, inducing another round of
1341 // simplification on the wide IVs.
Andrew Trick2fabd462011-06-21 03:22:38 +00001342 while (!LoopPhis.empty()) {
Andrew Trick15832f62011-06-28 02:49:20 +00001343 // Evaluate as many IV expressions as possible before widening any IVs. This
Andrew Trick99a92f62011-06-28 16:45:04 +00001344 // forces SCEV to set no-wrap flags before evaluating sign/zero
Andrew Trick15832f62011-06-28 02:49:20 +00001345 // extension. The first time SCEV attempts to normalize sign/zero extension,
1346 // the result becomes final. So for the most predictable results, we delay
1347 // evaluation of sign/zero extend evaluation until needed, and avoid running
1348 // other SCEV based analysis prior to SimplifyIVUsersNoRewrite.
1349 do {
1350 PHINode *CurrIV = LoopPhis.pop_back_val();
Andrew Trick2fabd462011-06-21 03:22:38 +00001351
Andrew Trick15832f62011-06-28 02:49:20 +00001352 // Information about sign/zero extensions of CurrIV.
1353 WideIVInfo WI;
Andrew Trick2fabd462011-06-21 03:22:38 +00001354
Andrew Trick15832f62011-06-28 02:49:20 +00001355 // Instructions processed by SimplifyIVUsers for CurrIV.
1356 SmallPtrSet<Instruction*,16> Simplified;
Andrew Trick2fabd462011-06-21 03:22:38 +00001357
Andrew Trick037d1c02011-07-06 20:50:43 +00001358 // Use-def pairs if IV users waiting to be processed for CurrIV.
Andrew Trick15832f62011-06-28 02:49:20 +00001359 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
Andrew Trick2fabd462011-06-21 03:22:38 +00001360
Andrew Trick60ac7192011-06-30 01:27:23 +00001361 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
1362 // called multiple times for the same LoopPhi. This is the proper thing to
1363 // do for loop header phis that use each other.
Andrew Trick15832f62011-06-28 02:49:20 +00001364 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
1365
1366 while (!SimpleIVUsers.empty()) {
1367 Instruction *UseInst, *Operand;
1368 tie(UseInst, Operand) = SimpleIVUsers.pop_back_val();
Andrew Trick6e0ce242011-06-30 19:02:17 +00001369 // Bypass back edges to avoid extra work.
1370 if (UseInst == CurrIV) continue;
Andrew Trick15832f62011-06-28 02:49:20 +00001371
1372 if (EliminateIVUser(UseInst, Operand)) {
1373 pushIVUsers(Operand, Simplified, SimpleIVUsers);
1374 continue;
Andrew Trick2fabd462011-06-21 03:22:38 +00001375 }
Andrew Trick15832f62011-06-28 02:49:20 +00001376 if (CastInst *Cast = dyn_cast<CastInst>(UseInst)) {
1377 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
1378 if (IsSigned || Cast->getOpcode() == Instruction::ZExt) {
1379 CollectExtend(Cast, IsSigned, WI, SE, TD);
1380 }
1381 continue;
1382 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001383 if (isSimpleIVUser(UseInst, L, SE)) {
Andrew Trick15832f62011-06-28 02:49:20 +00001384 pushIVUsers(UseInst, Simplified, SimpleIVUsers);
1385 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001386 }
Andrew Trick15832f62011-06-28 02:49:20 +00001387 if (WI.WidestNativeType) {
1388 WideIVMap[CurrIV] = WI;
Andrew Trick2fabd462011-06-21 03:22:38 +00001389 }
Andrew Trick15832f62011-06-28 02:49:20 +00001390 } while(!LoopPhis.empty());
1391
1392 for (std::map<PHINode *, WideIVInfo>::const_iterator I = WideIVMap.begin(),
1393 E = WideIVMap.end(); I != E; ++I) {
1394 WidenIV Widener(I->first, I->second, LI, SE, DT, DeadInsts);
Andrew Trick2fabd462011-06-21 03:22:38 +00001395 if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
1396 Changed = true;
1397 LoopPhis.push_back(WidePhi);
1398 }
1399 }
Andrew Trick15832f62011-06-28 02:49:20 +00001400 WideIVMap.clear();
Andrew Trick2fabd462011-06-21 03:22:38 +00001401 }
1402}
1403
Andrew Trick037d1c02011-07-06 20:50:43 +00001404/// SimplifyCongruentIVs - Check for congruent phis in this loop header and
1405/// populate ExprToIVMap for use later.
1406///
1407void IndVarSimplify::SimplifyCongruentIVs(Loop *L) {
Andrew Trick6f684b02011-07-16 01:06:48 +00001408 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Andrew Trick037d1c02011-07-06 20:50:43 +00001409 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1410 PHINode *Phi = cast<PHINode>(I);
Andrew Trick1a54bb22011-07-12 00:08:50 +00001411 if (!SE->isSCEVable(Phi->getType()))
1412 continue;
1413
Andrew Trick037d1c02011-07-06 20:50:43 +00001414 const SCEV *S = SE->getSCEV(Phi);
Andrew Trick6f684b02011-07-16 01:06:48 +00001415 DenseMap<const SCEV *, PHINode *>::const_iterator Pos;
Andrew Trick037d1c02011-07-06 20:50:43 +00001416 bool Inserted;
1417 tie(Pos, Inserted) = ExprToIVMap.insert(std::make_pair(S, Phi));
1418 if (Inserted)
1419 continue;
1420 PHINode *OrigPhi = Pos->second;
1421 // Replacing the congruent phi is sufficient because acyclic redundancy
1422 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1423 // that a phi is congruent, it's almost certain to be the head of an IV
1424 // user cycle that is isomorphic with the original phi. So it's worth
1425 // eagerly cleaning up the common case of a single IV increment.
1426 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1427 Instruction *OrigInc =
1428 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1429 Instruction *IsomorphicInc =
1430 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1431 if (OrigInc != IsomorphicInc &&
1432 SE->getSCEV(OrigInc) == SE->getSCEV(IsomorphicInc) &&
1433 HoistStep(OrigInc, IsomorphicInc, DT)) {
1434 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1435 << *IsomorphicInc << '\n');
1436 IsomorphicInc->replaceAllUsesWith(OrigInc);
1437 DeadInsts.push_back(IsomorphicInc);
1438 }
1439 }
1440 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1441 ++NumElimIV;
1442 Phi->replaceAllUsesWith(OrigPhi);
1443 DeadInsts.push_back(Phi);
1444 }
1445}
1446
Andrew Trick1a54bb22011-07-12 00:08:50 +00001447//===----------------------------------------------------------------------===//
1448// LinearFunctionTestReplace and its kin. Rewrite the loop exit condition.
1449//===----------------------------------------------------------------------===//
1450
1451/// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
1452/// count expression can be safely and cheaply expanded into an instruction
1453/// sequence that can be used by LinearFunctionTestReplace.
1454static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) {
1455 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1456 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1457 BackedgeTakenCount->isZero())
1458 return false;
1459
1460 if (!L->getExitingBlock())
1461 return false;
1462
1463 // Can't rewrite non-branch yet.
1464 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1465 if (!BI)
1466 return false;
1467
1468 // Special case: If the backedge-taken count is a UDiv, it's very likely a
1469 // UDiv that ScalarEvolution produced in order to compute a precise
1470 // expression, rather than a UDiv from the user's code. If we can't find a
1471 // UDiv in the code with some simple searching, assume the former and forego
1472 // rewriting the loop.
1473 if (isa<SCEVUDivExpr>(BackedgeTakenCount)) {
1474 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
1475 if (!OrigCond) return false;
1476 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
1477 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
1478 if (R != BackedgeTakenCount) {
1479 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
1480 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
1481 if (L != BackedgeTakenCount)
1482 return false;
1483 }
1484 }
1485 return true;
1486}
1487
1488/// getBackedgeIVType - Get the widest type used by the loop test after peeking
1489/// through Truncs.
1490///
1491/// TODO: Unnecessary if LFTR does not force a canonical IV.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001492static Type *getBackedgeIVType(Loop *L) {
Andrew Trick1a54bb22011-07-12 00:08:50 +00001493 if (!L->getExitingBlock())
1494 return 0;
1495
1496 // Can't rewrite non-branch yet.
1497 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1498 if (!BI)
1499 return 0;
1500
1501 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1502 if (!Cond)
1503 return 0;
1504
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001505 Type *Ty = 0;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001506 for(User::op_iterator OI = Cond->op_begin(), OE = Cond->op_end();
1507 OI != OE; ++OI) {
1508 assert((!Ty || Ty == (*OI)->getType()) && "bad icmp operand types");
1509 TruncInst *Trunc = dyn_cast<TruncInst>(*OI);
1510 if (!Trunc)
1511 continue;
1512
1513 return Trunc->getSrcTy();
1514 }
1515 return Ty;
1516}
1517
1518/// LinearFunctionTestReplace - This method rewrites the exit condition of the
1519/// loop to be a canonical != comparison against the incremented loop induction
1520/// variable. This pass is able to rewrite the exit tests of any loop where the
1521/// SCEV analysis can determine a loop-invariant trip count of the loop, which
1522/// is actually a much broader range than just linear tests.
1523ICmpInst *IndVarSimplify::
1524LinearFunctionTestReplace(Loop *L,
1525 const SCEV *BackedgeTakenCount,
1526 PHINode *IndVar,
1527 SCEVExpander &Rewriter) {
1528 assert(canExpandBackedgeTakenCount(L, SE) && "precondition");
1529 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1530
1531 // If the exiting block is not the same as the backedge block, we must compare
1532 // against the preincremented value, otherwise we prefer to compare against
1533 // the post-incremented value.
1534 Value *CmpIndVar;
1535 const SCEV *RHS = BackedgeTakenCount;
1536 if (L->getExitingBlock() == L->getLoopLatch()) {
1537 // Add one to the "backedge-taken" count to get the trip count.
1538 // If this addition may overflow, we have to be more pessimistic and
1539 // cast the induction variable before doing the add.
1540 const SCEV *Zero = SE->getConstant(BackedgeTakenCount->getType(), 0);
1541 const SCEV *N =
1542 SE->getAddExpr(BackedgeTakenCount,
1543 SE->getConstant(BackedgeTakenCount->getType(), 1));
1544 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
1545 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
1546 // No overflow. Cast the sum.
1547 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
1548 } else {
1549 // Potential overflow. Cast before doing the add.
1550 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
1551 IndVar->getType());
1552 RHS = SE->getAddExpr(RHS,
1553 SE->getConstant(IndVar->getType(), 1));
1554 }
1555
1556 // The BackedgeTaken expression contains the number of times that the
1557 // backedge branches to the loop header. This is one less than the
1558 // number of times the loop executes, so use the incremented indvar.
1559 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
1560 } else {
1561 // We have to use the preincremented value...
1562 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
1563 IndVar->getType());
1564 CmpIndVar = IndVar;
1565 }
1566
1567 // Expand the code for the iteration count.
1568 assert(SE->isLoopInvariant(RHS, L) &&
1569 "Computed iteration count is not loop invariant!");
1570 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
1571
1572 // Insert a new icmp_ne or icmp_eq instruction before the branch.
1573 ICmpInst::Predicate Opcode;
1574 if (L->contains(BI->getSuccessor(0)))
1575 Opcode = ICmpInst::ICMP_NE;
1576 else
1577 Opcode = ICmpInst::ICMP_EQ;
1578
1579 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
1580 << " LHS:" << *CmpIndVar << '\n'
1581 << " op:\t"
1582 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
1583 << " RHS:\t" << *RHS << "\n");
1584
1585 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
1586 Cond->setDebugLoc(BI->getDebugLoc());
1587 Value *OrigCond = BI->getCondition();
1588 // It's tempting to use replaceAllUsesWith here to fully replace the old
1589 // comparison, but that's not immediately safe, since users of the old
1590 // comparison may not be dominated by the new comparison. Instead, just
1591 // update the branch to use the new comparison; in the common case this
1592 // will make old comparison dead.
1593 BI->setCondition(Cond);
1594 DeadInsts.push_back(OrigCond);
1595
1596 ++NumLFTR;
1597 Changed = true;
1598 return Cond;
1599}
1600
1601//===----------------------------------------------------------------------===//
1602// SinkUnusedInvariants. A late subpass to cleanup loop preheaders.
1603//===----------------------------------------------------------------------===//
1604
1605/// If there's a single exit block, sink any loop-invariant values that
1606/// were defined in the preheader but not used inside the loop into the
1607/// exit block to reduce register pressure in the loop.
1608void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
1609 BasicBlock *ExitBlock = L->getExitBlock();
1610 if (!ExitBlock) return;
1611
1612 BasicBlock *Preheader = L->getLoopPreheader();
1613 if (!Preheader) return;
1614
1615 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
1616 BasicBlock::iterator I = Preheader->getTerminator();
1617 while (I != Preheader->begin()) {
1618 --I;
1619 // New instructions were inserted at the end of the preheader.
1620 if (isa<PHINode>(I))
1621 break;
1622
1623 // Don't move instructions which might have side effects, since the side
1624 // effects need to complete before instructions inside the loop. Also don't
1625 // move instructions which might read memory, since the loop may modify
1626 // memory. Note that it's okay if the instruction might have undefined
1627 // behavior: LoopSimplify guarantees that the preheader dominates the exit
1628 // block.
1629 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
1630 continue;
1631
1632 // Skip debug info intrinsics.
1633 if (isa<DbgInfoIntrinsic>(I))
1634 continue;
1635
1636 // Don't sink static AllocaInsts out of the entry block, which would
1637 // turn them into dynamic allocas!
1638 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
1639 if (AI->isStaticAlloca())
1640 continue;
1641
1642 // Determine if there is a use in or before the loop (direct or
1643 // otherwise).
1644 bool UsedInLoop = false;
1645 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1646 UI != UE; ++UI) {
1647 User *U = *UI;
1648 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
1649 if (PHINode *P = dyn_cast<PHINode>(U)) {
1650 unsigned i =
1651 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
1652 UseBB = P->getIncomingBlock(i);
1653 }
1654 if (UseBB == Preheader || L->contains(UseBB)) {
1655 UsedInLoop = true;
1656 break;
1657 }
1658 }
1659
1660 // If there is, the def must remain in the preheader.
1661 if (UsedInLoop)
1662 continue;
1663
1664 // Otherwise, sink it to the exit block.
1665 Instruction *ToMove = I;
1666 bool Done = false;
1667
1668 if (I != Preheader->begin()) {
1669 // Skip debug info intrinsics.
1670 do {
1671 --I;
1672 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
1673
1674 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
1675 Done = true;
1676 } else {
1677 Done = true;
1678 }
1679
1680 ToMove->moveBefore(InsertPt);
1681 if (Done) break;
1682 InsertPt = ToMove;
1683 }
1684}
1685
1686//===----------------------------------------------------------------------===//
1687// IndVarSimplify driver. Manage several subpasses of IV simplification.
1688//===----------------------------------------------------------------------===//
1689
Dan Gohmanc2390b12009-02-12 22:19:27 +00001690bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmana5283822010-06-18 01:35:11 +00001691 // If LoopSimplify form is not available, stay out of trouble. Some notes:
1692 // - LSR currently only supports LoopSimplify-form loops. Indvars'
1693 // canonicalization can be a pessimization without LSR to "clean up"
1694 // afterwards.
1695 // - We depend on having a preheader; in particular,
1696 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
1697 // and we're in trouble if we can't find the induction variable even when
1698 // we've manually inserted one.
1699 if (!L->isLoopSimplifyForm())
1700 return false;
1701
Andrew Trick2fabd462011-06-21 03:22:38 +00001702 if (!DisableIVRewrite)
1703 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +00001704 LI = &getAnalysis<LoopInfo>();
1705 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +00001706 DT = &getAnalysis<DominatorTree>();
Andrew Trick37da4082011-05-04 02:10:13 +00001707 TD = getAnalysisIfAvailable<TargetData>();
1708
Andrew Trickb12a7542011-03-17 23:51:11 +00001709 DeadInsts.clear();
Devang Patel5ee99972007-03-07 06:39:01 +00001710 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +00001711
Dan Gohman2d1be872009-04-16 03:18:22 +00001712 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +00001713 // transform them to use integer recurrences.
1714 RewriteNonIntegerIVs(L);
1715
Dan Gohman0bba49c2009-07-07 17:06:11 +00001716 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +00001717
Dan Gohman667d7872009-06-26 22:53:46 +00001718 // Create a rewriter object which we'll use to transform the code with.
Andrew Trick5e7645b2011-06-28 05:07:32 +00001719 SCEVExpander Rewriter(*SE, "indvars");
Andrew Trick156d4602011-06-27 23:17:44 +00001720
1721 // Eliminate redundant IV users.
Andrew Trick15832f62011-06-28 02:49:20 +00001722 //
1723 // Simplification works best when run before other consumers of SCEV. We
1724 // attempt to avoid evaluating SCEVs for sign/zero extend operations until
1725 // other expressions involving loop IVs have been evaluated. This helps SCEV
Andrew Trick99a92f62011-06-28 16:45:04 +00001726 // set no-wrap flags before normalizing sign/zero extension.
Andrew Trick156d4602011-06-27 23:17:44 +00001727 if (DisableIVRewrite) {
Andrew Trick37da4082011-05-04 02:10:13 +00001728 Rewriter.disableCanonicalMode();
Andrew Trick156d4602011-06-27 23:17:44 +00001729 SimplifyIVUsersNoRewrite(L, Rewriter);
1730 }
Andrew Trick37da4082011-05-04 02:10:13 +00001731
Chris Lattner40bf8b42004-04-02 20:24:31 +00001732 // Check to see if this loop has a computable loop-invariant execution count.
1733 // If so, this means that we can compute the final value of any expressions
1734 // that are recurrent in the loop, and substitute the exit values from the
1735 // loop into any instructions outside of the loop that use the final values of
1736 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +00001737 //
Dan Gohman46bdfb02009-02-24 18:55:53 +00001738 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman454d26d2010-02-22 04:11:59 +00001739 RewriteLoopExitValues(L, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +00001740
Andrew Trickf85092c2011-05-20 18:25:42 +00001741 // Eliminate redundant IV users.
Andrew Trick156d4602011-06-27 23:17:44 +00001742 if (!DisableIVRewrite)
Andrew Trick2fabd462011-06-21 03:22:38 +00001743 SimplifyIVUsers(Rewriter);
Dan Gohmana590b792010-04-13 01:46:36 +00001744
Andrew Trick6f684b02011-07-16 01:06:48 +00001745 // Eliminate redundant IV cycles.
Andrew Trick037d1c02011-07-06 20:50:43 +00001746 if (DisableIVRewrite)
1747 SimplifyCongruentIVs(L);
1748
Dan Gohman81db61a2009-05-12 02:17:14 +00001749 // Compute the type of the largest recurrence expression, and decide whether
1750 // a canonical induction variable should be inserted.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001751 Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00001752 bool NeedCannIV = false;
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001753 bool ExpandBECount = canExpandBackedgeTakenCount(L, SE);
Andrew Trick4dfdf242011-05-03 22:24:10 +00001754 if (ExpandBECount) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001755 // If we have a known trip count and a single exit block, we'll be
1756 // rewriting the loop exit test condition below, which requires a
1757 // canonical induction variable.
Andrew Trick4dfdf242011-05-03 22:24:10 +00001758 NeedCannIV = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001759 Type *Ty = BackedgeTakenCount->getType();
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001760 if (DisableIVRewrite) {
1761 // In this mode, SimplifyIVUsers may have already widened the IV used by
1762 // the backedge test and inserted a Trunc on the compare's operand. Get
1763 // the wider type to avoid creating a redundant narrow IV only used by the
1764 // loop test.
1765 LargestType = getBackedgeIVType(L);
1766 }
Andrew Trick4dfdf242011-05-03 22:24:10 +00001767 if (!LargestType ||
1768 SE->getTypeSizeInBits(Ty) >
1769 SE->getTypeSizeInBits(LargestType))
1770 LargestType = SE->getEffectiveSCEVType(Ty);
Chris Lattnerf50af082004-04-17 18:08:33 +00001771 }
Andrew Trick37da4082011-05-04 02:10:13 +00001772 if (!DisableIVRewrite) {
1773 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
1774 NeedCannIV = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001775 Type *Ty =
Andrew Trick37da4082011-05-04 02:10:13 +00001776 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
1777 if (!LargestType ||
1778 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001779 SE->getTypeSizeInBits(LargestType))
Andrew Trick37da4082011-05-04 02:10:13 +00001780 LargestType = Ty;
1781 }
Chris Lattner6148c022001-12-03 17:28:42 +00001782 }
1783
Dan Gohmanf451cb82010-02-10 16:03:48 +00001784 // Now that we know the largest of the induction variable expressions
Dan Gohman81db61a2009-05-12 02:17:14 +00001785 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohman43ef3fb2010-07-20 17:18:52 +00001786 PHINode *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00001787 if (NeedCannIV) {
Dan Gohman85669632010-02-25 06:57:05 +00001788 // Check to see if the loop already has any canonical-looking induction
1789 // variables. If any are present and wider than the planned canonical
1790 // induction variable, temporarily remove them, so that the Rewriter
1791 // doesn't attempt to reuse them.
1792 SmallVector<PHINode *, 2> OldCannIVs;
1793 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
Dan Gohman4d8414f2009-06-13 16:25:49 +00001794 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
1795 SE->getTypeSizeInBits(LargestType))
1796 OldCannIV->removeFromParent();
1797 else
Dan Gohman85669632010-02-25 06:57:05 +00001798 break;
1799 OldCannIVs.push_back(OldCannIV);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001800 }
1801
Dan Gohman667d7872009-06-26 22:53:46 +00001802 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001803
Dan Gohmanc2390b12009-02-12 22:19:27 +00001804 ++NumInserted;
1805 Changed = true;
David Greenef67ef312010-01-05 01:27:06 +00001806 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +00001807
1808 // Now that the official induction variable is established, reinsert
Dan Gohman85669632010-02-25 06:57:05 +00001809 // any old canonical-looking variables after it so that the IR remains
1810 // consistent. They will be deleted as part of the dead-PHI deletion at
Dan Gohman4d8414f2009-06-13 16:25:49 +00001811 // the end of the pass.
Dan Gohman85669632010-02-25 06:57:05 +00001812 while (!OldCannIVs.empty()) {
1813 PHINode *OldCannIV = OldCannIVs.pop_back_val();
1814 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
1815 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001816 }
Chris Lattner15cad752003-12-23 07:47:09 +00001817
Dan Gohmanc2390b12009-02-12 22:19:27 +00001818 // If we have a trip count expression, rewrite the loop's exit condition
1819 // using it. We can currently only handle loops with a single exit.
Dan Gohman81db61a2009-05-12 02:17:14 +00001820 ICmpInst *NewICmp = 0;
Andrew Trick4dfdf242011-05-03 22:24:10 +00001821 if (ExpandBECount) {
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001822 assert(canExpandBackedgeTakenCount(L, SE) &&
Andrew Trick4dfdf242011-05-03 22:24:10 +00001823 "canonical IV disrupted BackedgeTaken expansion");
Dan Gohman81db61a2009-05-12 02:17:14 +00001824 assert(NeedCannIV &&
1825 "LinearFunctionTestReplace requires a canonical induction variable");
Andrew Trick56147692011-07-16 01:18:53 +00001826 // Check preconditions for proper SCEVExpander operation. SCEV does not
1827 // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
1828 // pass that uses the SCEVExpander must do it. This does not work well for
1829 // loop passes because SCEVExpander makes assumptions about all loops, while
1830 // LoopPassManager only forces the current loop to be simplified.
1831 //
1832 // FIXME: SCEV expansion has no way to bail out, so the caller must
1833 // explicitly check any assumptions made by SCEV. Brittle.
1834 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
1835 if (!AR || AR->getLoop()->getLoopPreheader())
1836 NewICmp =
1837 LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +00001838 }
Andrew Trickb12a7542011-03-17 23:51:11 +00001839 // Rewrite IV-derived expressions.
Andrew Trick37da4082011-05-04 02:10:13 +00001840 if (!DisableIVRewrite)
1841 RewriteIVExpressions(L, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +00001842
Andrew Trickb12a7542011-03-17 23:51:11 +00001843 // Clear the rewriter cache, because values that are in the rewriter's cache
1844 // can be deleted in the loop below, causing the AssertingVH in the cache to
1845 // trigger.
1846 Rewriter.clear();
1847
1848 // Now that we're done iterating through lists, clean up any instructions
1849 // which are now dead.
1850 while (!DeadInsts.empty())
1851 if (Instruction *Inst =
1852 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
1853 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1854
Dan Gohman667d7872009-06-26 22:53:46 +00001855 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +00001856
Dan Gohman81db61a2009-05-12 02:17:14 +00001857 // Loop-invariant instructions in the preheader that aren't used in the
1858 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +00001859 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +00001860
1861 // For completeness, inform IVUsers of the IV use in the newly-created
1862 // loop exit test instruction.
Andrew Trick2fabd462011-06-21 03:22:38 +00001863 if (NewICmp && IU)
Andrew Trick4417e532011-06-21 15:43:52 +00001864 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
Dan Gohman81db61a2009-05-12 02:17:14 +00001865
1866 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +00001867 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +00001868 // Check a post-condition.
Dan Gohmanbbf81d82010-03-10 19:38:49 +00001869 assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
Devang Patel5ee99972007-03-07 06:39:01 +00001870 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +00001871}