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