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