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