Teach IndVarSimplify how to eliminate comparisons involving induction
[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/ADT/SmallVector.h"
61 #include "llvm/ADT/Statistic.h"
62 #include "llvm/ADT/STLExtras.h"
63 using namespace llvm;
64
65 STATISTIC(NumRemoved , "Number of aux indvars removed");
66 STATISTIC(NumInserted, "Number of canonical indvars added");
67 STATISTIC(NumReplaced, "Number of exit values replaced");
68 STATISTIC(NumLFTR    , "Number of loop exit tests replaced");
69
70 namespace {
71   class IndVarSimplify : public LoopPass {
72     IVUsers         *IU;
73     LoopInfo        *LI;
74     ScalarEvolution *SE;
75     DominatorTree   *DT;
76     bool Changed;
77   public:
78
79     static char ID; // Pass identification, replacement for typeid
80     IndVarSimplify() : LoopPass(&ID) {}
81
82     virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
83
84     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
85       AU.addRequired<DominatorTree>();
86       AU.addRequired<LoopInfo>();
87       AU.addRequired<ScalarEvolution>();
88       AU.addRequiredID(LoopSimplifyID);
89       AU.addRequiredID(LCSSAID);
90       AU.addRequired<IVUsers>();
91       AU.addPreserved<ScalarEvolution>();
92       AU.addPreservedID(LoopSimplifyID);
93       AU.addPreservedID(LCSSAID);
94       AU.addPreserved<IVUsers>();
95       AU.setPreservesCFG();
96     }
97
98   private:
99
100     void EliminateIVComparisons();
101     void RewriteNonIntegerIVs(Loop *L);
102
103     ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
104                                    Value *IndVar,
105                                    BasicBlock *ExitingBlock,
106                                    BranchInst *BI,
107                                    SCEVExpander &Rewriter);
108     void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
109
110     void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
111
112     void SinkUnusedInvariants(Loop *L);
113
114     void HandleFloatingPointIV(Loop *L, PHINode *PH);
115   };
116 }
117
118 char IndVarSimplify::ID = 0;
119 static RegisterPass<IndVarSimplify>
120 X("indvars", "Canonicalize Induction Variables");
121
122 Pass *llvm::createIndVarSimplifyPass() {
123   return new IndVarSimplify();
124 }
125
126 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
127 /// loop to be a canonical != comparison against the incremented loop induction
128 /// variable.  This pass is able to rewrite the exit tests of any loop where the
129 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
130 /// is actually a much broader range than just linear tests.
131 ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
132                                    const SCEV *BackedgeTakenCount,
133                                    Value *IndVar,
134                                    BasicBlock *ExitingBlock,
135                                    BranchInst *BI,
136                                    SCEVExpander &Rewriter) {
137   // If the exiting block is not the same as the backedge block, we must compare
138   // against the preincremented value, otherwise we prefer to compare against
139   // the post-incremented value.
140   Value *CmpIndVar;
141   const SCEV *RHS = BackedgeTakenCount;
142   if (ExitingBlock == L->getLoopLatch()) {
143     // Add one to the "backedge-taken" count to get the trip count.
144     // If this addition may overflow, we have to be more pessimistic and
145     // cast the induction variable before doing the add.
146     const SCEV *Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
147     const SCEV *N =
148       SE->getAddExpr(BackedgeTakenCount,
149                      SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
150     if ((isa<SCEVConstant>(N) && !N->isZero()) ||
151         SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
152       // No overflow. Cast the sum.
153       RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
154     } else {
155       // Potential overflow. Cast before doing the add.
156       RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
157                                         IndVar->getType());
158       RHS = SE->getAddExpr(RHS,
159                            SE->getIntegerSCEV(1, IndVar->getType()));
160     }
161
162     // The BackedgeTaken expression contains the number of times that the
163     // backedge branches to the loop header.  This is one less than the
164     // number of times the loop executes, so use the incremented indvar.
165     CmpIndVar = L->getCanonicalInductionVariableIncrement();
166   } else {
167     // We have to use the preincremented value...
168     RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
169                                       IndVar->getType());
170     CmpIndVar = IndVar;
171   }
172
173   // Expand the code for the iteration count.
174   assert(RHS->isLoopInvariant(L) &&
175          "Computed iteration count is not loop invariant!");
176   Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
177
178   // Insert a new icmp_ne or icmp_eq instruction before the branch.
179   ICmpInst::Predicate Opcode;
180   if (L->contains(BI->getSuccessor(0)))
181     Opcode = ICmpInst::ICMP_NE;
182   else
183     Opcode = ICmpInst::ICMP_EQ;
184
185   DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
186                << "      LHS:" << *CmpIndVar << '\n'
187                << "       op:\t"
188                << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
189                << "      RHS:\t" << *RHS << "\n");
190
191   ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
192
193   Value *OrigCond = BI->getCondition();
194   // It's tempting to use replaceAllUsesWith here to fully replace the old
195   // comparison, but that's not immediately safe, since users of the old
196   // comparison may not be dominated by the new comparison. Instead, just
197   // update the branch to use the new comparison; in the common case this
198   // will make old comparison dead.
199   BI->setCondition(Cond);
200   RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
201
202   ++NumLFTR;
203   Changed = true;
204   return Cond;
205 }
206
207 /// RewriteLoopExitValues - Check to see if this loop has a computable
208 /// loop-invariant execution count.  If so, this means that we can compute the
209 /// final value of any expressions that are recurrent in the loop, and
210 /// substitute the exit values from the loop into any instructions outside of
211 /// the loop that use the final values of the current expressions.
212 ///
213 /// This is mostly redundant with the regular IndVarSimplify activities that
214 /// happen later, except that it's more powerful in some cases, because it's
215 /// able to brute-force evaluate arbitrary instructions as long as they have
216 /// constant operands at the beginning of the loop.
217 void IndVarSimplify::RewriteLoopExitValues(Loop *L,
218                                            SCEVExpander &Rewriter) {
219   // Verify the input to the pass in already in LCSSA form.
220   assert(L->isLCSSAForm(*DT));
221
222   SmallVector<BasicBlock*, 8> ExitBlocks;
223   L->getUniqueExitBlocks(ExitBlocks);
224
225   // Find all values that are computed inside the loop, but used outside of it.
226   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
227   // the exit blocks of the loop to find them.
228   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
229     BasicBlock *ExitBB = ExitBlocks[i];
230
231     // If there are no PHI nodes in this exit block, then no values defined
232     // inside the loop are used on this path, skip it.
233     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
234     if (!PN) continue;
235
236     unsigned NumPreds = PN->getNumIncomingValues();
237
238     // Iterate over all of the PHI nodes.
239     BasicBlock::iterator BBI = ExitBB->begin();
240     while ((PN = dyn_cast<PHINode>(BBI++))) {
241       if (PN->use_empty())
242         continue; // dead use, don't replace it
243
244       // SCEV only supports integer expressions for now.
245       if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
246         continue;
247
248       // It's necessary to tell ScalarEvolution about this explicitly so that
249       // it can walk the def-use list and forget all SCEVs, as it may not be
250       // watching the PHI itself. Once the new exit value is in place, there
251       // may not be a def-use connection between the loop and every instruction
252       // which got a SCEVAddRecExpr for that loop.
253       SE->forgetValue(PN);
254
255       // Iterate over all of the values in all the PHI nodes.
256       for (unsigned i = 0; i != NumPreds; ++i) {
257         // If the value being merged in is not integer or is not defined
258         // in the loop, skip it.
259         Value *InVal = PN->getIncomingValue(i);
260         if (!isa<Instruction>(InVal))
261           continue;
262
263         // If this pred is for a subloop, not L itself, skip it.
264         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
265           continue; // The Block is in a subloop, skip it.
266
267         // Check that InVal is defined in the loop.
268         Instruction *Inst = cast<Instruction>(InVal);
269         if (!L->contains(Inst))
270           continue;
271
272         // Okay, this instruction has a user outside of the current loop
273         // and varies predictably *inside* the loop.  Evaluate the value it
274         // contains when the loop exits, if possible.
275         const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
276         if (!ExitValue->isLoopInvariant(L))
277           continue;
278
279         Changed = true;
280         ++NumReplaced;
281
282         Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
283
284         DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
285                      << "  LoopVal = " << *Inst << "\n");
286
287         PN->setIncomingValue(i, ExitVal);
288
289         // If this instruction is dead now, delete it.
290         RecursivelyDeleteTriviallyDeadInstructions(Inst);
291
292         if (NumPreds == 1) {
293           // Completely replace a single-pred PHI. This is safe, because the
294           // NewVal won't be variant in the loop, so we don't need an LCSSA phi
295           // node anymore.
296           PN->replaceAllUsesWith(ExitVal);
297           RecursivelyDeleteTriviallyDeadInstructions(PN);
298         }
299       }
300       if (NumPreds != 1) {
301         // Clone the PHI and delete the original one. This lets IVUsers and
302         // any other maps purge the original user from their records.
303         PHINode *NewPN = cast<PHINode>(PN->clone());
304         NewPN->takeName(PN);
305         NewPN->insertBefore(PN);
306         PN->replaceAllUsesWith(NewPN);
307         PN->eraseFromParent();
308       }
309     }
310   }
311
312   // The insertion point instruction may have been deleted; clear it out
313   // so that the rewriter doesn't trip over it later.
314   Rewriter.clearInsertPoint();
315 }
316
317 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
318   // First step.  Check to see if there are any floating-point recurrences.
319   // If there are, change them into integer recurrences, permitting analysis by
320   // the SCEV routines.
321   //
322   BasicBlock *Header    = L->getHeader();
323
324   SmallVector<WeakVH, 8> PHIs;
325   for (BasicBlock::iterator I = Header->begin();
326        PHINode *PN = dyn_cast<PHINode>(I); ++I)
327     PHIs.push_back(PN);
328
329   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
330     if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i]))
331       HandleFloatingPointIV(L, PN);
332
333   // If the loop previously had floating-point IV, ScalarEvolution
334   // may not have been able to compute a trip count. Now that we've done some
335   // re-writing, the trip count may be computable.
336   if (Changed)
337     SE->forgetLoop(L);
338 }
339
340 void IndVarSimplify::EliminateIVComparisons() {
341   // Look for ICmp users.
342   for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E;) {
343     IVStrideUse &UI = *I++;
344     ICmpInst *ICmp = dyn_cast<ICmpInst>(UI.getUser());
345     if (!ICmp) continue;
346
347     bool Swapped = UI.getOperandValToReplace() == ICmp->getOperand(1);
348     ICmpInst::Predicate Pred = ICmp->getPredicate();
349     if (Swapped) Pred = ICmpInst::getSwappedPredicate(Pred);
350
351     // Get the SCEVs for the ICmp operands.
352     const SCEV *S = IU->getReplacementExpr(UI);
353     const SCEV *X = SE->getSCEV(ICmp->getOperand(!Swapped));
354
355     // Simplify unnecessary loops away.
356     const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
357     S = SE->getSCEVAtScope(S, ICmpLoop);
358     X = SE->getSCEVAtScope(X, ICmpLoop);
359
360     // If the condition is always true or always false, replace it with
361     // a constant value.
362     if (SE->isKnownPredicate(Pred, S, X))
363       ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
364     else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
365       ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
366     else
367       continue;
368
369     DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
370     ICmp->eraseFromParent();
371   }
372 }
373
374 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
375   IU = &getAnalysis<IVUsers>();
376   LI = &getAnalysis<LoopInfo>();
377   SE = &getAnalysis<ScalarEvolution>();
378   DT = &getAnalysis<DominatorTree>();
379   Changed = false;
380
381   // If there are any floating-point recurrences, attempt to
382   // transform them to use integer recurrences.
383   RewriteNonIntegerIVs(L);
384
385   BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
386   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
387
388   // Create a rewriter object which we'll use to transform the code with.
389   SCEVExpander Rewriter(*SE);
390
391   // Check to see if this loop has a computable loop-invariant execution count.
392   // If so, this means that we can compute the final value of any expressions
393   // that are recurrent in the loop, and substitute the exit values from the
394   // loop into any instructions outside of the loop that use the final values of
395   // the current expressions.
396   //
397   if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
398     RewriteLoopExitValues(L, Rewriter);
399
400   // Simplify ICmp IV users.
401   EliminateIVComparisons();
402
403   // Compute the type of the largest recurrence expression, and decide whether
404   // a canonical induction variable should be inserted.
405   const Type *LargestType = 0;
406   bool NeedCannIV = false;
407   if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
408     LargestType = BackedgeTakenCount->getType();
409     LargestType = SE->getEffectiveSCEVType(LargestType);
410     // If we have a known trip count and a single exit block, we'll be
411     // rewriting the loop exit test condition below, which requires a
412     // canonical induction variable.
413     if (ExitingBlock)
414       NeedCannIV = true;
415   }
416   for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
417     const Type *Ty =
418       SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
419     if (!LargestType ||
420         SE->getTypeSizeInBits(Ty) >
421           SE->getTypeSizeInBits(LargestType))
422       LargestType = Ty;
423     NeedCannIV = true;
424   }
425
426   // Now that we know the largest of the induction variable expressions
427   // in this loop, insert a canonical induction variable of the largest size.
428   Value *IndVar = 0;
429   if (NeedCannIV) {
430     // Check to see if the loop already has any canonical-looking induction
431     // variables. If any are present and wider than the planned canonical
432     // induction variable, temporarily remove them, so that the Rewriter
433     // doesn't attempt to reuse them.
434     SmallVector<PHINode *, 2> OldCannIVs;
435     while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
436       if (SE->getTypeSizeInBits(OldCannIV->getType()) >
437           SE->getTypeSizeInBits(LargestType))
438         OldCannIV->removeFromParent();
439       else
440         break;
441       OldCannIVs.push_back(OldCannIV);
442     }
443
444     IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
445
446     ++NumInserted;
447     Changed = true;
448     DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
449
450     // Now that the official induction variable is established, reinsert
451     // any old canonical-looking variables after it so that the IR remains
452     // consistent. They will be deleted as part of the dead-PHI deletion at
453     // the end of the pass.
454     while (!OldCannIVs.empty()) {
455       PHINode *OldCannIV = OldCannIVs.pop_back_val();
456       OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
457     }
458   }
459
460   // If we have a trip count expression, rewrite the loop's exit condition
461   // using it.  We can currently only handle loops with a single exit.
462   ICmpInst *NewICmp = 0;
463   if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
464       !BackedgeTakenCount->isZero() &&
465       ExitingBlock) {
466     assert(NeedCannIV &&
467            "LinearFunctionTestReplace requires a canonical induction variable");
468     // Can't rewrite non-branch yet.
469     if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
470       NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
471                                           ExitingBlock, BI, Rewriter);
472   }
473
474   // Rewrite IV-derived expressions. Clears the rewriter cache.
475   RewriteIVExpressions(L, Rewriter);
476
477   // The Rewriter may not be used from this point on.
478
479   // Loop-invariant instructions in the preheader that aren't used in the
480   // loop may be sunk below the loop to reduce register pressure.
481   SinkUnusedInvariants(L);
482
483   // For completeness, inform IVUsers of the IV use in the newly-created
484   // loop exit test instruction.
485   if (NewICmp)
486     IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
487
488   // Clean up dead instructions.
489   Changed |= DeleteDeadPHIs(L->getHeader());
490   // Check a post-condition.
491   assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
492   return Changed;
493 }
494
495 // FIXME: It is an extremely bad idea to indvar substitute anything more
496 // complex than affine induction variables.  Doing so will put expensive
497 // polynomial evaluations inside of the loop, and the str reduction pass
498 // currently can only reduce affine polynomials.  For now just disable
499 // indvar subst on anything more complex than an affine addrec, unless
500 // it can be expanded to a trivial value.
501 static bool isSafe(const SCEV *S, const Loop *L) {
502   // Loop-invariant values are safe.
503   if (S->isLoopInvariant(L)) return true;
504
505   // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
506   // to transform them into efficient code.
507   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
508     return AR->isAffine();
509
510   // An add is safe it all its operands are safe.
511   if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
512     for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
513          E = Commutative->op_end(); I != E; ++I)
514       if (!isSafe(*I, L)) return false;
515     return true;
516   }
517   
518   // A cast is safe if its operand is.
519   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
520     return isSafe(C->getOperand(), L);
521
522   // A udiv is safe if its operands are.
523   if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
524     return isSafe(UD->getLHS(), L) &&
525            isSafe(UD->getRHS(), L);
526
527   // SCEVUnknown is always safe.
528   if (isa<SCEVUnknown>(S))
529     return true;
530
531   // Nothing else is safe.
532   return false;
533 }
534
535 void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
536   SmallVector<WeakVH, 16> DeadInsts;
537
538   // Rewrite all induction variable expressions in terms of the canonical
539   // induction variable.
540   //
541   // If there were induction variables of other sizes or offsets, manually
542   // add the offsets to the primary induction variable and cast, avoiding
543   // the need for the code evaluation methods to insert induction variables
544   // of different sizes.
545   for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
546     Value *Op = UI->getOperandValToReplace();
547     const Type *UseTy = Op->getType();
548     Instruction *User = UI->getUser();
549
550     // Compute the final addrec to expand into code.
551     const SCEV *AR = IU->getReplacementExpr(*UI);
552
553     // Evaluate the expression out of the loop, if possible.
554     if (!L->contains(UI->getUser())) {
555       const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
556       if (ExitVal->isLoopInvariant(L))
557         AR = ExitVal;
558     }
559
560     // FIXME: It is an extremely bad idea to indvar substitute anything more
561     // complex than affine induction variables.  Doing so will put expensive
562     // polynomial evaluations inside of the loop, and the str reduction pass
563     // currently can only reduce affine polynomials.  For now just disable
564     // indvar subst on anything more complex than an affine addrec, unless
565     // it can be expanded to a trivial value.
566     if (!isSafe(AR, L))
567       continue;
568
569     // Determine the insertion point for this user. By default, insert
570     // immediately before the user. The SCEVExpander class will automatically
571     // hoist loop invariants out of the loop. For PHI nodes, there may be
572     // multiple uses, so compute the nearest common dominator for the
573     // incoming blocks.
574     Instruction *InsertPt = User;
575     if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
576       for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
577         if (PHI->getIncomingValue(i) == Op) {
578           if (InsertPt == User)
579             InsertPt = PHI->getIncomingBlock(i)->getTerminator();
580           else
581             InsertPt =
582               DT->findNearestCommonDominator(InsertPt->getParent(),
583                                              PHI->getIncomingBlock(i))
584                     ->getTerminator();
585         }
586
587     // Now expand it into actual Instructions and patch it into place.
588     Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
589
590     // Inform ScalarEvolution that this value is changing. The change doesn't
591     // affect its value, but it does potentially affect which use lists the
592     // value will be on after the replacement, which affects ScalarEvolution's
593     // ability to walk use lists and drop dangling pointers when a value is
594     // deleted.
595     SE->forgetValue(User);
596
597     // Patch the new value into place.
598     if (Op->hasName())
599       NewVal->takeName(Op);
600     User->replaceUsesOfWith(Op, NewVal);
601     UI->setOperandValToReplace(NewVal);
602     DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
603                  << "   into = " << *NewVal << "\n");
604     ++NumRemoved;
605     Changed = true;
606
607     // The old value may be dead now.
608     DeadInsts.push_back(Op);
609   }
610
611   // Clear the rewriter cache, because values that are in the rewriter's cache
612   // can be deleted in the loop below, causing the AssertingVH in the cache to
613   // trigger.
614   Rewriter.clear();
615   // Now that we're done iterating through lists, clean up any instructions
616   // which are now dead.
617   while (!DeadInsts.empty())
618     if (Instruction *Inst =
619           dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
620       RecursivelyDeleteTriviallyDeadInstructions(Inst);
621 }
622
623 /// If there's a single exit block, sink any loop-invariant values that
624 /// were defined in the preheader but not used inside the loop into the
625 /// exit block to reduce register pressure in the loop.
626 void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
627   BasicBlock *ExitBlock = L->getExitBlock();
628   if (!ExitBlock) return;
629
630   BasicBlock *Preheader = L->getLoopPreheader();
631   if (!Preheader) return;
632
633   Instruction *InsertPt = ExitBlock->getFirstNonPHI();
634   BasicBlock::iterator I = Preheader->getTerminator();
635   while (I != Preheader->begin()) {
636     --I;
637     // New instructions were inserted at the end of the preheader.
638     if (isa<PHINode>(I))
639       break;
640
641     // Don't move instructions which might have side effects, since the side
642     // effects need to complete before instructions inside the loop.  Also don't
643     // move instructions which might read memory, since the loop may modify
644     // memory. Note that it's okay if the instruction might have undefined
645     // behavior: LoopSimplify guarantees that the preheader dominates the exit
646     // block.
647     if (I->mayHaveSideEffects() || I->mayReadFromMemory())
648       continue;
649
650     // Skip debug info intrinsics.
651     if (isa<DbgInfoIntrinsic>(I))
652       continue;
653
654     // Don't sink static AllocaInsts out of the entry block, which would
655     // turn them into dynamic allocas!
656     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
657       if (AI->isStaticAlloca())
658         continue;
659
660     // Determine if there is a use in or before the loop (direct or
661     // otherwise).
662     bool UsedInLoop = false;
663     for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
664          UI != UE; ++UI) {
665       BasicBlock *UseBB = cast<Instruction>(UI)->getParent();
666       if (PHINode *P = dyn_cast<PHINode>(UI)) {
667         unsigned i =
668           PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
669         UseBB = P->getIncomingBlock(i);
670       }
671       if (UseBB == Preheader || L->contains(UseBB)) {
672         UsedInLoop = true;
673         break;
674       }
675     }
676
677     // If there is, the def must remain in the preheader.
678     if (UsedInLoop)
679       continue;
680
681     // Otherwise, sink it to the exit block.
682     Instruction *ToMove = I;
683     bool Done = false;
684
685     if (I != Preheader->begin()) {
686       // Skip debug info intrinsics.
687       do {
688         --I;
689       } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
690
691       if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
692         Done = true;
693     } else {
694       Done = true;
695     }
696
697     ToMove->moveBefore(InsertPt);
698     if (Done) break;
699     InsertPt = ToMove;
700   }
701 }
702
703 /// ConvertToSInt - Convert APF to an integer, if possible.
704 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
705   bool isExact = false;
706   if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
707     return false;
708   // See if we can convert this to an int64_t
709   uint64_t UIntVal;
710   if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
711                            &isExact) != APFloat::opOK || !isExact)
712     return false;
713   IntVal = UIntVal;
714   return true;
715 }
716
717 /// HandleFloatingPointIV - If the loop has floating induction variable
718 /// then insert corresponding integer induction variable if possible.
719 /// For example,
720 /// for(double i = 0; i < 10000; ++i)
721 ///   bar(i)
722 /// is converted into
723 /// for(int i = 0; i < 10000; ++i)
724 ///   bar((double)i);
725 ///
726 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
727   unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
728   unsigned BackEdge     = IncomingEdge^1;
729
730   // Check incoming value.
731   ConstantFP *InitValueVal =
732     dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
733
734   int64_t InitValue;
735   if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
736     return;
737
738   // Check IV increment. Reject this PN if increment operation is not
739   // an add or increment value can not be represented by an integer.
740   BinaryOperator *Incr =
741     dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
742   if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
743   
744   // If this is not an add of the PHI with a constantfp, or if the constant fp
745   // is not an integer, bail out.
746   ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
747   int64_t IncValue;
748   if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
749       !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
750     return;
751
752   // Check Incr uses. One user is PN and the other user is an exit condition
753   // used by the conditional terminator.
754   Value::use_iterator IncrUse = Incr->use_begin();
755   Instruction *U1 = cast<Instruction>(IncrUse++);
756   if (IncrUse == Incr->use_end()) return;
757   Instruction *U2 = cast<Instruction>(IncrUse++);
758   if (IncrUse != Incr->use_end()) return;
759
760   // Find exit condition, which is an fcmp.  If it doesn't exist, or if it isn't
761   // only used by a branch, we can't transform it.
762   FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
763   if (!Compare)
764     Compare = dyn_cast<FCmpInst>(U2);
765   if (Compare == 0 || !Compare->hasOneUse() ||
766       !isa<BranchInst>(Compare->use_back()))
767     return;
768   
769   BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
770
771   // We need to verify that the branch actually controls the iteration count
772   // of the loop.  If not, the new IV can overflow and no one will notice.
773   // The branch block must be in the loop and one of the successors must be out
774   // of the loop.
775   assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
776   if (!L->contains(TheBr->getParent()) ||
777       (L->contains(TheBr->getSuccessor(0)) &&
778        L->contains(TheBr->getSuccessor(1))))
779     return;
780   
781   
782   // If it isn't a comparison with an integer-as-fp (the exit value), we can't
783   // transform it.
784   ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
785   int64_t ExitValue;
786   if (ExitValueVal == 0 ||
787       !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
788     return;
789   
790   // Find new predicate for integer comparison.
791   CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
792   switch (Compare->getPredicate()) {
793   default: return;  // Unknown comparison.
794   case CmpInst::FCMP_OEQ:
795   case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
796   case CmpInst::FCMP_ONE:
797   case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
798   case CmpInst::FCMP_OGT:
799   case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
800   case CmpInst::FCMP_OGE:
801   case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
802   case CmpInst::FCMP_OLT:
803   case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
804   case CmpInst::FCMP_OLE:
805   case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
806   }
807   
808   // We convert the floating point induction variable to a signed i32 value if
809   // we can.  This is only safe if the comparison will not overflow in a way
810   // that won't be trapped by the integer equivalent operations.  Check for this
811   // now.
812   // TODO: We could use i64 if it is native and the range requires it.
813   
814   // The start/stride/exit values must all fit in signed i32.
815   if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
816     return;
817
818   // If not actually striding (add x, 0.0), avoid touching the code.
819   if (IncValue == 0)
820     return;
821
822   // Positive and negative strides have different safety conditions.
823   if (IncValue > 0) {
824     // If we have a positive stride, we require the init to be less than the
825     // exit value and an equality or less than comparison.
826     if (InitValue >= ExitValue ||
827         NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
828       return;
829     
830     uint32_t Range = uint32_t(ExitValue-InitValue);
831     if (NewPred == CmpInst::ICMP_SLE) {
832       // Normalize SLE -> SLT, check for infinite loop.
833       if (++Range == 0) return;  // Range overflows.
834     }
835     
836     unsigned Leftover = Range % uint32_t(IncValue);
837     
838     // If this is an equality comparison, we require that the strided value
839     // exactly land on the exit value, otherwise the IV condition will wrap
840     // around and do things the fp IV wouldn't.
841     if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
842         Leftover != 0)
843       return;
844     
845     // If the stride would wrap around the i32 before exiting, we can't
846     // transform the IV.
847     if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
848       return;
849     
850   } else {
851     // If we have a negative stride, we require the init to be greater than the
852     // exit value and an equality or greater than comparison.
853     if (InitValue >= ExitValue ||
854         NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
855       return;
856     
857     uint32_t Range = uint32_t(InitValue-ExitValue);
858     if (NewPred == CmpInst::ICMP_SGE) {
859       // Normalize SGE -> SGT, check for infinite loop.
860       if (++Range == 0) return;  // Range overflows.
861     }
862     
863     unsigned Leftover = Range % uint32_t(-IncValue);
864     
865     // If this is an equality comparison, we require that the strided value
866     // exactly land on the exit value, otherwise the IV condition will wrap
867     // around and do things the fp IV wouldn't.
868     if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
869         Leftover != 0)
870       return;
871     
872     // If the stride would wrap around the i32 before exiting, we can't
873     // transform the IV.
874     if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
875       return;
876   }
877   
878   const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
879
880   // Insert new integer induction variable.
881   PHINode *NewPHI = PHINode::Create(Int32Ty, PN->getName()+".int", PN);
882   NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
883                       PN->getIncomingBlock(IncomingEdge));
884
885   Value *NewAdd =
886     BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
887                               Incr->getName()+".int", Incr);
888   NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
889
890   ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
891                                       ConstantInt::get(Int32Ty, ExitValue),
892                                       Compare->getName());
893
894   // In the following deletions, PN may become dead and may be deleted.
895   // Use a WeakVH to observe whether this happens.
896   WeakVH WeakPH = PN;
897
898   // Delete the old floating point exit comparison.  The branch starts using the
899   // new comparison.
900   NewCompare->takeName(Compare);
901   Compare->replaceAllUsesWith(NewCompare);
902   RecursivelyDeleteTriviallyDeadInstructions(Compare);
903
904   // Delete the old floating point increment.
905   Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
906   RecursivelyDeleteTriviallyDeadInstructions(Incr);
907
908   // If the FP induction variable still has uses, this is because something else
909   // in the loop uses its value.  In order to canonicalize the induction
910   // variable, we chose to eliminate the IV and rewrite it in terms of an
911   // int->fp cast.
912   //
913   // We give preference to sitofp over uitofp because it is faster on most
914   // platforms.
915   if (WeakPH) {
916     Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
917                                  PN->getParent()->getFirstNonPHI());
918     PN->replaceAllUsesWith(Conv);
919     RecursivelyDeleteTriviallyDeadInstructions(PN);
920   }
921
922   // Add a new IVUsers entry for the newly-created integer PHI.
923   IU->AddUsersIfInteresting(NewPHI);
924 }