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