ScalarEvolution.cpp revision 5cd28fad15b3bab840dac5ecdc2bdfde4f74816a
1//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
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 file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library.  First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
17// can handle.  These classes are reference counted, managed by the SCEVHandle
18// class.  We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression.  These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
31//
32// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
36// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43//  Chains of recurrences -- a method to expedite the evaluation
44//  of closed-form functions
45//  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47//  On computational properties of chains of recurrences
48//  Eugene V. Zima
49//
50//  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51//  Robert A. van Engelen
52//
53//  Efficient Symbolic Analysis for Optimizing Compilers
54//  Robert A. van Engelen
55//
56//  Using the chains of recurrences algebra for data dependence testing and
57//  induction variable substitution
58//  MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
62#define DEBUG_TYPE "scalar-evolution"
63#include "llvm/Analysis/ScalarEvolutionExpressions.h"
64#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
66#include "llvm/GlobalVariable.h"
67#include "llvm/Instructions.h"
68#include "llvm/Analysis/ConstantFolding.h"
69#include "llvm/Analysis/Dominators.h"
70#include "llvm/Analysis/LoopInfo.h"
71#include "llvm/Assembly/Writer.h"
72#include "llvm/Target/TargetData.h"
73#include "llvm/Transforms/Scalar.h"
74#include "llvm/Support/CFG.h"
75#include "llvm/Support/CommandLine.h"
76#include "llvm/Support/Compiler.h"
77#include "llvm/Support/ConstantRange.h"
78#include "llvm/Support/GetElementPtrTypeIterator.h"
79#include "llvm/Support/InstIterator.h"
80#include "llvm/Support/ManagedStatic.h"
81#include "llvm/Support/MathExtras.h"
82#include "llvm/Support/raw_ostream.h"
83#include "llvm/ADT/Statistic.h"
84#include "llvm/ADT/STLExtras.h"
85#include <ostream>
86#include <algorithm>
87#include <cmath>
88using namespace llvm;
89
90STATISTIC(NumArrayLenItCounts,
91          "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93          "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95          "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97          "Number of loops with trip counts computed by force");
98
99static cl::opt<unsigned>
100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101                        cl::desc("Maximum number of iterations SCEV will "
102                                 "symbolically execute a constant derived loop"),
103                        cl::init(100));
104
105static RegisterPass<ScalarEvolution>
106R("scalar-evolution", "Scalar Evolution Analysis", false, true);
107char ScalarEvolution::ID = 0;
108
109//===----------------------------------------------------------------------===//
110//                           SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
116SCEV::~SCEV() {}
117void SCEV::dump() const {
118  print(errs());
119  errs() << '\n';
120}
121
122void SCEV::print(std::ostream &o) const {
123  raw_os_ostream OS(o);
124  print(OS);
125}
126
127bool SCEV::isZero() const {
128  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
129    return SC->getValue()->isZero();
130  return false;
131}
132
133
134SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
135SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
136
137bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
138  assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
139  return false;
140}
141
142const Type *SCEVCouldNotCompute::getType() const {
143  assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
144  return 0;
145}
146
147bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
148  assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
149  return false;
150}
151
152SCEVHandle SCEVCouldNotCompute::
153replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
154                                  const SCEVHandle &Conc,
155                                  ScalarEvolution &SE) const {
156  return this;
157}
158
159void SCEVCouldNotCompute::print(raw_ostream &OS) const {
160  OS << "***COULDNOTCOMPUTE***";
161}
162
163bool SCEVCouldNotCompute::classof(const SCEV *S) {
164  return S->getSCEVType() == scCouldNotCompute;
165}
166
167
168// SCEVConstants - Only allow the creation of one SCEVConstant for any
169// particular value.  Don't use a SCEVHandle here, or else the object will
170// never be deleted!
171static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
172
173
174SCEVConstant::~SCEVConstant() {
175  SCEVConstants->erase(V);
176}
177
178SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
179  SCEVConstant *&R = (*SCEVConstants)[V];
180  if (R == 0) R = new SCEVConstant(V);
181  return R;
182}
183
184SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
185  return getConstant(ConstantInt::get(Val));
186}
187
188const Type *SCEVConstant::getType() const { return V->getType(); }
189
190void SCEVConstant::print(raw_ostream &OS) const {
191  WriteAsOperand(OS, V, false);
192}
193
194SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
195                           const SCEVHandle &op, const Type *ty)
196  : SCEV(SCEVTy), Op(op), Ty(ty) {}
197
198SCEVCastExpr::~SCEVCastExpr() {}
199
200bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
201  return Op->dominates(BB, DT);
202}
203
204// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
205// particular input.  Don't use a SCEVHandle here, or else the object will
206// never be deleted!
207static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
208                     SCEVTruncateExpr*> > SCEVTruncates;
209
210SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
211  : SCEVCastExpr(scTruncate, op, ty) {
212  assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
213         (Ty->isInteger() || isa<PointerType>(Ty)) &&
214         "Cannot truncate non-integer value!");
215}
216
217SCEVTruncateExpr::~SCEVTruncateExpr() {
218  SCEVTruncates->erase(std::make_pair(Op, Ty));
219}
220
221void SCEVTruncateExpr::print(raw_ostream &OS) const {
222  OS << "(truncate " << *Op << " to " << *Ty << ")";
223}
224
225// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
226// particular input.  Don't use a SCEVHandle here, or else the object will never
227// be deleted!
228static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
229                     SCEVZeroExtendExpr*> > SCEVZeroExtends;
230
231SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
232  : SCEVCastExpr(scZeroExtend, op, ty) {
233  assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
234         (Ty->isInteger() || isa<PointerType>(Ty)) &&
235         "Cannot zero extend non-integer value!");
236}
237
238SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
239  SCEVZeroExtends->erase(std::make_pair(Op, Ty));
240}
241
242void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
243  OS << "(zeroextend " << *Op << " to " << *Ty << ")";
244}
245
246// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
247// particular input.  Don't use a SCEVHandle here, or else the object will never
248// be deleted!
249static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
250                     SCEVSignExtendExpr*> > SCEVSignExtends;
251
252SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
253  : SCEVCastExpr(scSignExtend, op, ty) {
254  assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
255         (Ty->isInteger() || isa<PointerType>(Ty)) &&
256         "Cannot sign extend non-integer value!");
257}
258
259SCEVSignExtendExpr::~SCEVSignExtendExpr() {
260  SCEVSignExtends->erase(std::make_pair(Op, Ty));
261}
262
263void SCEVSignExtendExpr::print(raw_ostream &OS) const {
264  OS << "(signextend " << *Op << " to " << *Ty << ")";
265}
266
267// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
268// particular input.  Don't use a SCEVHandle here, or else the object will never
269// be deleted!
270static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
271                     SCEVCommutativeExpr*> > SCEVCommExprs;
272
273SCEVCommutativeExpr::~SCEVCommutativeExpr() {
274  SCEVCommExprs->erase(std::make_pair(getSCEVType(),
275                                      std::vector<SCEV*>(Operands.begin(),
276                                                         Operands.end())));
277}
278
279void SCEVCommutativeExpr::print(raw_ostream &OS) const {
280  assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
281  const char *OpStr = getOperationStr();
282  OS << "(" << *Operands[0];
283  for (unsigned i = 1, e = Operands.size(); i != e; ++i)
284    OS << OpStr << *Operands[i];
285  OS << ")";
286}
287
288SCEVHandle SCEVCommutativeExpr::
289replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
290                                  const SCEVHandle &Conc,
291                                  ScalarEvolution &SE) const {
292  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
293    SCEVHandle H =
294      getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
295    if (H != getOperand(i)) {
296      std::vector<SCEVHandle> NewOps;
297      NewOps.reserve(getNumOperands());
298      for (unsigned j = 0; j != i; ++j)
299        NewOps.push_back(getOperand(j));
300      NewOps.push_back(H);
301      for (++i; i != e; ++i)
302        NewOps.push_back(getOperand(i)->
303                         replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
304
305      if (isa<SCEVAddExpr>(this))
306        return SE.getAddExpr(NewOps);
307      else if (isa<SCEVMulExpr>(this))
308        return SE.getMulExpr(NewOps);
309      else if (isa<SCEVSMaxExpr>(this))
310        return SE.getSMaxExpr(NewOps);
311      else if (isa<SCEVUMaxExpr>(this))
312        return SE.getUMaxExpr(NewOps);
313      else
314        assert(0 && "Unknown commutative expr!");
315    }
316  }
317  return this;
318}
319
320bool SCEVCommutativeExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
321  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
322    if (!getOperand(i)->dominates(BB, DT))
323      return false;
324  }
325  return true;
326}
327
328
329// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
330// input.  Don't use a SCEVHandle here, or else the object will never be
331// deleted!
332static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
333                     SCEVUDivExpr*> > SCEVUDivs;
334
335SCEVUDivExpr::~SCEVUDivExpr() {
336  SCEVUDivs->erase(std::make_pair(LHS, RHS));
337}
338
339bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
340  return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
341}
342
343void SCEVUDivExpr::print(raw_ostream &OS) const {
344  OS << "(" << *LHS << " /u " << *RHS << ")";
345}
346
347const Type *SCEVUDivExpr::getType() const {
348  return LHS->getType();
349}
350
351// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
352// particular input.  Don't use a SCEVHandle here, or else the object will never
353// be deleted!
354static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
355                     SCEVAddRecExpr*> > SCEVAddRecExprs;
356
357SCEVAddRecExpr::~SCEVAddRecExpr() {
358  SCEVAddRecExprs->erase(std::make_pair(L,
359                                        std::vector<SCEV*>(Operands.begin(),
360                                                           Operands.end())));
361}
362
363bool SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
364  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
365    if (!getOperand(i)->dominates(BB, DT))
366      return false;
367  }
368  return true;
369}
370
371
372SCEVHandle SCEVAddRecExpr::
373replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
374                                  const SCEVHandle &Conc,
375                                  ScalarEvolution &SE) const {
376  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
377    SCEVHandle H =
378      getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
379    if (H != getOperand(i)) {
380      std::vector<SCEVHandle> NewOps;
381      NewOps.reserve(getNumOperands());
382      for (unsigned j = 0; j != i; ++j)
383        NewOps.push_back(getOperand(j));
384      NewOps.push_back(H);
385      for (++i; i != e; ++i)
386        NewOps.push_back(getOperand(i)->
387                         replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
388
389      return SE.getAddRecExpr(NewOps, L);
390    }
391  }
392  return this;
393}
394
395
396bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
397  // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
398  // contain L and if the start is invariant.
399  return !QueryLoop->contains(L->getHeader()) &&
400         getOperand(0)->isLoopInvariant(QueryLoop);
401}
402
403
404void SCEVAddRecExpr::print(raw_ostream &OS) const {
405  OS << "{" << *Operands[0];
406  for (unsigned i = 1, e = Operands.size(); i != e; ++i)
407    OS << ",+," << *Operands[i];
408  OS << "}<" << L->getHeader()->getName() + ">";
409}
410
411// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
412// value.  Don't use a SCEVHandle here, or else the object will never be
413// deleted!
414static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
415
416SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
417
418bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
419  // All non-instruction values are loop invariant.  All instructions are loop
420  // invariant if they are not contained in the specified loop.
421  if (Instruction *I = dyn_cast<Instruction>(V))
422    return !L->contains(I->getParent());
423  return true;
424}
425
426bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
427  if (Instruction *I = dyn_cast<Instruction>(getValue()))
428    return DT->dominates(I->getParent(), BB);
429  return true;
430}
431
432const Type *SCEVUnknown::getType() const {
433  return V->getType();
434}
435
436void SCEVUnknown::print(raw_ostream &OS) const {
437  if (isa<PointerType>(V->getType()))
438    OS << "(ptrtoint " << *V->getType() << " ";
439  WriteAsOperand(OS, V, false);
440  if (isa<PointerType>(V->getType()))
441    OS << " to iPTR)";
442}
443
444//===----------------------------------------------------------------------===//
445//                               SCEV Utilities
446//===----------------------------------------------------------------------===//
447
448namespace {
449  /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
450  /// than the complexity of the RHS.  This comparator is used to canonicalize
451  /// expressions.
452  struct VISIBILITY_HIDDEN SCEVComplexityCompare {
453    bool operator()(const SCEV *LHS, const SCEV *RHS) const {
454      return LHS->getSCEVType() < RHS->getSCEVType();
455    }
456  };
457}
458
459/// GroupByComplexity - Given a list of SCEV objects, order them by their
460/// complexity, and group objects of the same complexity together by value.
461/// When this routine is finished, we know that any duplicates in the vector are
462/// consecutive and that complexity is monotonically increasing.
463///
464/// Note that we go take special precautions to ensure that we get determinstic
465/// results from this routine.  In other words, we don't want the results of
466/// this to depend on where the addresses of various SCEV objects happened to
467/// land in memory.
468///
469static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
470  if (Ops.size() < 2) return;  // Noop
471  if (Ops.size() == 2) {
472    // This is the common case, which also happens to be trivially simple.
473    // Special case it.
474    if (SCEVComplexityCompare()(Ops[1], Ops[0]))
475      std::swap(Ops[0], Ops[1]);
476    return;
477  }
478
479  // Do the rough sort by complexity.
480  std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
481
482  // Now that we are sorted by complexity, group elements of the same
483  // complexity.  Note that this is, at worst, N^2, but the vector is likely to
484  // be extremely short in practice.  Note that we take this approach because we
485  // do not want to depend on the addresses of the objects we are grouping.
486  for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
487    SCEV *S = Ops[i];
488    unsigned Complexity = S->getSCEVType();
489
490    // If there are any objects of the same complexity and same value as this
491    // one, group them.
492    for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
493      if (Ops[j] == S) { // Found a duplicate.
494        // Move it to immediately after i'th element.
495        std::swap(Ops[i+1], Ops[j]);
496        ++i;   // no need to rescan it.
497        if (i == e-2) return;  // Done!
498      }
499    }
500  }
501}
502
503
504
505//===----------------------------------------------------------------------===//
506//                      Simple SCEV method implementations
507//===----------------------------------------------------------------------===//
508
509/// BinomialCoefficient - Compute BC(It, K).  The result has width W.
510// Assume, K > 0.
511static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
512                                      ScalarEvolution &SE,
513                                      const Type* ResultTy) {
514  // Handle the simplest case efficiently.
515  if (K == 1)
516    return SE.getTruncateOrZeroExtend(It, ResultTy);
517
518  // We are using the following formula for BC(It, K):
519  //
520  //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
521  //
522  // Suppose, W is the bitwidth of the return value.  We must be prepared for
523  // overflow.  Hence, we must assure that the result of our computation is
524  // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
525  // safe in modular arithmetic.
526  //
527  // However, this code doesn't use exactly that formula; the formula it uses
528  // is something like the following, where T is the number of factors of 2 in
529  // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
530  // exponentiation:
531  //
532  //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
533  //
534  // This formula is trivially equivalent to the previous formula.  However,
535  // this formula can be implemented much more efficiently.  The trick is that
536  // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
537  // arithmetic.  To do exact division in modular arithmetic, all we have
538  // to do is multiply by the inverse.  Therefore, this step can be done at
539  // width W.
540  //
541  // The next issue is how to safely do the division by 2^T.  The way this
542  // is done is by doing the multiplication step at a width of at least W + T
543  // bits.  This way, the bottom W+T bits of the product are accurate. Then,
544  // when we perform the division by 2^T (which is equivalent to a right shift
545  // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
546  // truncated out after the division by 2^T.
547  //
548  // In comparison to just directly using the first formula, this technique
549  // is much more efficient; using the first formula requires W * K bits,
550  // but this formula less than W + K bits. Also, the first formula requires
551  // a division step, whereas this formula only requires multiplies and shifts.
552  //
553  // It doesn't matter whether the subtraction step is done in the calculation
554  // width or the input iteration count's width; if the subtraction overflows,
555  // the result must be zero anyway.  We prefer here to do it in the width of
556  // the induction variable because it helps a lot for certain cases; CodeGen
557  // isn't smart enough to ignore the overflow, which leads to much less
558  // efficient code if the width of the subtraction is wider than the native
559  // register width.
560  //
561  // (It's possible to not widen at all by pulling out factors of 2 before
562  // the multiplication; for example, K=2 can be calculated as
563  // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
564  // extra arithmetic, so it's not an obvious win, and it gets
565  // much more complicated for K > 3.)
566
567  // Protection from insane SCEVs; this bound is conservative,
568  // but it probably doesn't matter.
569  if (K > 1000)
570    return SE.getCouldNotCompute();
571
572  unsigned W = SE.getTypeSizeInBits(ResultTy);
573
574  // Calculate K! / 2^T and T; we divide out the factors of two before
575  // multiplying for calculating K! / 2^T to avoid overflow.
576  // Other overflow doesn't matter because we only care about the bottom
577  // W bits of the result.
578  APInt OddFactorial(W, 1);
579  unsigned T = 1;
580  for (unsigned i = 3; i <= K; ++i) {
581    APInt Mult(W, i);
582    unsigned TwoFactors = Mult.countTrailingZeros();
583    T += TwoFactors;
584    Mult = Mult.lshr(TwoFactors);
585    OddFactorial *= Mult;
586  }
587
588  // We need at least W + T bits for the multiplication step
589  unsigned CalculationBits = W + T;
590
591  // Calcuate 2^T, at width T+W.
592  APInt DivFactor = APInt(CalculationBits, 1).shl(T);
593
594  // Calculate the multiplicative inverse of K! / 2^T;
595  // this multiplication factor will perform the exact division by
596  // K! / 2^T.
597  APInt Mod = APInt::getSignedMinValue(W+1);
598  APInt MultiplyFactor = OddFactorial.zext(W+1);
599  MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
600  MultiplyFactor = MultiplyFactor.trunc(W);
601
602  // Calculate the product, at width T+W
603  const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
604  SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
605  for (unsigned i = 1; i != K; ++i) {
606    SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
607    Dividend = SE.getMulExpr(Dividend,
608                             SE.getTruncateOrZeroExtend(S, CalculationTy));
609  }
610
611  // Divide by 2^T
612  SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
613
614  // Truncate the result, and divide by K! / 2^T.
615
616  return SE.getMulExpr(SE.getConstant(MultiplyFactor),
617                       SE.getTruncateOrZeroExtend(DivResult, ResultTy));
618}
619
620/// evaluateAtIteration - Return the value of this chain of recurrences at
621/// the specified iteration number.  We can evaluate this recurrence by
622/// multiplying each element in the chain by the binomial coefficient
623/// corresponding to it.  In other words, we can evaluate {A,+,B,+,C,+,D} as:
624///
625///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
626///
627/// where BC(It, k) stands for binomial coefficient.
628///
629SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
630                                               ScalarEvolution &SE) const {
631  SCEVHandle Result = getStart();
632  for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
633    // The computation is correct in the face of overflow provided that the
634    // multiplication is performed _after_ the evaluation of the binomial
635    // coefficient.
636    SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
637    if (isa<SCEVCouldNotCompute>(Coeff))
638      return Coeff;
639
640    Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
641  }
642  return Result;
643}
644
645//===----------------------------------------------------------------------===//
646//                    SCEV Expression folder implementations
647//===----------------------------------------------------------------------===//
648
649SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
650  assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
651         "This is not a truncating conversion!");
652
653  if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
654    return getUnknown(
655        ConstantExpr::getTrunc(SC->getValue(), Ty));
656
657  // trunc(trunc(x)) --> trunc(x)
658  if (SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
659    return getTruncateExpr(ST->getOperand(), Ty);
660
661  // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
662  if (SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
663    return getTruncateOrSignExtend(SS->getOperand(), Ty);
664
665  // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
666  if (SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
667    return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
668
669  // If the input value is a chrec scev made out of constants, truncate
670  // all of the constants.
671  if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
672    std::vector<SCEVHandle> Operands;
673    for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
674      // FIXME: This should allow truncation of other expression types!
675      if (isa<SCEVConstant>(AddRec->getOperand(i)))
676        Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
677      else
678        break;
679    if (Operands.size() == AddRec->getNumOperands())
680      return getAddRecExpr(Operands, AddRec->getLoop());
681  }
682
683  SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
684  if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
685  return Result;
686}
687
688SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
689                                              const Type *Ty) {
690  assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
691         "This is not an extending conversion!");
692
693  if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
694    const Type *IntTy = getEffectiveSCEVType(Ty);
695    Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
696    if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
697    return getUnknown(C);
698  }
699
700  // zext(zext(x)) --> zext(x)
701  if (SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
702    return getZeroExtendExpr(SZ->getOperand(), Ty);
703
704  // FIXME: If the input value is a chrec scev, and we can prove that the value
705  // did not overflow the old, smaller, value, we can zero extend all of the
706  // operands (often constants).  This would allow analysis of something like
707  // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
708
709  SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
710  if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
711  return Result;
712}
713
714SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
715  assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
716         "This is not an extending conversion!");
717
718  if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
719    const Type *IntTy = getEffectiveSCEVType(Ty);
720    Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
721    if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
722    return getUnknown(C);
723  }
724
725  // sext(sext(x)) --> sext(x)
726  if (SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
727    return getSignExtendExpr(SS->getOperand(), Ty);
728
729  // FIXME: If the input value is a chrec scev, and we can prove that the value
730  // did not overflow the old, smaller, value, we can sign extend all of the
731  // operands (often constants).  This would allow analysis of something like
732  // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
733
734  SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
735  if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
736  return Result;
737}
738
739// get - Get a canonical add expression, or something simpler if possible.
740SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
741  assert(!Ops.empty() && "Cannot get empty add!");
742  if (Ops.size() == 1) return Ops[0];
743
744  // Sort by complexity, this groups all similar expression types together.
745  GroupByComplexity(Ops);
746
747  // If there are any constants, fold them together.
748  unsigned Idx = 0;
749  if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
750    ++Idx;
751    assert(Idx < Ops.size());
752    while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
753      // We found two constants, fold them together!
754      ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
755                                           RHSC->getValue()->getValue());
756      Ops[0] = getConstant(Fold);
757      Ops.erase(Ops.begin()+1);  // Erase the folded element
758      if (Ops.size() == 1) return Ops[0];
759      LHSC = cast<SCEVConstant>(Ops[0]);
760    }
761
762    // If we are left with a constant zero being added, strip it off.
763    if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
764      Ops.erase(Ops.begin());
765      --Idx;
766    }
767  }
768
769  if (Ops.size() == 1) return Ops[0];
770
771  // Okay, check to see if the same value occurs in the operand list twice.  If
772  // so, merge them together into an multiply expression.  Since we sorted the
773  // list, these values are required to be adjacent.
774  const Type *Ty = Ops[0]->getType();
775  for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
776    if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
777      // Found a match, merge the two values into a multiply, and add any
778      // remaining values to the result.
779      SCEVHandle Two = getIntegerSCEV(2, Ty);
780      SCEVHandle Mul = getMulExpr(Ops[i], Two);
781      if (Ops.size() == 2)
782        return Mul;
783      Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
784      Ops.push_back(Mul);
785      return getAddExpr(Ops);
786    }
787
788  // Now we know the first non-constant operand.  Skip past any cast SCEVs.
789  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
790    ++Idx;
791
792  // If there are add operands they would be next.
793  if (Idx < Ops.size()) {
794    bool DeletedAdd = false;
795    while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
796      // If we have an add, expand the add operands onto the end of the operands
797      // list.
798      Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
799      Ops.erase(Ops.begin()+Idx);
800      DeletedAdd = true;
801    }
802
803    // If we deleted at least one add, we added operands to the end of the list,
804    // and they are not necessarily sorted.  Recurse to resort and resimplify
805    // any operands we just aquired.
806    if (DeletedAdd)
807      return getAddExpr(Ops);
808  }
809
810  // Skip over the add expression until we get to a multiply.
811  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
812    ++Idx;
813
814  // If we are adding something to a multiply expression, make sure the
815  // something is not already an operand of the multiply.  If so, merge it into
816  // the multiply.
817  for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
818    SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
819    for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
820      SCEV *MulOpSCEV = Mul->getOperand(MulOp);
821      for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
822        if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
823          // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
824          SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
825          if (Mul->getNumOperands() != 2) {
826            // If the multiply has more than two operands, we must get the
827            // Y*Z term.
828            std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
829            MulOps.erase(MulOps.begin()+MulOp);
830            InnerMul = getMulExpr(MulOps);
831          }
832          SCEVHandle One = getIntegerSCEV(1, Ty);
833          SCEVHandle AddOne = getAddExpr(InnerMul, One);
834          SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
835          if (Ops.size() == 2) return OuterMul;
836          if (AddOp < Idx) {
837            Ops.erase(Ops.begin()+AddOp);
838            Ops.erase(Ops.begin()+Idx-1);
839          } else {
840            Ops.erase(Ops.begin()+Idx);
841            Ops.erase(Ops.begin()+AddOp-1);
842          }
843          Ops.push_back(OuterMul);
844          return getAddExpr(Ops);
845        }
846
847      // Check this multiply against other multiplies being added together.
848      for (unsigned OtherMulIdx = Idx+1;
849           OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
850           ++OtherMulIdx) {
851        SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
852        // If MulOp occurs in OtherMul, we can fold the two multiplies
853        // together.
854        for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
855             OMulOp != e; ++OMulOp)
856          if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
857            // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
858            SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
859            if (Mul->getNumOperands() != 2) {
860              std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
861              MulOps.erase(MulOps.begin()+MulOp);
862              InnerMul1 = getMulExpr(MulOps);
863            }
864            SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
865            if (OtherMul->getNumOperands() != 2) {
866              std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
867                                             OtherMul->op_end());
868              MulOps.erase(MulOps.begin()+OMulOp);
869              InnerMul2 = getMulExpr(MulOps);
870            }
871            SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
872            SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
873            if (Ops.size() == 2) return OuterMul;
874            Ops.erase(Ops.begin()+Idx);
875            Ops.erase(Ops.begin()+OtherMulIdx-1);
876            Ops.push_back(OuterMul);
877            return getAddExpr(Ops);
878          }
879      }
880    }
881  }
882
883  // If there are any add recurrences in the operands list, see if any other
884  // added values are loop invariant.  If so, we can fold them into the
885  // recurrence.
886  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
887    ++Idx;
888
889  // Scan over all recurrences, trying to fold loop invariants into them.
890  for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
891    // Scan all of the other operands to this add and add them to the vector if
892    // they are loop invariant w.r.t. the recurrence.
893    std::vector<SCEVHandle> LIOps;
894    SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
895    for (unsigned i = 0, e = Ops.size(); i != e; ++i)
896      if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
897        LIOps.push_back(Ops[i]);
898        Ops.erase(Ops.begin()+i);
899        --i; --e;
900      }
901
902    // If we found some loop invariants, fold them into the recurrence.
903    if (!LIOps.empty()) {
904      //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
905      LIOps.push_back(AddRec->getStart());
906
907      std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
908      AddRecOps[0] = getAddExpr(LIOps);
909
910      SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
911      // If all of the other operands were loop invariant, we are done.
912      if (Ops.size() == 1) return NewRec;
913
914      // Otherwise, add the folded AddRec by the non-liv parts.
915      for (unsigned i = 0;; ++i)
916        if (Ops[i] == AddRec) {
917          Ops[i] = NewRec;
918          break;
919        }
920      return getAddExpr(Ops);
921    }
922
923    // Okay, if there weren't any loop invariants to be folded, check to see if
924    // there are multiple AddRec's with the same loop induction variable being
925    // added together.  If so, we can fold them.
926    for (unsigned OtherIdx = Idx+1;
927         OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
928      if (OtherIdx != Idx) {
929        SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
930        if (AddRec->getLoop() == OtherAddRec->getLoop()) {
931          // Other + {A,+,B} + {C,+,D}  -->  Other + {A+C,+,B+D}
932          std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
933          for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
934            if (i >= NewOps.size()) {
935              NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
936                            OtherAddRec->op_end());
937              break;
938            }
939            NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
940          }
941          SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
942
943          if (Ops.size() == 2) return NewAddRec;
944
945          Ops.erase(Ops.begin()+Idx);
946          Ops.erase(Ops.begin()+OtherIdx-1);
947          Ops.push_back(NewAddRec);
948          return getAddExpr(Ops);
949        }
950      }
951
952    // Otherwise couldn't fold anything into this recurrence.  Move onto the
953    // next one.
954  }
955
956  // Okay, it looks like we really DO need an add expr.  Check to see if we
957  // already have one, otherwise create a new one.
958  std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
959  SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
960                                                                 SCEVOps)];
961  if (Result == 0) Result = new SCEVAddExpr(Ops);
962  return Result;
963}
964
965
966SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
967  assert(!Ops.empty() && "Cannot get empty mul!");
968
969  // Sort by complexity, this groups all similar expression types together.
970  GroupByComplexity(Ops);
971
972  // If there are any constants, fold them together.
973  unsigned Idx = 0;
974  if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
975
976    // C1*(C2+V) -> C1*C2 + C1*V
977    if (Ops.size() == 2)
978      if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
979        if (Add->getNumOperands() == 2 &&
980            isa<SCEVConstant>(Add->getOperand(0)))
981          return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
982                            getMulExpr(LHSC, Add->getOperand(1)));
983
984
985    ++Idx;
986    while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
987      // We found two constants, fold them together!
988      ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
989                                           RHSC->getValue()->getValue());
990      Ops[0] = getConstant(Fold);
991      Ops.erase(Ops.begin()+1);  // Erase the folded element
992      if (Ops.size() == 1) return Ops[0];
993      LHSC = cast<SCEVConstant>(Ops[0]);
994    }
995
996    // If we are left with a constant one being multiplied, strip it off.
997    if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
998      Ops.erase(Ops.begin());
999      --Idx;
1000    } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1001      // If we have a multiply of zero, it will always be zero.
1002      return Ops[0];
1003    }
1004  }
1005
1006  // Skip over the add expression until we get to a multiply.
1007  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1008    ++Idx;
1009
1010  if (Ops.size() == 1)
1011    return Ops[0];
1012
1013  // If there are mul operands inline them all into this expression.
1014  if (Idx < Ops.size()) {
1015    bool DeletedMul = false;
1016    while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1017      // If we have an mul, expand the mul operands onto the end of the operands
1018      // list.
1019      Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1020      Ops.erase(Ops.begin()+Idx);
1021      DeletedMul = true;
1022    }
1023
1024    // If we deleted at least one mul, we added operands to the end of the list,
1025    // and they are not necessarily sorted.  Recurse to resort and resimplify
1026    // any operands we just aquired.
1027    if (DeletedMul)
1028      return getMulExpr(Ops);
1029  }
1030
1031  // If there are any add recurrences in the operands list, see if any other
1032  // added values are loop invariant.  If so, we can fold them into the
1033  // recurrence.
1034  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1035    ++Idx;
1036
1037  // Scan over all recurrences, trying to fold loop invariants into them.
1038  for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1039    // Scan all of the other operands to this mul and add them to the vector if
1040    // they are loop invariant w.r.t. the recurrence.
1041    std::vector<SCEVHandle> LIOps;
1042    SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1043    for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1044      if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1045        LIOps.push_back(Ops[i]);
1046        Ops.erase(Ops.begin()+i);
1047        --i; --e;
1048      }
1049
1050    // If we found some loop invariants, fold them into the recurrence.
1051    if (!LIOps.empty()) {
1052      //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
1053      std::vector<SCEVHandle> NewOps;
1054      NewOps.reserve(AddRec->getNumOperands());
1055      if (LIOps.size() == 1) {
1056        SCEV *Scale = LIOps[0];
1057        for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
1058          NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
1059      } else {
1060        for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1061          std::vector<SCEVHandle> MulOps(LIOps);
1062          MulOps.push_back(AddRec->getOperand(i));
1063          NewOps.push_back(getMulExpr(MulOps));
1064        }
1065      }
1066
1067      SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
1068
1069      // If all of the other operands were loop invariant, we are done.
1070      if (Ops.size() == 1) return NewRec;
1071
1072      // Otherwise, multiply the folded AddRec by the non-liv parts.
1073      for (unsigned i = 0;; ++i)
1074        if (Ops[i] == AddRec) {
1075          Ops[i] = NewRec;
1076          break;
1077        }
1078      return getMulExpr(Ops);
1079    }
1080
1081    // Okay, if there weren't any loop invariants to be folded, check to see if
1082    // there are multiple AddRec's with the same loop induction variable being
1083    // multiplied together.  If so, we can fold them.
1084    for (unsigned OtherIdx = Idx+1;
1085         OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1086      if (OtherIdx != Idx) {
1087        SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1088        if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1089          // F * G  -->  {A,+,B} * {C,+,D}  -->  {A*C,+,F*D + G*B + B*D}
1090          SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
1091          SCEVHandle NewStart = getMulExpr(F->getStart(),
1092                                                 G->getStart());
1093          SCEVHandle B = F->getStepRecurrence(*this);
1094          SCEVHandle D = G->getStepRecurrence(*this);
1095          SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1096                                          getMulExpr(G, B),
1097                                          getMulExpr(B, D));
1098          SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1099                                               F->getLoop());
1100          if (Ops.size() == 2) return NewAddRec;
1101
1102          Ops.erase(Ops.begin()+Idx);
1103          Ops.erase(Ops.begin()+OtherIdx-1);
1104          Ops.push_back(NewAddRec);
1105          return getMulExpr(Ops);
1106        }
1107      }
1108
1109    // Otherwise couldn't fold anything into this recurrence.  Move onto the
1110    // next one.
1111  }
1112
1113  // Okay, it looks like we really DO need an mul expr.  Check to see if we
1114  // already have one, otherwise create a new one.
1115  std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1116  SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1117                                                                 SCEVOps)];
1118  if (Result == 0)
1119    Result = new SCEVMulExpr(Ops);
1120  return Result;
1121}
1122
1123SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1124  if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1125    if (RHSC->getValue()->equalsInt(1))
1126      return LHS;                            // X udiv 1 --> x
1127
1128    if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1129      Constant *LHSCV = LHSC->getValue();
1130      Constant *RHSCV = RHSC->getValue();
1131      return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
1132    }
1133  }
1134
1135  // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1136
1137  SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1138  if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
1139  return Result;
1140}
1141
1142
1143/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1144/// specified loop.  Simplify the expression as much as possible.
1145SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
1146                               const SCEVHandle &Step, const Loop *L) {
1147  std::vector<SCEVHandle> Operands;
1148  Operands.push_back(Start);
1149  if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1150    if (StepChrec->getLoop() == L) {
1151      Operands.insert(Operands.end(), StepChrec->op_begin(),
1152                      StepChrec->op_end());
1153      return getAddRecExpr(Operands, L);
1154    }
1155
1156  Operands.push_back(Step);
1157  return getAddRecExpr(Operands, L);
1158}
1159
1160/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1161/// specified loop.  Simplify the expression as much as possible.
1162SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
1163                                          const Loop *L) {
1164  if (Operands.size() == 1) return Operands[0];
1165
1166  if (Operands.back()->isZero()) {
1167    Operands.pop_back();
1168    return getAddRecExpr(Operands, L);             // {X,+,0}  -->  X
1169  }
1170
1171  // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1172  if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1173    const Loop* NestedLoop = NestedAR->getLoop();
1174    if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1175      std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1176                                             NestedAR->op_end());
1177      SCEVHandle NestedARHandle(NestedAR);
1178      Operands[0] = NestedAR->getStart();
1179      NestedOperands[0] = getAddRecExpr(Operands, L);
1180      return getAddRecExpr(NestedOperands, NestedLoop);
1181    }
1182  }
1183
1184  SCEVAddRecExpr *&Result =
1185    (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1186                                                            Operands.end()))];
1187  if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1188  return Result;
1189}
1190
1191SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1192                                        const SCEVHandle &RHS) {
1193  std::vector<SCEVHandle> Ops;
1194  Ops.push_back(LHS);
1195  Ops.push_back(RHS);
1196  return getSMaxExpr(Ops);
1197}
1198
1199SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1200  assert(!Ops.empty() && "Cannot get empty smax!");
1201  if (Ops.size() == 1) return Ops[0];
1202
1203  // Sort by complexity, this groups all similar expression types together.
1204  GroupByComplexity(Ops);
1205
1206  // If there are any constants, fold them together.
1207  unsigned Idx = 0;
1208  if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1209    ++Idx;
1210    assert(Idx < Ops.size());
1211    while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1212      // We found two constants, fold them together!
1213      ConstantInt *Fold = ConstantInt::get(
1214                              APIntOps::smax(LHSC->getValue()->getValue(),
1215                                             RHSC->getValue()->getValue()));
1216      Ops[0] = getConstant(Fold);
1217      Ops.erase(Ops.begin()+1);  // Erase the folded element
1218      if (Ops.size() == 1) return Ops[0];
1219      LHSC = cast<SCEVConstant>(Ops[0]);
1220    }
1221
1222    // If we are left with a constant -inf, strip it off.
1223    if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1224      Ops.erase(Ops.begin());
1225      --Idx;
1226    }
1227  }
1228
1229  if (Ops.size() == 1) return Ops[0];
1230
1231  // Find the first SMax
1232  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1233    ++Idx;
1234
1235  // Check to see if one of the operands is an SMax. If so, expand its operands
1236  // onto our operand list, and recurse to simplify.
1237  if (Idx < Ops.size()) {
1238    bool DeletedSMax = false;
1239    while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1240      Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1241      Ops.erase(Ops.begin()+Idx);
1242      DeletedSMax = true;
1243    }
1244
1245    if (DeletedSMax)
1246      return getSMaxExpr(Ops);
1247  }
1248
1249  // Okay, check to see if the same value occurs in the operand list twice.  If
1250  // so, delete one.  Since we sorted the list, these values are required to
1251  // be adjacent.
1252  for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1253    if (Ops[i] == Ops[i+1]) {      //  X smax Y smax Y  -->  X smax Y
1254      Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1255      --i; --e;
1256    }
1257
1258  if (Ops.size() == 1) return Ops[0];
1259
1260  assert(!Ops.empty() && "Reduced smax down to nothing!");
1261
1262  // Okay, it looks like we really DO need an smax expr.  Check to see if we
1263  // already have one, otherwise create a new one.
1264  std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1265  SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1266                                                                 SCEVOps)];
1267  if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1268  return Result;
1269}
1270
1271SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1272                                        const SCEVHandle &RHS) {
1273  std::vector<SCEVHandle> Ops;
1274  Ops.push_back(LHS);
1275  Ops.push_back(RHS);
1276  return getUMaxExpr(Ops);
1277}
1278
1279SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1280  assert(!Ops.empty() && "Cannot get empty umax!");
1281  if (Ops.size() == 1) return Ops[0];
1282
1283  // Sort by complexity, this groups all similar expression types together.
1284  GroupByComplexity(Ops);
1285
1286  // If there are any constants, fold them together.
1287  unsigned Idx = 0;
1288  if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1289    ++Idx;
1290    assert(Idx < Ops.size());
1291    while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1292      // We found two constants, fold them together!
1293      ConstantInt *Fold = ConstantInt::get(
1294                              APIntOps::umax(LHSC->getValue()->getValue(),
1295                                             RHSC->getValue()->getValue()));
1296      Ops[0] = getConstant(Fold);
1297      Ops.erase(Ops.begin()+1);  // Erase the folded element
1298      if (Ops.size() == 1) return Ops[0];
1299      LHSC = cast<SCEVConstant>(Ops[0]);
1300    }
1301
1302    // If we are left with a constant zero, strip it off.
1303    if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1304      Ops.erase(Ops.begin());
1305      --Idx;
1306    }
1307  }
1308
1309  if (Ops.size() == 1) return Ops[0];
1310
1311  // Find the first UMax
1312  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1313    ++Idx;
1314
1315  // Check to see if one of the operands is a UMax. If so, expand its operands
1316  // onto our operand list, and recurse to simplify.
1317  if (Idx < Ops.size()) {
1318    bool DeletedUMax = false;
1319    while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1320      Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1321      Ops.erase(Ops.begin()+Idx);
1322      DeletedUMax = true;
1323    }
1324
1325    if (DeletedUMax)
1326      return getUMaxExpr(Ops);
1327  }
1328
1329  // Okay, check to see if the same value occurs in the operand list twice.  If
1330  // so, delete one.  Since we sorted the list, these values are required to
1331  // be adjacent.
1332  for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1333    if (Ops[i] == Ops[i+1]) {      //  X umax Y umax Y  -->  X umax Y
1334      Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1335      --i; --e;
1336    }
1337
1338  if (Ops.size() == 1) return Ops[0];
1339
1340  assert(!Ops.empty() && "Reduced umax down to nothing!");
1341
1342  // Okay, it looks like we really DO need a umax expr.  Check to see if we
1343  // already have one, otherwise create a new one.
1344  std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1345  SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1346                                                                 SCEVOps)];
1347  if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1348  return Result;
1349}
1350
1351SCEVHandle ScalarEvolution::getUnknown(Value *V) {
1352  if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1353    return getConstant(CI);
1354  if (isa<ConstantPointerNull>(V))
1355    return getIntegerSCEV(0, V->getType());
1356  SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1357  if (Result == 0) Result = new SCEVUnknown(V);
1358  return Result;
1359}
1360
1361//===----------------------------------------------------------------------===//
1362//            Basic SCEV Analysis and PHI Idiom Recognition Code
1363//
1364
1365/// deleteValueFromRecords - This method should be called by the
1366/// client before it removes an instruction from the program, to make sure
1367/// that no dangling references are left around.
1368void ScalarEvolution::deleteValueFromRecords(Value *V) {
1369  SmallVector<Value *, 16> Worklist;
1370
1371  if (Scalars.erase(V)) {
1372    if (PHINode *PN = dyn_cast<PHINode>(V))
1373      ConstantEvolutionLoopExitValue.erase(PN);
1374    Worklist.push_back(V);
1375  }
1376
1377  while (!Worklist.empty()) {
1378    Value *VV = Worklist.back();
1379    Worklist.pop_back();
1380
1381    for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1382         UI != UE; ++UI) {
1383      Instruction *Inst = cast<Instruction>(*UI);
1384      if (Scalars.erase(Inst)) {
1385        if (PHINode *PN = dyn_cast<PHINode>(VV))
1386          ConstantEvolutionLoopExitValue.erase(PN);
1387        Worklist.push_back(Inst);
1388      }
1389    }
1390  }
1391}
1392
1393/// isSCEVable - Test if values of the given type are analyzable within
1394/// the SCEV framework. This primarily includes integer types, and it
1395/// can optionally include pointer types if the ScalarEvolution class
1396/// has access to target-specific information.
1397bool ScalarEvolution::isSCEVable(const Type *Ty) const {
1398  // Integers are always SCEVable.
1399  if (Ty->isInteger())
1400    return true;
1401
1402  // Pointers are SCEVable if TargetData information is available
1403  // to provide pointer size information.
1404  if (isa<PointerType>(Ty))
1405    return TD != NULL;
1406
1407  // Otherwise it's not SCEVable.
1408  return false;
1409}
1410
1411/// getTypeSizeInBits - Return the size in bits of the specified type,
1412/// for which isSCEVable must return true.
1413uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
1414  assert(isSCEVable(Ty) && "Type is not SCEVable!");
1415
1416  // If we have a TargetData, use it!
1417  if (TD)
1418    return TD->getTypeSizeInBits(Ty);
1419
1420  // Otherwise, we support only integer types.
1421  assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1422  return Ty->getPrimitiveSizeInBits();
1423}
1424
1425/// getEffectiveSCEVType - Return a type with the same bitwidth as
1426/// the given type and which represents how SCEV will treat the given
1427/// type, for which isSCEVable must return true. For pointer types,
1428/// this is the pointer-sized integer type.
1429const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
1430  assert(isSCEVable(Ty) && "Type is not SCEVable!");
1431
1432  if (Ty->isInteger())
1433    return Ty;
1434
1435  assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1436  return TD->getIntPtrType();
1437}
1438
1439SCEVHandle ScalarEvolution::getCouldNotCompute() {
1440  return UnknownValue;
1441}
1442
1443/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1444/// expression and create a new one.
1445SCEVHandle ScalarEvolution::getSCEV(Value *V) {
1446  assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
1447
1448  std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1449  if (I != Scalars.end()) return I->second;
1450  SCEVHandle S = createSCEV(V);
1451  Scalars.insert(std::make_pair(V, S));
1452  return S;
1453}
1454
1455/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1456/// specified signed integer value and return a SCEV for the constant.
1457SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1458  Ty = getEffectiveSCEVType(Ty);
1459  Constant *C;
1460  if (Val == 0)
1461    C = Constant::getNullValue(Ty);
1462  else if (Ty->isFloatingPoint())
1463    C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1464                                APFloat::IEEEdouble, Val));
1465  else
1466    C = ConstantInt::get(Ty, Val);
1467  return getUnknown(C);
1468}
1469
1470/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1471///
1472SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
1473  if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1474    return getUnknown(ConstantExpr::getNeg(VC->getValue()));
1475
1476  const Type *Ty = V->getType();
1477  Ty = getEffectiveSCEVType(Ty);
1478  return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
1479}
1480
1481/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1482SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
1483  if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1484    return getUnknown(ConstantExpr::getNot(VC->getValue()));
1485
1486  const Type *Ty = V->getType();
1487  Ty = getEffectiveSCEVType(Ty);
1488  SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
1489  return getMinusSCEV(AllOnes, V);
1490}
1491
1492/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1493///
1494SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
1495                                         const SCEVHandle &RHS) {
1496  // X - Y --> X + -Y
1497  return getAddExpr(LHS, getNegativeSCEV(RHS));
1498}
1499
1500/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1501/// input value to the specified type.  If the type must be extended, it is zero
1502/// extended.
1503SCEVHandle
1504ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
1505                                         const Type *Ty) {
1506  const Type *SrcTy = V->getType();
1507  assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1508         (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1509         "Cannot truncate or zero extend with non-integer arguments!");
1510  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1511    return V;  // No conversion
1512  if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
1513    return getTruncateExpr(V, Ty);
1514  return getZeroExtendExpr(V, Ty);
1515}
1516
1517/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1518/// input value to the specified type.  If the type must be extended, it is sign
1519/// extended.
1520SCEVHandle
1521ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
1522                                         const Type *Ty) {
1523  const Type *SrcTy = V->getType();
1524  assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1525         (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1526         "Cannot truncate or zero extend with non-integer arguments!");
1527  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1528    return V;  // No conversion
1529  if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
1530    return getTruncateExpr(V, Ty);
1531  return getSignExtendExpr(V, Ty);
1532}
1533
1534/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1535/// the specified instruction and replaces any references to the symbolic value
1536/// SymName with the specified value.  This is used during PHI resolution.
1537void ScalarEvolution::
1538ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1539                                 const SCEVHandle &NewVal) {
1540  std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1541  if (SI == Scalars.end()) return;
1542
1543  SCEVHandle NV =
1544    SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
1545  if (NV == SI->second) return;  // No change.
1546
1547  SI->second = NV;       // Update the scalars map!
1548
1549  // Any instruction values that use this instruction might also need to be
1550  // updated!
1551  for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1552       UI != E; ++UI)
1553    ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1554}
1555
1556/// createNodeForPHI - PHI nodes have two cases.  Either the PHI node exists in
1557/// a loop header, making it a potential recurrence, or it doesn't.
1558///
1559SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
1560  if (PN->getNumIncomingValues() == 2)  // The loops have been canonicalized.
1561    if (const Loop *L = LI->getLoopFor(PN->getParent()))
1562      if (L->getHeader() == PN->getParent()) {
1563        // If it lives in the loop header, it has two incoming values, one
1564        // from outside the loop, and one from inside.
1565        unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1566        unsigned BackEdge     = IncomingEdge^1;
1567
1568        // While we are analyzing this PHI node, handle its value symbolically.
1569        SCEVHandle SymbolicName = getUnknown(PN);
1570        assert(Scalars.find(PN) == Scalars.end() &&
1571               "PHI node already processed?");
1572        Scalars.insert(std::make_pair(PN, SymbolicName));
1573
1574        // Using this symbolic name for the PHI, analyze the value coming around
1575        // the back-edge.
1576        SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1577
1578        // NOTE: If BEValue is loop invariant, we know that the PHI node just
1579        // has a special value for the first iteration of the loop.
1580
1581        // If the value coming around the backedge is an add with the symbolic
1582        // value we just inserted, then we found a simple induction variable!
1583        if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1584          // If there is a single occurrence of the symbolic value, replace it
1585          // with a recurrence.
1586          unsigned FoundIndex = Add->getNumOperands();
1587          for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1588            if (Add->getOperand(i) == SymbolicName)
1589              if (FoundIndex == e) {
1590                FoundIndex = i;
1591                break;
1592              }
1593
1594          if (FoundIndex != Add->getNumOperands()) {
1595            // Create an add with everything but the specified operand.
1596            std::vector<SCEVHandle> Ops;
1597            for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1598              if (i != FoundIndex)
1599                Ops.push_back(Add->getOperand(i));
1600            SCEVHandle Accum = getAddExpr(Ops);
1601
1602            // This is not a valid addrec if the step amount is varying each
1603            // loop iteration, but is not itself an addrec in this loop.
1604            if (Accum->isLoopInvariant(L) ||
1605                (isa<SCEVAddRecExpr>(Accum) &&
1606                 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1607              SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1608              SCEVHandle PHISCEV  = getAddRecExpr(StartVal, Accum, L);
1609
1610              // Okay, for the entire analysis of this edge we assumed the PHI
1611              // to be symbolic.  We now need to go back and update all of the
1612              // entries for the scalars that use the PHI (except for the PHI
1613              // itself) to use the new analyzed value instead of the "symbolic"
1614              // value.
1615              ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1616              return PHISCEV;
1617            }
1618          }
1619        } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1620          // Otherwise, this could be a loop like this:
1621          //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
1622          // In this case, j = {1,+,1}  and BEValue is j.
1623          // Because the other in-value of i (0) fits the evolution of BEValue
1624          // i really is an addrec evolution.
1625          if (AddRec->getLoop() == L && AddRec->isAffine()) {
1626            SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1627
1628            // If StartVal = j.start - j.stride, we can use StartVal as the
1629            // initial step of the addrec evolution.
1630            if (StartVal == getMinusSCEV(AddRec->getOperand(0),
1631                                            AddRec->getOperand(1))) {
1632              SCEVHandle PHISCEV =
1633                 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
1634
1635              // Okay, for the entire analysis of this edge we assumed the PHI
1636              // to be symbolic.  We now need to go back and update all of the
1637              // entries for the scalars that use the PHI (except for the PHI
1638              // itself) to use the new analyzed value instead of the "symbolic"
1639              // value.
1640              ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1641              return PHISCEV;
1642            }
1643          }
1644        }
1645
1646        return SymbolicName;
1647      }
1648
1649  // If it's not a loop phi, we can't handle it yet.
1650  return getUnknown(PN);
1651}
1652
1653/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1654/// guaranteed to end in (at every loop iteration).  It is, at the same time,
1655/// the minimum number of times S is divisible by 2.  For example, given {4,+,8}
1656/// it returns 2.  If S is guaranteed to be 0, it returns the bitwidth of S.
1657static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
1658  if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
1659    return C->getValue()->getValue().countTrailingZeros();
1660
1661  if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1662    return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1663                    (uint32_t)SE.getTypeSizeInBits(T->getType()));
1664
1665  if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1666    uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1667    return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1668             SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
1669  }
1670
1671  if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1672    uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1673    return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1674             SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
1675  }
1676
1677  if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1678    // The result is the min of all operands results.
1679    uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
1680    for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1681      MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
1682    return MinOpRes;
1683  }
1684
1685  if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1686    // The result is the sum of all operands results.
1687    uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1688    uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
1689    for (unsigned i = 1, e = M->getNumOperands();
1690         SumOpRes != BitWidth && i != e; ++i)
1691      SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
1692                          BitWidth);
1693    return SumOpRes;
1694  }
1695
1696  if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
1697    // The result is the min of all operands results.
1698    uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
1699    for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1700      MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
1701    return MinOpRes;
1702  }
1703
1704  if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1705    // The result is the min of all operands results.
1706    uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1707    for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1708      MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
1709    return MinOpRes;
1710  }
1711
1712  if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1713    // The result is the min of all operands results.
1714    uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1715    for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1716      MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
1717    return MinOpRes;
1718  }
1719
1720  // SCEVUDivExpr, SCEVUnknown
1721  return 0;
1722}
1723
1724/// createSCEV - We know that there is no SCEV for the specified value.
1725/// Analyze the expression.
1726///
1727SCEVHandle ScalarEvolution::createSCEV(Value *V) {
1728  if (!isSCEVable(V->getType()))
1729    return getUnknown(V);
1730
1731  unsigned Opcode = Instruction::UserOp1;
1732  if (Instruction *I = dyn_cast<Instruction>(V))
1733    Opcode = I->getOpcode();
1734  else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1735    Opcode = CE->getOpcode();
1736  else
1737    return getUnknown(V);
1738
1739  User *U = cast<User>(V);
1740  switch (Opcode) {
1741  case Instruction::Add:
1742    return getAddExpr(getSCEV(U->getOperand(0)),
1743                      getSCEV(U->getOperand(1)));
1744  case Instruction::Mul:
1745    return getMulExpr(getSCEV(U->getOperand(0)),
1746                      getSCEV(U->getOperand(1)));
1747  case Instruction::UDiv:
1748    return getUDivExpr(getSCEV(U->getOperand(0)),
1749                       getSCEV(U->getOperand(1)));
1750  case Instruction::Sub:
1751    return getMinusSCEV(getSCEV(U->getOperand(0)),
1752                        getSCEV(U->getOperand(1)));
1753  case Instruction::And:
1754    // For an expression like x&255 that merely masks off the high bits,
1755    // use zext(trunc(x)) as the SCEV expression.
1756    if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1757      const APInt &A = CI->getValue();
1758      unsigned Ones = A.countTrailingOnes();
1759      if (APIntOps::isMask(Ones, A))
1760        return
1761          getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
1762                                            IntegerType::get(Ones)),
1763                            U->getType());
1764    }
1765    break;
1766  case Instruction::Or:
1767    // If the RHS of the Or is a constant, we may have something like:
1768    // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
1769    // optimizations will transparently handle this case.
1770    //
1771    // In order for this transformation to be safe, the LHS must be of the
1772    // form X*(2^n) and the Or constant must be less than 2^n.
1773    if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1774      SCEVHandle LHS = getSCEV(U->getOperand(0));
1775      const APInt &CIVal = CI->getValue();
1776      if (GetMinTrailingZeros(LHS, *this) >=
1777          (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1778        return getAddExpr(LHS, getSCEV(U->getOperand(1)));
1779    }
1780    break;
1781  case Instruction::Xor:
1782    if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1783      // If the RHS of the xor is a signbit, then this is just an add.
1784      // Instcombine turns add of signbit into xor as a strength reduction step.
1785      if (CI->getValue().isSignBit())
1786        return getAddExpr(getSCEV(U->getOperand(0)),
1787                          getSCEV(U->getOperand(1)));
1788
1789      // If the RHS of xor is -1, then this is a not operation.
1790      else if (CI->isAllOnesValue())
1791        return getNotSCEV(getSCEV(U->getOperand(0)));
1792    }
1793    break;
1794
1795  case Instruction::Shl:
1796    // Turn shift left of a constant amount into a multiply.
1797    if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1798      uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1799      Constant *X = ConstantInt::get(
1800        APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1801      return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1802    }
1803    break;
1804
1805  case Instruction::LShr:
1806    // Turn logical shift right of a constant into a unsigned divide.
1807    if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1808      uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1809      Constant *X = ConstantInt::get(
1810        APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1811      return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1812    }
1813    break;
1814
1815  case Instruction::AShr:
1816    // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
1817    if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
1818      if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
1819        if (L->getOpcode() == Instruction::Shl &&
1820            L->getOperand(1) == U->getOperand(1)) {
1821          uint64_t Amt = getTypeSizeInBits(U->getType()) - CI->getZExtValue();
1822          return
1823            getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
1824                                                    IntegerType::get(Amt)),
1825                                 U->getType());
1826        }
1827    break;
1828
1829  case Instruction::Trunc:
1830    return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1831
1832  case Instruction::ZExt:
1833    return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1834
1835  case Instruction::SExt:
1836    return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1837
1838  case Instruction::BitCast:
1839    // BitCasts are no-op casts so we just eliminate the cast.
1840    if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
1841      return getSCEV(U->getOperand(0));
1842    break;
1843
1844  case Instruction::IntToPtr:
1845    if (!TD) break; // Without TD we can't analyze pointers.
1846    return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1847                                   TD->getIntPtrType());
1848
1849  case Instruction::PtrToInt:
1850    if (!TD) break; // Without TD we can't analyze pointers.
1851    return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1852                                   U->getType());
1853
1854  case Instruction::GetElementPtr: {
1855    if (!TD) break; // Without TD we can't analyze pointers.
1856    const Type *IntPtrTy = TD->getIntPtrType();
1857    Value *Base = U->getOperand(0);
1858    SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
1859    gep_type_iterator GTI = gep_type_begin(U);
1860    for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
1861                                        E = U->op_end();
1862         I != E; ++I) {
1863      Value *Index = *I;
1864      // Compute the (potentially symbolic) offset in bytes for this index.
1865      if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1866        // For a struct, add the member offset.
1867        const StructLayout &SL = *TD->getStructLayout(STy);
1868        unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1869        uint64_t Offset = SL.getElementOffset(FieldNo);
1870        TotalOffset = getAddExpr(TotalOffset,
1871                                    getIntegerSCEV(Offset, IntPtrTy));
1872      } else {
1873        // For an array, add the element offset, explicitly scaled.
1874        SCEVHandle LocalOffset = getSCEV(Index);
1875        if (!isa<PointerType>(LocalOffset->getType()))
1876          // Getelementptr indicies are signed.
1877          LocalOffset = getTruncateOrSignExtend(LocalOffset,
1878                                                IntPtrTy);
1879        LocalOffset =
1880          getMulExpr(LocalOffset,
1881                     getIntegerSCEV(TD->getTypePaddedSize(*GTI),
1882                                    IntPtrTy));
1883        TotalOffset = getAddExpr(TotalOffset, LocalOffset);
1884      }
1885    }
1886    return getAddExpr(getSCEV(Base), TotalOffset);
1887  }
1888
1889  case Instruction::PHI:
1890    return createNodeForPHI(cast<PHINode>(U));
1891
1892  case Instruction::Select:
1893    // This could be a smax or umax that was lowered earlier.
1894    // Try to recover it.
1895    if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1896      Value *LHS = ICI->getOperand(0);
1897      Value *RHS = ICI->getOperand(1);
1898      switch (ICI->getPredicate()) {
1899      case ICmpInst::ICMP_SLT:
1900      case ICmpInst::ICMP_SLE:
1901        std::swap(LHS, RHS);
1902        // fall through
1903      case ICmpInst::ICMP_SGT:
1904      case ICmpInst::ICMP_SGE:
1905        if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1906          return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1907        else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1908          // ~smax(~x, ~y) == smin(x, y).
1909          return getNotSCEV(getSMaxExpr(
1910                                   getNotSCEV(getSCEV(LHS)),
1911                                   getNotSCEV(getSCEV(RHS))));
1912        break;
1913      case ICmpInst::ICMP_ULT:
1914      case ICmpInst::ICMP_ULE:
1915        std::swap(LHS, RHS);
1916        // fall through
1917      case ICmpInst::ICMP_UGT:
1918      case ICmpInst::ICMP_UGE:
1919        if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1920          return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1921        else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1922          // ~umax(~x, ~y) == umin(x, y)
1923          return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
1924                                        getNotSCEV(getSCEV(RHS))));
1925        break;
1926      default:
1927        break;
1928      }
1929    }
1930
1931  default: // We cannot analyze this expression.
1932    break;
1933  }
1934
1935  return getUnknown(V);
1936}
1937
1938
1939
1940//===----------------------------------------------------------------------===//
1941//                   Iteration Count Computation Code
1942//
1943
1944/// getBackedgeTakenCount - If the specified loop has a predictable
1945/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
1946/// object. The backedge-taken count is the number of times the loop header
1947/// will be branched to from within the loop. This is one less than the
1948/// trip count of the loop, since it doesn't count the first iteration,
1949/// when the header is branched to from outside the loop.
1950///
1951/// Note that it is not valid to call this method on a loop without a
1952/// loop-invariant backedge-taken count (see
1953/// hasLoopInvariantBackedgeTakenCount).
1954///
1955SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
1956  std::map<const Loop*, SCEVHandle>::iterator I = BackedgeTakenCounts.find(L);
1957  if (I == BackedgeTakenCounts.end()) {
1958    SCEVHandle ItCount = ComputeBackedgeTakenCount(L);
1959    I = BackedgeTakenCounts.insert(std::make_pair(L, ItCount)).first;
1960    if (ItCount != UnknownValue) {
1961      assert(ItCount->isLoopInvariant(L) &&
1962             "Computed trip count isn't loop invariant for loop!");
1963      ++NumTripCountsComputed;
1964    } else if (isa<PHINode>(L->getHeader()->begin())) {
1965      // Only count loops that have phi nodes as not being computable.
1966      ++NumTripCountsNotComputed;
1967    }
1968  }
1969  return I->second;
1970}
1971
1972/// forgetLoopBackedgeTakenCount - This method should be called by the
1973/// client when it has changed a loop in a way that may effect
1974/// ScalarEvolution's ability to compute a trip count, or if the loop
1975/// is deleted.
1976void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
1977  BackedgeTakenCounts.erase(L);
1978}
1979
1980/// ComputeBackedgeTakenCount - Compute the number of times the backedge
1981/// of the specified loop will execute.
1982SCEVHandle ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
1983  // If the loop has a non-one exit block count, we can't analyze it.
1984  SmallVector<BasicBlock*, 8> ExitBlocks;
1985  L->getExitBlocks(ExitBlocks);
1986  if (ExitBlocks.size() != 1) return UnknownValue;
1987
1988  // Okay, there is one exit block.  Try to find the condition that causes the
1989  // loop to be exited.
1990  BasicBlock *ExitBlock = ExitBlocks[0];
1991
1992  BasicBlock *ExitingBlock = 0;
1993  for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1994       PI != E; ++PI)
1995    if (L->contains(*PI)) {
1996      if (ExitingBlock == 0)
1997        ExitingBlock = *PI;
1998      else
1999        return UnknownValue;   // More than one block exiting!
2000    }
2001  assert(ExitingBlock && "No exits from loop, something is broken!");
2002
2003  // Okay, we've computed the exiting block.  See what condition causes us to
2004  // exit.
2005  //
2006  // FIXME: we should be able to handle switch instructions (with a single exit)
2007  BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2008  if (ExitBr == 0) return UnknownValue;
2009  assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2010
2011  // At this point, we know we have a conditional branch that determines whether
2012  // the loop is exited.  However, we don't know if the branch is executed each
2013  // time through the loop.  If not, then the execution count of the branch will
2014  // not be equal to the trip count of the loop.
2015  //
2016  // Currently we check for this by checking to see if the Exit branch goes to
2017  // the loop header.  If so, we know it will always execute the same number of
2018  // times as the loop.  We also handle the case where the exit block *is* the
2019  // loop header.  This is common for un-rotated loops.  More extensive analysis
2020  // could be done to handle more cases here.
2021  if (ExitBr->getSuccessor(0) != L->getHeader() &&
2022      ExitBr->getSuccessor(1) != L->getHeader() &&
2023      ExitBr->getParent() != L->getHeader())
2024    return UnknownValue;
2025
2026  ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2027
2028  // If it's not an integer comparison then compute it the hard way.
2029  // Note that ICmpInst deals with pointer comparisons too so we must check
2030  // the type of the operand.
2031  if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
2032    return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
2033                                          ExitBr->getSuccessor(0) == ExitBlock);
2034
2035  // If the condition was exit on true, convert the condition to exit on false
2036  ICmpInst::Predicate Cond;
2037  if (ExitBr->getSuccessor(1) == ExitBlock)
2038    Cond = ExitCond->getPredicate();
2039  else
2040    Cond = ExitCond->getInversePredicate();
2041
2042  // Handle common loops like: for (X = "string"; *X; ++X)
2043  if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2044    if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2045      SCEVHandle ItCnt =
2046        ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
2047      if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2048    }
2049
2050  SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2051  SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2052
2053  // Try to evaluate any dependencies out of the loop.
2054  SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2055  if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2056  Tmp = getSCEVAtScope(RHS, L);
2057  if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2058
2059  // At this point, we would like to compute how many iterations of the
2060  // loop the predicate will return true for these inputs.
2061  if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2062    // If there is a loop-invariant, force it into the RHS.
2063    std::swap(LHS, RHS);
2064    Cond = ICmpInst::getSwappedPredicate(Cond);
2065  }
2066
2067  // If we have a comparison of a chrec against a constant, try to use value
2068  // ranges to answer this query.
2069  if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2070    if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2071      if (AddRec->getLoop() == L) {
2072        // Form the comparison range using the constant of the correct type so
2073        // that the ConstantRange class knows to do a signed or unsigned
2074        // comparison.
2075        ConstantInt *CompVal = RHSC->getValue();
2076        const Type *RealTy = ExitCond->getOperand(0)->getType();
2077        CompVal = dyn_cast<ConstantInt>(
2078          ConstantExpr::getBitCast(CompVal, RealTy));
2079        if (CompVal) {
2080          // Form the constant range.
2081          ConstantRange CompRange(
2082              ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2083
2084          SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
2085          if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2086        }
2087      }
2088
2089  switch (Cond) {
2090  case ICmpInst::ICMP_NE: {                     // while (X != Y)
2091    // Convert to: while (X-Y != 0)
2092    SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
2093    if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2094    break;
2095  }
2096  case ICmpInst::ICMP_EQ: {
2097    // Convert to: while (X-Y == 0)           // while (X == Y)
2098    SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
2099    if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2100    break;
2101  }
2102  case ICmpInst::ICMP_SLT: {
2103    SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
2104    if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2105    break;
2106  }
2107  case ICmpInst::ICMP_SGT: {
2108    SCEVHandle TC = HowManyLessThans(getNotSCEV(LHS),
2109                                     getNotSCEV(RHS), L, true);
2110    if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2111    break;
2112  }
2113  case ICmpInst::ICMP_ULT: {
2114    SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
2115    if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2116    break;
2117  }
2118  case ICmpInst::ICMP_UGT: {
2119    SCEVHandle TC = HowManyLessThans(getNotSCEV(LHS),
2120                                     getNotSCEV(RHS), L, false);
2121    if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2122    break;
2123  }
2124  default:
2125#if 0
2126    errs() << "ComputeBackedgeTakenCount ";
2127    if (ExitCond->getOperand(0)->getType()->isUnsigned())
2128      errs() << "[unsigned] ";
2129    errs() << *LHS << "   "
2130         << Instruction::getOpcodeName(Instruction::ICmp)
2131         << "   " << *RHS << "\n";
2132#endif
2133    break;
2134  }
2135  return
2136    ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2137                                          ExitBr->getSuccessor(0) == ExitBlock);
2138}
2139
2140static ConstantInt *
2141EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2142                                ScalarEvolution &SE) {
2143  SCEVHandle InVal = SE.getConstant(C);
2144  SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
2145  assert(isa<SCEVConstant>(Val) &&
2146         "Evaluation of SCEV at constant didn't fold correctly?");
2147  return cast<SCEVConstant>(Val)->getValue();
2148}
2149
2150/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2151/// and a GEP expression (missing the pointer index) indexing into it, return
2152/// the addressed element of the initializer or null if the index expression is
2153/// invalid.
2154static Constant *
2155GetAddressedElementFromGlobal(GlobalVariable *GV,
2156                              const std::vector<ConstantInt*> &Indices) {
2157  Constant *Init = GV->getInitializer();
2158  for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2159    uint64_t Idx = Indices[i]->getZExtValue();
2160    if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2161      assert(Idx < CS->getNumOperands() && "Bad struct index!");
2162      Init = cast<Constant>(CS->getOperand(Idx));
2163    } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2164      if (Idx >= CA->getNumOperands()) return 0;  // Bogus program
2165      Init = cast<Constant>(CA->getOperand(Idx));
2166    } else if (isa<ConstantAggregateZero>(Init)) {
2167      if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2168        assert(Idx < STy->getNumElements() && "Bad struct index!");
2169        Init = Constant::getNullValue(STy->getElementType(Idx));
2170      } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2171        if (Idx >= ATy->getNumElements()) return 0;  // Bogus program
2172        Init = Constant::getNullValue(ATy->getElementType());
2173      } else {
2174        assert(0 && "Unknown constant aggregate type!");
2175      }
2176      return 0;
2177    } else {
2178      return 0; // Unknown initializer type
2179    }
2180  }
2181  return Init;
2182}
2183
2184/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2185/// 'icmp op load X, cst', try to see if we can compute the backedge
2186/// execution count.
2187SCEVHandle ScalarEvolution::
2188ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2189                                             const Loop *L,
2190                                             ICmpInst::Predicate predicate) {
2191  if (LI->isVolatile()) return UnknownValue;
2192
2193  // Check to see if the loaded pointer is a getelementptr of a global.
2194  GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2195  if (!GEP) return UnknownValue;
2196
2197  // Make sure that it is really a constant global we are gepping, with an
2198  // initializer, and make sure the first IDX is really 0.
2199  GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2200  if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2201      GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2202      !cast<Constant>(GEP->getOperand(1))->isNullValue())
2203    return UnknownValue;
2204
2205  // Okay, we allow one non-constant index into the GEP instruction.
2206  Value *VarIdx = 0;
2207  std::vector<ConstantInt*> Indexes;
2208  unsigned VarIdxNum = 0;
2209  for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2210    if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2211      Indexes.push_back(CI);
2212    } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2213      if (VarIdx) return UnknownValue;  // Multiple non-constant idx's.
2214      VarIdx = GEP->getOperand(i);
2215      VarIdxNum = i-2;
2216      Indexes.push_back(0);
2217    }
2218
2219  // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2220  // Check to see if X is a loop variant variable value now.
2221  SCEVHandle Idx = getSCEV(VarIdx);
2222  SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2223  if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2224
2225  // We can only recognize very limited forms of loop index expressions, in
2226  // particular, only affine AddRec's like {C1,+,C2}.
2227  SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2228  if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2229      !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2230      !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2231    return UnknownValue;
2232
2233  unsigned MaxSteps = MaxBruteForceIterations;
2234  for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2235    ConstantInt *ItCst =
2236      ConstantInt::get(IdxExpr->getType(), IterationNum);
2237    ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
2238
2239    // Form the GEP offset.
2240    Indexes[VarIdxNum] = Val;
2241
2242    Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2243    if (Result == 0) break;  // Cannot compute!
2244
2245    // Evaluate the condition for this iteration.
2246    Result = ConstantExpr::getICmp(predicate, Result, RHS);
2247    if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
2248    if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2249#if 0
2250      errs() << "\n***\n*** Computed loop count " << *ItCst
2251             << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2252             << "***\n";
2253#endif
2254      ++NumArrayLenItCounts;
2255      return getConstant(ItCst);   // Found terminating iteration!
2256    }
2257  }
2258  return UnknownValue;
2259}
2260
2261
2262/// CanConstantFold - Return true if we can constant fold an instruction of the
2263/// specified type, assuming that all operands were constants.
2264static bool CanConstantFold(const Instruction *I) {
2265  if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2266      isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2267    return true;
2268
2269  if (const CallInst *CI = dyn_cast<CallInst>(I))
2270    if (const Function *F = CI->getCalledFunction())
2271      return canConstantFoldCallTo(F);
2272  return false;
2273}
2274
2275/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2276/// in the loop that V is derived from.  We allow arbitrary operations along the
2277/// way, but the operands of an operation must either be constants or a value
2278/// derived from a constant PHI.  If this expression does not fit with these
2279/// constraints, return null.
2280static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2281  // If this is not an instruction, or if this is an instruction outside of the
2282  // loop, it can't be derived from a loop PHI.
2283  Instruction *I = dyn_cast<Instruction>(V);
2284  if (I == 0 || !L->contains(I->getParent())) return 0;
2285
2286  if (PHINode *PN = dyn_cast<PHINode>(I)) {
2287    if (L->getHeader() == I->getParent())
2288      return PN;
2289    else
2290      // We don't currently keep track of the control flow needed to evaluate
2291      // PHIs, so we cannot handle PHIs inside of loops.
2292      return 0;
2293  }
2294
2295  // If we won't be able to constant fold this expression even if the operands
2296  // are constants, return early.
2297  if (!CanConstantFold(I)) return 0;
2298
2299  // Otherwise, we can evaluate this instruction if all of its operands are
2300  // constant or derived from a PHI node themselves.
2301  PHINode *PHI = 0;
2302  for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2303    if (!(isa<Constant>(I->getOperand(Op)) ||
2304          isa<GlobalValue>(I->getOperand(Op)))) {
2305      PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2306      if (P == 0) return 0;  // Not evolving from PHI
2307      if (PHI == 0)
2308        PHI = P;
2309      else if (PHI != P)
2310        return 0;  // Evolving from multiple different PHIs.
2311    }
2312
2313  // This is a expression evolving from a constant PHI!
2314  return PHI;
2315}
2316
2317/// EvaluateExpression - Given an expression that passes the
2318/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2319/// in the loop has the value PHIVal.  If we can't fold this expression for some
2320/// reason, return null.
2321static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2322  if (isa<PHINode>(V)) return PHIVal;
2323  if (Constant *C = dyn_cast<Constant>(V)) return C;
2324  if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
2325  Instruction *I = cast<Instruction>(V);
2326
2327  std::vector<Constant*> Operands;
2328  Operands.resize(I->getNumOperands());
2329
2330  for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2331    Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2332    if (Operands[i] == 0) return 0;
2333  }
2334
2335  if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2336    return ConstantFoldCompareInstOperands(CI->getPredicate(),
2337                                           &Operands[0], Operands.size());
2338  else
2339    return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2340                                    &Operands[0], Operands.size());
2341}
2342
2343/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2344/// in the header of its containing loop, we know the loop executes a
2345/// constant number of times, and the PHI node is just a recurrence
2346/// involving constants, fold it.
2347Constant *ScalarEvolution::
2348getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
2349  std::map<PHINode*, Constant*>::iterator I =
2350    ConstantEvolutionLoopExitValue.find(PN);
2351  if (I != ConstantEvolutionLoopExitValue.end())
2352    return I->second;
2353
2354  if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
2355    return ConstantEvolutionLoopExitValue[PN] = 0;  // Not going to evaluate it.
2356
2357  Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2358
2359  // Since the loop is canonicalized, the PHI node must have two entries.  One
2360  // entry must be a constant (coming in from outside of the loop), and the
2361  // second must be derived from the same PHI.
2362  bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2363  Constant *StartCST =
2364    dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2365  if (StartCST == 0)
2366    return RetVal = 0;  // Must be a constant.
2367
2368  Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2369  PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2370  if (PN2 != PN)
2371    return RetVal = 0;  // Not derived from same PHI.
2372
2373  // Execute the loop symbolically to determine the exit value.
2374  if (BEs.getActiveBits() >= 32)
2375    return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2376
2377  unsigned NumIterations = BEs.getZExtValue(); // must be in range
2378  unsigned IterationNum = 0;
2379  for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2380    if (IterationNum == NumIterations)
2381      return RetVal = PHIVal;  // Got exit value!
2382
2383    // Compute the value of the PHI node for the next iteration.
2384    Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2385    if (NextPHI == PHIVal)
2386      return RetVal = NextPHI;  // Stopped evolving!
2387    if (NextPHI == 0)
2388      return 0;        // Couldn't evaluate!
2389    PHIVal = NextPHI;
2390  }
2391}
2392
2393/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
2394/// constant number of times (the condition evolves only from constants),
2395/// try to evaluate a few iterations of the loop until we get the exit
2396/// condition gets a value of ExitWhen (true or false).  If we cannot
2397/// evaluate the trip count of the loop, return UnknownValue.
2398SCEVHandle ScalarEvolution::
2399ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2400  PHINode *PN = getConstantEvolvingPHI(Cond, L);
2401  if (PN == 0) return UnknownValue;
2402
2403  // Since the loop is canonicalized, the PHI node must have two entries.  One
2404  // entry must be a constant (coming in from outside of the loop), and the
2405  // second must be derived from the same PHI.
2406  bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2407  Constant *StartCST =
2408    dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2409  if (StartCST == 0) return UnknownValue;  // Must be a constant.
2410
2411  Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2412  PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2413  if (PN2 != PN) return UnknownValue;  // Not derived from same PHI.
2414
2415  // Okay, we find a PHI node that defines the trip count of this loop.  Execute
2416  // the loop symbolically to determine when the condition gets a value of
2417  // "ExitWhen".
2418  unsigned IterationNum = 0;
2419  unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
2420  for (Constant *PHIVal = StartCST;
2421       IterationNum != MaxIterations; ++IterationNum) {
2422    ConstantInt *CondVal =
2423      dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2424
2425    // Couldn't symbolically evaluate.
2426    if (!CondVal) return UnknownValue;
2427
2428    if (CondVal->getValue() == uint64_t(ExitWhen)) {
2429      ConstantEvolutionLoopExitValue[PN] = PHIVal;
2430      ++NumBruteForceTripCountsComputed;
2431      return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
2432    }
2433
2434    // Compute the value of the PHI node for the next iteration.
2435    Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2436    if (NextPHI == 0 || NextPHI == PHIVal)
2437      return UnknownValue;  // Couldn't evaluate or not making progress...
2438    PHIVal = NextPHI;
2439  }
2440
2441  // Too many iterations were needed to evaluate.
2442  return UnknownValue;
2443}
2444
2445/// getSCEVAtScope - Compute the value of the specified expression within the
2446/// indicated loop (which may be null to indicate in no loop).  If the
2447/// expression cannot be evaluated, return UnknownValue.
2448SCEVHandle ScalarEvolution::getSCEVAtScope(SCEV *V, const Loop *L) {
2449  // FIXME: this should be turned into a virtual method on SCEV!
2450
2451  if (isa<SCEVConstant>(V)) return V;
2452
2453  // If this instruction is evolved from a constant-evolving PHI, compute the
2454  // exit value from the loop without using SCEVs.
2455  if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2456    if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2457      const Loop *LI = (*this->LI)[I->getParent()];
2458      if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
2459        if (PHINode *PN = dyn_cast<PHINode>(I))
2460          if (PN->getParent() == LI->getHeader()) {
2461            // Okay, there is no closed form solution for the PHI node.  Check
2462            // to see if the loop that contains it has a known backedge-taken
2463            // count.  If so, we may be able to force computation of the exit
2464            // value.
2465            SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2466            if (SCEVConstant *BTCC =
2467                  dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
2468              // Okay, we know how many times the containing loop executes.  If
2469              // this is a constant evolving PHI node, get the final value at
2470              // the specified iteration number.
2471              Constant *RV = getConstantEvolutionLoopExitValue(PN,
2472                                                   BTCC->getValue()->getValue(),
2473                                                               LI);
2474              if (RV) return getUnknown(RV);
2475            }
2476          }
2477
2478      // Okay, this is an expression that we cannot symbolically evaluate
2479      // into a SCEV.  Check to see if it's possible to symbolically evaluate
2480      // the arguments into constants, and if so, try to constant propagate the
2481      // result.  This is particularly useful for computing loop exit values.
2482      if (CanConstantFold(I)) {
2483        std::vector<Constant*> Operands;
2484        Operands.reserve(I->getNumOperands());
2485        for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2486          Value *Op = I->getOperand(i);
2487          if (Constant *C = dyn_cast<Constant>(Op)) {
2488            Operands.push_back(C);
2489          } else {
2490            // If any of the operands is non-constant and if they are
2491            // non-integer and non-pointer, don't even try to analyze them
2492            // with scev techniques.
2493            if (!isa<IntegerType>(Op->getType()) &&
2494                !isa<PointerType>(Op->getType()))
2495              return V;
2496
2497            SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2498            if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2499              Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2500                                                              Op->getType(),
2501                                                              false));
2502            else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2503              if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2504                Operands.push_back(ConstantExpr::getIntegerCast(C,
2505                                                                Op->getType(),
2506                                                                false));
2507              else
2508                return V;
2509            } else {
2510              return V;
2511            }
2512          }
2513        }
2514
2515        Constant *C;
2516        if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2517          C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2518                                              &Operands[0], Operands.size());
2519        else
2520          C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2521                                       &Operands[0], Operands.size());
2522        return getUnknown(C);
2523      }
2524    }
2525
2526    // This is some other type of SCEVUnknown, just return it.
2527    return V;
2528  }
2529
2530  if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2531    // Avoid performing the look-up in the common case where the specified
2532    // expression has no loop-variant portions.
2533    for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2534      SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2535      if (OpAtScope != Comm->getOperand(i)) {
2536        if (OpAtScope == UnknownValue) return UnknownValue;
2537        // Okay, at least one of these operands is loop variant but might be
2538        // foldable.  Build a new instance of the folded commutative expression.
2539        std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2540        NewOps.push_back(OpAtScope);
2541
2542        for (++i; i != e; ++i) {
2543          OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2544          if (OpAtScope == UnknownValue) return UnknownValue;
2545          NewOps.push_back(OpAtScope);
2546        }
2547        if (isa<SCEVAddExpr>(Comm))
2548          return getAddExpr(NewOps);
2549        if (isa<SCEVMulExpr>(Comm))
2550          return getMulExpr(NewOps);
2551        if (isa<SCEVSMaxExpr>(Comm))
2552          return getSMaxExpr(NewOps);
2553        if (isa<SCEVUMaxExpr>(Comm))
2554          return getUMaxExpr(NewOps);
2555        assert(0 && "Unknown commutative SCEV type!");
2556      }
2557    }
2558    // If we got here, all operands are loop invariant.
2559    return Comm;
2560  }
2561
2562  if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2563    SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2564    if (LHS == UnknownValue) return LHS;
2565    SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2566    if (RHS == UnknownValue) return RHS;
2567    if (LHS == Div->getLHS() && RHS == Div->getRHS())
2568      return Div;   // must be loop invariant
2569    return getUDivExpr(LHS, RHS);
2570  }
2571
2572  // If this is a loop recurrence for a loop that does not contain L, then we
2573  // are dealing with the final value computed by the loop.
2574  if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2575    if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2576      // To evaluate this recurrence, we need to know how many times the AddRec
2577      // loop iterates.  Compute this now.
2578      SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2579      if (BackedgeTakenCount == UnknownValue) return UnknownValue;
2580
2581      // Then, evaluate the AddRec.
2582      return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
2583    }
2584    return UnknownValue;
2585  }
2586
2587  //assert(0 && "Unknown SCEV type!");
2588  return UnknownValue;
2589}
2590
2591/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2592/// at the specified scope in the program.  The L value specifies a loop
2593/// nest to evaluate the expression at, where null is the top-level or a
2594/// specified loop is immediately inside of the loop.
2595///
2596/// This method can be used to compute the exit value for a variable defined
2597/// in a loop by querying what the value will hold in the parent loop.
2598///
2599/// If this value is not computable at this scope, a SCEVCouldNotCompute
2600/// object is returned.
2601SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2602  return getSCEVAtScope(getSCEV(V), L);
2603}
2604
2605/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2606/// following equation:
2607///
2608///     A * X = B (mod N)
2609///
2610/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2611/// A and B isn't important.
2612///
2613/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2614static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2615                                               ScalarEvolution &SE) {
2616  uint32_t BW = A.getBitWidth();
2617  assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2618  assert(A != 0 && "A must be non-zero.");
2619
2620  // 1. D = gcd(A, N)
2621  //
2622  // The gcd of A and N may have only one prime factor: 2. The number of
2623  // trailing zeros in A is its multiplicity
2624  uint32_t Mult2 = A.countTrailingZeros();
2625  // D = 2^Mult2
2626
2627  // 2. Check if B is divisible by D.
2628  //
2629  // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2630  // is not less than multiplicity of this prime factor for D.
2631  if (B.countTrailingZeros() < Mult2)
2632    return SE.getCouldNotCompute();
2633
2634  // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2635  // modulo (N / D).
2636  //
2637  // (N / D) may need BW+1 bits in its representation.  Hence, we'll use this
2638  // bit width during computations.
2639  APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
2640  APInt Mod(BW + 1, 0);
2641  Mod.set(BW - Mult2);  // Mod = N / D
2642  APInt I = AD.multiplicativeInverse(Mod);
2643
2644  // 4. Compute the minimum unsigned root of the equation:
2645  // I * (B / D) mod (N / D)
2646  APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2647
2648  // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2649  // bits.
2650  return SE.getConstant(Result.trunc(BW));
2651}
2652
2653/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2654/// given quadratic chrec {L,+,M,+,N}.  This returns either the two roots (which
2655/// might be the same) or two SCEVCouldNotCompute objects.
2656///
2657static std::pair<SCEVHandle,SCEVHandle>
2658SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
2659  assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2660  SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2661  SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2662  SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2663
2664  // We currently can only solve this if the coefficients are constants.
2665  if (!LC || !MC || !NC) {
2666    SCEV *CNC = SE.getCouldNotCompute();
2667    return std::make_pair(CNC, CNC);
2668  }
2669
2670  uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2671  const APInt &L = LC->getValue()->getValue();
2672  const APInt &M = MC->getValue()->getValue();
2673  const APInt &N = NC->getValue()->getValue();
2674  APInt Two(BitWidth, 2);
2675  APInt Four(BitWidth, 4);
2676
2677  {
2678    using namespace APIntOps;
2679    const APInt& C = L;
2680    // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2681    // The B coefficient is M-N/2
2682    APInt B(M);
2683    B -= sdiv(N,Two);
2684
2685    // The A coefficient is N/2
2686    APInt A(N.sdiv(Two));
2687
2688    // Compute the B^2-4ac term.
2689    APInt SqrtTerm(B);
2690    SqrtTerm *= B;
2691    SqrtTerm -= Four * (A * C);
2692
2693    // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2694    // integer value or else APInt::sqrt() will assert.
2695    APInt SqrtVal(SqrtTerm.sqrt());
2696
2697    // Compute the two solutions for the quadratic formula.
2698    // The divisions must be performed as signed divisions.
2699    APInt NegB(-B);
2700    APInt TwoA( A << 1 );
2701    if (TwoA.isMinValue()) {
2702      SCEV *CNC = SE.getCouldNotCompute();
2703      return std::make_pair(CNC, CNC);
2704    }
2705
2706    ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2707    ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2708
2709    return std::make_pair(SE.getConstant(Solution1),
2710                          SE.getConstant(Solution2));
2711    } // end APIntOps namespace
2712}
2713
2714/// HowFarToZero - Return the number of times a backedge comparing the specified
2715/// value to zero will execute.  If not computable, return UnknownValue
2716SCEVHandle ScalarEvolution::HowFarToZero(SCEV *V, const Loop *L) {
2717  // If the value is a constant
2718  if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2719    // If the value is already zero, the branch will execute zero times.
2720    if (C->getValue()->isZero()) return C;
2721    return UnknownValue;  // Otherwise it will loop infinitely.
2722  }
2723
2724  SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2725  if (!AddRec || AddRec->getLoop() != L)
2726    return UnknownValue;
2727
2728  if (AddRec->isAffine()) {
2729    // If this is an affine expression, the execution count of this branch is
2730    // the minimum unsigned root of the following equation:
2731    //
2732    //     Start + Step*N = 0 (mod 2^BW)
2733    //
2734    // equivalent to:
2735    //
2736    //             Step*N = -Start (mod 2^BW)
2737    //
2738    // where BW is the common bit width of Start and Step.
2739
2740    // Get the initial value for the loop.
2741    SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2742    if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2743
2744    SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
2745
2746    if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2747      // For now we handle only constant steps.
2748
2749      // First, handle unitary steps.
2750      if (StepC->getValue()->equalsInt(1))      // 1*N = -Start (mod 2^BW), so:
2751        return getNegativeSCEV(Start);       //   N = -Start (as unsigned)
2752      if (StepC->getValue()->isAllOnesValue())  // -1*N = -Start (mod 2^BW), so:
2753        return Start;                           //    N = Start (as unsigned)
2754
2755      // Then, try to solve the above equation provided that Start is constant.
2756      if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2757        return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2758                                            -StartC->getValue()->getValue(),
2759                                            *this);
2760    }
2761  } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2762    // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2763    // the quadratic equation to solve it.
2764    std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
2765                                                                    *this);
2766    SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2767    SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2768    if (R1) {
2769#if 0
2770      errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2771             << "  sol#2: " << *R2 << "\n";
2772#endif
2773      // Pick the smallest positive root value.
2774      if (ConstantInt *CB =
2775          dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2776                                   R1->getValue(), R2->getValue()))) {
2777        if (CB->getZExtValue() == false)
2778          std::swap(R1, R2);   // R1 is the minimum root now.
2779
2780        // We can only use this value if the chrec ends up with an exact zero
2781        // value at this index.  When solving for "X*X != 5", for example, we
2782        // should not accept a root of 2.
2783        SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
2784        if (Val->isZero())
2785          return R1;  // We found a quadratic root!
2786      }
2787    }
2788  }
2789
2790  return UnknownValue;
2791}
2792
2793/// HowFarToNonZero - Return the number of times a backedge checking the
2794/// specified value for nonzero will execute.  If not computable, return
2795/// UnknownValue
2796SCEVHandle ScalarEvolution::HowFarToNonZero(SCEV *V, const Loop *L) {
2797  // Loops that look like: while (X == 0) are very strange indeed.  We don't
2798  // handle them yet except for the trivial case.  This could be expanded in the
2799  // future as needed.
2800
2801  // If the value is a constant, check to see if it is known to be non-zero
2802  // already.  If so, the backedge will execute zero times.
2803  if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2804    if (!C->getValue()->isNullValue())
2805      return getIntegerSCEV(0, C->getType());
2806    return UnknownValue;  // Otherwise it will loop infinitely.
2807  }
2808
2809  // We could implement others, but I really doubt anyone writes loops like
2810  // this, and if they did, they would already be constant folded.
2811  return UnknownValue;
2812}
2813
2814/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2815/// (which may not be an immediate predecessor) which has exactly one
2816/// successor from which BB is reachable, or null if no such block is
2817/// found.
2818///
2819BasicBlock *
2820ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2821  // If the block has a unique predecessor, the predecessor must have
2822  // no other successors from which BB is reachable.
2823  if (BasicBlock *Pred = BB->getSinglePredecessor())
2824    return Pred;
2825
2826  // A loop's header is defined to be a block that dominates the loop.
2827  // If the loop has a preheader, it must be a block that has exactly
2828  // one successor that can reach BB. This is slightly more strict
2829  // than necessary, but works if critical edges are split.
2830  if (Loop *L = LI->getLoopFor(BB))
2831    return L->getLoopPreheader();
2832
2833  return 0;
2834}
2835
2836/// isLoopGuardedByCond - Test whether entry to the loop is protected by
2837/// a conditional between LHS and RHS.
2838bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
2839                                               ICmpInst::Predicate Pred,
2840                                               SCEV *LHS, SCEV *RHS) {
2841  BasicBlock *Preheader = L->getLoopPreheader();
2842  BasicBlock *PreheaderDest = L->getHeader();
2843
2844  // Starting at the preheader, climb up the predecessor chain, as long as
2845  // there are predecessors that can be found that have unique successors
2846  // leading to the original header.
2847  for (; Preheader;
2848       PreheaderDest = Preheader,
2849       Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
2850
2851    BranchInst *LoopEntryPredicate =
2852      dyn_cast<BranchInst>(Preheader->getTerminator());
2853    if (!LoopEntryPredicate ||
2854        LoopEntryPredicate->isUnconditional())
2855      continue;
2856
2857    ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2858    if (!ICI) continue;
2859
2860    // Now that we found a conditional branch that dominates the loop, check to
2861    // see if it is the comparison we are looking for.
2862    Value *PreCondLHS = ICI->getOperand(0);
2863    Value *PreCondRHS = ICI->getOperand(1);
2864    ICmpInst::Predicate Cond;
2865    if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2866      Cond = ICI->getPredicate();
2867    else
2868      Cond = ICI->getInversePredicate();
2869
2870    if (Cond == Pred)
2871      ; // An exact match.
2872    else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
2873      ; // The actual condition is beyond sufficient.
2874    else
2875      // Check a few special cases.
2876      switch (Cond) {
2877      case ICmpInst::ICMP_UGT:
2878        if (Pred == ICmpInst::ICMP_ULT) {
2879          std::swap(PreCondLHS, PreCondRHS);
2880          Cond = ICmpInst::ICMP_ULT;
2881          break;
2882        }
2883        continue;
2884      case ICmpInst::ICMP_SGT:
2885        if (Pred == ICmpInst::ICMP_SLT) {
2886          std::swap(PreCondLHS, PreCondRHS);
2887          Cond = ICmpInst::ICMP_SLT;
2888          break;
2889        }
2890        continue;
2891      case ICmpInst::ICMP_NE:
2892        // Expressions like (x >u 0) are often canonicalized to (x != 0),
2893        // so check for this case by checking if the NE is comparing against
2894        // a minimum or maximum constant.
2895        if (!ICmpInst::isTrueWhenEqual(Pred))
2896          if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
2897            const APInt &A = CI->getValue();
2898            switch (Pred) {
2899            case ICmpInst::ICMP_SLT:
2900              if (A.isMaxSignedValue()) break;
2901              continue;
2902            case ICmpInst::ICMP_SGT:
2903              if (A.isMinSignedValue()) break;
2904              continue;
2905            case ICmpInst::ICMP_ULT:
2906              if (A.isMaxValue()) break;
2907              continue;
2908            case ICmpInst::ICMP_UGT:
2909              if (A.isMinValue()) break;
2910              continue;
2911            default:
2912              continue;
2913            }
2914            Cond = ICmpInst::ICMP_NE;
2915            // NE is symmetric but the original comparison may not be. Swap
2916            // the operands if necessary so that they match below.
2917            if (isa<SCEVConstant>(LHS))
2918              std::swap(PreCondLHS, PreCondRHS);
2919            break;
2920          }
2921        continue;
2922      default:
2923        // We weren't able to reconcile the condition.
2924        continue;
2925      }
2926
2927    if (!PreCondLHS->getType()->isInteger()) continue;
2928
2929    SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2930    SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2931    if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
2932        (LHS == getNotSCEV(PreCondRHSSCEV) &&
2933         RHS == getNotSCEV(PreCondLHSSCEV)))
2934      return true;
2935  }
2936
2937  return false;
2938}
2939
2940/// HowManyLessThans - Return the number of times a backedge containing the
2941/// specified less-than comparison will execute.  If not computable, return
2942/// UnknownValue.
2943SCEVHandle ScalarEvolution::
2944HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
2945  // Only handle:  "ADDREC < LoopInvariant".
2946  if (!RHS->isLoopInvariant(L)) return UnknownValue;
2947
2948  SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2949  if (!AddRec || AddRec->getLoop() != L)
2950    return UnknownValue;
2951
2952  if (AddRec->isAffine()) {
2953    // FORNOW: We only support unit strides.
2954    SCEVHandle One = getIntegerSCEV(1, RHS->getType());
2955    if (AddRec->getOperand(1) != One)
2956      return UnknownValue;
2957
2958    // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2959    // m.  So, we count the number of iterations in which {n,+,1} < m is true.
2960    // Note that we cannot simply return max(m-n,0) because it's not safe to
2961    // treat m-n as signed nor unsigned due to overflow possibility.
2962
2963    // First, we get the value of the LHS in the first iteration: n
2964    SCEVHandle Start = AddRec->getOperand(0);
2965
2966    if (isLoopGuardedByCond(L,
2967                            isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2968                            getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
2969      // Since we know that the condition is true in order to enter the loop,
2970      // we know that it will run exactly m-n times.
2971      return getMinusSCEV(RHS, Start);
2972    } else {
2973      // Then, we get the value of the LHS in the first iteration in which the
2974      // above condition doesn't hold.  This equals to max(m,n).
2975      SCEVHandle End = isSigned ? getSMaxExpr(RHS, Start)
2976                                : getUMaxExpr(RHS, Start);
2977
2978      // Finally, we subtract these two values to get the number of times the
2979      // backedge is executed: max(m,n)-n.
2980      return getMinusSCEV(End, Start);
2981    }
2982  }
2983
2984  return UnknownValue;
2985}
2986
2987/// getNumIterationsInRange - Return the number of iterations of this loop that
2988/// produce values in the specified constant range.  Another way of looking at
2989/// this is that it returns the first iteration number where the value is not in
2990/// the condition, thus computing the exit count. If the iteration count can't
2991/// be computed, an instance of SCEVCouldNotCompute is returned.
2992SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2993                                                   ScalarEvolution &SE) const {
2994  if (Range.isFullSet())  // Infinite loop.
2995    return SE.getCouldNotCompute();
2996
2997  // If the start is a non-zero constant, shift the range to simplify things.
2998  if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2999    if (!SC->getValue()->isZero()) {
3000      std::vector<SCEVHandle> Operands(op_begin(), op_end());
3001      Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3002      SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
3003      if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3004        return ShiftedAddRec->getNumIterationsInRange(
3005                           Range.subtract(SC->getValue()->getValue()), SE);
3006      // This is strange and shouldn't happen.
3007      return SE.getCouldNotCompute();
3008    }
3009
3010  // The only time we can solve this is when we have all constant indices.
3011  // Otherwise, we cannot determine the overflow conditions.
3012  for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3013    if (!isa<SCEVConstant>(getOperand(i)))
3014      return SE.getCouldNotCompute();
3015
3016
3017  // Okay at this point we know that all elements of the chrec are constants and
3018  // that the start element is zero.
3019
3020  // First check to see if the range contains zero.  If not, the first
3021  // iteration exits.
3022  unsigned BitWidth = SE.getTypeSizeInBits(getType());
3023  if (!Range.contains(APInt(BitWidth, 0)))
3024    return SE.getConstant(ConstantInt::get(getType(),0));
3025
3026  if (isAffine()) {
3027    // If this is an affine expression then we have this situation:
3028    //   Solve {0,+,A} in Range  ===  Ax in Range
3029
3030    // We know that zero is in the range.  If A is positive then we know that
3031    // the upper value of the range must be the first possible exit value.
3032    // If A is negative then the lower of the range is the last possible loop
3033    // value.  Also note that we already checked for a full range.
3034    APInt One(BitWidth,1);
3035    APInt A     = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3036    APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3037
3038    // The exit value should be (End+A)/A.
3039    APInt ExitVal = (End + A).udiv(A);
3040    ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3041
3042    // Evaluate at the exit value.  If we really did fall out of the valid
3043    // range, then we computed our trip count, otherwise wrap around or other
3044    // things must have happened.
3045    ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
3046    if (Range.contains(Val->getValue()))
3047      return SE.getCouldNotCompute();  // Something strange happened
3048
3049    // Ensure that the previous value is in the range.  This is a sanity check.
3050    assert(Range.contains(
3051           EvaluateConstantChrecAtConstant(this,
3052           ConstantInt::get(ExitVal - One), SE)->getValue()) &&
3053           "Linear scev computation is off in a bad way!");
3054    return SE.getConstant(ExitValue);
3055  } else if (isQuadratic()) {
3056    // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3057    // quadratic equation to solve it.  To do this, we must frame our problem in
3058    // terms of figuring out when zero is crossed, instead of when
3059    // Range.getUpper() is crossed.
3060    std::vector<SCEVHandle> NewOps(op_begin(), op_end());
3061    NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3062    SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
3063
3064    // Next, solve the constructed addrec
3065    std::pair<SCEVHandle,SCEVHandle> Roots =
3066      SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
3067    SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3068    SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3069    if (R1) {
3070      // Pick the smallest positive root value.
3071      if (ConstantInt *CB =
3072          dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3073                                   R1->getValue(), R2->getValue()))) {
3074        if (CB->getZExtValue() == false)
3075          std::swap(R1, R2);   // R1 is the minimum root now.
3076
3077        // Make sure the root is not off by one.  The returned iteration should
3078        // not be in the range, but the previous one should be.  When solving
3079        // for "X*X < 5", for example, we should not return a root of 2.
3080        ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
3081                                                             R1->getValue(),
3082                                                             SE);
3083        if (Range.contains(R1Val->getValue())) {
3084          // The next iteration must be out of the range...
3085          ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3086
3087          R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3088          if (!Range.contains(R1Val->getValue()))
3089            return SE.getConstant(NextVal);
3090          return SE.getCouldNotCompute();  // Something strange happened
3091        }
3092
3093        // If R1 was not in the range, then it is a good return value.  Make
3094        // sure that R1-1 WAS in the range though, just in case.
3095        ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
3096        R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
3097        if (Range.contains(R1Val->getValue()))
3098          return R1;
3099        return SE.getCouldNotCompute();  // Something strange happened
3100      }
3101    }
3102  }
3103
3104  return SE.getCouldNotCompute();
3105}
3106
3107
3108
3109//===----------------------------------------------------------------------===//
3110//                   ScalarEvolution Class Implementation
3111//===----------------------------------------------------------------------===//
3112
3113ScalarEvolution::ScalarEvolution()
3114  : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3115}
3116
3117bool ScalarEvolution::runOnFunction(Function &F) {
3118  this->F = &F;
3119  LI = &getAnalysis<LoopInfo>();
3120  TD = getAnalysisIfAvailable<TargetData>();
3121  return false;
3122}
3123
3124void ScalarEvolution::releaseMemory() {
3125  Scalars.clear();
3126  BackedgeTakenCounts.clear();
3127  ConstantEvolutionLoopExitValue.clear();
3128}
3129
3130void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3131  AU.setPreservesAll();
3132  AU.addRequiredTransitive<LoopInfo>();
3133}
3134
3135bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
3136  return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
3137}
3138
3139static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
3140                          const Loop *L) {
3141  // Print all inner loops first
3142  for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3143    PrintLoopInfo(OS, SE, *I);
3144
3145  OS << "Loop " << L->getHeader()->getName() << ": ";
3146
3147  SmallVector<BasicBlock*, 8> ExitBlocks;
3148  L->getExitBlocks(ExitBlocks);
3149  if (ExitBlocks.size() != 1)
3150    OS << "<multiple exits> ";
3151
3152  if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3153    OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
3154  } else {
3155    OS << "Unpredictable backedge-taken count. ";
3156  }
3157
3158  OS << "\n";
3159}
3160
3161void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
3162  // ScalarEvolution's implementaiton of the print method is to print
3163  // out SCEV values of all instructions that are interesting. Doing
3164  // this potentially causes it to create new SCEV objects though,
3165  // which technically conflicts with the const qualifier. This isn't
3166  // observable from outside the class though (the hasSCEV function
3167  // notwithstanding), so casting away the const isn't dangerous.
3168  ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
3169
3170  OS << "Classifying expressions for: " << F->getName() << "\n";
3171  for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3172    if (I->getType()->isInteger()) {
3173      OS << *I;
3174      OS << "  -->  ";
3175      SCEVHandle SV = SE.getSCEV(&*I);
3176      SV->print(OS);
3177      OS << "\t\t";
3178
3179      if (const Loop *L = LI->getLoopFor((*I).getParent())) {
3180        OS << "Exits: ";
3181        SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
3182        if (isa<SCEVCouldNotCompute>(ExitValue)) {
3183          OS << "<<Unknown>>";
3184        } else {
3185          OS << *ExitValue;
3186        }
3187      }
3188
3189
3190      OS << "\n";
3191    }
3192
3193  OS << "Determining loop execution counts for: " << F->getName() << "\n";
3194  for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3195    PrintLoopInfo(OS, &SE, *I);
3196}
3197
3198void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3199  raw_os_ostream OS(o);
3200  print(OS, M);
3201}
3202