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