blob: ab61424664e81ed90f820b01b877cc3903a8e770 [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//
Andrew Trick4b4bb712011-08-10 03:46:27 +000014// Additionally, unless -disable-iv-rewrite is on, this transformation makes the
15// following changes to each loop with an identifiable induction variable:
Chris Lattner40bf8b42004-04-02 20:24:31 +000016// 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 Trick4b4bb712011-08-10 03:46:27 +000060#include "llvm/Transforms/Utils/SimplifyIndVar.h"
Andrew Trick37da4082011-05-04 02:10:13 +000061#include "llvm/Target/TargetData.h"
Andrew Trick037d1c02011-07-06 20:50:43 +000062#include "llvm/ADT/DenseMap.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000063#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000064#include "llvm/ADT/Statistic.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");
Andrew Trick2fabd462011-06-21 03:22:38 +000072STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");
Andrew Trick037d1c02011-07-06 20:50:43 +000073STATISTIC(NumElimIV , "Number of congruent IVs eliminated");
Chris Lattner3324e712003-12-22 03:58:44 +000074
Andrew Trick4b4bb712011-08-10 03:46:27 +000075namespace llvm {
76 cl::opt<bool> DisableIVRewrite(
77 "disable-iv-rewrite", cl::Hidden,
78 cl::desc("Disable canonical induction variable rewriting"));
Andrew Trick75ebc0e2011-09-06 20:20:38 +000079
80 // Trip count verification can be enabled by default under NDEBUG if we
81 // implement a strong expression equivalence checker in SCEV. Until then, we
82 // use the verify-indvars flag, which may assert in some cases.
83 cl::opt<bool> VerifyIndvars(
84 "verify-indvars", cl::Hidden,
85 cl::desc("Verify the ScalarEvolution result after running indvars"));
Andrew Trick4b4bb712011-08-10 03:46:27 +000086}
Andrew Trick37da4082011-05-04 02:10:13 +000087
Andrew Trickfc933c02011-07-18 20:32:31 +000088// Temporary flag for use with -disable-iv-rewrite to force a canonical IV for
89// LFTR purposes.
90static cl::opt<bool> ForceLFTR(
91 "force-lftr", cl::Hidden,
92 cl::desc("Enable forced linear function test replacement"));
93
Chris Lattner0e5f4992006-12-19 21:40:18 +000094namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000095 class IndVarSimplify : public LoopPass {
Dan Gohman81db61a2009-05-12 02:17:14 +000096 IVUsers *IU;
Chris Lattner40bf8b42004-04-02 20:24:31 +000097 LoopInfo *LI;
98 ScalarEvolution *SE;
Dan Gohmande53dc02009-06-27 05:16:57 +000099 DominatorTree *DT;
Andrew Trick37da4082011-05-04 02:10:13 +0000100 TargetData *TD;
Andrew Trick2fabd462011-06-21 03:22:38 +0000101
Andrew Trickb12a7542011-03-17 23:51:11 +0000102 SmallVector<WeakVH, 16> DeadInsts;
Chris Lattner15cad752003-12-23 07:47:09 +0000103 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +0000104 public:
Devang Patel794fd752007-05-01 21:15:47 +0000105
Dan Gohman5668cf72009-07-15 01:26:32 +0000106 static char ID; // Pass identification, replacement for typeid
Andrew Trick2fabd462011-06-21 03:22:38 +0000107 IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0),
Andrew Trick15832f62011-06-28 02:49:20 +0000108 Changed(false) {
Owen Anderson081c34b2010-10-19 17:21:58 +0000109 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
110 }
Devang Patel794fd752007-05-01 21:15:47 +0000111
Dan Gohman5668cf72009-07-15 01:26:32 +0000112 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Dan Gohman60f8a632009-02-17 20:49:49 +0000113
Dan Gohman5668cf72009-07-15 01:26:32 +0000114 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
115 AU.addRequired<DominatorTree>();
116 AU.addRequired<LoopInfo>();
117 AU.addRequired<ScalarEvolution>();
118 AU.addRequiredID(LoopSimplifyID);
119 AU.addRequiredID(LCSSAID);
Andrew Trick56caa092011-06-28 03:01:46 +0000120 if (!DisableIVRewrite)
121 AU.addRequired<IVUsers>();
Dan Gohman5668cf72009-07-15 01:26:32 +0000122 AU.addPreserved<ScalarEvolution>();
123 AU.addPreservedID(LoopSimplifyID);
124 AU.addPreservedID(LCSSAID);
Andrew Trick2fabd462011-06-21 03:22:38 +0000125 if (!DisableIVRewrite)
126 AU.addPreserved<IVUsers>();
Dan Gohman5668cf72009-07-15 01:26:32 +0000127 AU.setPreservesCFG();
128 }
Chris Lattner15cad752003-12-23 07:47:09 +0000129
Chris Lattner40bf8b42004-04-02 20:24:31 +0000130 private:
Andrew Trick037d1c02011-07-06 20:50:43 +0000131 virtual void releaseMemory() {
Andrew Trick037d1c02011-07-06 20:50:43 +0000132 DeadInsts.clear();
133 }
134
Andrew Trickb12a7542011-03-17 23:51:11 +0000135 bool isValidRewrite(Value *FromVal, Value *ToVal);
Devang Patel5ee99972007-03-07 06:39:01 +0000136
Andrew Trick1a54bb22011-07-12 00:08:50 +0000137 void HandleFloatingPointIV(Loop *L, PHINode *PH);
138 void RewriteNonIntegerIVs(Loop *L);
139
Andrew Trick4b4bb712011-08-10 03:46:27 +0000140 void SimplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LPPassManager &LPM);
Andrew Trick06988bc2011-08-06 07:00:37 +0000141
Andrew Trick037d1c02011-07-06 20:50:43 +0000142 void SimplifyCongruentIVs(Loop *L);
143
Andrew Trick4b4bb712011-08-10 03:46:27 +0000144 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
145
Dan Gohman454d26d2010-02-22 04:11:59 +0000146 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
Devang Pateld22a8492008-09-09 21:41:07 +0000147
Andrew Trickfc933c02011-07-18 20:32:31 +0000148 Value *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
149 PHINode *IndVar, SCEVExpander &Rewriter);
Dan Gohman81db61a2009-05-12 02:17:14 +0000150
Andrew Trick1a54bb22011-07-12 00:08:50 +0000151 void SinkUnusedInvariants(Loop *L);
Chris Lattner3324e712003-12-22 03:58:44 +0000152 };
Chris Lattner5e761402002-09-10 05:24:05 +0000153}
Chris Lattner394437f2001-12-04 04:32:29 +0000154
Dan Gohman844731a2008-05-13 00:00:25 +0000155char IndVarSimplify::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000156INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000157 "Induction Variable Simplification", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000158INITIALIZE_PASS_DEPENDENCY(DominatorTree)
159INITIALIZE_PASS_DEPENDENCY(LoopInfo)
160INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
161INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
162INITIALIZE_PASS_DEPENDENCY(LCSSA)
163INITIALIZE_PASS_DEPENDENCY(IVUsers)
164INITIALIZE_PASS_END(IndVarSimplify, "indvars",
Andrew Trick37da4082011-05-04 02:10:13 +0000165 "Induction Variable Simplification", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000166
Daniel Dunbar394f0442008-10-22 23:32:42 +0000167Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000168 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000169}
170
Andrew Trickb12a7542011-03-17 23:51:11 +0000171/// isValidRewrite - Return true if the SCEV expansion generated by the
172/// rewriter can replace the original value. SCEV guarantees that it
173/// produces the same value, but the way it is produced may be illegal IR.
174/// Ideally, this function will only be called for verification.
175bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
176 // If an SCEV expression subsumed multiple pointers, its expansion could
177 // reassociate the GEP changing the base pointer. This is illegal because the
178 // final address produced by a GEP chain must be inbounds relative to its
179 // underlying object. Otherwise basic alias analysis, among other things,
180 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
181 // producing an expression involving multiple pointers. Until then, we must
182 // bail out here.
183 //
184 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
185 // because it understands lcssa phis while SCEV does not.
186 Value *FromPtr = FromVal;
187 Value *ToPtr = ToVal;
188 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
189 FromPtr = GEP->getPointerOperand();
190 }
191 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
192 ToPtr = GEP->getPointerOperand();
193 }
194 if (FromPtr != FromVal || ToPtr != ToVal) {
195 // Quickly check the common case
196 if (FromPtr == ToPtr)
197 return true;
198
199 // SCEV may have rewritten an expression that produces the GEP's pointer
200 // operand. That's ok as long as the pointer operand has the same base
201 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
202 // base of a recurrence. This handles the case in which SCEV expansion
203 // converts a pointer type recurrence into a nonrecurrent pointer base
204 // indexed by an integer recurrence.
205 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
206 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
207 if (FromBase == ToBase)
208 return true;
209
210 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
211 << *FromBase << " != " << *ToBase << "\n");
212
213 return false;
214 }
215 return true;
216}
217
Andrew Trick86c98142011-07-20 05:32:06 +0000218/// Determine the insertion point for this user. By default, insert immediately
219/// before the user. SCEVExpander or LICM will hoist loop invariants out of the
220/// loop. For PHI nodes, there may be multiple uses, so compute the nearest
221/// common dominator for the incoming blocks.
222static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
223 DominatorTree *DT) {
224 PHINode *PHI = dyn_cast<PHINode>(User);
225 if (!PHI)
226 return User;
227
228 Instruction *InsertPt = 0;
229 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
230 if (PHI->getIncomingValue(i) != Def)
231 continue;
232
233 BasicBlock *InsertBB = PHI->getIncomingBlock(i);
234 if (!InsertPt) {
235 InsertPt = InsertBB->getTerminator();
236 continue;
237 }
238 InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
239 InsertPt = InsertBB->getTerminator();
240 }
241 assert(InsertPt && "Missing phi operand");
Jay Foad626f52d2011-07-20 08:15:21 +0000242 assert((!isa<Instruction>(Def) ||
243 DT->dominates(cast<Instruction>(Def), InsertPt)) &&
Andrew Trick86c98142011-07-20 05:32:06 +0000244 "def does not dominate all uses");
245 return InsertPt;
246}
247
Andrew Trick1a54bb22011-07-12 00:08:50 +0000248//===----------------------------------------------------------------------===//
249// RewriteNonIntegerIVs and helpers. Prefer integer IVs.
250//===----------------------------------------------------------------------===//
Andrew Trick4dfdf242011-05-03 22:24:10 +0000251
Andrew Trick1a54bb22011-07-12 00:08:50 +0000252/// ConvertToSInt - Convert APF to an integer, if possible.
253static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
254 bool isExact = false;
255 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000256 return false;
Andrew Trick1a54bb22011-07-12 00:08:50 +0000257 // See if we can convert this to an int64_t
258 uint64_t UIntVal;
259 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
260 &isExact) != APFloat::opOK || !isExact)
Andrew Trick4dfdf242011-05-03 22:24:10 +0000261 return false;
Andrew Trick1a54bb22011-07-12 00:08:50 +0000262 IntVal = UIntVal;
Andrew Trick4dfdf242011-05-03 22:24:10 +0000263 return true;
264}
265
Andrew Trick1a54bb22011-07-12 00:08:50 +0000266/// HandleFloatingPointIV - If the loop has floating induction variable
267/// then insert corresponding integer induction variable if possible.
268/// For example,
269/// for(double i = 0; i < 10000; ++i)
270/// bar(i)
271/// is converted into
272/// for(int i = 0; i < 10000; ++i)
273/// bar((double)i);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000274///
Andrew Trick1a54bb22011-07-12 00:08:50 +0000275void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
276 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
277 unsigned BackEdge = IncomingEdge^1;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000278
Andrew Trick1a54bb22011-07-12 00:08:50 +0000279 // Check incoming value.
280 ConstantFP *InitValueVal =
281 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000282
Andrew Trick1a54bb22011-07-12 00:08:50 +0000283 int64_t InitValue;
284 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
285 return;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000286
Andrew Trick1a54bb22011-07-12 00:08:50 +0000287 // Check IV increment. Reject this PN if increment operation is not
288 // an add or increment value can not be represented by an integer.
289 BinaryOperator *Incr =
290 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
291 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000292
Andrew Trick1a54bb22011-07-12 00:08:50 +0000293 // If this is not an add of the PHI with a constantfp, or if the constant fp
294 // is not an integer, bail out.
295 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
296 int64_t IncValue;
297 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
298 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
299 return;
300
301 // Check Incr uses. One user is PN and the other user is an exit condition
302 // used by the conditional terminator.
303 Value::use_iterator IncrUse = Incr->use_begin();
304 Instruction *U1 = cast<Instruction>(*IncrUse++);
305 if (IncrUse == Incr->use_end()) return;
306 Instruction *U2 = cast<Instruction>(*IncrUse++);
307 if (IncrUse != Incr->use_end()) return;
308
309 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
310 // only used by a branch, we can't transform it.
311 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
312 if (!Compare)
313 Compare = dyn_cast<FCmpInst>(U2);
314 if (Compare == 0 || !Compare->hasOneUse() ||
315 !isa<BranchInst>(Compare->use_back()))
316 return;
317
318 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
319
320 // We need to verify that the branch actually controls the iteration count
321 // of the loop. If not, the new IV can overflow and no one will notice.
322 // The branch block must be in the loop and one of the successors must be out
323 // of the loop.
324 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
325 if (!L->contains(TheBr->getParent()) ||
326 (L->contains(TheBr->getSuccessor(0)) &&
327 L->contains(TheBr->getSuccessor(1))))
328 return;
329
330
331 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
332 // transform it.
333 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
334 int64_t ExitValue;
335 if (ExitValueVal == 0 ||
336 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
337 return;
338
339 // Find new predicate for integer comparison.
340 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
341 switch (Compare->getPredicate()) {
342 default: return; // Unknown comparison.
343 case CmpInst::FCMP_OEQ:
344 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
345 case CmpInst::FCMP_ONE:
346 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
347 case CmpInst::FCMP_OGT:
348 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
349 case CmpInst::FCMP_OGE:
350 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
351 case CmpInst::FCMP_OLT:
352 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
353 case CmpInst::FCMP_OLE:
354 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000355 }
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000356
Andrew Trick1a54bb22011-07-12 00:08:50 +0000357 // We convert the floating point induction variable to a signed i32 value if
358 // we can. This is only safe if the comparison will not overflow in a way
359 // that won't be trapped by the integer equivalent operations. Check for this
360 // now.
361 // TODO: We could use i64 if it is native and the range requires it.
Dan Gohmanca9b7032010-04-12 21:13:43 +0000362
Andrew Trick1a54bb22011-07-12 00:08:50 +0000363 // The start/stride/exit values must all fit in signed i32.
364 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
365 return;
366
367 // If not actually striding (add x, 0.0), avoid touching the code.
368 if (IncValue == 0)
369 return;
370
371 // Positive and negative strides have different safety conditions.
372 if (IncValue > 0) {
373 // If we have a positive stride, we require the init to be less than the
374 // exit value and an equality or less than comparison.
375 if (InitValue >= ExitValue ||
376 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
377 return;
378
379 uint32_t Range = uint32_t(ExitValue-InitValue);
380 if (NewPred == CmpInst::ICMP_SLE) {
381 // Normalize SLE -> SLT, check for infinite loop.
382 if (++Range == 0) return; // Range overflows.
Dan Gohmanc2390b12009-02-12 22:19:27 +0000383 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000384
Andrew Trick1a54bb22011-07-12 00:08:50 +0000385 unsigned Leftover = Range % uint32_t(IncValue);
386
387 // If this is an equality comparison, we require that the strided value
388 // exactly land on the exit value, otherwise the IV condition will wrap
389 // around and do things the fp IV wouldn't.
390 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
391 Leftover != 0)
392 return;
393
394 // If the stride would wrap around the i32 before exiting, we can't
395 // transform the IV.
396 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
397 return;
398
Chris Lattnerd2440572004-04-15 20:26:22 +0000399 } else {
Andrew Trick1a54bb22011-07-12 00:08:50 +0000400 // If we have a negative stride, we require the init to be greater than the
401 // exit value and an equality or greater than comparison.
402 if (InitValue >= ExitValue ||
403 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
404 return;
405
406 uint32_t Range = uint32_t(InitValue-ExitValue);
407 if (NewPred == CmpInst::ICMP_SGE) {
408 // Normalize SGE -> SGT, check for infinite loop.
409 if (++Range == 0) return; // Range overflows.
410 }
411
412 unsigned Leftover = Range % uint32_t(-IncValue);
413
414 // If this is an equality comparison, we require that the strided value
415 // exactly land on the exit value, otherwise the IV condition will wrap
416 // around and do things the fp IV wouldn't.
417 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
418 Leftover != 0)
419 return;
420
421 // If the stride would wrap around the i32 before exiting, we can't
422 // transform the IV.
423 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
424 return;
Chris Lattnerd2440572004-04-15 20:26:22 +0000425 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000426
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000427 IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000428
Andrew Trick1a54bb22011-07-12 00:08:50 +0000429 // Insert new integer induction variable.
430 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
431 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
432 PN->getIncomingBlock(IncomingEdge));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000433
Andrew Trick1a54bb22011-07-12 00:08:50 +0000434 Value *NewAdd =
435 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
436 Incr->getName()+".int", Incr);
437 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
Dan Gohmanc2390b12009-02-12 22:19:27 +0000438
Andrew Trick1a54bb22011-07-12 00:08:50 +0000439 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
440 ConstantInt::get(Int32Ty, ExitValue),
441 Compare->getName());
Dan Gohman81db61a2009-05-12 02:17:14 +0000442
Andrew Trick1a54bb22011-07-12 00:08:50 +0000443 // In the following deletions, PN may become dead and may be deleted.
444 // Use a WeakVH to observe whether this happens.
445 WeakVH WeakPH = PN;
446
447 // Delete the old floating point exit comparison. The branch starts using the
448 // new comparison.
449 NewCompare->takeName(Compare);
450 Compare->replaceAllUsesWith(NewCompare);
451 RecursivelyDeleteTriviallyDeadInstructions(Compare);
452
453 // Delete the old floating point increment.
454 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
455 RecursivelyDeleteTriviallyDeadInstructions(Incr);
456
457 // If the FP induction variable still has uses, this is because something else
458 // in the loop uses its value. In order to canonicalize the induction
459 // variable, we chose to eliminate the IV and rewrite it in terms of an
460 // int->fp cast.
461 //
462 // We give preference to sitofp over uitofp because it is faster on most
463 // platforms.
464 if (WeakPH) {
465 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
Bill Wendlingb05fdd62011-08-24 20:28:43 +0000466 PN->getParent()->getFirstInsertionPt());
Andrew Trick1a54bb22011-07-12 00:08:50 +0000467 PN->replaceAllUsesWith(Conv);
468 RecursivelyDeleteTriviallyDeadInstructions(PN);
469 }
470
471 // Add a new IVUsers entry for the newly-created integer PHI.
472 if (IU)
473 IU->AddUsersIfInteresting(NewPHI);
Andrew Trick4b4bb712011-08-10 03:46:27 +0000474
475 Changed = true;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000476}
477
Andrew Trick1a54bb22011-07-12 00:08:50 +0000478void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
479 // First step. Check to see if there are any floating-point recurrences.
480 // If there are, change them into integer recurrences, permitting analysis by
481 // the SCEV routines.
482 //
483 BasicBlock *Header = L->getHeader();
484
485 SmallVector<WeakVH, 8> PHIs;
486 for (BasicBlock::iterator I = Header->begin();
487 PHINode *PN = dyn_cast<PHINode>(I); ++I)
488 PHIs.push_back(PN);
489
490 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
491 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
492 HandleFloatingPointIV(L, PN);
493
494 // If the loop previously had floating-point IV, ScalarEvolution
495 // may not have been able to compute a trip count. Now that we've done some
496 // re-writing, the trip count may be computable.
497 if (Changed)
498 SE->forgetLoop(L);
499}
500
501//===----------------------------------------------------------------------===//
502// RewriteLoopExitValues - Optimize IV users outside the loop.
503// As a side effect, reduces the amount of IV processing within the loop.
504//===----------------------------------------------------------------------===//
505
Chris Lattner40bf8b42004-04-02 20:24:31 +0000506/// RewriteLoopExitValues - Check to see if this loop has a computable
507/// loop-invariant execution count. If so, this means that we can compute the
508/// final value of any expressions that are recurrent in the loop, and
509/// substitute the exit values from the loop into any instructions outside of
510/// the loop that use the final values of the current expressions.
Dan Gohman81db61a2009-05-12 02:17:14 +0000511///
512/// This is mostly redundant with the regular IndVarSimplify activities that
513/// happen later, except that it's more powerful in some cases, because it's
514/// able to brute-force evaluate arbitrary instructions as long as they have
515/// constant operands at the beginning of the loop.
Chris Lattnerf1859892011-01-09 02:16:18 +0000516void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
Dan Gohman81db61a2009-05-12 02:17:14 +0000517 // Verify the input to the pass in already in LCSSA form.
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000518 assert(L->isLCSSAForm(*DT));
Dan Gohman81db61a2009-05-12 02:17:14 +0000519
Devang Patelb7211a22007-08-21 00:31:24 +0000520 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000521 L->getUniqueExitBlocks(ExitBlocks);
Misha Brukmanfd939082005-04-21 23:48:37 +0000522
Chris Lattner9f3d7382007-03-04 03:43:23 +0000523 // Find all values that are computed inside the loop, but used outside of it.
524 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
525 // the exit blocks of the loop to find them.
526 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
527 BasicBlock *ExitBB = ExitBlocks[i];
Dan Gohmancafb8132009-02-17 19:13:57 +0000528
Chris Lattner9f3d7382007-03-04 03:43:23 +0000529 // If there are no PHI nodes in this exit block, then no values defined
530 // inside the loop are used on this path, skip it.
531 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
532 if (!PN) continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000533
Chris Lattner9f3d7382007-03-04 03:43:23 +0000534 unsigned NumPreds = PN->getNumIncomingValues();
Dan Gohmancafb8132009-02-17 19:13:57 +0000535
Chris Lattner9f3d7382007-03-04 03:43:23 +0000536 // Iterate over all of the PHI nodes.
537 BasicBlock::iterator BBI = ExitBB->begin();
538 while ((PN = dyn_cast<PHINode>(BBI++))) {
Torok Edwin3790fb02009-05-24 19:36:09 +0000539 if (PN->use_empty())
540 continue; // dead use, don't replace it
Dan Gohman814f2b22010-02-18 21:34:02 +0000541
542 // SCEV only supports integer expressions for now.
543 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
544 continue;
545
Dale Johannesen45a2d7d2010-02-19 07:14:22 +0000546 // It's necessary to tell ScalarEvolution about this explicitly so that
547 // it can walk the def-use list and forget all SCEVs, as it may not be
548 // watching the PHI itself. Once the new exit value is in place, there
549 // may not be a def-use connection between the loop and every instruction
550 // which got a SCEVAddRecExpr for that loop.
551 SE->forgetValue(PN);
552
Chris Lattner9f3d7382007-03-04 03:43:23 +0000553 // Iterate over all of the values in all the PHI nodes.
554 for (unsigned i = 0; i != NumPreds; ++i) {
555 // If the value being merged in is not integer or is not defined
556 // in the loop, skip it.
557 Value *InVal = PN->getIncomingValue(i);
Dan Gohman814f2b22010-02-18 21:34:02 +0000558 if (!isa<Instruction>(InVal))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000559 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000560
Chris Lattner9f3d7382007-03-04 03:43:23 +0000561 // If this pred is for a subloop, not L itself, skip it.
Dan Gohmancafb8132009-02-17 19:13:57 +0000562 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
Chris Lattner9f3d7382007-03-04 03:43:23 +0000563 continue; // The Block is in a subloop, skip it.
564
565 // Check that InVal is defined in the loop.
566 Instruction *Inst = cast<Instruction>(InVal);
Dan Gohman92329c72009-12-18 01:24:09 +0000567 if (!L->contains(Inst))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000568 continue;
Dan Gohmancafb8132009-02-17 19:13:57 +0000569
Chris Lattner9f3d7382007-03-04 03:43:23 +0000570 // Okay, this instruction has a user outside of the current loop
571 // and varies predictably *inside* the loop. Evaluate the value it
572 // contains when the loop exits, if possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000573 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
Dan Gohman17ead4f2010-11-17 21:23:15 +0000574 if (!SE->isLoopInvariant(ExitValue, L))
Chris Lattner9f3d7382007-03-04 03:43:23 +0000575 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000576
Dan Gohman667d7872009-06-26 22:53:46 +0000577 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000578
David Greenef67ef312010-01-05 01:27:06 +0000579 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000580 << " LoopVal = " << *Inst << "\n");
Chris Lattner9f3d7382007-03-04 03:43:23 +0000581
Andrew Trickb12a7542011-03-17 23:51:11 +0000582 if (!isValidRewrite(Inst, ExitVal)) {
583 DeadInsts.push_back(ExitVal);
584 continue;
585 }
586 Changed = true;
587 ++NumReplaced;
588
Chris Lattner9f3d7382007-03-04 03:43:23 +0000589 PN->setIncomingValue(i, ExitVal);
Dan Gohmancafb8132009-02-17 19:13:57 +0000590
Dan Gohman81db61a2009-05-12 02:17:14 +0000591 // If this instruction is dead now, delete it.
592 RecursivelyDeleteTriviallyDeadInstructions(Inst);
Dan Gohmancafb8132009-02-17 19:13:57 +0000593
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000594 if (NumPreds == 1) {
595 // Completely replace a single-pred PHI. This is safe, because the
596 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
597 // node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000598 PN->replaceAllUsesWith(ExitVal);
Dan Gohman81db61a2009-05-12 02:17:14 +0000599 RecursivelyDeleteTriviallyDeadInstructions(PN);
Chris Lattnerc9838f22007-03-03 22:48:48 +0000600 }
601 }
Dan Gohman65d1e2b2009-07-14 01:09:02 +0000602 if (NumPreds != 1) {
Dan Gohman667d7872009-06-26 22:53:46 +0000603 // Clone the PHI and delete the original one. This lets IVUsers and
604 // any other maps purge the original user from their records.
Devang Patel50b6e332009-10-27 22:16:29 +0000605 PHINode *NewPN = cast<PHINode>(PN->clone());
Dan Gohman667d7872009-06-26 22:53:46 +0000606 NewPN->takeName(PN);
607 NewPN->insertBefore(PN);
608 PN->replaceAllUsesWith(NewPN);
609 PN->eraseFromParent();
610 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000611 }
612 }
Dan Gohman472fdf72010-03-20 03:53:53 +0000613
614 // The insertion point instruction may have been deleted; clear it out
615 // so that the rewriter doesn't trip over it later.
616 Rewriter.clearInsertPoint();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000617}
618
Andrew Trick1a54bb22011-07-12 00:08:50 +0000619//===----------------------------------------------------------------------===//
620// Rewrite IV users based on a canonical IV.
621// To be replaced by -disable-iv-rewrite.
622//===----------------------------------------------------------------------===//
Dale Johannesenc671d892009-04-15 23:31:51 +0000623
Andrew Trick39d78022011-09-09 17:35:10 +0000624/// FIXME: It is an extremely bad idea to indvar substitute anything more
625/// complex than affine induction variables. Doing so will put expensive
626/// polynomial evaluations inside of the loop, and the str reduction pass
627/// currently can only reduce affine polynomials. For now just disable
628/// indvar subst on anything more complex than an affine addrec, unless
629/// it can be expanded to a trivial value.
Andrew Trick1a54bb22011-07-12 00:08:50 +0000630static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
631 // Loop-invariant values are safe.
632 if (SE->isLoopInvariant(S, L)) return true;
633
634 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
635 // to transform them into efficient code.
636 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
637 return AR->isAffine();
638
639 // An add is safe it all its operands are safe.
Andrew Trick39d78022011-09-09 17:35:10 +0000640 if (const SCEVCommutativeExpr *Commutative
641 = dyn_cast<SCEVCommutativeExpr>(S)) {
Andrew Trick1a54bb22011-07-12 00:08:50 +0000642 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
643 E = Commutative->op_end(); I != E; ++I)
644 if (!isSafe(*I, L, SE)) return false;
645 return true;
646 }
647
648 // A cast is safe if its operand is.
649 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
650 return isSafe(C->getOperand(), L, SE);
651
652 // A udiv is safe if its operands are.
653 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
654 return isSafe(UD->getLHS(), L, SE) &&
655 isSafe(UD->getRHS(), L, SE);
656
657 // SCEVUnknown is always safe.
658 if (isa<SCEVUnknown>(S))
659 return true;
660
661 // Nothing else is safe.
662 return false;
663}
664
665void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
666 // Rewrite all induction variable expressions in terms of the canonical
667 // induction variable.
668 //
669 // If there were induction variables of other sizes or offsets, manually
670 // add the offsets to the primary induction variable and cast, avoiding
671 // the need for the code evaluation methods to insert induction variables
672 // of different sizes.
673 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
674 Value *Op = UI->getOperandValToReplace();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000675 Type *UseTy = Op->getType();
Andrew Trick1a54bb22011-07-12 00:08:50 +0000676 Instruction *User = UI->getUser();
677
678 // Compute the final addrec to expand into code.
679 const SCEV *AR = IU->getReplacementExpr(*UI);
680
681 // Evaluate the expression out of the loop, if possible.
682 if (!L->contains(UI->getUser())) {
683 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
684 if (SE->isLoopInvariant(ExitVal, L))
685 AR = ExitVal;
686 }
687
688 // FIXME: It is an extremely bad idea to indvar substitute anything more
689 // complex than affine induction variables. Doing so will put expensive
690 // polynomial evaluations inside of the loop, and the str reduction pass
691 // currently can only reduce affine polynomials. For now just disable
692 // indvar subst on anything more complex than an affine addrec, unless
693 // it can be expanded to a trivial value.
694 if (!isSafe(AR, L, SE))
695 continue;
696
697 // Determine the insertion point for this user. By default, insert
698 // immediately before the user. The SCEVExpander class will automatically
699 // hoist loop invariants out of the loop. For PHI nodes, there may be
700 // multiple uses, so compute the nearest common dominator for the
701 // incoming blocks.
Andrew Trick86c98142011-07-20 05:32:06 +0000702 Instruction *InsertPt = getInsertPointForUses(User, Op, DT);
Andrew Trick1a54bb22011-07-12 00:08:50 +0000703
704 // Now expand it into actual Instructions and patch it into place.
705 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
706
707 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
708 << " into = " << *NewVal << "\n");
709
710 if (!isValidRewrite(Op, NewVal)) {
711 DeadInsts.push_back(NewVal);
712 continue;
713 }
714 // Inform ScalarEvolution that this value is changing. The change doesn't
715 // affect its value, but it does potentially affect which use lists the
716 // value will be on after the replacement, which affects ScalarEvolution's
717 // ability to walk use lists and drop dangling pointers when a value is
718 // deleted.
719 SE->forgetValue(User);
720
721 // Patch the new value into place.
722 if (Op->hasName())
723 NewVal->takeName(Op);
724 if (Instruction *NewValI = dyn_cast<Instruction>(NewVal))
725 NewValI->setDebugLoc(User->getDebugLoc());
726 User->replaceUsesOfWith(Op, NewVal);
727 UI->setOperandValToReplace(NewVal);
728
729 ++NumRemoved;
730 Changed = true;
731
732 // The old value may be dead now.
733 DeadInsts.push_back(Op);
734 }
735}
736
737//===----------------------------------------------------------------------===//
738// IV Widening - Extend the width of an IV to cover its widest uses.
739//===----------------------------------------------------------------------===//
740
Andrew Trickf85092c2011-05-20 18:25:42 +0000741namespace {
742 // Collect information about induction variables that are used by sign/zero
743 // extend operations. This information is recorded by CollectExtend and
744 // provides the input to WidenIV.
745 struct WideIVInfo {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000746 Type *WidestNativeType; // Widest integer type created [sz]ext
Andrew Trick4b4bb712011-08-10 03:46:27 +0000747 bool IsSigned; // Was an sext user seen before a zext?
Andrew Trickf85092c2011-05-20 18:25:42 +0000748
749 WideIVInfo() : WidestNativeType(0), IsSigned(false) {}
750 };
Andrew Trick4b4bb712011-08-10 03:46:27 +0000751
752 class WideIVVisitor : public IVVisitor {
753 ScalarEvolution *SE;
754 const TargetData *TD;
755
756 public:
757 WideIVInfo WI;
758
759 WideIVVisitor(ScalarEvolution *SCEV, const TargetData *TData) :
760 SE(SCEV), TD(TData) {}
761
762 // Implement the interface used by simplifyUsersOfIV.
763 virtual void visitCast(CastInst *Cast);
764 };
Andrew Trickf85092c2011-05-20 18:25:42 +0000765}
766
Andrew Trick4b4bb712011-08-10 03:46:27 +0000767/// visitCast - Update information about the induction variable that is
Andrew Trickf85092c2011-05-20 18:25:42 +0000768/// extended by this sign or zero extend operation. This is used to determine
769/// the final width of the IV before actually widening it.
Andrew Trick4b4bb712011-08-10 03:46:27 +0000770void WideIVVisitor::visitCast(CastInst *Cast) {
771 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
772 if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)
773 return;
774
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000775 Type *Ty = Cast->getType();
Andrew Trickf85092c2011-05-20 18:25:42 +0000776 uint64_t Width = SE->getTypeSizeInBits(Ty);
777 if (TD && !TD->isLegalInteger(Width))
778 return;
779
Andrew Trick2fabd462011-06-21 03:22:38 +0000780 if (!WI.WidestNativeType) {
781 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
782 WI.IsSigned = IsSigned;
Andrew Trickf85092c2011-05-20 18:25:42 +0000783 return;
784 }
785
786 // We extend the IV to satisfy the sign of its first user, arbitrarily.
Andrew Trick2fabd462011-06-21 03:22:38 +0000787 if (WI.IsSigned != IsSigned)
Andrew Trickf85092c2011-05-20 18:25:42 +0000788 return;
789
Andrew Trick2fabd462011-06-21 03:22:38 +0000790 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
791 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
Andrew Trickf85092c2011-05-20 18:25:42 +0000792}
793
794namespace {
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000795
796/// NarrowIVDefUse - Record a link in the Narrow IV def-use chain along with the
797/// WideIV that computes the same value as the Narrow IV def. This avoids
798/// caching Use* pointers.
799struct NarrowIVDefUse {
800 Instruction *NarrowDef;
801 Instruction *NarrowUse;
802 Instruction *WideDef;
803
804 NarrowIVDefUse(): NarrowDef(0), NarrowUse(0), WideDef(0) {}
805
806 NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD):
807 NarrowDef(ND), NarrowUse(NU), WideDef(WD) {}
808};
809
Andrew Trickf85092c2011-05-20 18:25:42 +0000810/// WidenIV - The goal of this transform is to remove sign and zero extends
811/// without creating any new induction variables. To do this, it creates a new
812/// phi of the wider type and redirects all users, either removing extends or
813/// inserting truncs whenever we stop propagating the type.
814///
815class WidenIV {
Andrew Trick2fabd462011-06-21 03:22:38 +0000816 // Parameters
Andrew Trickf85092c2011-05-20 18:25:42 +0000817 PHINode *OrigPhi;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000818 Type *WideType;
Andrew Trickf85092c2011-05-20 18:25:42 +0000819 bool IsSigned;
820
Andrew Trick2fabd462011-06-21 03:22:38 +0000821 // Context
822 LoopInfo *LI;
823 Loop *L;
Andrew Trickf85092c2011-05-20 18:25:42 +0000824 ScalarEvolution *SE;
Andrew Trick2fabd462011-06-21 03:22:38 +0000825 DominatorTree *DT;
Andrew Trickf85092c2011-05-20 18:25:42 +0000826
Andrew Trick2fabd462011-06-21 03:22:38 +0000827 // Result
Andrew Trickf85092c2011-05-20 18:25:42 +0000828 PHINode *WidePhi;
829 Instruction *WideInc;
830 const SCEV *WideIncExpr;
Andrew Trick2fabd462011-06-21 03:22:38 +0000831 SmallVectorImpl<WeakVH> &DeadInsts;
Andrew Trickf85092c2011-05-20 18:25:42 +0000832
Andrew Trick2fabd462011-06-21 03:22:38 +0000833 SmallPtrSet<Instruction*,16> Widened;
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000834 SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
Andrew Trickf85092c2011-05-20 18:25:42 +0000835
836public:
Andrew Trick2fabd462011-06-21 03:22:38 +0000837 WidenIV(PHINode *PN, const WideIVInfo &WI, LoopInfo *LInfo,
838 ScalarEvolution *SEv, DominatorTree *DTree,
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000839 SmallVectorImpl<WeakVH> &DI) :
Andrew Trickf85092c2011-05-20 18:25:42 +0000840 OrigPhi(PN),
Andrew Trick2fabd462011-06-21 03:22:38 +0000841 WideType(WI.WidestNativeType),
842 IsSigned(WI.IsSigned),
Andrew Trickf85092c2011-05-20 18:25:42 +0000843 LI(LInfo),
844 L(LI->getLoopFor(OrigPhi->getParent())),
845 SE(SEv),
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000846 DT(DTree),
Andrew Trickf85092c2011-05-20 18:25:42 +0000847 WidePhi(0),
848 WideInc(0),
Andrew Trick2fabd462011-06-21 03:22:38 +0000849 WideIncExpr(0),
850 DeadInsts(DI) {
Andrew Trickf85092c2011-05-20 18:25:42 +0000851 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
852 }
853
Andrew Trick2fabd462011-06-21 03:22:38 +0000854 PHINode *CreateWideIV(SCEVExpander &Rewriter);
Andrew Trickf85092c2011-05-20 18:25:42 +0000855
856protected:
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000857 Instruction *CloneIVUser(NarrowIVDefUse DU);
Andrew Trickf85092c2011-05-20 18:25:42 +0000858
Andrew Tricke0dc2fa2011-07-05 18:19:39 +0000859 const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
860
Andrew Trick20151da2011-09-10 01:24:17 +0000861 const SCEVAddRecExpr* GetExtendedOperandRecurrence(NarrowIVDefUse DU);
862
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000863 Instruction *WidenIVUse(NarrowIVDefUse DU);
Andrew Trick4b029152011-07-02 02:34:25 +0000864
865 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
Andrew Trickf85092c2011-05-20 18:25:42 +0000866};
867} // anonymous namespace
868
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000869static Value *getExtend( Value *NarrowOper, Type *WideType,
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000870 bool IsSigned, IRBuilder<> &Builder) {
871 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
872 Builder.CreateZExt(NarrowOper, WideType);
Andrew Trickf85092c2011-05-20 18:25:42 +0000873}
874
875/// CloneIVUser - Instantiate a wide operation to replace a narrow
876/// operation. This only needs to handle operations that can evaluation to
877/// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000878Instruction *WidenIV::CloneIVUser(NarrowIVDefUse DU) {
879 unsigned Opcode = DU.NarrowUse->getOpcode();
Andrew Trickf85092c2011-05-20 18:25:42 +0000880 switch (Opcode) {
881 default:
882 return 0;
883 case Instruction::Add:
884 case Instruction::Mul:
885 case Instruction::UDiv:
886 case Instruction::Sub:
887 case Instruction::And:
888 case Instruction::Or:
889 case Instruction::Xor:
890 case Instruction::Shl:
891 case Instruction::LShr:
892 case Instruction::AShr:
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000893 DEBUG(dbgs() << "Cloning IVUser: " << *DU.NarrowUse << "\n");
Andrew Trickf85092c2011-05-20 18:25:42 +0000894
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000895 IRBuilder<> Builder(DU.NarrowUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000896
897 // Replace NarrowDef operands with WideDef. Otherwise, we don't know
898 // anything about the narrow operand yet so must insert a [sz]ext. It is
899 // probably loop invariant and will be folded or hoisted. If it actually
900 // comes from a widened IV, it should be removed during a future call to
901 // WidenIVUse.
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000902 Value *LHS = (DU.NarrowUse->getOperand(0) == DU.NarrowDef) ? DU.WideDef :
903 getExtend(DU.NarrowUse->getOperand(0), WideType, IsSigned, Builder);
904 Value *RHS = (DU.NarrowUse->getOperand(1) == DU.NarrowDef) ? DU.WideDef :
905 getExtend(DU.NarrowUse->getOperand(1), WideType, IsSigned, Builder);
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000906
Andrew Trick13bcf2e2011-07-20 04:39:24 +0000907 BinaryOperator *NarrowBO = cast<BinaryOperator>(DU.NarrowUse);
Andrew Trickf85092c2011-05-20 18:25:42 +0000908 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000909 LHS, RHS,
Andrew Trickf85092c2011-05-20 18:25:42 +0000910 NarrowBO->getName());
Andrew Trickf85092c2011-05-20 18:25:42 +0000911 Builder.Insert(WideBO);
Andrew Trick6e0ce242011-06-30 19:02:17 +0000912 if (const OverflowingBinaryOperator *OBO =
913 dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
914 if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
915 if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
916 }
Andrew Trick03d3d3b2011-05-25 04:42:22 +0000917 return WideBO;
Andrew Trickf85092c2011-05-20 18:25:42 +0000918 }
919 llvm_unreachable(0);
920}
921
Andrew Trickfcdc9a42011-05-26 00:46:11 +0000922/// HoistStep - Attempt to hoist an IV increment above a potential use.
923///
924/// To successfully hoist, two criteria must be met:
925/// - IncV operands dominate InsertPos and
926/// - InsertPos dominates IncV
927///
928/// Meeting the second condition means that we don't need to check all of IncV's
929/// existing uses (it's moving up in the domtree).
930///
931/// This does not yet recursively hoist the operands, although that would
932/// not be difficult.
933static bool HoistStep(Instruction *IncV, Instruction *InsertPos,
934 const DominatorTree *DT)
935{
936 if (DT->dominates(IncV, InsertPos))
937 return true;
938
939 if (!DT->dominates(InsertPos->getParent(), IncV->getParent()))
940 return false;
941
942 if (IncV->mayHaveSideEffects())
943 return false;
944
945 // Attempt to hoist IncV
946 for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end();
947 OI != OE; ++OI) {
948 Instruction *OInst = dyn_cast<Instruction>(OI);
949 if (OInst && !DT->dominates(OInst, InsertPos))
950 return false;
951 }
952 IncV->moveBefore(InsertPos);
953 return true;
954}
955
Andrew Trick20151da2011-09-10 01:24:17 +0000956/// No-wrap operations can transfer sign extension of their result to their
957/// operands. Generate the SCEV value for the widened operation without
958/// actually modifying the IR yet. If the expression after extending the
959/// operands is an AddRec for this loop, return it.
960const SCEVAddRecExpr* WidenIV::GetExtendedOperandRecurrence(NarrowIVDefUse DU) {
961 // Handle the common case of add<nsw/nuw>
962 if (DU.NarrowUse->getOpcode() != Instruction::Add)
963 return 0;
964
965 // One operand (NarrowDef) has already been extended to WideDef. Now determine
966 // if extending the other will lead to a recurrence.
967 unsigned ExtendOperIdx = DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
968 assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU");
969
970 const SCEV *ExtendOperExpr = 0;
971 const OverflowingBinaryOperator *OBO =
972 cast<OverflowingBinaryOperator>(DU.NarrowUse);
973 if (IsSigned && OBO->hasNoSignedWrap())
974 ExtendOperExpr = SE->getSignExtendExpr(
975 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
976 else if(!IsSigned && OBO->hasNoUnsignedWrap())
977 ExtendOperExpr = SE->getZeroExtendExpr(
978 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
979 else
980 return 0;
981
982 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(
983 SE->getAddExpr(SE->getSCEV(DU.WideDef), ExtendOperExpr,
984 IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW));
985
986 if (!AddRec || AddRec->getLoop() != L)
987 return 0;
988 return AddRec;
989}
990
Andrew Trick39d78022011-09-09 17:35:10 +0000991/// GetWideRecurrence - Is this instruction potentially interesting from
992/// IVUsers' perspective after widening it's type? In other words, can the
993/// extend be safely hoisted out of the loop with SCEV reducing the value to a
994/// recurrence on the same loop. If so, return the sign or zero extended
995/// recurrence. Otherwise return NULL.
Andrew Tricke0dc2fa2011-07-05 18:19:39 +0000996const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
997 if (!SE->isSCEVable(NarrowUse->getType()))
998 return 0;
999
1000 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
1001 if (SE->getTypeSizeInBits(NarrowExpr->getType())
1002 >= SE->getTypeSizeInBits(WideType)) {
1003 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
1004 // index. So don't follow this use.
1005 return 0;
1006 }
1007
1008 const SCEV *WideExpr = IsSigned ?
1009 SE->getSignExtendExpr(NarrowExpr, WideType) :
1010 SE->getZeroExtendExpr(NarrowExpr, WideType);
1011 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
1012 if (!AddRec || AddRec->getLoop() != L)
1013 return 0;
Andrew Tricke0dc2fa2011-07-05 18:19:39 +00001014 return AddRec;
1015}
1016
Andrew Trickf85092c2011-05-20 18:25:42 +00001017/// WidenIVUse - Determine whether an individual user of the narrow IV can be
1018/// widened. If so, return the wide clone of the user.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001019Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU) {
Andrew Trickcc359d92011-06-29 23:03:57 +00001020
Andrew Trick4b029152011-07-02 02:34:25 +00001021 // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001022 if (isa<PHINode>(DU.NarrowUse) &&
1023 LI->getLoopFor(DU.NarrowUse->getParent()) != L)
Andrew Trickf85092c2011-05-20 18:25:42 +00001024 return 0;
1025
Andrew Trickf85092c2011-05-20 18:25:42 +00001026 // Our raison d'etre! Eliminate sign and zero extension.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001027 if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) {
1028 Value *NewDef = DU.WideDef;
1029 if (DU.NarrowUse->getType() != WideType) {
1030 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001031 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1032 if (CastWidth < IVWidth) {
1033 // The cast isn't as wide as the IV, so insert a Trunc.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001034 IRBuilder<> Builder(DU.NarrowUse);
1035 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001036 }
1037 else {
1038 // A wider extend was hidden behind a narrower one. This may induce
1039 // another round of IV widening in which the intermediate IV becomes
1040 // dead. It should be very rare.
1041 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001042 << " not wide enough to subsume " << *DU.NarrowUse << "\n");
1043 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1044 NewDef = DU.NarrowUse;
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001045 }
1046 }
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001047 if (NewDef != DU.NarrowUse) {
1048 DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1049 << " replaced by " << *DU.WideDef << "\n");
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001050 ++NumElimExt;
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001051 DU.NarrowUse->replaceAllUsesWith(NewDef);
1052 DeadInsts.push_back(DU.NarrowUse);
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001053 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001054 // Now that the extend is gone, we want to expose it's uses for potential
1055 // further simplification. We don't need to directly inform SimplifyIVUsers
1056 // of the new users, because their parent IV will be processed later as a
1057 // new loop phi. If we preserved IVUsers analysis, we would also want to
1058 // push the uses of WideDef here.
Andrew Trickf85092c2011-05-20 18:25:42 +00001059
1060 // No further widening is needed. The deceased [sz]ext had done it for us.
1061 return 0;
1062 }
Andrew Trick4b029152011-07-02 02:34:25 +00001063
1064 // Does this user itself evaluate to a recurrence after widening?
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001065 const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(DU.NarrowUse);
Andrew Trickf85092c2011-05-20 18:25:42 +00001066 if (!WideAddRec) {
Andrew Trick20151da2011-09-10 01:24:17 +00001067 WideAddRec = GetExtendedOperandRecurrence(DU);
1068 }
1069 if (!WideAddRec) {
Andrew Trickf85092c2011-05-20 18:25:42 +00001070 // This user does not evaluate to a recurence after widening, so don't
1071 // follow it. Instead insert a Trunc to kill off the original use,
1072 // eventually isolating the original narrow IV so it can be removed.
Andrew Trick86c98142011-07-20 05:32:06 +00001073 IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT));
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001074 Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
1075 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
Andrew Trickf85092c2011-05-20 18:25:42 +00001076 return 0;
1077 }
Andrew Trickfc933c02011-07-18 20:32:31 +00001078 // Assume block terminators cannot evaluate to a recurrence. We can't to
Andrew Trick4b029152011-07-02 02:34:25 +00001079 // insert a Trunc after a terminator if there happens to be a critical edge.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001080 assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
Andrew Trick4b029152011-07-02 02:34:25 +00001081 "SCEV is not expected to evaluate a block terminator");
Andrew Trickcc359d92011-06-29 23:03:57 +00001082
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001083 // Reuse the IV increment that SCEVExpander created as long as it dominates
1084 // NarrowUse.
Andrew Trickf85092c2011-05-20 18:25:42 +00001085 Instruction *WideUse = 0;
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001086 if (WideAddRec == WideIncExpr && HoistStep(WideInc, DU.NarrowUse, DT)) {
Andrew Trickf85092c2011-05-20 18:25:42 +00001087 WideUse = WideInc;
1088 }
1089 else {
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001090 WideUse = CloneIVUser(DU);
Andrew Trickf85092c2011-05-20 18:25:42 +00001091 if (!WideUse)
1092 return 0;
1093 }
Andrew Trick4b029152011-07-02 02:34:25 +00001094 // Evaluation of WideAddRec ensured that the narrow expression could be
1095 // extended outside the loop without overflow. This suggests that the wide use
Andrew Trickf85092c2011-05-20 18:25:42 +00001096 // evaluates to the same expression as the extended narrow use, but doesn't
1097 // absolutely guarantee it. Hence the following failsafe check. In rare cases
Andrew Trick2fabd462011-06-21 03:22:38 +00001098 // where it fails, we simply throw away the newly created wide use.
Andrew Trickf85092c2011-05-20 18:25:42 +00001099 if (WideAddRec != SE->getSCEV(WideUse)) {
1100 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
1101 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
1102 DeadInsts.push_back(WideUse);
1103 return 0;
1104 }
1105
1106 // Returning WideUse pushes it on the worklist.
1107 return WideUse;
1108}
1109
Andrew Trick4b029152011-07-02 02:34:25 +00001110/// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers.
1111///
1112void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1113 for (Value::use_iterator UI = NarrowDef->use_begin(),
1114 UE = NarrowDef->use_end(); UI != UE; ++UI) {
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001115 Instruction *NarrowUse = cast<Instruction>(*UI);
Andrew Trick4b029152011-07-02 02:34:25 +00001116
1117 // Handle data flow merges and bizarre phi cycles.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001118 if (!Widened.insert(NarrowUse))
Andrew Trick4b029152011-07-02 02:34:25 +00001119 continue;
1120
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001121 NarrowIVUsers.push_back(NarrowIVDefUse(NarrowDef, NarrowUse, WideDef));
Andrew Trick4b029152011-07-02 02:34:25 +00001122 }
1123}
1124
Andrew Trickf85092c2011-05-20 18:25:42 +00001125/// CreateWideIV - Process a single induction variable. First use the
1126/// SCEVExpander to create a wide induction variable that evaluates to the same
1127/// recurrence as the original narrow IV. Then use a worklist to forward
Andrew Trick2fabd462011-06-21 03:22:38 +00001128/// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
Andrew Trickf85092c2011-05-20 18:25:42 +00001129/// interesting IV users, the narrow IV will be isolated for removal by
1130/// DeleteDeadPHIs.
1131///
1132/// It would be simpler to delete uses as they are processed, but we must avoid
1133/// invalidating SCEV expressions.
1134///
Andrew Trick2fabd462011-06-21 03:22:38 +00001135PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
Andrew Trickf85092c2011-05-20 18:25:42 +00001136 // Is this phi an induction variable?
1137 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1138 if (!AddRec)
Andrew Trick2fabd462011-06-21 03:22:38 +00001139 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +00001140
1141 // Widen the induction variable expression.
1142 const SCEV *WideIVExpr = IsSigned ?
1143 SE->getSignExtendExpr(AddRec, WideType) :
1144 SE->getZeroExtendExpr(AddRec, WideType);
1145
1146 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1147 "Expect the new IV expression to preserve its type");
1148
1149 // Can the IV be extended outside the loop without overflow?
1150 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1151 if (!AddRec || AddRec->getLoop() != L)
Andrew Trick2fabd462011-06-21 03:22:38 +00001152 return NULL;
Andrew Trickf85092c2011-05-20 18:25:42 +00001153
Andrew Trick2fabd462011-06-21 03:22:38 +00001154 // An AddRec must have loop-invariant operands. Since this AddRec is
Andrew Trickf85092c2011-05-20 18:25:42 +00001155 // materialized by a loop header phi, the expression cannot have any post-loop
1156 // operands, so they must dominate the loop header.
1157 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1158 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
1159 && "Loop header phi recurrence inputs do not dominate the loop");
1160
1161 // The rewriter provides a value for the desired IV expression. This may
1162 // either find an existing phi or materialize a new one. Either way, we
1163 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1164 // of the phi-SCC dominates the loop entry.
1165 Instruction *InsertPt = L->getHeader()->begin();
1166 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
1167
1168 // Remembering the WideIV increment generated by SCEVExpander allows
1169 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
1170 // employ a general reuse mechanism because the call above is the only call to
1171 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001172 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1173 WideInc =
1174 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1175 WideIncExpr = SE->getSCEV(WideInc);
1176 }
Andrew Trickf85092c2011-05-20 18:25:42 +00001177
1178 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1179 ++NumWidened;
1180
1181 // Traverse the def-use chain using a worklist starting at the original IV.
Andrew Trick4b029152011-07-02 02:34:25 +00001182 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
Andrew Trickf85092c2011-05-20 18:25:42 +00001183
Andrew Trick4b029152011-07-02 02:34:25 +00001184 Widened.insert(OrigPhi);
1185 pushNarrowIVUsers(OrigPhi, WidePhi);
1186
Andrew Trickf85092c2011-05-20 18:25:42 +00001187 while (!NarrowIVUsers.empty()) {
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001188 NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
Andrew Trickf85092c2011-05-20 18:25:42 +00001189
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001190 // Process a def-use edge. This may replace the use, so don't hold a
1191 // use_iterator across it.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001192 Instruction *WideUse = WidenIVUse(DU);
Andrew Trickf85092c2011-05-20 18:25:42 +00001193
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001194 // Follow all def-use edges from the previous narrow use.
Andrew Trick4b029152011-07-02 02:34:25 +00001195 if (WideUse)
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001196 pushNarrowIVUsers(DU.NarrowUse, WideUse);
Andrew Trick4b029152011-07-02 02:34:25 +00001197
Andrew Trickfcdc9a42011-05-26 00:46:11 +00001198 // WidenIVUse may have removed the def-use edge.
Andrew Trick13bcf2e2011-07-20 04:39:24 +00001199 if (DU.NarrowDef->use_empty())
1200 DeadInsts.push_back(DU.NarrowDef);
Andrew Trickf85092c2011-05-20 18:25:42 +00001201 }
Andrew Trick2fabd462011-06-21 03:22:38 +00001202 return WidePhi;
Andrew Trickf85092c2011-05-20 18:25:42 +00001203}
1204
Andrew Trick1a54bb22011-07-12 00:08:50 +00001205//===----------------------------------------------------------------------===//
1206// Simplification of IV users based on SCEV evaluation.
1207//===----------------------------------------------------------------------===//
1208
Andrew Trickaeee4612011-05-12 00:04:28 +00001209
Andrew Trick4b4bb712011-08-10 03:46:27 +00001210/// SimplifyAndExtend - Iteratively perform simplification on a worklist of IV
1211/// users. Each successive simplification may push more users which may
Andrew Trick2fabd462011-06-21 03:22:38 +00001212/// themselves be candidates for simplification.
1213///
Andrew Trick4b4bb712011-08-10 03:46:27 +00001214/// Sign/Zero extend elimination is interleaved with IV simplification.
Andrew Trick2fabd462011-06-21 03:22:38 +00001215///
Andrew Trick4b4bb712011-08-10 03:46:27 +00001216void IndVarSimplify::SimplifyAndExtend(Loop *L,
1217 SCEVExpander &Rewriter,
1218 LPPassManager &LPM) {
Andrew Trick15832f62011-06-28 02:49:20 +00001219 std::map<PHINode *, WideIVInfo> WideIVMap;
1220
Andrew Trick2fabd462011-06-21 03:22:38 +00001221 SmallVector<PHINode*, 8> LoopPhis;
1222 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1223 LoopPhis.push_back(cast<PHINode>(I));
1224 }
Andrew Trick15832f62011-06-28 02:49:20 +00001225 // Each round of simplification iterates through the SimplifyIVUsers worklist
1226 // for all current phis, then determines whether any IVs can be
1227 // widened. Widening adds new phis to LoopPhis, inducing another round of
1228 // simplification on the wide IVs.
Andrew Trick2fabd462011-06-21 03:22:38 +00001229 while (!LoopPhis.empty()) {
Andrew Trick15832f62011-06-28 02:49:20 +00001230 // Evaluate as many IV expressions as possible before widening any IVs. This
Andrew Trick99a92f62011-06-28 16:45:04 +00001231 // forces SCEV to set no-wrap flags before evaluating sign/zero
Andrew Trick15832f62011-06-28 02:49:20 +00001232 // extension. The first time SCEV attempts to normalize sign/zero extension,
1233 // the result becomes final. So for the most predictable results, we delay
1234 // evaluation of sign/zero extend evaluation until needed, and avoid running
Andrew Trick4b4bb712011-08-10 03:46:27 +00001235 // other SCEV based analysis prior to SimplifyAndExtend.
Andrew Trick15832f62011-06-28 02:49:20 +00001236 do {
1237 PHINode *CurrIV = LoopPhis.pop_back_val();
Andrew Trick2fabd462011-06-21 03:22:38 +00001238
Andrew Trick15832f62011-06-28 02:49:20 +00001239 // Information about sign/zero extensions of CurrIV.
Andrew Trick4b4bb712011-08-10 03:46:27 +00001240 WideIVVisitor WIV(SE, TD);
Andrew Trick2fabd462011-06-21 03:22:38 +00001241
Andrew Trickbddb7f82011-08-10 04:22:26 +00001242 Changed |= simplifyUsersOfIV(CurrIV, SE, &LPM, DeadInsts, &WIV);
Andrew Trick2fabd462011-06-21 03:22:38 +00001243
Andrew Trick4b4bb712011-08-10 03:46:27 +00001244 if (WIV.WI.WidestNativeType) {
1245 WideIVMap[CurrIV] = WIV.WI;
Andrew Trick2fabd462011-06-21 03:22:38 +00001246 }
Andrew Trick15832f62011-06-28 02:49:20 +00001247 } while(!LoopPhis.empty());
1248
1249 for (std::map<PHINode *, WideIVInfo>::const_iterator I = WideIVMap.begin(),
1250 E = WideIVMap.end(); I != E; ++I) {
1251 WidenIV Widener(I->first, I->second, LI, SE, DT, DeadInsts);
Andrew Trick2fabd462011-06-21 03:22:38 +00001252 if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
1253 Changed = true;
1254 LoopPhis.push_back(WidePhi);
1255 }
1256 }
Andrew Trick15832f62011-06-28 02:49:20 +00001257 WideIVMap.clear();
Andrew Trick2fabd462011-06-21 03:22:38 +00001258 }
1259}
1260
Andrew Trick037d1c02011-07-06 20:50:43 +00001261/// SimplifyCongruentIVs - Check for congruent phis in this loop header and
Andrew Trick4b4bb712011-08-10 03:46:27 +00001262/// replace them with their chosen representative.
Andrew Trick037d1c02011-07-06 20:50:43 +00001263///
1264void IndVarSimplify::SimplifyCongruentIVs(Loop *L) {
Andrew Trick6f684b02011-07-16 01:06:48 +00001265 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Andrew Trick037d1c02011-07-06 20:50:43 +00001266 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1267 PHINode *Phi = cast<PHINode>(I);
Andrew Trick1a54bb22011-07-12 00:08:50 +00001268 if (!SE->isSCEVable(Phi->getType()))
1269 continue;
1270
Andrew Trick037d1c02011-07-06 20:50:43 +00001271 const SCEV *S = SE->getSCEV(Phi);
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001272 std::pair<DenseMap<const SCEV *, PHINode *>::const_iterator, bool> Tmp =
1273 ExprToIVMap.insert(std::make_pair(S, Phi));
1274 if (Tmp.second)
Andrew Trick037d1c02011-07-06 20:50:43 +00001275 continue;
Chris Lattnerc30a38f2011-07-21 06:21:31 +00001276 PHINode *OrigPhi = Tmp.first->second;
Andrew Trickf22d9572011-07-20 02:08:58 +00001277
1278 // If one phi derives from the other via GEPs, types may differ.
1279 if (OrigPhi->getType() != Phi->getType())
1280 continue;
1281
Andrew Trick037d1c02011-07-06 20:50:43 +00001282 // Replacing the congruent phi is sufficient because acyclic redundancy
1283 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1284 // that a phi is congruent, it's almost certain to be the head of an IV
1285 // user cycle that is isomorphic with the original phi. So it's worth
1286 // eagerly cleaning up the common case of a single IV increment.
1287 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1288 Instruction *OrigInc =
1289 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1290 Instruction *IsomorphicInc =
1291 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1292 if (OrigInc != IsomorphicInc &&
Andrew Trickf22d9572011-07-20 02:08:58 +00001293 OrigInc->getType() == IsomorphicInc->getType() &&
Andrew Trick037d1c02011-07-06 20:50:43 +00001294 SE->getSCEV(OrigInc) == SE->getSCEV(IsomorphicInc) &&
1295 HoistStep(OrigInc, IsomorphicInc, DT)) {
1296 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1297 << *IsomorphicInc << '\n');
1298 IsomorphicInc->replaceAllUsesWith(OrigInc);
1299 DeadInsts.push_back(IsomorphicInc);
1300 }
1301 }
1302 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1303 ++NumElimIV;
1304 Phi->replaceAllUsesWith(OrigPhi);
1305 DeadInsts.push_back(Phi);
1306 }
1307}
1308
Andrew Trick1a54bb22011-07-12 00:08:50 +00001309//===----------------------------------------------------------------------===//
1310// LinearFunctionTestReplace and its kin. Rewrite the loop exit condition.
1311//===----------------------------------------------------------------------===//
1312
Andrew Trick39d78022011-09-09 17:35:10 +00001313/// Check for expressions that ScalarEvolution generates to compute
1314/// BackedgeTakenInfo. If these expressions have not been reduced, then
1315/// expanding them may incur additional cost (albeit in the loop preheader).
Andrew Trick5241b792011-07-18 18:21:35 +00001316static bool isHighCostExpansion(const SCEV *S, BranchInst *BI,
1317 ScalarEvolution *SE) {
1318 // If the backedge-taken count is a UDiv, it's very likely a UDiv that
1319 // ScalarEvolution's HowFarToZero or HowManyLessThans produced to compute a
1320 // precise expression, rather than a UDiv from the user's code. If we can't
1321 // find a UDiv in the code with some simple searching, assume the former and
1322 // forego rewriting the loop.
1323 if (isa<SCEVUDivExpr>(S)) {
1324 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
1325 if (!OrigCond) return true;
1326 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
1327 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
1328 if (R != S) {
1329 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
1330 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
1331 if (L != S)
1332 return true;
1333 }
1334 }
1335
Andrew Trickfc933c02011-07-18 20:32:31 +00001336 if (!DisableIVRewrite || ForceLFTR)
Andrew Trick5241b792011-07-18 18:21:35 +00001337 return false;
1338
1339 // Recurse past add expressions, which commonly occur in the
1340 // BackedgeTakenCount. They may already exist in program code, and if not,
1341 // they are not too expensive rematerialize.
1342 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1343 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1344 I != E; ++I) {
1345 if (isHighCostExpansion(*I, BI, SE))
1346 return true;
1347 }
1348 return false;
1349 }
1350
1351 // HowManyLessThans uses a Max expression whenever the loop is not guarded by
1352 // the exit condition.
1353 if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
1354 return true;
1355
1356 // If we haven't recognized an expensive SCEV patter, assume its an expression
1357 // produced by program code.
1358 return false;
1359}
1360
Andrew Trick1a54bb22011-07-12 00:08:50 +00001361/// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
1362/// count expression can be safely and cheaply expanded into an instruction
1363/// sequence that can be used by LinearFunctionTestReplace.
1364static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) {
1365 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1366 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1367 BackedgeTakenCount->isZero())
1368 return false;
1369
1370 if (!L->getExitingBlock())
1371 return false;
1372
1373 // Can't rewrite non-branch yet.
1374 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1375 if (!BI)
1376 return false;
1377
Andrew Trick5241b792011-07-18 18:21:35 +00001378 if (isHighCostExpansion(BackedgeTakenCount, BI, SE))
1379 return false;
1380
Andrew Trick1a54bb22011-07-12 00:08:50 +00001381 return true;
1382}
1383
1384/// getBackedgeIVType - Get the widest type used by the loop test after peeking
1385/// through Truncs.
1386///
Andrew Trickfc933c02011-07-18 20:32:31 +00001387/// TODO: Unnecessary when ForceLFTR is removed.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001388static Type *getBackedgeIVType(Loop *L) {
Andrew Trick1a54bb22011-07-12 00:08:50 +00001389 if (!L->getExitingBlock())
1390 return 0;
1391
1392 // Can't rewrite non-branch yet.
1393 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1394 if (!BI)
1395 return 0;
1396
1397 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1398 if (!Cond)
1399 return 0;
1400
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001401 Type *Ty = 0;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001402 for(User::op_iterator OI = Cond->op_begin(), OE = Cond->op_end();
1403 OI != OE; ++OI) {
1404 assert((!Ty || Ty == (*OI)->getType()) && "bad icmp operand types");
1405 TruncInst *Trunc = dyn_cast<TruncInst>(*OI);
1406 if (!Trunc)
1407 continue;
1408
1409 return Trunc->getSrcTy();
1410 }
1411 return Ty;
1412}
1413
Andrew Trickfc933c02011-07-18 20:32:31 +00001414/// isLoopInvariant - Perform a quick domtree based check for loop invariance
1415/// assuming that V is used within the loop. LoopInfo::isLoopInvariant() seems
1416/// gratuitous for this purpose.
1417static bool isLoopInvariant(Value *V, Loop *L, DominatorTree *DT) {
1418 Instruction *Inst = dyn_cast<Instruction>(V);
1419 if (!Inst)
1420 return true;
1421
1422 return DT->properlyDominates(Inst->getParent(), L->getHeader());
1423}
1424
1425/// getLoopPhiForCounter - Return the loop header phi IFF IncV adds a loop
1426/// invariant value to the phi.
1427static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
1428 Instruction *IncI = dyn_cast<Instruction>(IncV);
1429 if (!IncI)
1430 return 0;
1431
1432 switch (IncI->getOpcode()) {
1433 case Instruction::Add:
1434 case Instruction::Sub:
1435 break;
1436 case Instruction::GetElementPtr:
1437 // An IV counter must preserve its type.
1438 if (IncI->getNumOperands() == 2)
1439 break;
1440 default:
1441 return 0;
1442 }
1443
1444 PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
1445 if (Phi && Phi->getParent() == L->getHeader()) {
1446 if (isLoopInvariant(IncI->getOperand(1), L, DT))
1447 return Phi;
1448 return 0;
1449 }
1450 if (IncI->getOpcode() == Instruction::GetElementPtr)
1451 return 0;
1452
1453 // Allow add/sub to be commuted.
1454 Phi = dyn_cast<PHINode>(IncI->getOperand(1));
1455 if (Phi && Phi->getParent() == L->getHeader()) {
1456 if (isLoopInvariant(IncI->getOperand(0), L, DT))
1457 return Phi;
1458 }
1459 return 0;
1460}
1461
1462/// needsLFTR - LinearFunctionTestReplace policy. Return true unless we can show
1463/// that the current exit test is already sufficiently canonical.
1464static bool needsLFTR(Loop *L, DominatorTree *DT) {
1465 assert(L->getExitingBlock() && "expected loop exit");
1466
1467 BasicBlock *LatchBlock = L->getLoopLatch();
1468 // Don't bother with LFTR if the loop is not properly simplified.
1469 if (!LatchBlock)
1470 return false;
1471
1472 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1473 assert(BI && "expected exit branch");
1474
1475 // Do LFTR to simplify the exit condition to an ICMP.
1476 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1477 if (!Cond)
1478 return true;
1479
1480 // Do LFTR to simplify the exit ICMP to EQ/NE
1481 ICmpInst::Predicate Pred = Cond->getPredicate();
1482 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
1483 return true;
1484
1485 // Look for a loop invariant RHS
1486 Value *LHS = Cond->getOperand(0);
1487 Value *RHS = Cond->getOperand(1);
1488 if (!isLoopInvariant(RHS, L, DT)) {
1489 if (!isLoopInvariant(LHS, L, DT))
1490 return true;
1491 std::swap(LHS, RHS);
1492 }
1493 // Look for a simple IV counter LHS
1494 PHINode *Phi = dyn_cast<PHINode>(LHS);
1495 if (!Phi)
1496 Phi = getLoopPhiForCounter(LHS, L, DT);
1497
1498 if (!Phi)
1499 return true;
1500
1501 // Do LFTR if the exit condition's IV is *not* a simple counter.
1502 Value *IncV = Phi->getIncomingValueForBlock(L->getLoopLatch());
1503 return Phi != getLoopPhiForCounter(IncV, L, DT);
1504}
1505
1506/// AlmostDeadIV - Return true if this IV has any uses other than the (soon to
1507/// be rewritten) loop exit test.
1508static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
1509 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1510 Value *IncV = Phi->getIncomingValue(LatchIdx);
1511
1512 for (Value::use_iterator UI = Phi->use_begin(), UE = Phi->use_end();
1513 UI != UE; ++UI) {
1514 if (*UI != Cond && *UI != IncV) return false;
1515 }
1516
1517 for (Value::use_iterator UI = IncV->use_begin(), UE = IncV->use_end();
1518 UI != UE; ++UI) {
1519 if (*UI != Cond && *UI != Phi) return false;
1520 }
1521 return true;
1522}
1523
1524/// FindLoopCounter - Find an affine IV in canonical form.
1525///
1526/// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
1527///
1528/// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
1529/// This is difficult in general for SCEV because of potential overflow. But we
1530/// could at least handle constant BECounts.
1531static PHINode *
1532FindLoopCounter(Loop *L, const SCEV *BECount,
1533 ScalarEvolution *SE, DominatorTree *DT, const TargetData *TD) {
1534 // I'm not sure how BECount could be a pointer type, but we definitely don't
1535 // want to LFTR that.
1536 if (BECount->getType()->isPointerTy())
1537 return 0;
1538
1539 uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
1540
1541 Value *Cond =
1542 cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
1543
1544 // Loop over all of the PHI nodes, looking for a simple counter.
1545 PHINode *BestPhi = 0;
1546 const SCEV *BestInit = 0;
1547 BasicBlock *LatchBlock = L->getLoopLatch();
1548 assert(LatchBlock && "needsLFTR should guarantee a loop latch");
1549
1550 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1551 PHINode *Phi = cast<PHINode>(I);
1552 if (!SE->isSCEVable(Phi->getType()))
1553 continue;
1554
1555 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
1556 if (!AR || AR->getLoop() != L || !AR->isAffine())
1557 continue;
1558
1559 // AR may be a pointer type, while BECount is an integer type.
1560 // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
1561 // AR may not be a narrower type, or we may never exit.
1562 uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
1563 if (PhiWidth < BCWidth || (TD && !TD->isLegalInteger(PhiWidth)))
1564 continue;
1565
1566 const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
1567 if (!Step || !Step->isOne())
1568 continue;
1569
1570 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1571 Value *IncV = Phi->getIncomingValue(LatchIdx);
1572 if (getLoopPhiForCounter(IncV, L, DT) != Phi)
1573 continue;
1574
1575 const SCEV *Init = AR->getStart();
1576
1577 if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
1578 // Don't force a live loop counter if another IV can be used.
1579 if (AlmostDeadIV(Phi, LatchBlock, Cond))
1580 continue;
1581
1582 // Prefer to count-from-zero. This is a more "canonical" counter form. It
1583 // also prefers integer to pointer IVs.
1584 if (BestInit->isZero() != Init->isZero()) {
1585 if (BestInit->isZero())
1586 continue;
1587 }
1588 // If two IVs both count from zero or both count from nonzero then the
1589 // narrower is likely a dead phi that has been widened. Use the wider phi
1590 // to allow the other to be eliminated.
1591 if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
1592 continue;
1593 }
1594 BestPhi = Phi;
1595 BestInit = Init;
1596 }
1597 return BestPhi;
1598}
1599
Andrew Trick1a54bb22011-07-12 00:08:50 +00001600/// LinearFunctionTestReplace - This method rewrites the exit condition of the
1601/// loop to be a canonical != comparison against the incremented loop induction
1602/// variable. This pass is able to rewrite the exit tests of any loop where the
1603/// SCEV analysis can determine a loop-invariant trip count of the loop, which
1604/// is actually a much broader range than just linear tests.
Andrew Trickfc933c02011-07-18 20:32:31 +00001605Value *IndVarSimplify::
Andrew Trick1a54bb22011-07-12 00:08:50 +00001606LinearFunctionTestReplace(Loop *L,
1607 const SCEV *BackedgeTakenCount,
1608 PHINode *IndVar,
1609 SCEVExpander &Rewriter) {
1610 assert(canExpandBackedgeTakenCount(L, SE) && "precondition");
1611 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1612
Andrew Trickfc933c02011-07-18 20:32:31 +00001613 // In DisableIVRewrite mode, IndVar is not necessarily a canonical IV. In this
1614 // mode, LFTR can ignore IV overflow and truncate to the width of
1615 // BECount. This avoids materializing the add(zext(add)) expression.
1616 Type *CntTy = DisableIVRewrite ?
1617 BackedgeTakenCount->getType() : IndVar->getType();
1618
1619 const SCEV *IVLimit = BackedgeTakenCount;
1620
Andrew Trick1a54bb22011-07-12 00:08:50 +00001621 // If the exiting block is not the same as the backedge block, we must compare
1622 // against the preincremented value, otherwise we prefer to compare against
1623 // the post-incremented value.
1624 Value *CmpIndVar;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001625 if (L->getExitingBlock() == L->getLoopLatch()) {
1626 // Add one to the "backedge-taken" count to get the trip count.
1627 // If this addition may overflow, we have to be more pessimistic and
1628 // cast the induction variable before doing the add.
Andrew Trick1a54bb22011-07-12 00:08:50 +00001629 const SCEV *N =
Andrew Trickfc933c02011-07-18 20:32:31 +00001630 SE->getAddExpr(IVLimit, SE->getConstant(IVLimit->getType(), 1));
1631 if (CntTy == IVLimit->getType())
1632 IVLimit = N;
1633 else {
1634 const SCEV *Zero = SE->getConstant(IVLimit->getType(), 0);
1635 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
1636 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
1637 // No overflow. Cast the sum.
1638 IVLimit = SE->getTruncateOrZeroExtend(N, CntTy);
1639 } else {
1640 // Potential overflow. Cast before doing the add.
1641 IVLimit = SE->getTruncateOrZeroExtend(IVLimit, CntTy);
1642 IVLimit = SE->getAddExpr(IVLimit, SE->getConstant(CntTy, 1));
1643 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001644 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001645 // The BackedgeTaken expression contains the number of times that the
1646 // backedge branches to the loop header. This is one less than the
1647 // number of times the loop executes, so use the incremented indvar.
1648 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
1649 } else {
1650 // We have to use the preincremented value...
Andrew Trickfc933c02011-07-18 20:32:31 +00001651 IVLimit = SE->getTruncateOrZeroExtend(IVLimit, CntTy);
Andrew Trick1a54bb22011-07-12 00:08:50 +00001652 CmpIndVar = IndVar;
1653 }
1654
Andrew Trickfc933c02011-07-18 20:32:31 +00001655 // For unit stride, IVLimit = Start + BECount with 2's complement overflow.
1656 // So for, non-zero start compute the IVLimit here.
1657 bool isPtrIV = false;
1658 Type *CmpTy = CntTy;
1659 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
1660 assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
1661 if (!AR->getStart()->isZero()) {
1662 assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
1663 const SCEV *IVInit = AR->getStart();
1664
1665 // For pointer types, sign extend BECount in order to materialize a GEP.
1666 // Note that for DisableIVRewrite, we never run SCEVExpander on a
1667 // pointer type, because we must preserve the existing GEPs. Instead we
1668 // directly generate a GEP later.
1669 if (IVInit->getType()->isPointerTy()) {
1670 isPtrIV = true;
1671 CmpTy = SE->getEffectiveSCEVType(IVInit->getType());
1672 IVLimit = SE->getTruncateOrSignExtend(IVLimit, CmpTy);
1673 }
1674 // For integer types, truncate the IV before computing IVInit + BECount.
1675 else {
1676 if (SE->getTypeSizeInBits(IVInit->getType())
1677 > SE->getTypeSizeInBits(CmpTy))
1678 IVInit = SE->getTruncateExpr(IVInit, CmpTy);
1679
1680 IVLimit = SE->getAddExpr(IVInit, IVLimit);
1681 }
1682 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001683 // Expand the code for the iteration count.
Andrew Trickfc933c02011-07-18 20:32:31 +00001684 IRBuilder<> Builder(BI);
1685
1686 assert(SE->isLoopInvariant(IVLimit, L) &&
Andrew Trick1a54bb22011-07-12 00:08:50 +00001687 "Computed iteration count is not loop invariant!");
Andrew Trickfc933c02011-07-18 20:32:31 +00001688 Value *ExitCnt = Rewriter.expandCodeFor(IVLimit, CmpTy, BI);
1689
1690 // Create a gep for IVInit + IVLimit from on an existing pointer base.
1691 assert(isPtrIV == IndVar->getType()->isPointerTy() &&
1692 "IndVar type must match IVInit type");
1693 if (isPtrIV) {
1694 Value *IVStart = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
1695 assert(AR->getStart() == SE->getSCEV(IVStart) && "bad loop counter");
Andrew Trick41e0d4e2011-07-18 21:15:03 +00001696 assert(SE->getSizeOfExpr(
1697 cast<PointerType>(IVStart->getType())->getElementType())->isOne()
1698 && "unit stride pointer IV must be i8*");
Andrew Trickfc933c02011-07-18 20:32:31 +00001699
1700 Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
1701 ExitCnt = Builder.CreateGEP(IVStart, ExitCnt, "lftr.limit");
1702 Builder.SetInsertPoint(BI);
1703 }
Andrew Trick1a54bb22011-07-12 00:08:50 +00001704
1705 // Insert a new icmp_ne or icmp_eq instruction before the branch.
Andrew Trickfc933c02011-07-18 20:32:31 +00001706 ICmpInst::Predicate P;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001707 if (L->contains(BI->getSuccessor(0)))
Andrew Trickfc933c02011-07-18 20:32:31 +00001708 P = ICmpInst::ICMP_NE;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001709 else
Andrew Trickfc933c02011-07-18 20:32:31 +00001710 P = ICmpInst::ICMP_EQ;
Andrew Trick1a54bb22011-07-12 00:08:50 +00001711
1712 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
1713 << " LHS:" << *CmpIndVar << '\n'
1714 << " op:\t"
Andrew Trickfc933c02011-07-18 20:32:31 +00001715 << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
1716 << " RHS:\t" << *ExitCnt << "\n"
1717 << " Expr:\t" << *IVLimit << "\n");
Andrew Trick1a54bb22011-07-12 00:08:50 +00001718
Andrew Trickfc933c02011-07-18 20:32:31 +00001719 if (SE->getTypeSizeInBits(CmpIndVar->getType())
1720 > SE->getTypeSizeInBits(CmpTy)) {
1721 CmpIndVar = Builder.CreateTrunc(CmpIndVar, CmpTy, "lftr.wideiv");
1722 }
1723
1724 Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
Andrew Trick1a54bb22011-07-12 00:08:50 +00001725 Value *OrigCond = BI->getCondition();
1726 // It's tempting to use replaceAllUsesWith here to fully replace the old
1727 // comparison, but that's not immediately safe, since users of the old
1728 // comparison may not be dominated by the new comparison. Instead, just
1729 // update the branch to use the new comparison; in the common case this
1730 // will make old comparison dead.
1731 BI->setCondition(Cond);
1732 DeadInsts.push_back(OrigCond);
1733
1734 ++NumLFTR;
1735 Changed = true;
1736 return Cond;
1737}
1738
1739//===----------------------------------------------------------------------===//
1740// SinkUnusedInvariants. A late subpass to cleanup loop preheaders.
1741//===----------------------------------------------------------------------===//
1742
1743/// If there's a single exit block, sink any loop-invariant values that
1744/// were defined in the preheader but not used inside the loop into the
1745/// exit block to reduce register pressure in the loop.
1746void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
1747 BasicBlock *ExitBlock = L->getExitBlock();
1748 if (!ExitBlock) return;
1749
1750 BasicBlock *Preheader = L->getLoopPreheader();
1751 if (!Preheader) return;
1752
Bill Wendlingb05fdd62011-08-24 20:28:43 +00001753 Instruction *InsertPt = ExitBlock->getFirstInsertionPt();
Andrew Trick1a54bb22011-07-12 00:08:50 +00001754 BasicBlock::iterator I = Preheader->getTerminator();
1755 while (I != Preheader->begin()) {
1756 --I;
1757 // New instructions were inserted at the end of the preheader.
1758 if (isa<PHINode>(I))
1759 break;
1760
1761 // Don't move instructions which might have side effects, since the side
1762 // effects need to complete before instructions inside the loop. Also don't
1763 // move instructions which might read memory, since the loop may modify
1764 // memory. Note that it's okay if the instruction might have undefined
1765 // behavior: LoopSimplify guarantees that the preheader dominates the exit
1766 // block.
1767 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
1768 continue;
1769
1770 // Skip debug info intrinsics.
1771 if (isa<DbgInfoIntrinsic>(I))
1772 continue;
1773
Bill Wendling2b188812011-08-26 20:40:15 +00001774 // Skip landingpad instructions.
1775 if (isa<LandingPadInst>(I))
1776 continue;
1777
Andrew Trick1a54bb22011-07-12 00:08:50 +00001778 // Don't sink static AllocaInsts out of the entry block, which would
1779 // turn them into dynamic allocas!
1780 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
1781 if (AI->isStaticAlloca())
1782 continue;
1783
1784 // Determine if there is a use in or before the loop (direct or
1785 // otherwise).
1786 bool UsedInLoop = false;
1787 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1788 UI != UE; ++UI) {
1789 User *U = *UI;
1790 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
1791 if (PHINode *P = dyn_cast<PHINode>(U)) {
1792 unsigned i =
1793 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
1794 UseBB = P->getIncomingBlock(i);
1795 }
1796 if (UseBB == Preheader || L->contains(UseBB)) {
1797 UsedInLoop = true;
1798 break;
1799 }
1800 }
1801
1802 // If there is, the def must remain in the preheader.
1803 if (UsedInLoop)
1804 continue;
1805
1806 // Otherwise, sink it to the exit block.
1807 Instruction *ToMove = I;
1808 bool Done = false;
1809
1810 if (I != Preheader->begin()) {
1811 // Skip debug info intrinsics.
1812 do {
1813 --I;
1814 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
1815
1816 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
1817 Done = true;
1818 } else {
1819 Done = true;
1820 }
1821
1822 ToMove->moveBefore(InsertPt);
1823 if (Done) break;
1824 InsertPt = ToMove;
1825 }
1826}
1827
1828//===----------------------------------------------------------------------===//
1829// IndVarSimplify driver. Manage several subpasses of IV simplification.
1830//===----------------------------------------------------------------------===//
1831
Dan Gohmanc2390b12009-02-12 22:19:27 +00001832bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Dan Gohmana5283822010-06-18 01:35:11 +00001833 // If LoopSimplify form is not available, stay out of trouble. Some notes:
1834 // - LSR currently only supports LoopSimplify-form loops. Indvars'
1835 // canonicalization can be a pessimization without LSR to "clean up"
1836 // afterwards.
1837 // - We depend on having a preheader; in particular,
1838 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
1839 // and we're in trouble if we can't find the induction variable even when
1840 // we've manually inserted one.
1841 if (!L->isLoopSimplifyForm())
1842 return false;
1843
Andrew Trick2fabd462011-06-21 03:22:38 +00001844 if (!DisableIVRewrite)
1845 IU = &getAnalysis<IVUsers>();
Devang Patel5ee99972007-03-07 06:39:01 +00001846 LI = &getAnalysis<LoopInfo>();
1847 SE = &getAnalysis<ScalarEvolution>();
Dan Gohmande53dc02009-06-27 05:16:57 +00001848 DT = &getAnalysis<DominatorTree>();
Andrew Trick37da4082011-05-04 02:10:13 +00001849 TD = getAnalysisIfAvailable<TargetData>();
1850
Andrew Trickb12a7542011-03-17 23:51:11 +00001851 DeadInsts.clear();
Devang Patel5ee99972007-03-07 06:39:01 +00001852 Changed = false;
Dan Gohman60f8a632009-02-17 20:49:49 +00001853
Dan Gohman2d1be872009-04-16 03:18:22 +00001854 // If there are any floating-point recurrences, attempt to
Dan Gohman60f8a632009-02-17 20:49:49 +00001855 // transform them to use integer recurrences.
1856 RewriteNonIntegerIVs(L);
1857
Dan Gohman0bba49c2009-07-07 17:06:11 +00001858 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
Chris Lattner9caed542007-03-04 01:00:28 +00001859
Dan Gohman667d7872009-06-26 22:53:46 +00001860 // Create a rewriter object which we'll use to transform the code with.
Andrew Trick5e7645b2011-06-28 05:07:32 +00001861 SCEVExpander Rewriter(*SE, "indvars");
Andrew Trick156d4602011-06-27 23:17:44 +00001862
1863 // Eliminate redundant IV users.
Andrew Trick15832f62011-06-28 02:49:20 +00001864 //
1865 // Simplification works best when run before other consumers of SCEV. We
1866 // attempt to avoid evaluating SCEVs for sign/zero extend operations until
1867 // other expressions involving loop IVs have been evaluated. This helps SCEV
Andrew Trick99a92f62011-06-28 16:45:04 +00001868 // set no-wrap flags before normalizing sign/zero extension.
Andrew Trick156d4602011-06-27 23:17:44 +00001869 if (DisableIVRewrite) {
Andrew Trick37da4082011-05-04 02:10:13 +00001870 Rewriter.disableCanonicalMode();
Andrew Trick4b4bb712011-08-10 03:46:27 +00001871 SimplifyAndExtend(L, Rewriter, LPM);
Andrew Trick156d4602011-06-27 23:17:44 +00001872 }
Andrew Trick37da4082011-05-04 02:10:13 +00001873
Chris Lattner40bf8b42004-04-02 20:24:31 +00001874 // Check to see if this loop has a computable loop-invariant execution count.
1875 // If so, this means that we can compute the final value of any expressions
1876 // that are recurrent in the loop, and substitute the exit values from the
1877 // loop into any instructions outside of the loop that use the final values of
1878 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +00001879 //
Dan Gohman46bdfb02009-02-24 18:55:53 +00001880 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
Dan Gohman454d26d2010-02-22 04:11:59 +00001881 RewriteLoopExitValues(L, Rewriter);
Chris Lattner6148c022001-12-03 17:28:42 +00001882
Andrew Trickf85092c2011-05-20 18:25:42 +00001883 // Eliminate redundant IV users.
Andrew Trick156d4602011-06-27 23:17:44 +00001884 if (!DisableIVRewrite)
Andrew Trickbddb7f82011-08-10 04:22:26 +00001885 Changed |= simplifyIVUsers(IU, SE, &LPM, DeadInsts);
Dan Gohmana590b792010-04-13 01:46:36 +00001886
Andrew Trick6f684b02011-07-16 01:06:48 +00001887 // Eliminate redundant IV cycles.
Andrew Trick037d1c02011-07-06 20:50:43 +00001888 if (DisableIVRewrite)
1889 SimplifyCongruentIVs(L);
1890
Dan Gohman81db61a2009-05-12 02:17:14 +00001891 // Compute the type of the largest recurrence expression, and decide whether
1892 // a canonical induction variable should be inserted.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001893 Type *LargestType = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00001894 bool NeedCannIV = false;
Andrew Trickfc933c02011-07-18 20:32:31 +00001895 bool ReuseIVForExit = DisableIVRewrite && !ForceLFTR;
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001896 bool ExpandBECount = canExpandBackedgeTakenCount(L, SE);
Andrew Trickfc933c02011-07-18 20:32:31 +00001897 if (ExpandBECount && !ReuseIVForExit) {
Dan Gohman81db61a2009-05-12 02:17:14 +00001898 // If we have a known trip count and a single exit block, we'll be
1899 // rewriting the loop exit test condition below, which requires a
1900 // canonical induction variable.
Andrew Trick4dfdf242011-05-03 22:24:10 +00001901 NeedCannIV = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001902 Type *Ty = BackedgeTakenCount->getType();
Andrew Trick03d3d3b2011-05-25 04:42:22 +00001903 if (DisableIVRewrite) {
1904 // In this mode, SimplifyIVUsers may have already widened the IV used by
1905 // the backedge test and inserted a Trunc on the compare's operand. Get
1906 // the wider type to avoid creating a redundant narrow IV only used by the
1907 // loop test.
1908 LargestType = getBackedgeIVType(L);
1909 }
Andrew Trick4dfdf242011-05-03 22:24:10 +00001910 if (!LargestType ||
1911 SE->getTypeSizeInBits(Ty) >
1912 SE->getTypeSizeInBits(LargestType))
1913 LargestType = SE->getEffectiveSCEVType(Ty);
Chris Lattnerf50af082004-04-17 18:08:33 +00001914 }
Andrew Trick37da4082011-05-04 02:10:13 +00001915 if (!DisableIVRewrite) {
1916 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
1917 NeedCannIV = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001918 Type *Ty =
Andrew Trick37da4082011-05-04 02:10:13 +00001919 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
1920 if (!LargestType ||
1921 SE->getTypeSizeInBits(Ty) >
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001922 SE->getTypeSizeInBits(LargestType))
Andrew Trick37da4082011-05-04 02:10:13 +00001923 LargestType = Ty;
1924 }
Chris Lattner6148c022001-12-03 17:28:42 +00001925 }
1926
Dan Gohmanf451cb82010-02-10 16:03:48 +00001927 // Now that we know the largest of the induction variable expressions
Dan Gohman81db61a2009-05-12 02:17:14 +00001928 // in this loop, insert a canonical induction variable of the largest size.
Dan Gohman43ef3fb2010-07-20 17:18:52 +00001929 PHINode *IndVar = 0;
Dan Gohman81db61a2009-05-12 02:17:14 +00001930 if (NeedCannIV) {
Dan Gohman85669632010-02-25 06:57:05 +00001931 // Check to see if the loop already has any canonical-looking induction
1932 // variables. If any are present and wider than the planned canonical
1933 // induction variable, temporarily remove them, so that the Rewriter
1934 // doesn't attempt to reuse them.
1935 SmallVector<PHINode *, 2> OldCannIVs;
1936 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
Dan Gohman4d8414f2009-06-13 16:25:49 +00001937 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
1938 SE->getTypeSizeInBits(LargestType))
1939 OldCannIV->removeFromParent();
1940 else
Dan Gohman85669632010-02-25 06:57:05 +00001941 break;
1942 OldCannIVs.push_back(OldCannIV);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001943 }
1944
Dan Gohman667d7872009-06-26 22:53:46 +00001945 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001946
Dan Gohmanc2390b12009-02-12 22:19:27 +00001947 ++NumInserted;
1948 Changed = true;
David Greenef67ef312010-01-05 01:27:06 +00001949 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
Dan Gohman4d8414f2009-06-13 16:25:49 +00001950
1951 // Now that the official induction variable is established, reinsert
Dan Gohman85669632010-02-25 06:57:05 +00001952 // any old canonical-looking variables after it so that the IR remains
1953 // consistent. They will be deleted as part of the dead-PHI deletion at
Dan Gohman4d8414f2009-06-13 16:25:49 +00001954 // the end of the pass.
Dan Gohman85669632010-02-25 06:57:05 +00001955 while (!OldCannIVs.empty()) {
1956 PHINode *OldCannIV = OldCannIVs.pop_back_val();
Bill Wendlingb05fdd62011-08-24 20:28:43 +00001957 OldCannIV->insertBefore(L->getHeader()->getFirstInsertionPt());
Dan Gohman85669632010-02-25 06:57:05 +00001958 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001959 }
Andrew Trickfc933c02011-07-18 20:32:31 +00001960 else if (ExpandBECount && ReuseIVForExit && needsLFTR(L, DT)) {
1961 IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT, TD);
1962 }
Dan Gohmanc2390b12009-02-12 22:19:27 +00001963 // If we have a trip count expression, rewrite the loop's exit condition
1964 // using it. We can currently only handle loops with a single exit.
Andrew Trickfc933c02011-07-18 20:32:31 +00001965 Value *NewICmp = 0;
1966 if (ExpandBECount && IndVar) {
Andrew Trick56147692011-07-16 01:18:53 +00001967 // Check preconditions for proper SCEVExpander operation. SCEV does not
1968 // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
1969 // pass that uses the SCEVExpander must do it. This does not work well for
1970 // loop passes because SCEVExpander makes assumptions about all loops, while
1971 // LoopPassManager only forces the current loop to be simplified.
1972 //
1973 // FIXME: SCEV expansion has no way to bail out, so the caller must
1974 // explicitly check any assumptions made by SCEV. Brittle.
1975 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
1976 if (!AR || AR->getLoop()->getLoopPreheader())
1977 NewICmp =
1978 LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar, Rewriter);
Chris Lattnerfcb81f52004-04-22 14:59:40 +00001979 }
Andrew Trickb12a7542011-03-17 23:51:11 +00001980 // Rewrite IV-derived expressions.
Andrew Trick37da4082011-05-04 02:10:13 +00001981 if (!DisableIVRewrite)
1982 RewriteIVExpressions(L, Rewriter);
Dan Gohmanc2390b12009-02-12 22:19:27 +00001983
Andrew Trickb12a7542011-03-17 23:51:11 +00001984 // Clear the rewriter cache, because values that are in the rewriter's cache
1985 // can be deleted in the loop below, causing the AssertingVH in the cache to
1986 // trigger.
1987 Rewriter.clear();
1988
1989 // Now that we're done iterating through lists, clean up any instructions
1990 // which are now dead.
1991 while (!DeadInsts.empty())
1992 if (Instruction *Inst =
1993 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
1994 RecursivelyDeleteTriviallyDeadInstructions(Inst);
1995
Dan Gohman667d7872009-06-26 22:53:46 +00001996 // The Rewriter may not be used from this point on.
Torok Edwin3d431382009-05-24 20:08:21 +00001997
Dan Gohman81db61a2009-05-12 02:17:14 +00001998 // Loop-invariant instructions in the preheader that aren't used in the
1999 // loop may be sunk below the loop to reduce register pressure.
Dan Gohman667d7872009-06-26 22:53:46 +00002000 SinkUnusedInvariants(L);
Dan Gohman81db61a2009-05-12 02:17:14 +00002001
2002 // For completeness, inform IVUsers of the IV use in the newly-created
2003 // loop exit test instruction.
Andrew Trickfc933c02011-07-18 20:32:31 +00002004 if (IU && NewICmp) {
2005 ICmpInst *NewICmpInst = dyn_cast<ICmpInst>(NewICmp);
2006 if (NewICmpInst)
2007 IU->AddUsersIfInteresting(cast<Instruction>(NewICmpInst->getOperand(0)));
2008 }
Dan Gohman81db61a2009-05-12 02:17:14 +00002009 // Clean up dead instructions.
Dan Gohman9fff2182010-01-05 16:31:45 +00002010 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohman81db61a2009-05-12 02:17:14 +00002011 // Check a post-condition.
Andrew Trickf6a0dba2011-07-18 18:44:20 +00002012 assert(L->isLCSSAForm(*DT) &&
2013 "Indvars did not leave the loop in lcssa form!");
2014
2015 // Verify that LFTR, and any other change have not interfered with SCEV's
2016 // ability to compute trip count.
2017#ifndef NDEBUG
Andrew Trick75ebc0e2011-09-06 20:20:38 +00002018 if (DisableIVRewrite && VerifyIndvars &&
2019 !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
Andrew Trickf6a0dba2011-07-18 18:44:20 +00002020 SE->forgetLoop(L);
2021 const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
2022 if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
2023 SE->getTypeSizeInBits(NewBECount->getType()))
2024 NewBECount = SE->getTruncateOrNoop(NewBECount,
2025 BackedgeTakenCount->getType());
2026 else
2027 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
2028 NewBECount->getType());
2029 assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");
2030 }
2031#endif
2032
Devang Patel5ee99972007-03-07 06:39:01 +00002033 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +00002034}