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