build/CMake: Finish removal of add_llvm_library_dependencies.
[oota-llvm.git] / lib / Transforms / Scalar / IndVarSimplify.cpp
1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // 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 //
14 // If the trip count of a loop is computable, this pass also makes the following
15 // changes:
16 //   1. The exit condition for the loop is canonicalized to compare the
17 //      induction value against the exit value.  This turns loops like:
18 //        'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
19 //   2. Any use outside of the loop of an expression derived from the indvar
20 //      is changed to compute the derived value outside of the loop, eliminating
21 //      the dependence on the exit value of the induction variable.  If the only
22 //      purpose of the loop is to compute the exit value of some derived
23 //      expression, this transformation will make the loop dead.
24 //
25 //===----------------------------------------------------------------------===//
26
27 #define DEBUG_TYPE "indvars"
28 #include "llvm/Transforms/Scalar.h"
29 #include "llvm/BasicBlock.h"
30 #include "llvm/Constants.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/IntrinsicInst.h"
33 #include "llvm/LLVMContext.h"
34 #include "llvm/Type.h"
35 #include "llvm/Analysis/Dominators.h"
36 #include "llvm/Analysis/IVUsers.h"
37 #include "llvm/Analysis/ScalarEvolutionExpander.h"
38 #include "llvm/Analysis/LoopInfo.h"
39 #include "llvm/Analysis/LoopPass.h"
40 #include "llvm/Support/CFG.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
47 #include "llvm/Target/TargetData.h"
48 #include "llvm/ADT/DenseMap.h"
49 #include "llvm/ADT/SmallVector.h"
50 #include "llvm/ADT/Statistic.h"
51 using namespace llvm;
52
53 STATISTIC(NumRemoved     , "Number of aux indvars removed");
54 STATISTIC(NumWidened     , "Number of indvars widened");
55 STATISTIC(NumInserted    , "Number of canonical indvars added");
56 STATISTIC(NumReplaced    , "Number of exit values replaced");
57 STATISTIC(NumLFTR        , "Number of loop exit tests replaced");
58 STATISTIC(NumElimExt     , "Number of IV sign/zero extends eliminated");
59 STATISTIC(NumElimIV      , "Number of congruent IVs eliminated");
60
61 static cl::opt<bool> EnableIVRewrite(
62   "enable-iv-rewrite", cl::Hidden,
63   cl::desc("Enable canonical induction variable rewriting"));
64
65 // Trip count verification can be enabled by default under NDEBUG if we
66 // implement a strong expression equivalence checker in SCEV. Until then, we
67 // use the verify-indvars flag, which may assert in some cases.
68 static cl::opt<bool> VerifyIndvars(
69   "verify-indvars", cl::Hidden,
70   cl::desc("Verify the ScalarEvolution result after running indvars"));
71
72 namespace {
73   class IndVarSimplify : public LoopPass {
74     IVUsers         *IU;
75     LoopInfo        *LI;
76     ScalarEvolution *SE;
77     DominatorTree   *DT;
78     TargetData      *TD;
79
80     SmallVector<WeakVH, 16> DeadInsts;
81     bool Changed;
82   public:
83
84     static char ID; // Pass identification, replacement for typeid
85     IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0),
86                        Changed(false) {
87       initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
88     }
89
90     virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
91
92     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
93       AU.addRequired<DominatorTree>();
94       AU.addRequired<LoopInfo>();
95       AU.addRequired<ScalarEvolution>();
96       AU.addRequiredID(LoopSimplifyID);
97       AU.addRequiredID(LCSSAID);
98       if (EnableIVRewrite)
99         AU.addRequired<IVUsers>();
100       AU.addPreserved<ScalarEvolution>();
101       AU.addPreservedID(LoopSimplifyID);
102       AU.addPreservedID(LCSSAID);
103       if (EnableIVRewrite)
104         AU.addPreserved<IVUsers>();
105       AU.setPreservesCFG();
106     }
107
108   private:
109     virtual void releaseMemory() {
110       DeadInsts.clear();
111     }
112
113     bool isValidRewrite(Value *FromVal, Value *ToVal);
114
115     void HandleFloatingPointIV(Loop *L, PHINode *PH);
116     void RewriteNonIntegerIVs(Loop *L);
117
118     void SimplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LPPassManager &LPM);
119
120     void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
121
122     void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
123
124     Value *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
125                                      PHINode *IndVar, SCEVExpander &Rewriter);
126
127     void SinkUnusedInvariants(Loop *L);
128   };
129 }
130
131 char IndVarSimplify::ID = 0;
132 INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
133                 "Induction Variable Simplification", false, false)
134 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
135 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
136 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
137 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
138 INITIALIZE_PASS_DEPENDENCY(LCSSA)
139 INITIALIZE_PASS_DEPENDENCY(IVUsers)
140 INITIALIZE_PASS_END(IndVarSimplify, "indvars",
141                 "Induction Variable Simplification", false, false)
142
143 Pass *llvm::createIndVarSimplifyPass() {
144   return new IndVarSimplify();
145 }
146
147 /// isValidRewrite - Return true if the SCEV expansion generated by the
148 /// rewriter can replace the original value. SCEV guarantees that it
149 /// produces the same value, but the way it is produced may be illegal IR.
150 /// Ideally, this function will only be called for verification.
151 bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
152   // If an SCEV expression subsumed multiple pointers, its expansion could
153   // reassociate the GEP changing the base pointer. This is illegal because the
154   // final address produced by a GEP chain must be inbounds relative to its
155   // underlying object. Otherwise basic alias analysis, among other things,
156   // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
157   // producing an expression involving multiple pointers. Until then, we must
158   // bail out here.
159   //
160   // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
161   // because it understands lcssa phis while SCEV does not.
162   Value *FromPtr = FromVal;
163   Value *ToPtr = ToVal;
164   if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
165     FromPtr = GEP->getPointerOperand();
166   }
167   if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
168     ToPtr = GEP->getPointerOperand();
169   }
170   if (FromPtr != FromVal || ToPtr != ToVal) {
171     // Quickly check the common case
172     if (FromPtr == ToPtr)
173       return true;
174
175     // SCEV may have rewritten an expression that produces the GEP's pointer
176     // operand. That's ok as long as the pointer operand has the same base
177     // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
178     // base of a recurrence. This handles the case in which SCEV expansion
179     // converts a pointer type recurrence into a nonrecurrent pointer base
180     // indexed by an integer recurrence.
181     const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
182     const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
183     if (FromBase == ToBase)
184       return true;
185
186     DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
187           << *FromBase << " != " << *ToBase << "\n");
188
189     return false;
190   }
191   return true;
192 }
193
194 /// Determine the insertion point for this user. By default, insert immediately
195 /// before the user. SCEVExpander or LICM will hoist loop invariants out of the
196 /// loop. For PHI nodes, there may be multiple uses, so compute the nearest
197 /// common dominator for the incoming blocks.
198 static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
199                                           DominatorTree *DT) {
200   PHINode *PHI = dyn_cast<PHINode>(User);
201   if (!PHI)
202     return User;
203
204   Instruction *InsertPt = 0;
205   for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
206     if (PHI->getIncomingValue(i) != Def)
207       continue;
208
209     BasicBlock *InsertBB = PHI->getIncomingBlock(i);
210     if (!InsertPt) {
211       InsertPt = InsertBB->getTerminator();
212       continue;
213     }
214     InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
215     InsertPt = InsertBB->getTerminator();
216   }
217   assert(InsertPt && "Missing phi operand");
218   assert((!isa<Instruction>(Def) ||
219           DT->dominates(cast<Instruction>(Def), InsertPt)) &&
220          "def does not dominate all uses");
221   return InsertPt;
222 }
223
224 //===----------------------------------------------------------------------===//
225 // RewriteNonIntegerIVs and helpers. Prefer integer IVs.
226 //===----------------------------------------------------------------------===//
227
228 /// ConvertToSInt - Convert APF to an integer, if possible.
229 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
230   bool isExact = false;
231   if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
232     return false;
233   // See if we can convert this to an int64_t
234   uint64_t UIntVal;
235   if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
236                            &isExact) != APFloat::opOK || !isExact)
237     return false;
238   IntVal = UIntVal;
239   return true;
240 }
241
242 /// HandleFloatingPointIV - If the loop has floating induction variable
243 /// then insert corresponding integer induction variable if possible.
244 /// For example,
245 /// for(double i = 0; i < 10000; ++i)
246 ///   bar(i)
247 /// is converted into
248 /// for(int i = 0; i < 10000; ++i)
249 ///   bar((double)i);
250 ///
251 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
252   unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
253   unsigned BackEdge     = IncomingEdge^1;
254
255   // Check incoming value.
256   ConstantFP *InitValueVal =
257     dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
258
259   int64_t InitValue;
260   if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
261     return;
262
263   // Check IV increment. Reject this PN if increment operation is not
264   // an add or increment value can not be represented by an integer.
265   BinaryOperator *Incr =
266     dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
267   if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
268
269   // If this is not an add of the PHI with a constantfp, or if the constant fp
270   // is not an integer, bail out.
271   ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
272   int64_t IncValue;
273   if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
274       !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
275     return;
276
277   // Check Incr uses. One user is PN and the other user is an exit condition
278   // used by the conditional terminator.
279   Value::use_iterator IncrUse = Incr->use_begin();
280   Instruction *U1 = cast<Instruction>(*IncrUse++);
281   if (IncrUse == Incr->use_end()) return;
282   Instruction *U2 = cast<Instruction>(*IncrUse++);
283   if (IncrUse != Incr->use_end()) return;
284
285   // Find exit condition, which is an fcmp.  If it doesn't exist, or if it isn't
286   // only used by a branch, we can't transform it.
287   FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
288   if (!Compare)
289     Compare = dyn_cast<FCmpInst>(U2);
290   if (Compare == 0 || !Compare->hasOneUse() ||
291       !isa<BranchInst>(Compare->use_back()))
292     return;
293
294   BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
295
296   // We need to verify that the branch actually controls the iteration count
297   // of the loop.  If not, the new IV can overflow and no one will notice.
298   // The branch block must be in the loop and one of the successors must be out
299   // of the loop.
300   assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
301   if (!L->contains(TheBr->getParent()) ||
302       (L->contains(TheBr->getSuccessor(0)) &&
303        L->contains(TheBr->getSuccessor(1))))
304     return;
305
306
307   // If it isn't a comparison with an integer-as-fp (the exit value), we can't
308   // transform it.
309   ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
310   int64_t ExitValue;
311   if (ExitValueVal == 0 ||
312       !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
313     return;
314
315   // Find new predicate for integer comparison.
316   CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
317   switch (Compare->getPredicate()) {
318   default: return;  // Unknown comparison.
319   case CmpInst::FCMP_OEQ:
320   case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
321   case CmpInst::FCMP_ONE:
322   case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
323   case CmpInst::FCMP_OGT:
324   case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
325   case CmpInst::FCMP_OGE:
326   case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
327   case CmpInst::FCMP_OLT:
328   case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
329   case CmpInst::FCMP_OLE:
330   case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
331   }
332
333   // We convert the floating point induction variable to a signed i32 value if
334   // we can.  This is only safe if the comparison will not overflow in a way
335   // that won't be trapped by the integer equivalent operations.  Check for this
336   // now.
337   // TODO: We could use i64 if it is native and the range requires it.
338
339   // The start/stride/exit values must all fit in signed i32.
340   if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
341     return;
342
343   // If not actually striding (add x, 0.0), avoid touching the code.
344   if (IncValue == 0)
345     return;
346
347   // Positive and negative strides have different safety conditions.
348   if (IncValue > 0) {
349     // If we have a positive stride, we require the init to be less than the
350     // exit value.
351     if (InitValue >= ExitValue)
352       return;
353
354     uint32_t Range = uint32_t(ExitValue-InitValue);
355     // Check for infinite loop, either:
356     // while (i <= Exit) or until (i > Exit)
357     if (NewPred == CmpInst::ICMP_SLE || NewPred == CmpInst::ICMP_SGT) {
358       if (++Range == 0) return;  // Range overflows.
359     }
360
361     unsigned Leftover = Range % uint32_t(IncValue);
362
363     // If this is an equality comparison, we require that the strided value
364     // exactly land on the exit value, otherwise the IV condition will wrap
365     // around and do things the fp IV wouldn't.
366     if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
367         Leftover != 0)
368       return;
369
370     // If the stride would wrap around the i32 before exiting, we can't
371     // transform the IV.
372     if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
373       return;
374
375   } else {
376     // If we have a negative stride, we require the init to be greater than the
377     // exit value.
378     if (InitValue <= ExitValue)
379       return;
380
381     uint32_t Range = uint32_t(InitValue-ExitValue);
382     // Check for infinite loop, either:
383     // while (i >= Exit) or until (i < Exit)
384     if (NewPred == CmpInst::ICMP_SGE || NewPred == CmpInst::ICMP_SLT) {
385       if (++Range == 0) return;  // Range overflows.
386     }
387
388     unsigned Leftover = Range % uint32_t(-IncValue);
389
390     // If this is an equality comparison, we require that the strided value
391     // exactly land on the exit value, otherwise the IV condition will wrap
392     // around and do things the fp IV wouldn't.
393     if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
394         Leftover != 0)
395       return;
396
397     // If the stride would wrap around the i32 before exiting, we can't
398     // transform the IV.
399     if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
400       return;
401   }
402
403   IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
404
405   // Insert new integer induction variable.
406   PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
407   NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
408                       PN->getIncomingBlock(IncomingEdge));
409
410   Value *NewAdd =
411     BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
412                               Incr->getName()+".int", Incr);
413   NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
414
415   ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
416                                       ConstantInt::get(Int32Ty, ExitValue),
417                                       Compare->getName());
418
419   // In the following deletions, PN may become dead and may be deleted.
420   // Use a WeakVH to observe whether this happens.
421   WeakVH WeakPH = PN;
422
423   // Delete the old floating point exit comparison.  The branch starts using the
424   // new comparison.
425   NewCompare->takeName(Compare);
426   Compare->replaceAllUsesWith(NewCompare);
427   RecursivelyDeleteTriviallyDeadInstructions(Compare);
428
429   // Delete the old floating point increment.
430   Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
431   RecursivelyDeleteTriviallyDeadInstructions(Incr);
432
433   // If the FP induction variable still has uses, this is because something else
434   // in the loop uses its value.  In order to canonicalize the induction
435   // variable, we chose to eliminate the IV and rewrite it in terms of an
436   // int->fp cast.
437   //
438   // We give preference to sitofp over uitofp because it is faster on most
439   // platforms.
440   if (WeakPH) {
441     Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
442                                  PN->getParent()->getFirstInsertionPt());
443     PN->replaceAllUsesWith(Conv);
444     RecursivelyDeleteTriviallyDeadInstructions(PN);
445   }
446
447   // Add a new IVUsers entry for the newly-created integer PHI.
448   if (IU)
449     IU->AddUsersIfInteresting(NewPHI);
450
451   Changed = true;
452 }
453
454 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
455   // First step.  Check to see if there are any floating-point recurrences.
456   // If there are, change them into integer recurrences, permitting analysis by
457   // the SCEV routines.
458   //
459   BasicBlock *Header = L->getHeader();
460
461   SmallVector<WeakVH, 8> PHIs;
462   for (BasicBlock::iterator I = Header->begin();
463        PHINode *PN = dyn_cast<PHINode>(I); ++I)
464     PHIs.push_back(PN);
465
466   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
467     if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
468       HandleFloatingPointIV(L, PN);
469
470   // If the loop previously had floating-point IV, ScalarEvolution
471   // may not have been able to compute a trip count. Now that we've done some
472   // re-writing, the trip count may be computable.
473   if (Changed)
474     SE->forgetLoop(L);
475 }
476
477 //===----------------------------------------------------------------------===//
478 // RewriteLoopExitValues - Optimize IV users outside the loop.
479 // As a side effect, reduces the amount of IV processing within the loop.
480 //===----------------------------------------------------------------------===//
481
482 /// RewriteLoopExitValues - Check to see if this loop has a computable
483 /// loop-invariant execution count.  If so, this means that we can compute the
484 /// final value of any expressions that are recurrent in the loop, and
485 /// substitute the exit values from the loop into any instructions outside of
486 /// the loop that use the final values of the current expressions.
487 ///
488 /// This is mostly redundant with the regular IndVarSimplify activities that
489 /// happen later, except that it's more powerful in some cases, because it's
490 /// able to brute-force evaluate arbitrary instructions as long as they have
491 /// constant operands at the beginning of the loop.
492 void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
493   // Verify the input to the pass in already in LCSSA form.
494   assert(L->isLCSSAForm(*DT));
495
496   SmallVector<BasicBlock*, 8> ExitBlocks;
497   L->getUniqueExitBlocks(ExitBlocks);
498
499   // Find all values that are computed inside the loop, but used outside of it.
500   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
501   // the exit blocks of the loop to find them.
502   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
503     BasicBlock *ExitBB = ExitBlocks[i];
504
505     // If there are no PHI nodes in this exit block, then no values defined
506     // inside the loop are used on this path, skip it.
507     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
508     if (!PN) continue;
509
510     unsigned NumPreds = PN->getNumIncomingValues();
511
512     // Iterate over all of the PHI nodes.
513     BasicBlock::iterator BBI = ExitBB->begin();
514     while ((PN = dyn_cast<PHINode>(BBI++))) {
515       if (PN->use_empty())
516         continue; // dead use, don't replace it
517
518       // SCEV only supports integer expressions for now.
519       if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
520         continue;
521
522       // It's necessary to tell ScalarEvolution about this explicitly so that
523       // it can walk the def-use list and forget all SCEVs, as it may not be
524       // watching the PHI itself. Once the new exit value is in place, there
525       // may not be a def-use connection between the loop and every instruction
526       // which got a SCEVAddRecExpr for that loop.
527       SE->forgetValue(PN);
528
529       // Iterate over all of the values in all the PHI nodes.
530       for (unsigned i = 0; i != NumPreds; ++i) {
531         // If the value being merged in is not integer or is not defined
532         // in the loop, skip it.
533         Value *InVal = PN->getIncomingValue(i);
534         if (!isa<Instruction>(InVal))
535           continue;
536
537         // If this pred is for a subloop, not L itself, skip it.
538         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
539           continue; // The Block is in a subloop, skip it.
540
541         // Check that InVal is defined in the loop.
542         Instruction *Inst = cast<Instruction>(InVal);
543         if (!L->contains(Inst))
544           continue;
545
546         // Okay, this instruction has a user outside of the current loop
547         // and varies predictably *inside* the loop.  Evaluate the value it
548         // contains when the loop exits, if possible.
549         const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
550         if (!SE->isLoopInvariant(ExitValue, L))
551           continue;
552
553         Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
554
555         DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
556                      << "  LoopVal = " << *Inst << "\n");
557
558         if (!isValidRewrite(Inst, ExitVal)) {
559           DeadInsts.push_back(ExitVal);
560           continue;
561         }
562         Changed = true;
563         ++NumReplaced;
564
565         PN->setIncomingValue(i, ExitVal);
566
567         // If this instruction is dead now, delete it.
568         RecursivelyDeleteTriviallyDeadInstructions(Inst);
569
570         if (NumPreds == 1) {
571           // Completely replace a single-pred PHI. This is safe, because the
572           // NewVal won't be variant in the loop, so we don't need an LCSSA phi
573           // node anymore.
574           PN->replaceAllUsesWith(ExitVal);
575           RecursivelyDeleteTriviallyDeadInstructions(PN);
576         }
577       }
578       if (NumPreds != 1) {
579         // Clone the PHI and delete the original one. This lets IVUsers and
580         // any other maps purge the original user from their records.
581         PHINode *NewPN = cast<PHINode>(PN->clone());
582         NewPN->takeName(PN);
583         NewPN->insertBefore(PN);
584         PN->replaceAllUsesWith(NewPN);
585         PN->eraseFromParent();
586       }
587     }
588   }
589
590   // The insertion point instruction may have been deleted; clear it out
591   // so that the rewriter doesn't trip over it later.
592   Rewriter.clearInsertPoint();
593 }
594
595 //===----------------------------------------------------------------------===//
596 //  Rewrite IV users based on a canonical IV.
597 //  Only for use with -enable-iv-rewrite.
598 //===----------------------------------------------------------------------===//
599
600 /// FIXME: It is an extremely bad idea to indvar substitute anything more
601 /// complex than affine induction variables.  Doing so will put expensive
602 /// polynomial evaluations inside of the loop, and the str reduction pass
603 /// currently can only reduce affine polynomials.  For now just disable
604 /// indvar subst on anything more complex than an affine addrec, unless
605 /// it can be expanded to a trivial value.
606 static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
607   // Loop-invariant values are safe.
608   if (SE->isLoopInvariant(S, L)) return true;
609
610   // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
611   // to transform them into efficient code.
612   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
613     return AR->isAffine();
614
615   // An add is safe it all its operands are safe.
616   if (const SCEVCommutativeExpr *Commutative
617       = dyn_cast<SCEVCommutativeExpr>(S)) {
618     for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
619          E = Commutative->op_end(); I != E; ++I)
620       if (!isSafe(*I, L, SE)) return false;
621     return true;
622   }
623
624   // A cast is safe if its operand is.
625   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
626     return isSafe(C->getOperand(), L, SE);
627
628   // A udiv is safe if its operands are.
629   if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
630     return isSafe(UD->getLHS(), L, SE) &&
631            isSafe(UD->getRHS(), L, SE);
632
633   // SCEVUnknown is always safe.
634   if (isa<SCEVUnknown>(S))
635     return true;
636
637   // Nothing else is safe.
638   return false;
639 }
640
641 void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
642   // Rewrite all induction variable expressions in terms of the canonical
643   // induction variable.
644   //
645   // If there were induction variables of other sizes or offsets, manually
646   // add the offsets to the primary induction variable and cast, avoiding
647   // the need for the code evaluation methods to insert induction variables
648   // of different sizes.
649   for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
650     Value *Op = UI->getOperandValToReplace();
651     Type *UseTy = Op->getType();
652     Instruction *User = UI->getUser();
653
654     // Compute the final addrec to expand into code.
655     const SCEV *AR = IU->getReplacementExpr(*UI);
656
657     // Evaluate the expression out of the loop, if possible.
658     if (!L->contains(UI->getUser())) {
659       const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
660       if (SE->isLoopInvariant(ExitVal, L))
661         AR = ExitVal;
662     }
663
664     // FIXME: It is an extremely bad idea to indvar substitute anything more
665     // complex than affine induction variables.  Doing so will put expensive
666     // polynomial evaluations inside of the loop, and the str reduction pass
667     // currently can only reduce affine polynomials.  For now just disable
668     // indvar subst on anything more complex than an affine addrec, unless
669     // it can be expanded to a trivial value.
670     if (!isSafe(AR, L, SE))
671       continue;
672
673     // Determine the insertion point for this user. By default, insert
674     // immediately before the user. The SCEVExpander class will automatically
675     // hoist loop invariants out of the loop. For PHI nodes, there may be
676     // multiple uses, so compute the nearest common dominator for the
677     // incoming blocks.
678     Instruction *InsertPt = getInsertPointForUses(User, Op, DT);
679
680     // Now expand it into actual Instructions and patch it into place.
681     Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
682
683     DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
684                  << "   into = " << *NewVal << "\n");
685
686     if (!isValidRewrite(Op, NewVal)) {
687       DeadInsts.push_back(NewVal);
688       continue;
689     }
690     // Inform ScalarEvolution that this value is changing. The change doesn't
691     // affect its value, but it does potentially affect which use lists the
692     // value will be on after the replacement, which affects ScalarEvolution's
693     // ability to walk use lists and drop dangling pointers when a value is
694     // deleted.
695     SE->forgetValue(User);
696
697     // Patch the new value into place.
698     if (Op->hasName())
699       NewVal->takeName(Op);
700     if (Instruction *NewValI = dyn_cast<Instruction>(NewVal))
701       NewValI->setDebugLoc(User->getDebugLoc());
702     User->replaceUsesOfWith(Op, NewVal);
703     UI->setOperandValToReplace(NewVal);
704
705     ++NumRemoved;
706     Changed = true;
707
708     // The old value may be dead now.
709     DeadInsts.push_back(Op);
710   }
711 }
712
713 //===----------------------------------------------------------------------===//
714 //  IV Widening - Extend the width of an IV to cover its widest uses.
715 //===----------------------------------------------------------------------===//
716
717 namespace {
718   // Collect information about induction variables that are used by sign/zero
719   // extend operations. This information is recorded by CollectExtend and
720   // provides the input to WidenIV.
721   struct WideIVInfo {
722     PHINode *NarrowIV;
723     Type *WidestNativeType; // Widest integer type created [sz]ext
724     bool IsSigned;          // Was an sext user seen before a zext?
725
726     WideIVInfo() : NarrowIV(0), WidestNativeType(0), IsSigned(false) {}
727   };
728
729   class WideIVVisitor : public IVVisitor {
730     ScalarEvolution *SE;
731     const TargetData *TD;
732
733   public:
734     WideIVInfo WI;
735
736     WideIVVisitor(PHINode *NarrowIV, ScalarEvolution *SCEV,
737                   const TargetData *TData) :
738       SE(SCEV), TD(TData) { WI.NarrowIV = NarrowIV; }
739
740     // Implement the interface used by simplifyUsersOfIV.
741     virtual void visitCast(CastInst *Cast);
742   };
743 }
744
745 /// visitCast - Update information about the induction variable that is
746 /// extended by this sign or zero extend operation. This is used to determine
747 /// the final width of the IV before actually widening it.
748 void WideIVVisitor::visitCast(CastInst *Cast) {
749   bool IsSigned = Cast->getOpcode() == Instruction::SExt;
750   if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)
751     return;
752
753   Type *Ty = Cast->getType();
754   uint64_t Width = SE->getTypeSizeInBits(Ty);
755   if (TD && !TD->isLegalInteger(Width))
756     return;
757
758   if (!WI.WidestNativeType) {
759     WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
760     WI.IsSigned = IsSigned;
761     return;
762   }
763
764   // We extend the IV to satisfy the sign of its first user, arbitrarily.
765   if (WI.IsSigned != IsSigned)
766     return;
767
768   if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
769     WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
770 }
771
772 namespace {
773
774 /// NarrowIVDefUse - Record a link in the Narrow IV def-use chain along with the
775 /// WideIV that computes the same value as the Narrow IV def.  This avoids
776 /// caching Use* pointers.
777 struct NarrowIVDefUse {
778   Instruction *NarrowDef;
779   Instruction *NarrowUse;
780   Instruction *WideDef;
781
782   NarrowIVDefUse(): NarrowDef(0), NarrowUse(0), WideDef(0) {}
783
784   NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD):
785     NarrowDef(ND), NarrowUse(NU), WideDef(WD) {}
786 };
787
788 /// WidenIV - The goal of this transform is to remove sign and zero extends
789 /// without creating any new induction variables. To do this, it creates a new
790 /// phi of the wider type and redirects all users, either removing extends or
791 /// inserting truncs whenever we stop propagating the type.
792 ///
793 class WidenIV {
794   // Parameters
795   PHINode *OrigPhi;
796   Type *WideType;
797   bool IsSigned;
798
799   // Context
800   LoopInfo        *LI;
801   Loop            *L;
802   ScalarEvolution *SE;
803   DominatorTree   *DT;
804
805   // Result
806   PHINode *WidePhi;
807   Instruction *WideInc;
808   const SCEV *WideIncExpr;
809   SmallVectorImpl<WeakVH> &DeadInsts;
810
811   SmallPtrSet<Instruction*,16> Widened;
812   SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
813
814 public:
815   WidenIV(const WideIVInfo &WI, LoopInfo *LInfo,
816           ScalarEvolution *SEv, DominatorTree *DTree,
817           SmallVectorImpl<WeakVH> &DI) :
818     OrigPhi(WI.NarrowIV),
819     WideType(WI.WidestNativeType),
820     IsSigned(WI.IsSigned),
821     LI(LInfo),
822     L(LI->getLoopFor(OrigPhi->getParent())),
823     SE(SEv),
824     DT(DTree),
825     WidePhi(0),
826     WideInc(0),
827     WideIncExpr(0),
828     DeadInsts(DI) {
829     assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
830   }
831
832   PHINode *CreateWideIV(SCEVExpander &Rewriter);
833
834 protected:
835   Value *getExtend(Value *NarrowOper, Type *WideType, bool IsSigned,
836                    Instruction *Use);
837
838   Instruction *CloneIVUser(NarrowIVDefUse DU);
839
840   const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
841
842   const SCEVAddRecExpr* GetExtendedOperandRecurrence(NarrowIVDefUse DU);
843
844   Instruction *WidenIVUse(NarrowIVDefUse DU);
845
846   void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
847 };
848 } // anonymous namespace
849
850 /// isLoopInvariant - Perform a quick domtree based check for loop invariance
851 /// assuming that V is used within the loop. LoopInfo::isLoopInvariant() seems
852 /// gratuitous for this purpose.
853 static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT) {
854   Instruction *Inst = dyn_cast<Instruction>(V);
855   if (!Inst)
856     return true;
857
858   return DT->properlyDominates(Inst->getParent(), L->getHeader());
859 }
860
861 Value *WidenIV::getExtend(Value *NarrowOper, Type *WideType, bool IsSigned,
862                           Instruction *Use) {
863   // Set the debug location and conservative insertion point.
864   IRBuilder<> Builder(Use);
865   // Hoist the insertion point into loop preheaders as far as possible.
866   for (const Loop *L = LI->getLoopFor(Use->getParent());
867        L && L->getLoopPreheader() && isLoopInvariant(NarrowOper, L, DT);
868        L = L->getParentLoop())
869     Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
870
871   return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
872                     Builder.CreateZExt(NarrowOper, WideType);
873 }
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.
878 Instruction *WidenIV::CloneIVUser(NarrowIVDefUse DU) {
879   unsigned Opcode = DU.NarrowUse->getOpcode();
880   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:
893     DEBUG(dbgs() << "Cloning IVUser: " << *DU.NarrowUse << "\n");
894
895     // Replace NarrowDef operands with WideDef. Otherwise, we don't know
896     // anything about the narrow operand yet so must insert a [sz]ext. It is
897     // probably loop invariant and will be folded or hoisted. If it actually
898     // comes from a widened IV, it should be removed during a future call to
899     // WidenIVUse.
900     Value *LHS = (DU.NarrowUse->getOperand(0) == DU.NarrowDef) ? DU.WideDef :
901       getExtend(DU.NarrowUse->getOperand(0), WideType, IsSigned, DU.NarrowUse);
902     Value *RHS = (DU.NarrowUse->getOperand(1) == DU.NarrowDef) ? DU.WideDef :
903       getExtend(DU.NarrowUse->getOperand(1), WideType, IsSigned, DU.NarrowUse);
904
905     BinaryOperator *NarrowBO = cast<BinaryOperator>(DU.NarrowUse);
906     BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
907                                                     LHS, RHS,
908                                                     NarrowBO->getName());
909     IRBuilder<> Builder(DU.NarrowUse);
910     Builder.Insert(WideBO);
911     if (const OverflowingBinaryOperator *OBO =
912         dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
913       if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
914       if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
915     }
916     return WideBO;
917   }
918   llvm_unreachable(0);
919 }
920
921 /// No-wrap operations can transfer sign extension of their result to their
922 /// operands. Generate the SCEV value for the widened operation without
923 /// actually modifying the IR yet. If the expression after extending the
924 /// operands is an AddRec for this loop, return it.
925 const SCEVAddRecExpr* WidenIV::GetExtendedOperandRecurrence(NarrowIVDefUse DU) {
926   // Handle the common case of add<nsw/nuw>
927   if (DU.NarrowUse->getOpcode() != Instruction::Add)
928     return 0;
929
930   // One operand (NarrowDef) has already been extended to WideDef. Now determine
931   // if extending the other will lead to a recurrence.
932   unsigned ExtendOperIdx = DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
933   assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU");
934
935   const SCEV *ExtendOperExpr = 0;
936   const OverflowingBinaryOperator *OBO =
937     cast<OverflowingBinaryOperator>(DU.NarrowUse);
938   if (IsSigned && OBO->hasNoSignedWrap())
939     ExtendOperExpr = SE->getSignExtendExpr(
940       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
941   else if(!IsSigned && OBO->hasNoUnsignedWrap())
942     ExtendOperExpr = SE->getZeroExtendExpr(
943       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
944   else
945     return 0;
946
947   // When creating this AddExpr, don't apply the current operations NSW or NUW
948   // flags. This instruction may be guarded by control flow that the no-wrap
949   // behavior depends on. Non-control-equivalent instructions can be mapped to
950   // the same SCEV expression, and it would be incorrect to transfer NSW/NUW
951   // semantics to those operations.
952   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(
953     SE->getAddExpr(SE->getSCEV(DU.WideDef), ExtendOperExpr));
954
955   if (!AddRec || AddRec->getLoop() != L)
956     return 0;
957   return AddRec;
958 }
959
960 /// GetWideRecurrence - Is this instruction potentially interesting from
961 /// IVUsers' perspective after widening it's type? In other words, can the
962 /// extend be safely hoisted out of the loop with SCEV reducing the value to a
963 /// recurrence on the same loop. If so, return the sign or zero extended
964 /// recurrence. Otherwise return NULL.
965 const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
966   if (!SE->isSCEVable(NarrowUse->getType()))
967     return 0;
968
969   const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
970   if (SE->getTypeSizeInBits(NarrowExpr->getType())
971       >= SE->getTypeSizeInBits(WideType)) {
972     // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
973     // index. So don't follow this use.
974     return 0;
975   }
976
977   const SCEV *WideExpr = IsSigned ?
978     SE->getSignExtendExpr(NarrowExpr, WideType) :
979     SE->getZeroExtendExpr(NarrowExpr, WideType);
980   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
981   if (!AddRec || AddRec->getLoop() != L)
982     return 0;
983   return AddRec;
984 }
985
986 /// WidenIVUse - Determine whether an individual user of the narrow IV can be
987 /// widened. If so, return the wide clone of the user.
988 Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU) {
989
990   // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
991   if (isa<PHINode>(DU.NarrowUse) &&
992       LI->getLoopFor(DU.NarrowUse->getParent()) != L)
993     return 0;
994
995   // Our raison d'etre! Eliminate sign and zero extension.
996   if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) {
997     Value *NewDef = DU.WideDef;
998     if (DU.NarrowUse->getType() != WideType) {
999       unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
1000       unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1001       if (CastWidth < IVWidth) {
1002         // The cast isn't as wide as the IV, so insert a Trunc.
1003         IRBuilder<> Builder(DU.NarrowUse);
1004         NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
1005       }
1006       else {
1007         // A wider extend was hidden behind a narrower one. This may induce
1008         // another round of IV widening in which the intermediate IV becomes
1009         // dead. It should be very rare.
1010         DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
1011               << " not wide enough to subsume " << *DU.NarrowUse << "\n");
1012         DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1013         NewDef = DU.NarrowUse;
1014       }
1015     }
1016     if (NewDef != DU.NarrowUse) {
1017       DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1018             << " replaced by " << *DU.WideDef << "\n");
1019       ++NumElimExt;
1020       DU.NarrowUse->replaceAllUsesWith(NewDef);
1021       DeadInsts.push_back(DU.NarrowUse);
1022     }
1023     // Now that the extend is gone, we want to expose it's uses for potential
1024     // further simplification. We don't need to directly inform SimplifyIVUsers
1025     // of the new users, because their parent IV will be processed later as a
1026     // new loop phi. If we preserved IVUsers analysis, we would also want to
1027     // push the uses of WideDef here.
1028
1029     // No further widening is needed. The deceased [sz]ext had done it for us.
1030     return 0;
1031   }
1032
1033   // Does this user itself evaluate to a recurrence after widening?
1034   const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(DU.NarrowUse);
1035   if (!WideAddRec) {
1036       WideAddRec = GetExtendedOperandRecurrence(DU);
1037   }
1038   if (!WideAddRec) {
1039     // This user does not evaluate to a recurence after widening, so don't
1040     // follow it. Instead insert a Trunc to kill off the original use,
1041     // eventually isolating the original narrow IV so it can be removed.
1042     IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT));
1043     Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
1044     DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
1045     return 0;
1046   }
1047   // Assume block terminators cannot evaluate to a recurrence. We can't to
1048   // insert a Trunc after a terminator if there happens to be a critical edge.
1049   assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
1050          "SCEV is not expected to evaluate a block terminator");
1051
1052   // Reuse the IV increment that SCEVExpander created as long as it dominates
1053   // NarrowUse.
1054   Instruction *WideUse = 0;
1055   if (WideAddRec == WideIncExpr
1056       && SCEVExpander::hoistStep(WideInc, DU.NarrowUse, DT))
1057     WideUse = WideInc;
1058   else {
1059     WideUse = CloneIVUser(DU);
1060     if (!WideUse)
1061       return 0;
1062   }
1063   // Evaluation of WideAddRec ensured that the narrow expression could be
1064   // extended outside the loop without overflow. This suggests that the wide use
1065   // evaluates to the same expression as the extended narrow use, but doesn't
1066   // absolutely guarantee it. Hence the following failsafe check. In rare cases
1067   // where it fails, we simply throw away the newly created wide use.
1068   if (WideAddRec != SE->getSCEV(WideUse)) {
1069     DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
1070           << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
1071     DeadInsts.push_back(WideUse);
1072     return 0;
1073   }
1074
1075   // Returning WideUse pushes it on the worklist.
1076   return WideUse;
1077 }
1078
1079 /// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers.
1080 ///
1081 void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1082   for (Value::use_iterator UI = NarrowDef->use_begin(),
1083          UE = NarrowDef->use_end(); UI != UE; ++UI) {
1084     Instruction *NarrowUse = cast<Instruction>(*UI);
1085
1086     // Handle data flow merges and bizarre phi cycles.
1087     if (!Widened.insert(NarrowUse))
1088       continue;
1089
1090     NarrowIVUsers.push_back(NarrowIVDefUse(NarrowDef, NarrowUse, WideDef));
1091   }
1092 }
1093
1094 /// CreateWideIV - Process a single induction variable. First use the
1095 /// SCEVExpander to create a wide induction variable that evaluates to the same
1096 /// recurrence as the original narrow IV. Then use a worklist to forward
1097 /// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
1098 /// interesting IV users, the narrow IV will be isolated for removal by
1099 /// DeleteDeadPHIs.
1100 ///
1101 /// It would be simpler to delete uses as they are processed, but we must avoid
1102 /// invalidating SCEV expressions.
1103 ///
1104 PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
1105   // Is this phi an induction variable?
1106   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1107   if (!AddRec)
1108     return NULL;
1109
1110   // Widen the induction variable expression.
1111   const SCEV *WideIVExpr = IsSigned ?
1112     SE->getSignExtendExpr(AddRec, WideType) :
1113     SE->getZeroExtendExpr(AddRec, WideType);
1114
1115   assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1116          "Expect the new IV expression to preserve its type");
1117
1118   // Can the IV be extended outside the loop without overflow?
1119   AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1120   if (!AddRec || AddRec->getLoop() != L)
1121     return NULL;
1122
1123   // An AddRec must have loop-invariant operands. Since this AddRec is
1124   // materialized by a loop header phi, the expression cannot have any post-loop
1125   // operands, so they must dominate the loop header.
1126   assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1127          SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
1128          && "Loop header phi recurrence inputs do not dominate the loop");
1129
1130   // The rewriter provides a value for the desired IV expression. This may
1131   // either find an existing phi or materialize a new one. Either way, we
1132   // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1133   // of the phi-SCC dominates the loop entry.
1134   Instruction *InsertPt = L->getHeader()->begin();
1135   WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
1136
1137   // Remembering the WideIV increment generated by SCEVExpander allows
1138   // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
1139   // employ a general reuse mechanism because the call above is the only call to
1140   // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
1141   if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1142     WideInc =
1143       cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1144     WideIncExpr = SE->getSCEV(WideInc);
1145   }
1146
1147   DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1148   ++NumWidened;
1149
1150   // Traverse the def-use chain using a worklist starting at the original IV.
1151   assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
1152
1153   Widened.insert(OrigPhi);
1154   pushNarrowIVUsers(OrigPhi, WidePhi);
1155
1156   while (!NarrowIVUsers.empty()) {
1157     NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
1158
1159     // Process a def-use edge. This may replace the use, so don't hold a
1160     // use_iterator across it.
1161     Instruction *WideUse = WidenIVUse(DU);
1162
1163     // Follow all def-use edges from the previous narrow use.
1164     if (WideUse)
1165       pushNarrowIVUsers(DU.NarrowUse, WideUse);
1166
1167     // WidenIVUse may have removed the def-use edge.
1168     if (DU.NarrowDef->use_empty())
1169       DeadInsts.push_back(DU.NarrowDef);
1170   }
1171   return WidePhi;
1172 }
1173
1174 //===----------------------------------------------------------------------===//
1175 //  Simplification of IV users based on SCEV evaluation.
1176 //===----------------------------------------------------------------------===//
1177
1178
1179 /// SimplifyAndExtend - Iteratively perform simplification on a worklist of IV
1180 /// users. Each successive simplification may push more users which may
1181 /// themselves be candidates for simplification.
1182 ///
1183 /// Sign/Zero extend elimination is interleaved with IV simplification.
1184 ///
1185 void IndVarSimplify::SimplifyAndExtend(Loop *L,
1186                                        SCEVExpander &Rewriter,
1187                                        LPPassManager &LPM) {
1188   SmallVector<WideIVInfo, 8> WideIVs;
1189
1190   SmallVector<PHINode*, 8> LoopPhis;
1191   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1192     LoopPhis.push_back(cast<PHINode>(I));
1193   }
1194   // Each round of simplification iterates through the SimplifyIVUsers worklist
1195   // for all current phis, then determines whether any IVs can be
1196   // widened. Widening adds new phis to LoopPhis, inducing another round of
1197   // simplification on the wide IVs.
1198   while (!LoopPhis.empty()) {
1199     // Evaluate as many IV expressions as possible before widening any IVs. This
1200     // forces SCEV to set no-wrap flags before evaluating sign/zero
1201     // extension. The first time SCEV attempts to normalize sign/zero extension,
1202     // the result becomes final. So for the most predictable results, we delay
1203     // evaluation of sign/zero extend evaluation until needed, and avoid running
1204     // other SCEV based analysis prior to SimplifyAndExtend.
1205     do {
1206       PHINode *CurrIV = LoopPhis.pop_back_val();
1207
1208       // Information about sign/zero extensions of CurrIV.
1209       WideIVVisitor WIV(CurrIV, SE, TD);
1210
1211       Changed |= simplifyUsersOfIV(CurrIV, SE, &LPM, DeadInsts, &WIV);
1212
1213       if (WIV.WI.WidestNativeType) {
1214         WideIVs.push_back(WIV.WI);
1215       }
1216     } while(!LoopPhis.empty());
1217
1218     for (; !WideIVs.empty(); WideIVs.pop_back()) {
1219       WidenIV Widener(WideIVs.back(), LI, SE, DT, DeadInsts);
1220       if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
1221         Changed = true;
1222         LoopPhis.push_back(WidePhi);
1223       }
1224     }
1225   }
1226 }
1227
1228 //===----------------------------------------------------------------------===//
1229 //  LinearFunctionTestReplace and its kin. Rewrite the loop exit condition.
1230 //===----------------------------------------------------------------------===//
1231
1232 /// Check for expressions that ScalarEvolution generates to compute
1233 /// BackedgeTakenInfo. If these expressions have not been reduced, then
1234 /// expanding them may incur additional cost (albeit in the loop preheader).
1235 static bool isHighCostExpansion(const SCEV *S, BranchInst *BI,
1236                                 ScalarEvolution *SE) {
1237   // If the backedge-taken count is a UDiv, it's very likely a UDiv that
1238   // ScalarEvolution's HowFarToZero or HowManyLessThans produced to compute a
1239   // precise expression, rather than a UDiv from the user's code. If we can't
1240   // find a UDiv in the code with some simple searching, assume the former and
1241   // forego rewriting the loop.
1242   if (isa<SCEVUDivExpr>(S)) {
1243     ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
1244     if (!OrigCond) return true;
1245     const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
1246     R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
1247     if (R != S) {
1248       const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
1249       L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
1250       if (L != S)
1251         return true;
1252     }
1253   }
1254
1255   if (EnableIVRewrite)
1256     return false;
1257
1258   // Recurse past add expressions, which commonly occur in the
1259   // BackedgeTakenCount. They may already exist in program code, and if not,
1260   // they are not too expensive rematerialize.
1261   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1262     for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1263          I != E; ++I) {
1264       if (isHighCostExpansion(*I, BI, SE))
1265         return true;
1266     }
1267     return false;
1268   }
1269
1270   // HowManyLessThans uses a Max expression whenever the loop is not guarded by
1271   // the exit condition.
1272   if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
1273     return true;
1274
1275   // If we haven't recognized an expensive SCEV patter, assume its an expression
1276   // produced by program code.
1277   return false;
1278 }
1279
1280 /// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
1281 /// count expression can be safely and cheaply expanded into an instruction
1282 /// sequence that can be used by LinearFunctionTestReplace.
1283 ///
1284 /// TODO: This fails for pointer-type loop counters with greater than one byte
1285 /// strides, consequently preventing LFTR from running. For the purpose of LFTR
1286 /// we could skip this check in the case that the LFTR loop counter (chosen by
1287 /// FindLoopCounter) is also pointer type. Instead, we could directly convert
1288 /// the loop test to an inequality test by checking the target data's alignment
1289 /// of element types (given that the initial pointer value originates from or is
1290 /// used by ABI constrained operation, as opposed to inttoptr/ptrtoint).
1291 /// However, we don't yet have a strong motivation for converting loop tests
1292 /// into inequality tests.
1293 static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) {
1294   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1295   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1296       BackedgeTakenCount->isZero())
1297     return false;
1298
1299   if (!L->getExitingBlock())
1300     return false;
1301
1302   // Can't rewrite non-branch yet.
1303   BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1304   if (!BI)
1305     return false;
1306
1307   if (isHighCostExpansion(BackedgeTakenCount, BI, SE))
1308     return false;
1309
1310   return true;
1311 }
1312
1313 /// getBackedgeIVType - Get the widest type used by the loop test after peeking
1314 /// through Truncs.
1315 ///
1316 /// TODO: Unnecessary when ForceLFTR is removed.
1317 static Type *getBackedgeIVType(Loop *L) {
1318   if (!L->getExitingBlock())
1319     return 0;
1320
1321   // Can't rewrite non-branch yet.
1322   BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1323   if (!BI)
1324     return 0;
1325
1326   ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1327   if (!Cond)
1328     return 0;
1329
1330   Type *Ty = 0;
1331   for(User::op_iterator OI = Cond->op_begin(), OE = Cond->op_end();
1332       OI != OE; ++OI) {
1333     assert((!Ty || Ty == (*OI)->getType()) && "bad icmp operand types");
1334     TruncInst *Trunc = dyn_cast<TruncInst>(*OI);
1335     if (!Trunc)
1336       continue;
1337
1338     return Trunc->getSrcTy();
1339   }
1340   return Ty;
1341 }
1342
1343 /// getLoopPhiForCounter - Return the loop header phi IFF IncV adds a loop
1344 /// invariant value to the phi.
1345 static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
1346   Instruction *IncI = dyn_cast<Instruction>(IncV);
1347   if (!IncI)
1348     return 0;
1349
1350   switch (IncI->getOpcode()) {
1351   case Instruction::Add:
1352   case Instruction::Sub:
1353     break;
1354   case Instruction::GetElementPtr:
1355     // An IV counter must preserve its type.
1356     if (IncI->getNumOperands() == 2)
1357       break;
1358   default:
1359     return 0;
1360   }
1361
1362   PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
1363   if (Phi && Phi->getParent() == L->getHeader()) {
1364     if (isLoopInvariant(IncI->getOperand(1), L, DT))
1365       return Phi;
1366     return 0;
1367   }
1368   if (IncI->getOpcode() == Instruction::GetElementPtr)
1369     return 0;
1370
1371   // Allow add/sub to be commuted.
1372   Phi = dyn_cast<PHINode>(IncI->getOperand(1));
1373   if (Phi && Phi->getParent() == L->getHeader()) {
1374     if (isLoopInvariant(IncI->getOperand(0), L, DT))
1375       return Phi;
1376   }
1377   return 0;
1378 }
1379
1380 /// needsLFTR - LinearFunctionTestReplace policy. Return true unless we can show
1381 /// that the current exit test is already sufficiently canonical.
1382 static bool needsLFTR(Loop *L, DominatorTree *DT) {
1383   assert(L->getExitingBlock() && "expected loop exit");
1384
1385   BasicBlock *LatchBlock = L->getLoopLatch();
1386   // Don't bother with LFTR if the loop is not properly simplified.
1387   if (!LatchBlock)
1388     return false;
1389
1390   BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1391   assert(BI && "expected exit branch");
1392
1393   // Do LFTR to simplify the exit condition to an ICMP.
1394   ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1395   if (!Cond)
1396     return true;
1397
1398   // Do LFTR to simplify the exit ICMP to EQ/NE
1399   ICmpInst::Predicate Pred = Cond->getPredicate();
1400   if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
1401     return true;
1402
1403   // Look for a loop invariant RHS
1404   Value *LHS = Cond->getOperand(0);
1405   Value *RHS = Cond->getOperand(1);
1406   if (!isLoopInvariant(RHS, L, DT)) {
1407     if (!isLoopInvariant(LHS, L, DT))
1408       return true;
1409     std::swap(LHS, RHS);
1410   }
1411   // Look for a simple IV counter LHS
1412   PHINode *Phi = dyn_cast<PHINode>(LHS);
1413   if (!Phi)
1414     Phi = getLoopPhiForCounter(LHS, L, DT);
1415
1416   if (!Phi)
1417     return true;
1418
1419   // Do LFTR if the exit condition's IV is *not* a simple counter.
1420   Value *IncV = Phi->getIncomingValueForBlock(L->getLoopLatch());
1421   return Phi != getLoopPhiForCounter(IncV, L, DT);
1422 }
1423
1424 /// AlmostDeadIV - Return true if this IV has any uses other than the (soon to
1425 /// be rewritten) loop exit test.
1426 static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
1427   int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1428   Value *IncV = Phi->getIncomingValue(LatchIdx);
1429
1430   for (Value::use_iterator UI = Phi->use_begin(), UE = Phi->use_end();
1431        UI != UE; ++UI) {
1432     if (*UI != Cond && *UI != IncV) return false;
1433   }
1434
1435   for (Value::use_iterator UI = IncV->use_begin(), UE = IncV->use_end();
1436        UI != UE; ++UI) {
1437     if (*UI != Cond && *UI != Phi) return false;
1438   }
1439   return true;
1440 }
1441
1442 /// FindLoopCounter - Find an affine IV in canonical form.
1443 ///
1444 /// BECount may be an i8* pointer type. The pointer difference is already
1445 /// valid count without scaling the address stride, so it remains a pointer
1446 /// expression as far as SCEV is concerned.
1447 ///
1448 /// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
1449 ///
1450 /// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
1451 /// This is difficult in general for SCEV because of potential overflow. But we
1452 /// could at least handle constant BECounts.
1453 static PHINode *
1454 FindLoopCounter(Loop *L, const SCEV *BECount,
1455                 ScalarEvolution *SE, DominatorTree *DT, const TargetData *TD) {
1456   uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
1457
1458   Value *Cond =
1459     cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
1460
1461   // Loop over all of the PHI nodes, looking for a simple counter.
1462   PHINode *BestPhi = 0;
1463   const SCEV *BestInit = 0;
1464   BasicBlock *LatchBlock = L->getLoopLatch();
1465   assert(LatchBlock && "needsLFTR should guarantee a loop latch");
1466
1467   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1468     PHINode *Phi = cast<PHINode>(I);
1469     if (!SE->isSCEVable(Phi->getType()))
1470       continue;
1471
1472     // Avoid comparing an integer IV against a pointer Limit.
1473     if (BECount->getType()->isPointerTy() && !Phi->getType()->isPointerTy())
1474       continue;
1475
1476     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
1477     if (!AR || AR->getLoop() != L || !AR->isAffine())
1478       continue;
1479
1480     // AR may be a pointer type, while BECount is an integer type.
1481     // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
1482     // AR may not be a narrower type, or we may never exit.
1483     uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
1484     if (PhiWidth < BCWidth || (TD && !TD->isLegalInteger(PhiWidth)))
1485       continue;
1486
1487     const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
1488     if (!Step || !Step->isOne())
1489       continue;
1490
1491     int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1492     Value *IncV = Phi->getIncomingValue(LatchIdx);
1493     if (getLoopPhiForCounter(IncV, L, DT) != Phi)
1494       continue;
1495
1496     const SCEV *Init = AR->getStart();
1497
1498     if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
1499       // Don't force a live loop counter if another IV can be used.
1500       if (AlmostDeadIV(Phi, LatchBlock, Cond))
1501         continue;
1502
1503       // Prefer to count-from-zero. This is a more "canonical" counter form. It
1504       // also prefers integer to pointer IVs.
1505       if (BestInit->isZero() != Init->isZero()) {
1506         if (BestInit->isZero())
1507           continue;
1508       }
1509       // If two IVs both count from zero or both count from nonzero then the
1510       // narrower is likely a dead phi that has been widened. Use the wider phi
1511       // to allow the other to be eliminated.
1512       if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
1513         continue;
1514     }
1515     BestPhi = Phi;
1516     BestInit = Init;
1517   }
1518   return BestPhi;
1519 }
1520
1521 /// genLoopLimit - Help LinearFunctionTestReplace by generating a value that
1522 /// holds the RHS of the new loop test.
1523 static Value *genLoopLimit(PHINode *IndVar, const SCEV *IVCount, Loop *L,
1524                            SCEVExpander &Rewriter, ScalarEvolution *SE) {
1525   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
1526   assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
1527   const SCEV *IVInit = AR->getStart();
1528
1529   // IVInit may be a pointer while IVCount is an integer when FindLoopCounter
1530   // finds a valid pointer IV. Sign extend BECount in order to materialize a
1531   // GEP. Avoid running SCEVExpander on a new pointer value, instead reusing
1532   // the existing GEPs whenever possible.
1533   if (IndVar->getType()->isPointerTy()
1534       && !IVCount->getType()->isPointerTy()) {
1535
1536     Type *OfsTy = SE->getEffectiveSCEVType(IVInit->getType());
1537     const SCEV *IVOffset = SE->getTruncateOrSignExtend(IVCount, OfsTy);
1538
1539     // Expand the code for the iteration count.
1540     assert(SE->isLoopInvariant(IVOffset, L) &&
1541            "Computed iteration count is not loop invariant!");
1542     BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1543     Value *GEPOffset = Rewriter.expandCodeFor(IVOffset, OfsTy, BI);
1544
1545     Value *GEPBase = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
1546     assert(AR->getStart() == SE->getSCEV(GEPBase) && "bad loop counter");
1547     // We could handle pointer IVs other than i8*, but we need to compensate for
1548     // gep index scaling. See canExpandBackedgeTakenCount comments.
1549     assert(SE->getSizeOfExpr(
1550              cast<PointerType>(GEPBase->getType())->getElementType())->isOne()
1551            && "unit stride pointer IV must be i8*");
1552
1553     IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
1554     return Builder.CreateGEP(GEPBase, GEPOffset, "lftr.limit");
1555   }
1556   else {
1557     // In any other case, convert both IVInit and IVCount to integers before
1558     // comparing. This may result in SCEV expension of pointers, but in practice
1559     // SCEV will fold the pointer arithmetic away as such:
1560     // BECount = (IVEnd - IVInit - 1) => IVLimit = IVInit (postinc).
1561     //
1562     // Valid Cases: (1) both integers is most common; (2) both may be pointers
1563     // for simple memset-style loops; (3) IVInit is an integer and IVCount is a
1564     // pointer may occur when enable-iv-rewrite generates a canonical IV on top
1565     // of case #2.
1566
1567     const SCEV *IVLimit = 0;
1568     // For unit stride, IVCount = Start + BECount with 2's complement overflow.
1569     // For non-zero Start, compute IVCount here.
1570     if (AR->getStart()->isZero())
1571       IVLimit = IVCount;
1572     else {
1573       assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
1574       const SCEV *IVInit = AR->getStart();
1575
1576       // For integer IVs, truncate the IV before computing IVInit + BECount.
1577       if (SE->getTypeSizeInBits(IVInit->getType())
1578           > SE->getTypeSizeInBits(IVCount->getType()))
1579         IVInit = SE->getTruncateExpr(IVInit, IVCount->getType());
1580
1581       IVLimit = SE->getAddExpr(IVInit, IVCount);
1582     }
1583     // Expand the code for the iteration count.
1584     BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1585     IRBuilder<> Builder(BI);
1586     assert(SE->isLoopInvariant(IVLimit, L) &&
1587            "Computed iteration count is not loop invariant!");
1588     // Ensure that we generate the same type as IndVar, or a smaller integer
1589     // type. In the presence of null pointer values, we have an integer type
1590     // SCEV expression (IVInit) for a pointer type IV value (IndVar).
1591     Type *LimitTy = IVCount->getType()->isPointerTy() ?
1592       IndVar->getType() : IVCount->getType();
1593     return Rewriter.expandCodeFor(IVLimit, LimitTy, BI);
1594   }
1595 }
1596
1597 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
1598 /// loop to be a canonical != comparison against the incremented loop induction
1599 /// variable.  This pass is able to rewrite the exit tests of any loop where the
1600 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
1601 /// is actually a much broader range than just linear tests.
1602 Value *IndVarSimplify::
1603 LinearFunctionTestReplace(Loop *L,
1604                           const SCEV *BackedgeTakenCount,
1605                           PHINode *IndVar,
1606                           SCEVExpander &Rewriter) {
1607   assert(canExpandBackedgeTakenCount(L, SE) && "precondition");
1608
1609   // LFTR can ignore IV overflow and truncate to the width of
1610   // BECount. This avoids materializing the add(zext(add)) expression.
1611   Type *CntTy = !EnableIVRewrite ?
1612     BackedgeTakenCount->getType() : IndVar->getType();
1613
1614   const SCEV *IVCount = BackedgeTakenCount;
1615
1616   // If the exiting block is the same as the backedge block, we prefer to
1617   // compare against the post-incremented value, otherwise we must compare
1618   // against the preincremented value.
1619   Value *CmpIndVar;
1620   if (L->getExitingBlock() == L->getLoopLatch()) {
1621     // Add one to the "backedge-taken" count to get the trip count.
1622     // If this addition may overflow, we have to be more pessimistic and
1623     // cast the induction variable before doing the add.
1624     const SCEV *N =
1625       SE->getAddExpr(IVCount, SE->getConstant(IVCount->getType(), 1));
1626     if (CntTy == IVCount->getType())
1627       IVCount = N;
1628     else {
1629       const SCEV *Zero = SE->getConstant(IVCount->getType(), 0);
1630       if ((isa<SCEVConstant>(N) && !N->isZero()) ||
1631           SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
1632         // No overflow. Cast the sum.
1633         IVCount = SE->getTruncateOrZeroExtend(N, CntTy);
1634       } else {
1635         // Potential overflow. Cast before doing the add.
1636         IVCount = SE->getTruncateOrZeroExtend(IVCount, CntTy);
1637         IVCount = SE->getAddExpr(IVCount, SE->getConstant(CntTy, 1));
1638       }
1639     }
1640     // The BackedgeTaken expression contains the number of times that the
1641     // backedge branches to the loop header.  This is one less than the
1642     // number of times the loop executes, so use the incremented indvar.
1643     CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
1644   } else {
1645     // We must use the preincremented value...
1646     IVCount = SE->getTruncateOrZeroExtend(IVCount, CntTy);
1647     CmpIndVar = IndVar;
1648   }
1649
1650   Value *ExitCnt = genLoopLimit(IndVar, IVCount, L, Rewriter, SE);
1651   assert(ExitCnt->getType()->isPointerTy() == IndVar->getType()->isPointerTy()
1652          && "genLoopLimit missed a cast");
1653
1654   // Insert a new icmp_ne or icmp_eq instruction before the branch.
1655   BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1656   ICmpInst::Predicate P;
1657   if (L->contains(BI->getSuccessor(0)))
1658     P = ICmpInst::ICMP_NE;
1659   else
1660     P = ICmpInst::ICMP_EQ;
1661
1662   DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
1663                << "      LHS:" << *CmpIndVar << '\n'
1664                << "       op:\t"
1665                << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
1666                << "      RHS:\t" << *ExitCnt << "\n"
1667                << "  IVCount:\t" << *IVCount << "\n");
1668
1669   IRBuilder<> Builder(BI);
1670   if (SE->getTypeSizeInBits(CmpIndVar->getType())
1671       > SE->getTypeSizeInBits(ExitCnt->getType())) {
1672     CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(),
1673                                     "lftr.wideiv");
1674   }
1675
1676   Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
1677   Value *OrigCond = BI->getCondition();
1678   // It's tempting to use replaceAllUsesWith here to fully replace the old
1679   // comparison, but that's not immediately safe, since users of the old
1680   // comparison may not be dominated by the new comparison. Instead, just
1681   // update the branch to use the new comparison; in the common case this
1682   // will make old comparison dead.
1683   BI->setCondition(Cond);
1684   DeadInsts.push_back(OrigCond);
1685
1686   ++NumLFTR;
1687   Changed = true;
1688   return Cond;
1689 }
1690
1691 //===----------------------------------------------------------------------===//
1692 //  SinkUnusedInvariants. A late subpass to cleanup loop preheaders.
1693 //===----------------------------------------------------------------------===//
1694
1695 /// If there's a single exit block, sink any loop-invariant values that
1696 /// were defined in the preheader but not used inside the loop into the
1697 /// exit block to reduce register pressure in the loop.
1698 void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
1699   BasicBlock *ExitBlock = L->getExitBlock();
1700   if (!ExitBlock) return;
1701
1702   BasicBlock *Preheader = L->getLoopPreheader();
1703   if (!Preheader) return;
1704
1705   Instruction *InsertPt = ExitBlock->getFirstInsertionPt();
1706   BasicBlock::iterator I = Preheader->getTerminator();
1707   while (I != Preheader->begin()) {
1708     --I;
1709     // New instructions were inserted at the end of the preheader.
1710     if (isa<PHINode>(I))
1711       break;
1712
1713     // Don't move instructions which might have side effects, since the side
1714     // effects need to complete before instructions inside the loop.  Also don't
1715     // move instructions which might read memory, since the loop may modify
1716     // memory. Note that it's okay if the instruction might have undefined
1717     // behavior: LoopSimplify guarantees that the preheader dominates the exit
1718     // block.
1719     if (I->mayHaveSideEffects() || I->mayReadFromMemory())
1720       continue;
1721
1722     // Skip debug info intrinsics.
1723     if (isa<DbgInfoIntrinsic>(I))
1724       continue;
1725
1726     // Skip landingpad instructions.
1727     if (isa<LandingPadInst>(I))
1728       continue;
1729
1730     // Don't sink alloca: we never want to sink static alloca's out of the
1731     // entry block, and correctly sinking dynamic alloca's requires
1732     // checks for stacksave/stackrestore intrinsics.
1733     // FIXME: Refactor this check somehow?
1734     if (isa<AllocaInst>(I))
1735       continue;
1736
1737     // Determine if there is a use in or before the loop (direct or
1738     // otherwise).
1739     bool UsedInLoop = false;
1740     for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1741          UI != UE; ++UI) {
1742       User *U = *UI;
1743       BasicBlock *UseBB = cast<Instruction>(U)->getParent();
1744       if (PHINode *P = dyn_cast<PHINode>(U)) {
1745         unsigned i =
1746           PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
1747         UseBB = P->getIncomingBlock(i);
1748       }
1749       if (UseBB == Preheader || L->contains(UseBB)) {
1750         UsedInLoop = true;
1751         break;
1752       }
1753     }
1754
1755     // If there is, the def must remain in the preheader.
1756     if (UsedInLoop)
1757       continue;
1758
1759     // Otherwise, sink it to the exit block.
1760     Instruction *ToMove = I;
1761     bool Done = false;
1762
1763     if (I != Preheader->begin()) {
1764       // Skip debug info intrinsics.
1765       do {
1766         --I;
1767       } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
1768
1769       if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
1770         Done = true;
1771     } else {
1772       Done = true;
1773     }
1774
1775     ToMove->moveBefore(InsertPt);
1776     if (Done) break;
1777     InsertPt = ToMove;
1778   }
1779 }
1780
1781 //===----------------------------------------------------------------------===//
1782 //  IndVarSimplify driver. Manage several subpasses of IV simplification.
1783 //===----------------------------------------------------------------------===//
1784
1785 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
1786   // If LoopSimplify form is not available, stay out of trouble. Some notes:
1787   //  - LSR currently only supports LoopSimplify-form loops. Indvars'
1788   //    canonicalization can be a pessimization without LSR to "clean up"
1789   //    afterwards.
1790   //  - We depend on having a preheader; in particular,
1791   //    Loop::getCanonicalInductionVariable only supports loops with preheaders,
1792   //    and we're in trouble if we can't find the induction variable even when
1793   //    we've manually inserted one.
1794   if (!L->isLoopSimplifyForm())
1795     return false;
1796
1797   if (EnableIVRewrite)
1798     IU = &getAnalysis<IVUsers>();
1799   LI = &getAnalysis<LoopInfo>();
1800   SE = &getAnalysis<ScalarEvolution>();
1801   DT = &getAnalysis<DominatorTree>();
1802   TD = getAnalysisIfAvailable<TargetData>();
1803
1804   DeadInsts.clear();
1805   Changed = false;
1806
1807   // If there are any floating-point recurrences, attempt to
1808   // transform them to use integer recurrences.
1809   RewriteNonIntegerIVs(L);
1810
1811   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1812
1813   // Create a rewriter object which we'll use to transform the code with.
1814   SCEVExpander Rewriter(*SE, "indvars");
1815 #ifndef NDEBUG
1816   Rewriter.setDebugType(DEBUG_TYPE);
1817 #endif
1818
1819   // Eliminate redundant IV users.
1820   //
1821   // Simplification works best when run before other consumers of SCEV. We
1822   // attempt to avoid evaluating SCEVs for sign/zero extend operations until
1823   // other expressions involving loop IVs have been evaluated. This helps SCEV
1824   // set no-wrap flags before normalizing sign/zero extension.
1825   if (!EnableIVRewrite) {
1826     Rewriter.disableCanonicalMode();
1827     SimplifyAndExtend(L, Rewriter, LPM);
1828   }
1829
1830   // Check to see if this loop has a computable loop-invariant execution count.
1831   // If so, this means that we can compute the final value of any expressions
1832   // that are recurrent in the loop, and substitute the exit values from the
1833   // loop into any instructions outside of the loop that use the final values of
1834   // the current expressions.
1835   //
1836   if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1837     RewriteLoopExitValues(L, Rewriter);
1838
1839   // Eliminate redundant IV users.
1840   if (EnableIVRewrite)
1841     Changed |= simplifyIVUsers(IU, SE, &LPM, DeadInsts);
1842
1843   // Eliminate redundant IV cycles.
1844   if (!EnableIVRewrite)
1845     NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts);
1846
1847   // Compute the type of the largest recurrence expression, and decide whether
1848   // a canonical induction variable should be inserted.
1849   Type *LargestType = 0;
1850   bool NeedCannIV = false;
1851   bool ExpandBECount = canExpandBackedgeTakenCount(L, SE);
1852   if (EnableIVRewrite && ExpandBECount) {
1853     // If we have a known trip count and a single exit block, we'll be
1854     // rewriting the loop exit test condition below, which requires a
1855     // canonical induction variable.
1856     NeedCannIV = true;
1857     Type *Ty = BackedgeTakenCount->getType();
1858     if (!EnableIVRewrite) {
1859       // In this mode, SimplifyIVUsers may have already widened the IV used by
1860       // the backedge test and inserted a Trunc on the compare's operand. Get
1861       // the wider type to avoid creating a redundant narrow IV only used by the
1862       // loop test.
1863       LargestType = getBackedgeIVType(L);
1864     }
1865     if (!LargestType ||
1866         SE->getTypeSizeInBits(Ty) >
1867         SE->getTypeSizeInBits(LargestType))
1868       LargestType = SE->getEffectiveSCEVType(Ty);
1869   }
1870   if (EnableIVRewrite) {
1871     for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
1872       NeedCannIV = true;
1873       Type *Ty =
1874         SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
1875       if (!LargestType ||
1876           SE->getTypeSizeInBits(Ty) >
1877           SE->getTypeSizeInBits(LargestType))
1878         LargestType = Ty;
1879     }
1880   }
1881
1882   // Now that we know the largest of the induction variable expressions
1883   // in this loop, insert a canonical induction variable of the largest size.
1884   PHINode *IndVar = 0;
1885   if (NeedCannIV) {
1886     // Check to see if the loop already has any canonical-looking induction
1887     // variables. If any are present and wider than the planned canonical
1888     // induction variable, temporarily remove them, so that the Rewriter
1889     // doesn't attempt to reuse them.
1890     SmallVector<PHINode *, 2> OldCannIVs;
1891     while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
1892       if (SE->getTypeSizeInBits(OldCannIV->getType()) >
1893           SE->getTypeSizeInBits(LargestType))
1894         OldCannIV->removeFromParent();
1895       else
1896         break;
1897       OldCannIVs.push_back(OldCannIV);
1898     }
1899
1900     IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
1901
1902     ++NumInserted;
1903     Changed = true;
1904     DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
1905
1906     // Now that the official induction variable is established, reinsert
1907     // any old canonical-looking variables after it so that the IR remains
1908     // consistent. They will be deleted as part of the dead-PHI deletion at
1909     // the end of the pass.
1910     while (!OldCannIVs.empty()) {
1911       PHINode *OldCannIV = OldCannIVs.pop_back_val();
1912       OldCannIV->insertBefore(L->getHeader()->getFirstInsertionPt());
1913     }
1914   }
1915   else if (!EnableIVRewrite && ExpandBECount && needsLFTR(L, DT)) {
1916     IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT, TD);
1917   }
1918   // If we have a trip count expression, rewrite the loop's exit condition
1919   // using it.  We can currently only handle loops with a single exit.
1920   Value *NewICmp = 0;
1921   if (ExpandBECount && IndVar) {
1922     // Check preconditions for proper SCEVExpander operation. SCEV does not
1923     // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
1924     // pass that uses the SCEVExpander must do it. This does not work well for
1925     // loop passes because SCEVExpander makes assumptions about all loops, while
1926     // LoopPassManager only forces the current loop to be simplified.
1927     //
1928     // FIXME: SCEV expansion has no way to bail out, so the caller must
1929     // explicitly check any assumptions made by SCEV. Brittle.
1930     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
1931     if (!AR || AR->getLoop()->getLoopPreheader())
1932       NewICmp =
1933         LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar, Rewriter);
1934   }
1935   // Rewrite IV-derived expressions.
1936   if (EnableIVRewrite)
1937     RewriteIVExpressions(L, Rewriter);
1938
1939   // Clear the rewriter cache, because values that are in the rewriter's cache
1940   // can be deleted in the loop below, causing the AssertingVH in the cache to
1941   // trigger.
1942   Rewriter.clear();
1943
1944   // Now that we're done iterating through lists, clean up any instructions
1945   // which are now dead.
1946   while (!DeadInsts.empty())
1947     if (Instruction *Inst =
1948           dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
1949       RecursivelyDeleteTriviallyDeadInstructions(Inst);
1950
1951   // The Rewriter may not be used from this point on.
1952
1953   // Loop-invariant instructions in the preheader that aren't used in the
1954   // loop may be sunk below the loop to reduce register pressure.
1955   SinkUnusedInvariants(L);
1956
1957   // For completeness, inform IVUsers of the IV use in the newly-created
1958   // loop exit test instruction.
1959   if (IU && NewICmp) {
1960     ICmpInst *NewICmpInst = dyn_cast<ICmpInst>(NewICmp);
1961     if (NewICmpInst)
1962       IU->AddUsersIfInteresting(cast<Instruction>(NewICmpInst->getOperand(0)));
1963   }
1964   // Clean up dead instructions.
1965   Changed |= DeleteDeadPHIs(L->getHeader());
1966   // Check a post-condition.
1967   assert(L->isLCSSAForm(*DT) &&
1968          "Indvars did not leave the loop in lcssa form!");
1969
1970   // Verify that LFTR, and any other change have not interfered with SCEV's
1971   // ability to compute trip count.
1972 #ifndef NDEBUG
1973   if (!EnableIVRewrite && VerifyIndvars &&
1974       !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
1975     SE->forgetLoop(L);
1976     const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
1977     if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
1978         SE->getTypeSizeInBits(NewBECount->getType()))
1979       NewBECount = SE->getTruncateOrNoop(NewBECount,
1980                                          BackedgeTakenCount->getType());
1981     else
1982       BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
1983                                                  NewBECount->getType());
1984     assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");
1985   }
1986 #endif
1987
1988   return Changed;
1989 }