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