ScalarEvolution.cpp revision b06432c2761ecb84f4149544b56362ac00ef68be
1//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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#include "llvm/Analysis/ScalarEvolutionExpressions.h"
63#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
65#include "llvm/Instructions.h"
66#include "llvm/Type.h"
67#include "llvm/Value.h"
68#include "llvm/Analysis/LoopInfo.h"
69#include "llvm/Assembly/Writer.h"
70#include "llvm/Transforms/Scalar.h"
71#include "llvm/Transforms/Utils/Local.h"
72#include "llvm/Support/CFG.h"
73#include "llvm/Support/ConstantRange.h"
74#include "llvm/Support/InstIterator.h"
75#include "Support/CommandLine.h"
76#include "Support/Statistic.h"
77#include <cmath>
78using namespace llvm;
79
80namespace {
81  RegisterAnalysis<ScalarEvolution>
82  R("scalar-evolution", "Scalar Evolution Analysis");
83
84  Statistic<>
85  NumBruteForceEvaluations("scalar-evolution",
86                           "Number of brute force evaluations needed to calculate high-order polynomial exit values");
87  Statistic<>
88  NumTripCountsComputed("scalar-evolution",
89                        "Number of loops with predictable loop counts");
90  Statistic<>
91  NumTripCountsNotComputed("scalar-evolution",
92                           "Number of loops without predictable loop counts");
93  Statistic<>
94  NumBruteForceTripCountsComputed("scalar-evolution",
95                        "Number of loops with trip counts computed by force");
96
97  cl::opt<unsigned>
98  MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
99                          cl::desc("Maximum number of iterations SCEV will symbolically execute a constant derived loop"),
100                          cl::init(100));
101}
102
103//===----------------------------------------------------------------------===//
104//                           SCEV class definitions
105//===----------------------------------------------------------------------===//
106
107//===----------------------------------------------------------------------===//
108// Implementation of the SCEV class.
109//
110namespace {
111  /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
112  /// than the complexity of the RHS.  If the SCEVs have identical complexity,
113  /// order them by their addresses.  This comparator is used to canonicalize
114  /// expressions.
115  struct SCEVComplexityCompare {
116    bool operator()(SCEV *LHS, SCEV *RHS) {
117      if (LHS->getSCEVType() < RHS->getSCEVType())
118        return true;
119      if (LHS->getSCEVType() == RHS->getSCEVType())
120        return LHS < RHS;
121      return false;
122    }
123  };
124}
125
126SCEV::~SCEV() {}
127void SCEV::dump() const {
128  print(std::cerr);
129}
130
131/// getValueRange - Return the tightest constant bounds that this value is
132/// known to have.  This method is only valid on integer SCEV objects.
133ConstantRange SCEV::getValueRange() const {
134  const Type *Ty = getType();
135  assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
136  Ty = Ty->getUnsignedVersion();
137  // Default to a full range if no better information is available.
138  return ConstantRange(getType());
139}
140
141
142SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
143
144bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
145  assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
146  return false;
147}
148
149const Type *SCEVCouldNotCompute::getType() const {
150  assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
151  return 0;
152}
153
154bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
155  assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
156  return false;
157}
158
159void SCEVCouldNotCompute::print(std::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 std::map<ConstantInt*, SCEVConstant*> SCEVConstants;
172
173
174SCEVConstant::~SCEVConstant() {
175  SCEVConstants.erase(V);
176}
177
178SCEVHandle SCEVConstant::get(ConstantInt *V) {
179  // Make sure that SCEVConstant instances are all unsigned.
180  if (V->getType()->isSigned()) {
181    const Type *NewTy = V->getType()->getUnsignedVersion();
182    V = cast<ConstantUInt>(ConstantExpr::getCast(V, NewTy));
183  }
184
185  SCEVConstant *&R = SCEVConstants[V];
186  if (R == 0) R = new SCEVConstant(V);
187  return R;
188}
189
190ConstantRange SCEVConstant::getValueRange() const {
191  return ConstantRange(V);
192}
193
194const Type *SCEVConstant::getType() const { return V->getType(); }
195
196void SCEVConstant::print(std::ostream &OS) const {
197  WriteAsOperand(OS, V, false);
198}
199
200// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
201// particular input.  Don't use a SCEVHandle here, or else the object will
202// never be deleted!
203static std::map<std::pair<SCEV*, const Type*>, SCEVTruncateExpr*> SCEVTruncates;
204
205SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
206  : SCEV(scTruncate), Op(op), Ty(ty) {
207  assert(Op->getType()->isInteger() && Ty->isInteger() &&
208         Ty->isUnsigned() &&
209         "Cannot truncate non-integer value!");
210  assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
211         "This is not a truncating conversion!");
212}
213
214SCEVTruncateExpr::~SCEVTruncateExpr() {
215  SCEVTruncates.erase(std::make_pair(Op, Ty));
216}
217
218ConstantRange SCEVTruncateExpr::getValueRange() const {
219  return getOperand()->getValueRange().truncate(getType());
220}
221
222void SCEVTruncateExpr::print(std::ostream &OS) const {
223  OS << "(truncate " << *Op << " to " << *Ty << ")";
224}
225
226// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
227// particular input.  Don't use a SCEVHandle here, or else the object will never
228// be deleted!
229static std::map<std::pair<SCEV*, const Type*>,
230                SCEVZeroExtendExpr*> SCEVZeroExtends;
231
232SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
233  : SCEV(scTruncate), Op(Op), Ty(ty) {
234  assert(Op->getType()->isInteger() && Ty->isInteger() &&
235         Ty->isUnsigned() &&
236         "Cannot zero extend non-integer value!");
237  assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
238         "This is not an extending conversion!");
239}
240
241SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
242  SCEVZeroExtends.erase(std::make_pair(Op, Ty));
243}
244
245ConstantRange SCEVZeroExtendExpr::getValueRange() const {
246  return getOperand()->getValueRange().zeroExtend(getType());
247}
248
249void SCEVZeroExtendExpr::print(std::ostream &OS) const {
250  OS << "(zeroextend " << *Op << " to " << *Ty << ")";
251}
252
253// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
254// particular input.  Don't use a SCEVHandle here, or else the object will never
255// be deleted!
256static std::map<std::pair<unsigned, std::vector<SCEV*> >,
257                SCEVCommutativeExpr*> SCEVCommExprs;
258
259SCEVCommutativeExpr::~SCEVCommutativeExpr() {
260  SCEVCommExprs.erase(std::make_pair(getSCEVType(),
261                                     std::vector<SCEV*>(Operands.begin(),
262                                                        Operands.end())));
263}
264
265void SCEVCommutativeExpr::print(std::ostream &OS) const {
266  assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
267  const char *OpStr = getOperationStr();
268  OS << "(" << *Operands[0];
269  for (unsigned i = 1, e = Operands.size(); i != e; ++i)
270    OS << OpStr << *Operands[i];
271  OS << ")";
272}
273
274// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
275// input.  Don't use a SCEVHandle here, or else the object will never be
276// deleted!
277static std::map<std::pair<SCEV*, SCEV*>, SCEVUDivExpr*> SCEVUDivs;
278
279SCEVUDivExpr::~SCEVUDivExpr() {
280  SCEVUDivs.erase(std::make_pair(LHS, RHS));
281}
282
283void SCEVUDivExpr::print(std::ostream &OS) const {
284  OS << "(" << *LHS << " /u " << *RHS << ")";
285}
286
287const Type *SCEVUDivExpr::getType() const {
288  const Type *Ty = LHS->getType();
289  if (Ty->isSigned()) Ty = Ty->getUnsignedVersion();
290  return Ty;
291}
292
293// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
294// particular input.  Don't use a SCEVHandle here, or else the object will never
295// be deleted!
296static std::map<std::pair<const Loop *, std::vector<SCEV*> >,
297                SCEVAddRecExpr*> SCEVAddRecExprs;
298
299SCEVAddRecExpr::~SCEVAddRecExpr() {
300  SCEVAddRecExprs.erase(std::make_pair(L,
301                                       std::vector<SCEV*>(Operands.begin(),
302                                                          Operands.end())));
303}
304
305bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
306  // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
307  // contain L.
308  return !QueryLoop->contains(L->getHeader());
309}
310
311
312void SCEVAddRecExpr::print(std::ostream &OS) const {
313  OS << "{" << *Operands[0];
314  for (unsigned i = 1, e = Operands.size(); i != e; ++i)
315    OS << ",+," << *Operands[i];
316  OS << "}<" << L->getHeader()->getName() + ">";
317}
318
319// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
320// value.  Don't use a SCEVHandle here, or else the object will never be
321// deleted!
322static std::map<Value*, SCEVUnknown*> SCEVUnknowns;
323
324SCEVUnknown::~SCEVUnknown() { SCEVUnknowns.erase(V); }
325
326bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
327  // All non-instruction values are loop invariant.  All instructions are loop
328  // invariant if they are not contained in the specified loop.
329  if (Instruction *I = dyn_cast<Instruction>(V))
330    return !L->contains(I->getParent());
331  return true;
332}
333
334const Type *SCEVUnknown::getType() const {
335  return V->getType();
336}
337
338void SCEVUnknown::print(std::ostream &OS) const {
339  WriteAsOperand(OS, V, false);
340}
341
342
343
344//===----------------------------------------------------------------------===//
345//                      Simple SCEV method implementations
346//===----------------------------------------------------------------------===//
347
348/// getIntegerSCEV - Given an integer or FP type, create a constant for the
349/// specified signed integer value and return a SCEV for the constant.
350SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
351  Constant *C;
352  if (Val == 0)
353    C = Constant::getNullValue(Ty);
354  else if (Ty->isFloatingPoint())
355    C = ConstantFP::get(Ty, Val);
356  else if (Ty->isSigned())
357    C = ConstantSInt::get(Ty, Val);
358  else {
359    C = ConstantSInt::get(Ty->getSignedVersion(), Val);
360    C = ConstantExpr::getCast(C, Ty);
361  }
362  return SCEVUnknown::get(C);
363}
364
365/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
366/// input value to the specified type.  If the type must be extended, it is zero
367/// extended.
368static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
369  const Type *SrcTy = V->getType();
370  assert(SrcTy->isInteger() && Ty->isInteger() &&
371         "Cannot truncate or zero extend with non-integer arguments!");
372  if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
373    return V;  // No conversion
374  if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
375    return SCEVTruncateExpr::get(V, Ty);
376  return SCEVZeroExtendExpr::get(V, Ty);
377}
378
379/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
380///
381static SCEVHandle getNegativeSCEV(const SCEVHandle &V) {
382  if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
383    return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
384
385  return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
386}
387
388/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
389///
390static SCEVHandle getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
391  // X - Y --> X + -Y
392  return SCEVAddExpr::get(LHS, getNegativeSCEV(RHS));
393}
394
395
396/// Binomial - Evaluate N!/((N-M)!*M!)  .  Note that N is often large and M is
397/// often very small, so we try to reduce the number of N! terms we need to
398/// evaluate by evaluating this as  (N!/(N-M)!)/M!
399static ConstantInt *Binomial(ConstantInt *N, unsigned M) {
400  uint64_t NVal = N->getRawValue();
401  uint64_t FirstTerm = 1;
402  for (unsigned i = 0; i != M; ++i)
403    FirstTerm *= NVal-i;
404
405  unsigned MFactorial = 1;
406  for (; M; --M)
407    MFactorial *= M;
408
409  Constant *Result = ConstantUInt::get(Type::ULongTy, FirstTerm/MFactorial);
410  Result = ConstantExpr::getCast(Result, N->getType());
411  assert(isa<ConstantInt>(Result) && "Cast of integer not folded??");
412  return cast<ConstantInt>(Result);
413}
414
415/// PartialFact - Compute V!/(V-NumSteps)!
416static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
417  // Handle this case efficiently, it is common to have constant iteration
418  // counts while computing loop exit values.
419  if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
420    uint64_t Val = SC->getValue()->getRawValue();
421    uint64_t Result = 1;
422    for (; NumSteps; --NumSteps)
423      Result *= Val-(NumSteps-1);
424    Constant *Res = ConstantUInt::get(Type::ULongTy, Result);
425    return SCEVUnknown::get(ConstantExpr::getCast(Res, V->getType()));
426  }
427
428  const Type *Ty = V->getType();
429  if (NumSteps == 0)
430    return SCEVUnknown::getIntegerSCEV(1, Ty);
431
432  SCEVHandle Result = V;
433  for (unsigned i = 1; i != NumSteps; ++i)
434    Result = SCEVMulExpr::get(Result, getMinusSCEV(V,
435                                          SCEVUnknown::getIntegerSCEV(i, Ty)));
436  return Result;
437}
438
439
440/// evaluateAtIteration - Return the value of this chain of recurrences at
441/// the specified iteration number.  We can evaluate this recurrence by
442/// multiplying each element in the chain by the binomial coefficient
443/// corresponding to it.  In other words, we can evaluate {A,+,B,+,C,+,D} as:
444///
445///   A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
446///
447/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
448/// Is the binomial equation safe using modular arithmetic??
449///
450SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
451  SCEVHandle Result = getStart();
452  int Divisor = 1;
453  const Type *Ty = It->getType();
454  for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
455    SCEVHandle BC = PartialFact(It, i);
456    Divisor *= i;
457    SCEVHandle Val = SCEVUDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
458                                       SCEVUnknown::getIntegerSCEV(Divisor,Ty));
459    Result = SCEVAddExpr::get(Result, Val);
460  }
461  return Result;
462}
463
464
465//===----------------------------------------------------------------------===//
466//                    SCEV Expression folder implementations
467//===----------------------------------------------------------------------===//
468
469SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
470  if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
471    return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
472
473  // If the input value is a chrec scev made out of constants, truncate
474  // all of the constants.
475  if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
476    std::vector<SCEVHandle> Operands;
477    for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
478      // FIXME: This should allow truncation of other expression types!
479      if (isa<SCEVConstant>(AddRec->getOperand(i)))
480        Operands.push_back(get(AddRec->getOperand(i), Ty));
481      else
482        break;
483    if (Operands.size() == AddRec->getNumOperands())
484      return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
485  }
486
487  SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
488  if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
489  return Result;
490}
491
492SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
493  if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
494    return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
495
496  // FIXME: If the input value is a chrec scev, and we can prove that the value
497  // did not overflow the old, smaller, value, we can zero extend all of the
498  // operands (often constants).  This would allow analysis of something like
499  // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
500
501  SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
502  if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
503  return Result;
504}
505
506// get - Get a canonical add expression, or something simpler if possible.
507SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
508  assert(!Ops.empty() && "Cannot get empty add!");
509  if (Ops.size() == 1) return Ops[0];
510
511  // Sort by complexity, this groups all similar expression types together.
512  std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
513
514  // If there are any constants, fold them together.
515  unsigned Idx = 0;
516  if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
517    ++Idx;
518    assert(Idx < Ops.size());
519    while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
520      // We found two constants, fold them together!
521      Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
522      if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
523        Ops[0] = SCEVConstant::get(CI);
524        Ops.erase(Ops.begin()+1);  // Erase the folded element
525        if (Ops.size() == 1) return Ops[0];
526      } else {
527        // If we couldn't fold the expression, move to the next constant.  Note
528        // that this is impossible to happen in practice because we always
529        // constant fold constant ints to constant ints.
530        ++Idx;
531      }
532    }
533
534    // If we are left with a constant zero being added, strip it off.
535    if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
536      Ops.erase(Ops.begin());
537      --Idx;
538    }
539  }
540
541  if (Ops.size() == 1) return Ops[0];
542
543  // Okay, check to see if the same value occurs in the operand list twice.  If
544  // so, merge them together into an multiply expression.  Since we sorted the
545  // list, these values are required to be adjacent.
546  const Type *Ty = Ops[0]->getType();
547  for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
548    if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
549      // Found a match, merge the two values into a multiply, and add any
550      // remaining values to the result.
551      SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
552      SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
553      if (Ops.size() == 2)
554        return Mul;
555      Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
556      Ops.push_back(Mul);
557      return SCEVAddExpr::get(Ops);
558    }
559
560  // Okay, now we know the first non-constant operand.  If there are add
561  // operands they would be next.
562  if (Idx < Ops.size()) {
563    bool DeletedAdd = false;
564    while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
565      // If we have an add, expand the add operands onto the end of the operands
566      // list.
567      Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
568      Ops.erase(Ops.begin()+Idx);
569      DeletedAdd = true;
570    }
571
572    // If we deleted at least one add, we added operands to the end of the list,
573    // and they are not necessarily sorted.  Recurse to resort and resimplify
574    // any operands we just aquired.
575    if (DeletedAdd)
576      return get(Ops);
577  }
578
579  // Skip over the add expression until we get to a multiply.
580  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
581    ++Idx;
582
583  // If we are adding something to a multiply expression, make sure the
584  // something is not already an operand of the multiply.  If so, merge it into
585  // the multiply.
586  for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
587    SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
588    for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
589      SCEV *MulOpSCEV = Mul->getOperand(MulOp);
590      for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
591        if (MulOpSCEV == Ops[AddOp] &&
592            (Mul->getNumOperands() != 2 || !isa<SCEVConstant>(MulOpSCEV))) {
593          // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
594          SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
595          if (Mul->getNumOperands() != 2) {
596            // If the multiply has more than two operands, we must get the
597            // Y*Z term.
598            std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
599            MulOps.erase(MulOps.begin()+MulOp);
600            InnerMul = SCEVMulExpr::get(MulOps);
601          }
602          SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
603          SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
604          SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
605          if (Ops.size() == 2) return OuterMul;
606          if (AddOp < Idx) {
607            Ops.erase(Ops.begin()+AddOp);
608            Ops.erase(Ops.begin()+Idx-1);
609          } else {
610            Ops.erase(Ops.begin()+Idx);
611            Ops.erase(Ops.begin()+AddOp-1);
612          }
613          Ops.push_back(OuterMul);
614          return SCEVAddExpr::get(Ops);
615        }
616
617      // Check this multiply against other multiplies being added together.
618      for (unsigned OtherMulIdx = Idx+1;
619           OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
620           ++OtherMulIdx) {
621        SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
622        // If MulOp occurs in OtherMul, we can fold the two multiplies
623        // together.
624        for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
625             OMulOp != e; ++OMulOp)
626          if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
627            // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
628            SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
629            if (Mul->getNumOperands() != 2) {
630              std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
631              MulOps.erase(MulOps.begin()+MulOp);
632              InnerMul1 = SCEVMulExpr::get(MulOps);
633            }
634            SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
635            if (OtherMul->getNumOperands() != 2) {
636              std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
637                                             OtherMul->op_end());
638              MulOps.erase(MulOps.begin()+OMulOp);
639              InnerMul2 = SCEVMulExpr::get(MulOps);
640            }
641            SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
642            SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
643            if (Ops.size() == 2) return OuterMul;
644            Ops.erase(Ops.begin()+Idx);
645            Ops.erase(Ops.begin()+OtherMulIdx-1);
646            Ops.push_back(OuterMul);
647            return SCEVAddExpr::get(Ops);
648          }
649      }
650    }
651  }
652
653  // If there are any add recurrences in the operands list, see if any other
654  // added values are loop invariant.  If so, we can fold them into the
655  // recurrence.
656  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
657    ++Idx;
658
659  // Scan over all recurrences, trying to fold loop invariants into them.
660  for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
661    // Scan all of the other operands to this add and add them to the vector if
662    // they are loop invariant w.r.t. the recurrence.
663    std::vector<SCEVHandle> LIOps;
664    SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
665    for (unsigned i = 0, e = Ops.size(); i != e; ++i)
666      if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
667        LIOps.push_back(Ops[i]);
668        Ops.erase(Ops.begin()+i);
669        --i; --e;
670      }
671
672    // If we found some loop invariants, fold them into the recurrence.
673    if (!LIOps.empty()) {
674      //  NLI + LI + { Start,+,Step}  -->  NLI + { LI+Start,+,Step }
675      LIOps.push_back(AddRec->getStart());
676
677      std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
678      AddRecOps[0] = SCEVAddExpr::get(LIOps);
679
680      SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
681      // If all of the other operands were loop invariant, we are done.
682      if (Ops.size() == 1) return NewRec;
683
684      // Otherwise, add the folded AddRec by the non-liv parts.
685      for (unsigned i = 0;; ++i)
686        if (Ops[i] == AddRec) {
687          Ops[i] = NewRec;
688          break;
689        }
690      return SCEVAddExpr::get(Ops);
691    }
692
693    // Okay, if there weren't any loop invariants to be folded, check to see if
694    // there are multiple AddRec's with the same loop induction variable being
695    // added together.  If so, we can fold them.
696    for (unsigned OtherIdx = Idx+1;
697         OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
698      if (OtherIdx != Idx) {
699        SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
700        if (AddRec->getLoop() == OtherAddRec->getLoop()) {
701          // Other + {A,+,B} + {C,+,D}  -->  Other + {A+C,+,B+D}
702          std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
703          for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
704            if (i >= NewOps.size()) {
705              NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
706                            OtherAddRec->op_end());
707              break;
708            }
709            NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
710          }
711          SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
712
713          if (Ops.size() == 2) return NewAddRec;
714
715          Ops.erase(Ops.begin()+Idx);
716          Ops.erase(Ops.begin()+OtherIdx-1);
717          Ops.push_back(NewAddRec);
718          return SCEVAddExpr::get(Ops);
719        }
720      }
721
722    // Otherwise couldn't fold anything into this recurrence.  Move onto the
723    // next one.
724  }
725
726  // Okay, it looks like we really DO need an add expr.  Check to see if we
727  // already have one, otherwise create a new one.
728  std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
729  SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
730                                                              SCEVOps)];
731  if (Result == 0) Result = new SCEVAddExpr(Ops);
732  return Result;
733}
734
735
736SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
737  assert(!Ops.empty() && "Cannot get empty mul!");
738
739  // Sort by complexity, this groups all similar expression types together.
740  std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
741
742  // If there are any constants, fold them together.
743  unsigned Idx = 0;
744  if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
745
746    // C1*(C2+V) -> C1*C2 + C1*V
747    if (Ops.size() == 2)
748      if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
749        if (Add->getNumOperands() == 2 &&
750            isa<SCEVConstant>(Add->getOperand(0)))
751          return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
752                                  SCEVMulExpr::get(LHSC, Add->getOperand(1)));
753
754
755    ++Idx;
756    while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
757      // We found two constants, fold them together!
758      Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
759      if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
760        Ops[0] = SCEVConstant::get(CI);
761        Ops.erase(Ops.begin()+1);  // Erase the folded element
762        if (Ops.size() == 1) return Ops[0];
763      } else {
764        // If we couldn't fold the expression, move to the next constant.  Note
765        // that this is impossible to happen in practice because we always
766        // constant fold constant ints to constant ints.
767        ++Idx;
768      }
769    }
770
771    // If we are left with a constant one being multiplied, strip it off.
772    if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
773      Ops.erase(Ops.begin());
774      --Idx;
775    } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
776      // If we have a multiply of zero, it will always be zero.
777      return Ops[0];
778    }
779  }
780
781  // Skip over the add expression until we get to a multiply.
782  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
783    ++Idx;
784
785  if (Ops.size() == 1)
786    return Ops[0];
787
788  // If there are mul operands inline them all into this expression.
789  if (Idx < Ops.size()) {
790    bool DeletedMul = false;
791    while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
792      // If we have an mul, expand the mul operands onto the end of the operands
793      // list.
794      Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
795      Ops.erase(Ops.begin()+Idx);
796      DeletedMul = true;
797    }
798
799    // If we deleted at least one mul, we added operands to the end of the list,
800    // and they are not necessarily sorted.  Recurse to resort and resimplify
801    // any operands we just aquired.
802    if (DeletedMul)
803      return get(Ops);
804  }
805
806  // If there are any add recurrences in the operands list, see if any other
807  // added values are loop invariant.  If so, we can fold them into the
808  // recurrence.
809  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
810    ++Idx;
811
812  // Scan over all recurrences, trying to fold loop invariants into them.
813  for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
814    // Scan all of the other operands to this mul and add them to the vector if
815    // they are loop invariant w.r.t. the recurrence.
816    std::vector<SCEVHandle> LIOps;
817    SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
818    for (unsigned i = 0, e = Ops.size(); i != e; ++i)
819      if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
820        LIOps.push_back(Ops[i]);
821        Ops.erase(Ops.begin()+i);
822        --i; --e;
823      }
824
825    // If we found some loop invariants, fold them into the recurrence.
826    if (!LIOps.empty()) {
827      //  NLI * LI * { Start,+,Step}  -->  NLI * { LI*Start,+,LI*Step }
828      std::vector<SCEVHandle> NewOps;
829      NewOps.reserve(AddRec->getNumOperands());
830      if (LIOps.size() == 1) {
831        SCEV *Scale = LIOps[0];
832        for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
833          NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
834      } else {
835        for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
836          std::vector<SCEVHandle> MulOps(LIOps);
837          MulOps.push_back(AddRec->getOperand(i));
838          NewOps.push_back(SCEVMulExpr::get(MulOps));
839        }
840      }
841
842      SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
843
844      // If all of the other operands were loop invariant, we are done.
845      if (Ops.size() == 1) return NewRec;
846
847      // Otherwise, multiply the folded AddRec by the non-liv parts.
848      for (unsigned i = 0;; ++i)
849        if (Ops[i] == AddRec) {
850          Ops[i] = NewRec;
851          break;
852        }
853      return SCEVMulExpr::get(Ops);
854    }
855
856    // Okay, if there weren't any loop invariants to be folded, check to see if
857    // there are multiple AddRec's with the same loop induction variable being
858    // multiplied together.  If so, we can fold them.
859    for (unsigned OtherIdx = Idx+1;
860         OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
861      if (OtherIdx != Idx) {
862        SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
863        if (AddRec->getLoop() == OtherAddRec->getLoop()) {
864          // F * G  -->  {A,+,B} * {C,+,D}  -->  {A*C,+,F*D + G*B + B*D}
865          SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
866          SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
867                                                 G->getStart());
868          SCEVHandle B = F->getStepRecurrence();
869          SCEVHandle D = G->getStepRecurrence();
870          SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
871                                                SCEVMulExpr::get(G, B),
872                                                SCEVMulExpr::get(B, D));
873          SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
874                                                     F->getLoop());
875          if (Ops.size() == 2) return NewAddRec;
876
877          Ops.erase(Ops.begin()+Idx);
878          Ops.erase(Ops.begin()+OtherIdx-1);
879          Ops.push_back(NewAddRec);
880          return SCEVMulExpr::get(Ops);
881        }
882      }
883
884    // Otherwise couldn't fold anything into this recurrence.  Move onto the
885    // next one.
886  }
887
888  // Okay, it looks like we really DO need an mul expr.  Check to see if we
889  // already have one, otherwise create a new one.
890  std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
891  SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
892                                                              SCEVOps)];
893  if (Result == 0) Result = new SCEVMulExpr(Ops);
894  return Result;
895}
896
897SCEVHandle SCEVUDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
898  if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
899    if (RHSC->getValue()->equalsInt(1))
900      return LHS;                            // X /u 1 --> x
901    if (RHSC->getValue()->isAllOnesValue())
902      return getNegativeSCEV(LHS);           // X /u -1  -->  -x
903
904    if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
905      Constant *LHSCV = LHSC->getValue();
906      Constant *RHSCV = RHSC->getValue();
907      if (LHSCV->getType()->isSigned())
908        LHSCV = ConstantExpr::getCast(LHSCV,
909                                      LHSCV->getType()->getUnsignedVersion());
910      if (RHSCV->getType()->isSigned())
911        RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType());
912      return SCEVUnknown::get(ConstantExpr::getDiv(LHSCV, RHSCV));
913    }
914  }
915
916  // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
917
918  SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
919  if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
920  return Result;
921}
922
923
924/// SCEVAddRecExpr::get - Get a add recurrence expression for the
925/// specified loop.  Simplify the expression as much as possible.
926SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
927                               const SCEVHandle &Step, const Loop *L) {
928  std::vector<SCEVHandle> Operands;
929  Operands.push_back(Start);
930  if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
931    if (StepChrec->getLoop() == L) {
932      Operands.insert(Operands.end(), StepChrec->op_begin(),
933                      StepChrec->op_end());
934      return get(Operands, L);
935    }
936
937  Operands.push_back(Step);
938  return get(Operands, L);
939}
940
941/// SCEVAddRecExpr::get - Get a add recurrence expression for the
942/// specified loop.  Simplify the expression as much as possible.
943SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
944                               const Loop *L) {
945  if (Operands.size() == 1) return Operands[0];
946
947  if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
948    if (StepC->getValue()->isNullValue()) {
949      Operands.pop_back();
950      return get(Operands, L);             // { X,+,0 }  -->  X
951    }
952
953  SCEVAddRecExpr *&Result =
954    SCEVAddRecExprs[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
955                                                         Operands.end()))];
956  if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
957  return Result;
958}
959
960SCEVHandle SCEVUnknown::get(Value *V) {
961  if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
962    return SCEVConstant::get(CI);
963  SCEVUnknown *&Result = SCEVUnknowns[V];
964  if (Result == 0) Result = new SCEVUnknown(V);
965  return Result;
966}
967
968
969//===----------------------------------------------------------------------===//
970//             ScalarEvolutionsImpl Definition and Implementation
971//===----------------------------------------------------------------------===//
972//
973/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
974/// evolution code.
975///
976namespace {
977  struct ScalarEvolutionsImpl {
978    /// F - The function we are analyzing.
979    ///
980    Function &F;
981
982    /// LI - The loop information for the function we are currently analyzing.
983    ///
984    LoopInfo &LI;
985
986    /// UnknownValue - This SCEV is used to represent unknown trip counts and
987    /// things.
988    SCEVHandle UnknownValue;
989
990    /// Scalars - This is a cache of the scalars we have analyzed so far.
991    ///
992    std::map<Value*, SCEVHandle> Scalars;
993
994    /// IterationCounts - Cache the iteration count of the loops for this
995    /// function as they are computed.
996    std::map<const Loop*, SCEVHandle> IterationCounts;
997
998    /// ConstantEvolutionLoopExitValue - This map contains entries for all of
999    /// the PHI instructions that we attempt to compute constant evolutions for.
1000    /// This allows us to avoid potentially expensive recomputation of these
1001    /// properties.  An instruction maps to null if we are unable to compute its
1002    /// exit value.
1003    std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1004
1005  public:
1006    ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1007      : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1008
1009    /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1010    /// expression and create a new one.
1011    SCEVHandle getSCEV(Value *V);
1012
1013    /// getSCEVAtScope - Compute the value of the specified expression within
1014    /// the indicated loop (which may be null to indicate in no loop).  If the
1015    /// expression cannot be evaluated, return UnknownValue itself.
1016    SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1017
1018
1019    /// hasLoopInvariantIterationCount - Return true if the specified loop has
1020    /// an analyzable loop-invariant iteration count.
1021    bool hasLoopInvariantIterationCount(const Loop *L);
1022
1023    /// getIterationCount - If the specified loop has a predictable iteration
1024    /// count, return it.  Note that it is not valid to call this method on a
1025    /// loop without a loop-invariant iteration count.
1026    SCEVHandle getIterationCount(const Loop *L);
1027
1028    /// deleteInstructionFromRecords - This method should be called by the
1029    /// client before it removes an instruction from the program, to make sure
1030    /// that no dangling references are left around.
1031    void deleteInstructionFromRecords(Instruction *I);
1032
1033  private:
1034    /// createSCEV - We know that there is no SCEV for the specified value.
1035    /// Analyze the expression.
1036    SCEVHandle createSCEV(Value *V);
1037    SCEVHandle createNodeForCast(CastInst *CI);
1038
1039    /// createNodeForPHI - Provide the special handling we need to analyze PHI
1040    /// SCEVs.
1041    SCEVHandle createNodeForPHI(PHINode *PN);
1042    void UpdatePHIUserScalarEntries(Instruction *I, PHINode *PN,
1043                                    std::set<Instruction*> &UpdatedInsts);
1044
1045    /// ComputeIterationCount - Compute the number of times the specified loop
1046    /// will iterate.
1047    SCEVHandle ComputeIterationCount(const Loop *L);
1048
1049    /// ComputeIterationCountExhaustively - If the trip is known to execute a
1050    /// constant number of times (the condition evolves only from constants),
1051    /// try to evaluate a few iterations of the loop until we get the exit
1052    /// condition gets a value of ExitWhen (true or false).  If we cannot
1053    /// evaluate the trip count of the loop, return UnknownValue.
1054    SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1055                                                 bool ExitWhen);
1056
1057    /// HowFarToZero - Return the number of times a backedge comparing the
1058    /// specified value to zero will execute.  If not computable, return
1059    /// UnknownValue
1060    SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1061
1062    /// HowFarToNonZero - Return the number of times a backedge checking the
1063    /// specified value for nonzero will execute.  If not computable, return
1064    /// UnknownValue
1065    SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1066
1067    /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1068    /// in the header of its containing loop, we know the loop executes a
1069    /// constant number of times, and the PHI node is just a recurrence
1070    /// involving constants, fold it.
1071    Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1072                                                const Loop *L);
1073  };
1074}
1075
1076//===----------------------------------------------------------------------===//
1077//            Basic SCEV Analysis and PHI Idiom Recognition Code
1078//
1079
1080/// deleteInstructionFromRecords - This method should be called by the
1081/// client before it removes an instruction from the program, to make sure
1082/// that no dangling references are left around.
1083void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1084  Scalars.erase(I);
1085  if (PHINode *PN = dyn_cast<PHINode>(I))
1086    ConstantEvolutionLoopExitValue.erase(PN);
1087}
1088
1089
1090/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1091/// expression and create a new one.
1092SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1093  assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1094
1095  std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1096  if (I != Scalars.end()) return I->second;
1097  SCEVHandle S = createSCEV(V);
1098  Scalars.insert(std::make_pair(V, S));
1099  return S;
1100}
1101
1102
1103/// UpdatePHIUserScalarEntries - After PHI node analysis, we have a bunch of
1104/// entries in the scalar map that refer to the "symbolic" PHI value instead of
1105/// the recurrence value.  After we resolve the PHI we must loop over all of the
1106/// using instructions that have scalar map entries and update them.
1107void ScalarEvolutionsImpl::UpdatePHIUserScalarEntries(Instruction *I,
1108                                                      PHINode *PN,
1109                                        std::set<Instruction*> &UpdatedInsts) {
1110  std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1111  if (SI == Scalars.end()) return;   // This scalar wasn't previous processed.
1112  if (UpdatedInsts.insert(I).second) {
1113    Scalars.erase(SI);                 // Remove the old entry
1114    getSCEV(I);                        // Calculate the new entry
1115
1116    for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1117         UI != E; ++UI)
1118      UpdatePHIUserScalarEntries(cast<Instruction>(*UI), PN, UpdatedInsts);
1119  }
1120}
1121
1122
1123/// createNodeForPHI - PHI nodes have two cases.  Either the PHI node exists in
1124/// a loop header, making it a potential recurrence, or it doesn't.
1125///
1126SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1127  if (PN->getNumIncomingValues() == 2)  // The loops have been canonicalized.
1128    if (const Loop *L = LI.getLoopFor(PN->getParent()))
1129      if (L->getHeader() == PN->getParent()) {
1130        // If it lives in the loop header, it has two incoming values, one
1131        // from outside the loop, and one from inside.
1132        unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1133        unsigned BackEdge     = IncomingEdge^1;
1134
1135        // While we are analyzing this PHI node, handle its value symbolically.
1136        SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1137        assert(Scalars.find(PN) == Scalars.end() &&
1138               "PHI node already processed?");
1139        Scalars.insert(std::make_pair(PN, SymbolicName));
1140
1141        // Using this symbolic name for the PHI, analyze the value coming around
1142        // the back-edge.
1143        SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1144
1145        // NOTE: If BEValue is loop invariant, we know that the PHI node just
1146        // has a special value for the first iteration of the loop.
1147
1148        // If the value coming around the backedge is an add with the symbolic
1149        // value we just inserted, then we found a simple induction variable!
1150        if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1151          // If there is a single occurrence of the symbolic value, replace it
1152          // with a recurrence.
1153          unsigned FoundIndex = Add->getNumOperands();
1154          for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1155            if (Add->getOperand(i) == SymbolicName)
1156              if (FoundIndex == e) {
1157                FoundIndex = i;
1158                break;
1159              }
1160
1161          if (FoundIndex != Add->getNumOperands()) {
1162            // Create an add with everything but the specified operand.
1163            std::vector<SCEVHandle> Ops;
1164            for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1165              if (i != FoundIndex)
1166                Ops.push_back(Add->getOperand(i));
1167            SCEVHandle Accum = SCEVAddExpr::get(Ops);
1168
1169            // This is not a valid addrec if the step amount is varying each
1170            // loop iteration, but is not itself an addrec in this loop.
1171            if (Accum->isLoopInvariant(L) ||
1172                (isa<SCEVAddRecExpr>(Accum) &&
1173                 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1174              SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1175              SCEVHandle PHISCEV  = SCEVAddRecExpr::get(StartVal, Accum, L);
1176
1177              // Okay, for the entire analysis of this edge we assumed the PHI
1178              // to be symbolic.  We now need to go back and update all of the
1179              // entries for the scalars that use the PHI (except for the PHI
1180              // itself) to use the new analyzed value instead of the "symbolic"
1181              // value.
1182              Scalars.find(PN)->second = PHISCEV;       // Update the PHI value
1183              std::set<Instruction*> UpdatedInsts;
1184              UpdatedInsts.insert(PN);
1185              for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
1186                   UI != E; ++UI)
1187                UpdatePHIUserScalarEntries(cast<Instruction>(*UI), PN,
1188                                           UpdatedInsts);
1189              return PHISCEV;
1190            }
1191          }
1192        }
1193
1194        return SymbolicName;
1195      }
1196
1197  // If it's not a loop phi, we can't handle it yet.
1198  return SCEVUnknown::get(PN);
1199}
1200
1201/// createNodeForCast - Handle the various forms of casts that we support.
1202///
1203SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) {
1204  const Type *SrcTy = CI->getOperand(0)->getType();
1205  const Type *DestTy = CI->getType();
1206
1207  // If this is a noop cast (ie, conversion from int to uint), ignore it.
1208  if (SrcTy->isLosslesslyConvertibleTo(DestTy))
1209    return getSCEV(CI->getOperand(0));
1210
1211  if (SrcTy->isInteger() && DestTy->isInteger()) {
1212    // Otherwise, if this is a truncating integer cast, we can represent this
1213    // cast.
1214    if (SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1215      return SCEVTruncateExpr::get(getSCEV(CI->getOperand(0)),
1216                                   CI->getType()->getUnsignedVersion());
1217    if (SrcTy->isUnsigned() &&
1218        SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1219      return SCEVZeroExtendExpr::get(getSCEV(CI->getOperand(0)),
1220                                     CI->getType()->getUnsignedVersion());
1221  }
1222
1223  // If this is an sign or zero extending cast and we can prove that the value
1224  // will never overflow, we could do similar transformations.
1225
1226  // Otherwise, we can't handle this cast!
1227  return SCEVUnknown::get(CI);
1228}
1229
1230
1231/// createSCEV - We know that there is no SCEV for the specified value.
1232/// Analyze the expression.
1233///
1234SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1235  if (Instruction *I = dyn_cast<Instruction>(V)) {
1236    switch (I->getOpcode()) {
1237    case Instruction::Add:
1238      return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1239                              getSCEV(I->getOperand(1)));
1240    case Instruction::Mul:
1241      return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1242                              getSCEV(I->getOperand(1)));
1243    case Instruction::Div:
1244      if (V->getType()->isInteger() && V->getType()->isUnsigned())
1245        return SCEVUDivExpr::get(getSCEV(I->getOperand(0)),
1246                                 getSCEV(I->getOperand(1)));
1247      break;
1248
1249    case Instruction::Sub:
1250      return getMinusSCEV(getSCEV(I->getOperand(0)), getSCEV(I->getOperand(1)));
1251
1252    case Instruction::Shl:
1253      // Turn shift left of a constant amount into a multiply.
1254      if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1255        Constant *X = ConstantInt::get(V->getType(), 1);
1256        X = ConstantExpr::getShl(X, SA);
1257        return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1258      }
1259      break;
1260
1261    case Instruction::Shr:
1262      if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1263        if (V->getType()->isUnsigned()) {
1264          Constant *X = ConstantInt::get(V->getType(), 1);
1265          X = ConstantExpr::getShl(X, SA);
1266          return SCEVUDivExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1267        }
1268      break;
1269
1270    case Instruction::Cast:
1271      return createNodeForCast(cast<CastInst>(I));
1272
1273    case Instruction::PHI:
1274      return createNodeForPHI(cast<PHINode>(I));
1275
1276    default: // We cannot analyze this expression.
1277      break;
1278    }
1279  }
1280
1281  return SCEVUnknown::get(V);
1282}
1283
1284
1285
1286//===----------------------------------------------------------------------===//
1287//                   Iteration Count Computation Code
1288//
1289
1290/// getIterationCount - If the specified loop has a predictable iteration
1291/// count, return it.  Note that it is not valid to call this method on a
1292/// loop without a loop-invariant iteration count.
1293SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1294  std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1295  if (I == IterationCounts.end()) {
1296    SCEVHandle ItCount = ComputeIterationCount(L);
1297    I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1298    if (ItCount != UnknownValue) {
1299      assert(ItCount->isLoopInvariant(L) &&
1300             "Computed trip count isn't loop invariant for loop!");
1301      ++NumTripCountsComputed;
1302    } else if (isa<PHINode>(L->getHeader()->begin())) {
1303      // Only count loops that have phi nodes as not being computable.
1304      ++NumTripCountsNotComputed;
1305    }
1306  }
1307  return I->second;
1308}
1309
1310/// ComputeIterationCount - Compute the number of times the specified loop
1311/// will iterate.
1312SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1313  // If the loop has a non-one exit block count, we can't analyze it.
1314  std::vector<BasicBlock*> ExitBlocks;
1315  L->getExitBlocks(ExitBlocks);
1316  if (ExitBlocks.size() != 1) return UnknownValue;
1317
1318  // Okay, there is one exit block.  Try to find the condition that causes the
1319  // loop to be exited.
1320  BasicBlock *ExitBlock = ExitBlocks[0];
1321
1322  BasicBlock *ExitingBlock = 0;
1323  for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1324       PI != E; ++PI)
1325    if (L->contains(*PI)) {
1326      if (ExitingBlock == 0)
1327        ExitingBlock = *PI;
1328      else
1329        return UnknownValue;   // More than one block exiting!
1330    }
1331  assert(ExitingBlock && "No exits from loop, something is broken!");
1332
1333  // Okay, we've computed the exiting block.  See what condition causes us to
1334  // exit.
1335  //
1336  // FIXME: we should be able to handle switch instructions (with a single exit)
1337  // FIXME: We should handle cast of int to bool as well
1338  BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1339  if (ExitBr == 0) return UnknownValue;
1340  assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1341  SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
1342  if (ExitCond == 0)  // Not a setcc
1343    return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1344                                          ExitBr->getSuccessor(0) == ExitBlock);
1345
1346  SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1347  SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1348
1349  // Try to evaluate any dependencies out of the loop.
1350  SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1351  if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1352  Tmp = getSCEVAtScope(RHS, L);
1353  if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1354
1355  // If the condition was exit on true, convert the condition to exit on false.
1356  Instruction::BinaryOps Cond;
1357  if (ExitBr->getSuccessor(1) == ExitBlock)
1358    Cond = ExitCond->getOpcode();
1359  else
1360    Cond = ExitCond->getInverseCondition();
1361
1362  // At this point, we would like to compute how many iterations of the loop the
1363  // predicate will return true for these inputs.
1364  if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1365    // If there is a constant, force it into the RHS.
1366    std::swap(LHS, RHS);
1367    Cond = SetCondInst::getSwappedCondition(Cond);
1368  }
1369
1370  // FIXME: think about handling pointer comparisons!  i.e.:
1371  // while (P != P+100) ++P;
1372
1373  // If we have a comparison of a chrec against a constant, try to use value
1374  // ranges to answer this query.
1375  if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1376    if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1377      if (AddRec->getLoop() == L) {
1378        // Form the comparison range using the constant of the correct type so
1379        // that the ConstantRange class knows to do a signed or unsigned
1380        // comparison.
1381        ConstantInt *CompVal = RHSC->getValue();
1382        const Type *RealTy = ExitCond->getOperand(0)->getType();
1383        CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1384        if (CompVal) {
1385          // Form the constant range.
1386          ConstantRange CompRange(Cond, CompVal);
1387
1388          // Now that we have it, if it's signed, convert it to an unsigned
1389          // range.
1390          if (CompRange.getLower()->getType()->isSigned()) {
1391            const Type *NewTy = RHSC->getValue()->getType();
1392            Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1393            Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1394            CompRange = ConstantRange(NewL, NewU);
1395          }
1396
1397          SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1398          if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1399        }
1400      }
1401
1402  switch (Cond) {
1403  case Instruction::SetNE:                     // while (X != Y)
1404    // Convert to: while (X-Y != 0)
1405    if (LHS->getType()->isInteger()) {
1406      SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
1407      if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1408    }
1409    break;
1410  case Instruction::SetEQ:
1411    // Convert to: while (X-Y == 0)           // while (X == Y)
1412    if (LHS->getType()->isInteger()) {
1413      SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
1414      if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1415    }
1416    break;
1417  default:
1418#if 0
1419    std::cerr << "ComputeIterationCount ";
1420    if (ExitCond->getOperand(0)->getType()->isUnsigned())
1421      std::cerr << "[unsigned] ";
1422    std::cerr << *LHS << "   "
1423              << Instruction::getOpcodeName(Cond) << "   " << *RHS << "\n";
1424#endif
1425    break;
1426  }
1427
1428  return ComputeIterationCountExhaustively(L, ExitCond,
1429                                         ExitBr->getSuccessor(0) == ExitBlock);
1430}
1431
1432/// CanConstantFold - Return true if we can constant fold an instruction of the
1433/// specified type, assuming that all operands were constants.
1434static bool CanConstantFold(const Instruction *I) {
1435  if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1436      isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1437    return true;
1438
1439  if (const CallInst *CI = dyn_cast<CallInst>(I))
1440    if (const Function *F = CI->getCalledFunction())
1441      return canConstantFoldCallTo((Function*)F);  // FIXME: elim cast
1442  return false;
1443}
1444
1445/// ConstantFold - Constant fold an instruction of the specified type with the
1446/// specified constant operands.  This function may modify the operands vector.
1447static Constant *ConstantFold(const Instruction *I,
1448                              std::vector<Constant*> &Operands) {
1449  if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1450    return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1451
1452  switch (I->getOpcode()) {
1453  case Instruction::Cast:
1454    return ConstantExpr::getCast(Operands[0], I->getType());
1455  case Instruction::Select:
1456    return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1457  case Instruction::Call:
1458    if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Operands[0])) {
1459      Operands.erase(Operands.begin());
1460      return ConstantFoldCall(cast<Function>(CPR->getValue()), Operands);
1461    }
1462
1463    return 0;
1464  case Instruction::GetElementPtr:
1465    Constant *Base = Operands[0];
1466    Operands.erase(Operands.begin());
1467    return ConstantExpr::getGetElementPtr(Base, Operands);
1468  }
1469  return 0;
1470}
1471
1472
1473/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1474/// in the loop that V is derived from.  We allow arbitrary operations along the
1475/// way, but the operands of an operation must either be constants or a value
1476/// derived from a constant PHI.  If this expression does not fit with these
1477/// constraints, return null.
1478static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1479  // If this is not an instruction, or if this is an instruction outside of the
1480  // loop, it can't be derived from a loop PHI.
1481  Instruction *I = dyn_cast<Instruction>(V);
1482  if (I == 0 || !L->contains(I->getParent())) return 0;
1483
1484  if (PHINode *PN = dyn_cast<PHINode>(I))
1485    if (L->getHeader() == I->getParent())
1486      return PN;
1487    else
1488      // We don't currently keep track of the control flow needed to evaluate
1489      // PHIs, so we cannot handle PHIs inside of loops.
1490      return 0;
1491
1492  // If we won't be able to constant fold this expression even if the operands
1493  // are constants, return early.
1494  if (!CanConstantFold(I)) return 0;
1495
1496  // Otherwise, we can evaluate this instruction if all of its operands are
1497  // constant or derived from a PHI node themselves.
1498  PHINode *PHI = 0;
1499  for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1500    if (!(isa<Constant>(I->getOperand(Op)) ||
1501          isa<GlobalValue>(I->getOperand(Op)))) {
1502      PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1503      if (P == 0) return 0;  // Not evolving from PHI
1504      if (PHI == 0)
1505        PHI = P;
1506      else if (PHI != P)
1507        return 0;  // Evolving from multiple different PHIs.
1508    }
1509
1510  // This is a expression evolving from a constant PHI!
1511  return PHI;
1512}
1513
1514/// EvaluateExpression - Given an expression that passes the
1515/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1516/// in the loop has the value PHIVal.  If we can't fold this expression for some
1517/// reason, return null.
1518static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1519  if (isa<PHINode>(V)) return PHIVal;
1520  if (Constant *C = dyn_cast<Constant>(V)) return C;
1521  if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
1522    return ConstantPointerRef::get(GV);
1523  Instruction *I = cast<Instruction>(V);
1524
1525  std::vector<Constant*> Operands;
1526  Operands.resize(I->getNumOperands());
1527
1528  for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1529    Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1530    if (Operands[i] == 0) return 0;
1531  }
1532
1533  return ConstantFold(I, Operands);
1534}
1535
1536/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1537/// in the header of its containing loop, we know the loop executes a
1538/// constant number of times, and the PHI node is just a recurrence
1539/// involving constants, fold it.
1540Constant *ScalarEvolutionsImpl::
1541getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1542  std::map<PHINode*, Constant*>::iterator I =
1543    ConstantEvolutionLoopExitValue.find(PN);
1544  if (I != ConstantEvolutionLoopExitValue.end())
1545    return I->second;
1546
1547  if (Its > MaxBruteForceIterations)
1548    return ConstantEvolutionLoopExitValue[PN] = 0;  // Not going to evaluate it.
1549
1550  Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1551
1552  // Since the loop is canonicalized, the PHI node must have two entries.  One
1553  // entry must be a constant (coming in from outside of the loop), and the
1554  // second must be derived from the same PHI.
1555  bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1556  Constant *StartCST =
1557    dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1558  if (StartCST == 0)
1559    return RetVal = 0;  // Must be a constant.
1560
1561  Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1562  PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1563  if (PN2 != PN)
1564    return RetVal = 0;  // Not derived from same PHI.
1565
1566  // Execute the loop symbolically to determine the exit value.
1567  unsigned IterationNum = 0;
1568  unsigned NumIterations = Its;
1569  if (NumIterations != Its)
1570    return RetVal = 0;  // More than 2^32 iterations??
1571
1572  for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1573    if (IterationNum == NumIterations)
1574      return RetVal = PHIVal;  // Got exit value!
1575
1576    // Compute the value of the PHI node for the next iteration.
1577    Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1578    if (NextPHI == PHIVal)
1579      return RetVal = NextPHI;  // Stopped evolving!
1580    if (NextPHI == 0)
1581      return 0;        // Couldn't evaluate!
1582    PHIVal = NextPHI;
1583  }
1584}
1585
1586/// ComputeIterationCountExhaustively - If the trip is known to execute a
1587/// constant number of times (the condition evolves only from constants),
1588/// try to evaluate a few iterations of the loop until we get the exit
1589/// condition gets a value of ExitWhen (true or false).  If we cannot
1590/// evaluate the trip count of the loop, return UnknownValue.
1591SCEVHandle ScalarEvolutionsImpl::
1592ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1593  PHINode *PN = getConstantEvolvingPHI(Cond, L);
1594  if (PN == 0) return UnknownValue;
1595
1596  // Since the loop is canonicalized, the PHI node must have two entries.  One
1597  // entry must be a constant (coming in from outside of the loop), and the
1598  // second must be derived from the same PHI.
1599  bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1600  Constant *StartCST =
1601    dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1602  if (StartCST == 0) return UnknownValue;  // Must be a constant.
1603
1604  Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1605  PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1606  if (PN2 != PN) return UnknownValue;  // Not derived from same PHI.
1607
1608  // Okay, we find a PHI node that defines the trip count of this loop.  Execute
1609  // the loop symbolically to determine when the condition gets a value of
1610  // "ExitWhen".
1611  unsigned IterationNum = 0;
1612  unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
1613  for (Constant *PHIVal = StartCST;
1614       IterationNum != MaxIterations; ++IterationNum) {
1615    ConstantBool *CondVal =
1616      dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1617    if (!CondVal) return UnknownValue;     // Couldn't symbolically evaluate.
1618
1619    if (CondVal->getValue() == ExitWhen) {
1620      ConstantEvolutionLoopExitValue[PN] = PHIVal;
1621      ++NumBruteForceTripCountsComputed;
1622      return SCEVConstant::get(ConstantUInt::get(Type::UIntTy, IterationNum));
1623    }
1624
1625    // Compute the value of the PHI node for the next iteration.
1626    Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1627    if (NextPHI == 0 || NextPHI == PHIVal)
1628      return UnknownValue;  // Couldn't evaluate or not making progress...
1629    PHIVal = NextPHI;
1630  }
1631
1632  // Too many iterations were needed to evaluate.
1633  return UnknownValue;
1634}
1635
1636/// getSCEVAtScope - Compute the value of the specified expression within the
1637/// indicated loop (which may be null to indicate in no loop).  If the
1638/// expression cannot be evaluated, return UnknownValue.
1639SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1640  // FIXME: this should be turned into a virtual method on SCEV!
1641
1642  if (isa<SCEVConstant>(V)) return V;
1643
1644  // If this instruction is evolves from a constant-evolving PHI, compute the
1645  // exit value from the loop without using SCEVs.
1646  if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1647    if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1648      const Loop *LI = this->LI[I->getParent()];
1649      if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
1650        if (PHINode *PN = dyn_cast<PHINode>(I))
1651          if (PN->getParent() == LI->getHeader()) {
1652            // Okay, there is no closed form solution for the PHI node.  Check
1653            // to see if the loop that contains it has a known iteration count.
1654            // If so, we may be able to force computation of the exit value.
1655            SCEVHandle IterationCount = getIterationCount(LI);
1656            if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1657              // Okay, we know how many times the containing loop executes.  If
1658              // this is a constant evolving PHI node, get the final value at
1659              // the specified iteration number.
1660              Constant *RV = getConstantEvolutionLoopExitValue(PN,
1661                                               ICC->getValue()->getRawValue(),
1662                                                               LI);
1663              if (RV) return SCEVUnknown::get(RV);
1664            }
1665          }
1666
1667      // Okay, this is a some expression that we cannot symbolically evaluate
1668      // into a SCEV.  Check to see if it's possible to symbolically evaluate
1669      // the arguments into constants, and if see, try to constant propagate the
1670      // result.  This is particularly useful for computing loop exit values.
1671      if (CanConstantFold(I)) {
1672        std::vector<Constant*> Operands;
1673        Operands.reserve(I->getNumOperands());
1674        for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1675          Value *Op = I->getOperand(i);
1676          if (Constant *C = dyn_cast<Constant>(Op)) {
1677            Operands.push_back(C);
1678          } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Op)) {
1679            Operands.push_back(ConstantPointerRef::get(GV));
1680          } else {
1681            SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1682            if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
1683              Operands.push_back(ConstantExpr::getCast(SC->getValue(),
1684                                                       Op->getType()));
1685            else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1686              if (Constant *C = dyn_cast<Constant>(SU->getValue()))
1687                Operands.push_back(ConstantExpr::getCast(C, Op->getType()));
1688              else
1689                return V;
1690            } else {
1691              return V;
1692            }
1693          }
1694        }
1695        return SCEVUnknown::get(ConstantFold(I, Operands));
1696      }
1697    }
1698
1699    // This is some other type of SCEVUnknown, just return it.
1700    return V;
1701  }
1702
1703  if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1704    // Avoid performing the look-up in the common case where the specified
1705    // expression has no loop-variant portions.
1706    for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1707      SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1708      if (OpAtScope != Comm->getOperand(i)) {
1709        if (OpAtScope == UnknownValue) return UnknownValue;
1710        // Okay, at least one of these operands is loop variant but might be
1711        // foldable.  Build a new instance of the folded commutative expression.
1712        std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
1713        NewOps.push_back(OpAtScope);
1714
1715        for (++i; i != e; ++i) {
1716          OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1717          if (OpAtScope == UnknownValue) return UnknownValue;
1718          NewOps.push_back(OpAtScope);
1719        }
1720        if (isa<SCEVAddExpr>(Comm))
1721          return SCEVAddExpr::get(NewOps);
1722        assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1723        return SCEVMulExpr::get(NewOps);
1724      }
1725    }
1726    // If we got here, all operands are loop invariant.
1727    return Comm;
1728  }
1729
1730  if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
1731    SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
1732    if (LHS == UnknownValue) return LHS;
1733    SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
1734    if (RHS == UnknownValue) return RHS;
1735    if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
1736      return UDiv;   // must be loop invariant
1737    return SCEVUDivExpr::get(LHS, RHS);
1738  }
1739
1740  // If this is a loop recurrence for a loop that does not contain L, then we
1741  // are dealing with the final value computed by the loop.
1742  if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1743    if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
1744      // To evaluate this recurrence, we need to know how many times the AddRec
1745      // loop iterates.  Compute this now.
1746      SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
1747      if (IterationCount == UnknownValue) return UnknownValue;
1748      IterationCount = getTruncateOrZeroExtend(IterationCount,
1749                                               AddRec->getType());
1750
1751      // If the value is affine, simplify the expression evaluation to just
1752      // Start + Step*IterationCount.
1753      if (AddRec->isAffine())
1754        return SCEVAddExpr::get(AddRec->getStart(),
1755                                SCEVMulExpr::get(IterationCount,
1756                                                 AddRec->getOperand(1)));
1757
1758      // Otherwise, evaluate it the hard way.
1759      return AddRec->evaluateAtIteration(IterationCount);
1760    }
1761    return UnknownValue;
1762  }
1763
1764  //assert(0 && "Unknown SCEV type!");
1765  return UnknownValue;
1766}
1767
1768
1769/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
1770/// given quadratic chrec {L,+,M,+,N}.  This returns either the two roots (which
1771/// might be the same) or two SCEVCouldNotCompute objects.
1772///
1773static std::pair<SCEVHandle,SCEVHandle>
1774SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
1775  assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
1776  SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
1777  SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
1778  SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
1779
1780  // We currently can only solve this if the coefficients are constants.
1781  if (!L || !M || !N) {
1782    SCEV *CNC = new SCEVCouldNotCompute();
1783    return std::make_pair(CNC, CNC);
1784  }
1785
1786  Constant *Two = ConstantInt::get(L->getValue()->getType(), 2);
1787
1788  // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
1789  Constant *C = L->getValue();
1790  // The B coefficient is M-N/2
1791  Constant *B = ConstantExpr::getSub(M->getValue(),
1792                                     ConstantExpr::getDiv(N->getValue(),
1793                                                          Two));
1794  // The A coefficient is N/2
1795  Constant *A = ConstantExpr::getDiv(N->getValue(), Two);
1796
1797  // Compute the B^2-4ac term.
1798  Constant *SqrtTerm =
1799    ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
1800                         ConstantExpr::getMul(A, C));
1801  SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
1802
1803  // Compute floor(sqrt(B^2-4ac))
1804  ConstantUInt *SqrtVal =
1805    cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm,
1806                                   SqrtTerm->getType()->getUnsignedVersion()));
1807  uint64_t SqrtValV = SqrtVal->getValue();
1808  uint64_t SqrtValV2 = (uint64_t)sqrt(SqrtValV);
1809  // The square root might not be precise for arbitrary 64-bit integer
1810  // values.  Do some sanity checks to ensure it's correct.
1811  if (SqrtValV2*SqrtValV2 > SqrtValV ||
1812      (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
1813    SCEV *CNC = new SCEVCouldNotCompute();
1814    return std::make_pair(CNC, CNC);
1815  }
1816
1817  SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2);
1818  SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
1819
1820  Constant *NegB = ConstantExpr::getNeg(B);
1821  Constant *TwoA = ConstantExpr::getMul(A, Two);
1822
1823  // The divisions must be performed as signed divisions.
1824  const Type *SignedTy = NegB->getType()->getSignedVersion();
1825  NegB = ConstantExpr::getCast(NegB, SignedTy);
1826  TwoA = ConstantExpr::getCast(TwoA, SignedTy);
1827  SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
1828
1829  Constant *Solution1 =
1830    ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
1831  Constant *Solution2 =
1832    ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
1833  return std::make_pair(SCEVUnknown::get(Solution1),
1834                        SCEVUnknown::get(Solution2));
1835}
1836
1837/// HowFarToZero - Return the number of times a backedge comparing the specified
1838/// value to zero will execute.  If not computable, return UnknownValue
1839SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
1840  // If the value is a constant
1841  if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
1842    // If the value is already zero, the branch will execute zero times.
1843    if (C->getValue()->isNullValue()) return C;
1844    return UnknownValue;  // Otherwise it will loop infinitely.
1845  }
1846
1847  SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
1848  if (!AddRec || AddRec->getLoop() != L)
1849    return UnknownValue;
1850
1851  if (AddRec->isAffine()) {
1852    // If this is an affine expression the execution count of this branch is
1853    // equal to:
1854    //
1855    //     (0 - Start/Step)    iff   Start % Step == 0
1856    //
1857    // Get the initial value for the loop.
1858    SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
1859    SCEVHandle Step = AddRec->getOperand(1);
1860
1861    Step = getSCEVAtScope(Step, L->getParentLoop());
1862
1863    // Figure out if Start % Step == 0.
1864    // FIXME: We should add DivExpr and RemExpr operations to our AST.
1865    if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
1866      if (StepC->getValue()->equalsInt(1))      // N % 1 == 0
1867        return getNegativeSCEV(Start);  // 0 - Start/1 == -Start
1868      if (StepC->getValue()->isAllOnesValue())  // N % -1 == 0
1869        return Start;                   // 0 - Start/-1 == Start
1870
1871      // Check to see if Start is divisible by SC with no remainder.
1872      if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
1873        ConstantInt *StartCC = StartC->getValue();
1874        Constant *StartNegC = ConstantExpr::getNeg(StartCC);
1875        Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue());
1876        if (Rem->isNullValue()) {
1877          Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue());
1878          return SCEVUnknown::get(Result);
1879        }
1880      }
1881    }
1882  } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
1883    // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
1884    // the quadratic equation to solve it.
1885    std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
1886    SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
1887    SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
1888    if (R1) {
1889#if 0
1890      std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
1891                << "  sol#2: " << *R2 << "\n";
1892#endif
1893      // Pick the smallest positive root value.
1894      assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
1895      if (ConstantBool *CB =
1896          dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
1897                                                        R2->getValue()))) {
1898        if (CB != ConstantBool::True)
1899          std::swap(R1, R2);   // R1 is the minimum root now.
1900
1901        // We can only use this value if the chrec ends up with an exact zero
1902        // value at this index.  When solving for "X*X != 5", for example, we
1903        // should not accept a root of 2.
1904        SCEVHandle Val = AddRec->evaluateAtIteration(R1);
1905        if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
1906          if (EvalVal->getValue()->isNullValue())
1907            return R1;  // We found a quadratic root!
1908      }
1909    }
1910  }
1911
1912  return UnknownValue;
1913}
1914
1915/// HowFarToNonZero - Return the number of times a backedge checking the
1916/// specified value for nonzero will execute.  If not computable, return
1917/// UnknownValue
1918SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
1919  // Loops that look like: while (X == 0) are very strange indeed.  We don't
1920  // handle them yet except for the trivial case.  This could be expanded in the
1921  // future as needed.
1922
1923  // If the value is a constant, check to see if it is known to be non-zero
1924  // already.  If so, the backedge will execute zero times.
1925  if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
1926    Constant *Zero = Constant::getNullValue(C->getValue()->getType());
1927    Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
1928    if (NonZero == ConstantBool::True)
1929      return getSCEV(Zero);
1930    return UnknownValue;  // Otherwise it will loop infinitely.
1931  }
1932
1933  // We could implement others, but I really doubt anyone writes loops like
1934  // this, and if they did, they would already be constant folded.
1935  return UnknownValue;
1936}
1937
1938static ConstantInt *
1939EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1940  SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1941  SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1942  assert(isa<SCEVConstant>(Val) &&
1943         "Evaluation of SCEV at constant didn't fold correctly?");
1944  return cast<SCEVConstant>(Val)->getValue();
1945}
1946
1947
1948/// getNumIterationsInRange - Return the number of iterations of this loop that
1949/// produce values in the specified constant range.  Another way of looking at
1950/// this is that it returns the first iteration number where the value is not in
1951/// the condition, thus computing the exit count. If the iteration count can't
1952/// be computed, an instance of SCEVCouldNotCompute is returned.
1953SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
1954  if (Range.isFullSet())  // Infinite loop.
1955    return new SCEVCouldNotCompute();
1956
1957  // If the start is a non-zero constant, shift the range to simplify things.
1958  if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
1959    if (!SC->getValue()->isNullValue()) {
1960      std::vector<SCEVHandle> Operands(op_begin(), op_end());
1961      Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
1962      SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
1963      if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
1964        return ShiftedAddRec->getNumIterationsInRange(
1965                                              Range.subtract(SC->getValue()));
1966      // This is strange and shouldn't happen.
1967      return new SCEVCouldNotCompute();
1968    }
1969
1970  // The only time we can solve this is when we have all constant indices.
1971  // Otherwise, we cannot determine the overflow conditions.
1972  for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1973    if (!isa<SCEVConstant>(getOperand(i)))
1974      return new SCEVCouldNotCompute();
1975
1976
1977  // Okay at this point we know that all elements of the chrec are constants and
1978  // that the start element is zero.
1979
1980  // First check to see if the range contains zero.  If not, the first
1981  // iteration exits.
1982  ConstantInt *Zero = ConstantInt::get(getType(), 0);
1983  if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
1984
1985  if (isAffine()) {
1986    // If this is an affine expression then we have this situation:
1987    //   Solve {0,+,A} in Range  ===  Ax in Range
1988
1989    // Since we know that zero is in the range, we know that the upper value of
1990    // the range must be the first possible exit value.  Also note that we
1991    // already checked for a full range.
1992    ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
1993    ConstantInt *A     = cast<SCEVConstant>(getOperand(1))->getValue();
1994    ConstantInt *One   = ConstantInt::get(getType(), 1);
1995
1996    // The exit value should be (Upper+A-1)/A.
1997    Constant *ExitValue = Upper;
1998    if (A != One) {
1999      ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
2000      ExitValue = ConstantExpr::getDiv(ExitValue, A);
2001    }
2002    assert(isa<ConstantInt>(ExitValue) &&
2003           "Constant folding of integers not implemented?");
2004
2005    // Evaluate at the exit value.  If we really did fall out of the valid
2006    // range, then we computed our trip count, otherwise wrap around or other
2007    // things must have happened.
2008    ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2009    if (Range.contains(Val))
2010      return new SCEVCouldNotCompute();  // Something strange happened
2011
2012    // Ensure that the previous value is in the range.  This is a sanity check.
2013    assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2014                              ConstantExpr::getSub(ExitValue, One))) &&
2015           "Linear scev computation is off in a bad way!");
2016    return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2017  } else if (isQuadratic()) {
2018    // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2019    // quadratic equation to solve it.  To do this, we must frame our problem in
2020    // terms of figuring out when zero is crossed, instead of when
2021    // Range.getUpper() is crossed.
2022    std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2023    NewOps[0] = getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
2024    SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2025
2026    // Next, solve the constructed addrec
2027    std::pair<SCEVHandle,SCEVHandle> Roots =
2028      SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2029    SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2030    SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2031    if (R1) {
2032      // Pick the smallest positive root value.
2033      assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2034      if (ConstantBool *CB =
2035          dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2036                                                        R2->getValue()))) {
2037        if (CB != ConstantBool::True)
2038          std::swap(R1, R2);   // R1 is the minimum root now.
2039
2040        // Make sure the root is not off by one.  The returned iteration should
2041        // not be in the range, but the previous one should be.  When solving
2042        // for "X*X < 5", for example, we should not return a root of 2.
2043        ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2044                                                             R1->getValue());
2045        if (Range.contains(R1Val)) {
2046          // The next iteration must be out of the range...
2047          Constant *NextVal =
2048            ConstantExpr::getAdd(R1->getValue(),
2049                                 ConstantInt::get(R1->getType(), 1));
2050
2051          R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2052          if (!Range.contains(R1Val))
2053            return SCEVUnknown::get(NextVal);
2054          return new SCEVCouldNotCompute();  // Something strange happened
2055        }
2056
2057        // If R1 was not in the range, then it is a good return value.  Make
2058        // sure that R1-1 WAS in the range though, just in case.
2059        Constant *NextVal =
2060          ConstantExpr::getSub(R1->getValue(),
2061                               ConstantInt::get(R1->getType(), 1));
2062        R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2063        if (Range.contains(R1Val))
2064          return R1;
2065        return new SCEVCouldNotCompute();  // Something strange happened
2066      }
2067    }
2068  }
2069
2070  // Fallback, if this is a general polynomial, figure out the progression
2071  // through brute force: evaluate until we find an iteration that fails the
2072  // test.  This is likely to be slow, but getting an accurate trip count is
2073  // incredibly important, we will be able to simplify the exit test a lot, and
2074  // we are almost guaranteed to get a trip count in this case.
2075  ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2076  ConstantInt *One     = ConstantInt::get(getType(), 1);
2077  ConstantInt *EndVal  = TestVal;  // Stop when we wrap around.
2078  do {
2079    ++NumBruteForceEvaluations;
2080    SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2081    if (!isa<SCEVConstant>(Val))  // This shouldn't happen.
2082      return new SCEVCouldNotCompute();
2083
2084    // Check to see if we found the value!
2085    if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2086      return SCEVConstant::get(TestVal);
2087
2088    // Increment to test the next index.
2089    TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2090  } while (TestVal != EndVal);
2091
2092  return new SCEVCouldNotCompute();
2093}
2094
2095
2096
2097//===----------------------------------------------------------------------===//
2098//                   ScalarEvolution Class Implementation
2099//===----------------------------------------------------------------------===//
2100
2101bool ScalarEvolution::runOnFunction(Function &F) {
2102  Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2103  return false;
2104}
2105
2106void ScalarEvolution::releaseMemory() {
2107  delete (ScalarEvolutionsImpl*)Impl;
2108  Impl = 0;
2109}
2110
2111void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2112  AU.setPreservesAll();
2113  AU.addRequiredID(LoopSimplifyID);
2114  AU.addRequiredTransitive<LoopInfo>();
2115}
2116
2117SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2118  return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2119}
2120
2121SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2122  return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2123}
2124
2125bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2126  return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2127}
2128
2129SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2130  return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2131}
2132
2133void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2134  return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2135}
2136
2137
2138/// shouldSubstituteIndVar - Return true if we should perform induction variable
2139/// substitution for this variable.  This is a hack because we don't have a
2140/// strength reduction pass yet.  When we do we will promote all vars, because
2141/// we can strength reduce them later as desired.
2142bool ScalarEvolution::shouldSubstituteIndVar(const SCEV *S) const {
2143  // Don't substitute high degree polynomials.
2144  if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S))
2145    if (AddRec->getNumOperands() > 3) return false;
2146  return true;
2147}
2148
2149
2150static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2151                          const Loop *L) {
2152  // Print all inner loops first
2153  for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2154    PrintLoopInfo(OS, SE, *I);
2155
2156  std::cerr << "Loop " << L->getHeader()->getName() << ": ";
2157
2158  std::vector<BasicBlock*> ExitBlocks;
2159  L->getExitBlocks(ExitBlocks);
2160  if (ExitBlocks.size() != 1)
2161    std::cerr << "<multiple exits> ";
2162
2163  if (SE->hasLoopInvariantIterationCount(L)) {
2164    std::cerr << *SE->getIterationCount(L) << " iterations! ";
2165  } else {
2166    std::cerr << "Unpredictable iteration count. ";
2167  }
2168
2169  std::cerr << "\n";
2170}
2171
2172void ScalarEvolution::print(std::ostream &OS) const {
2173  Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2174  LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2175
2176  OS << "Classifying expressions for: " << F.getName() << "\n";
2177  for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2178    if ((*I)->getType()->isInteger()) {
2179      OS << **I;
2180      OS << "  --> ";
2181      SCEVHandle SV = getSCEV(*I);
2182      SV->print(OS);
2183      OS << "\t\t";
2184
2185      if ((*I)->getType()->isIntegral()) {
2186        ConstantRange Bounds = SV->getValueRange();
2187        if (!Bounds.isFullSet())
2188          OS << "Bounds: " << Bounds << " ";
2189      }
2190
2191      if (const Loop *L = LI.getLoopFor((*I)->getParent())) {
2192        OS << "Exits: ";
2193        SCEVHandle ExitValue = getSCEVAtScope(*I, L->getParentLoop());
2194        if (isa<SCEVCouldNotCompute>(ExitValue)) {
2195          OS << "<<Unknown>>";
2196        } else {
2197          OS << *ExitValue;
2198        }
2199      }
2200
2201
2202      OS << "\n";
2203    }
2204
2205  OS << "Determining loop execution counts for: " << F.getName() << "\n";
2206  for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2207    PrintLoopInfo(OS, this, *I);
2208}
2209
2210