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