Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1 | //===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===// |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2 | // |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
Chris Lattner | 4ee451d | 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. |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7 | // |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file contains the implementation of the scalar evolution analysis |
| 11 | // engine, which is used primarily to analyze expressions involving induction |
| 12 | // variables in loops. |
| 13 | // |
| 14 | // There are several aspects to this library. First is the representation of |
| 15 | // scalar expressions, which are represented as subclasses of the SCEV class. |
| 16 | // These classes are used to represent certain types of subexpressions that we |
| 17 | // can handle. These classes are reference counted, managed by the SCEVHandle |
| 18 | // class. We only create one SCEV of a particular shape, so pointer-comparisons |
| 19 | // for equality are legal. |
| 20 | // |
| 21 | // One important aspect of the SCEV objects is that they are never cyclic, even |
| 22 | // if there is a cycle in the dataflow for an expression (ie, a PHI node). If |
| 23 | // the PHI node is one of the idioms that we can represent (e.g., a polynomial |
| 24 | // recurrence) then we represent it directly as a recurrence node, otherwise we |
| 25 | // represent it as a SCEVUnknown node. |
| 26 | // |
| 27 | // In addition to being able to represent expressions of various types, we also |
| 28 | // have folders that are used to build the *canonical* representation for a |
| 29 | // particular expression. These folders are capable of using a variety of |
| 30 | // rewrite rules to simplify the expressions. |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 31 | // |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 32 | // Once the folders are defined, we can implement the more interesting |
| 33 | // higher-level code, such as the code that recognizes PHI nodes of various |
| 34 | // types, computes the execution count of a loop, etc. |
| 35 | // |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 36 | // TODO: We should use these routines and value representations to implement |
| 37 | // dependence analysis! |
| 38 | // |
| 39 | //===----------------------------------------------------------------------===// |
| 40 | // |
| 41 | // There are several good references for the techniques used in this analysis. |
| 42 | // |
| 43 | // Chains of recurrences -- a method to expedite the evaluation |
| 44 | // of closed-form functions |
| 45 | // Olaf Bachmann, Paul S. Wang, Eugene V. Zima |
| 46 | // |
| 47 | // On computational properties of chains of recurrences |
| 48 | // Eugene V. Zima |
| 49 | // |
| 50 | // Symbolic Evaluation of Chains of Recurrences for Loop Optimization |
| 51 | // Robert A. van Engelen |
| 52 | // |
| 53 | // Efficient Symbolic Analysis for Optimizing Compilers |
| 54 | // Robert A. van Engelen |
| 55 | // |
| 56 | // Using the chains of recurrences algebra for data dependence testing and |
| 57 | // induction variable substitution |
| 58 | // MS Thesis, Johnie Birch |
| 59 | // |
| 60 | //===----------------------------------------------------------------------===// |
| 61 | |
Chris Lattner | 3b27d68 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 62 | #define DEBUG_TYPE "scalar-evolution" |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 63 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 64 | #include "llvm/Constants.h" |
| 65 | #include "llvm/DerivedTypes.h" |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 66 | #include "llvm/GlobalVariable.h" |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 67 | #include "llvm/Instructions.h" |
John Criswell | a115643 | 2005-10-27 15:54:34 +0000 | [diff] [blame] | 68 | #include "llvm/Analysis/ConstantFolding.h" |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 69 | #include "llvm/Analysis/LoopInfo.h" |
| 70 | #include "llvm/Assembly/Writer.h" |
| 71 | #include "llvm/Transforms/Scalar.h" |
| 72 | #include "llvm/Support/CFG.h" |
Chris Lattner | 9525528 | 2006-06-28 23:17:24 +0000 | [diff] [blame] | 73 | #include "llvm/Support/CommandLine.h" |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 74 | #include "llvm/Support/Compiler.h" |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 75 | #include "llvm/Support/ConstantRange.h" |
| 76 | #include "llvm/Support/InstIterator.h" |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 77 | #include "llvm/Support/ManagedStatic.h" |
Chris Lattner | 75de5ab | 2006-12-19 01:16:02 +0000 | [diff] [blame] | 78 | #include "llvm/Support/MathExtras.h" |
Bill Wendling | 6f81b51 | 2006-11-28 22:46:12 +0000 | [diff] [blame] | 79 | #include "llvm/Support/Streams.h" |
Reid Spencer | 551ccae | 2004-09-01 22:55:40 +0000 | [diff] [blame] | 80 | #include "llvm/ADT/Statistic.h" |
Bill Wendling | 6f81b51 | 2006-11-28 22:46:12 +0000 | [diff] [blame] | 81 | #include <ostream> |
Alkis Evlogimenos | 20aa474 | 2004-09-03 18:19:51 +0000 | [diff] [blame] | 82 | #include <algorithm> |
Jeff Cohen | 97af751 | 2006-12-02 02:22:01 +0000 | [diff] [blame] | 83 | #include <cmath> |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 84 | using namespace llvm; |
| 85 | |
Chris Lattner | 3b27d68 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 86 | STATISTIC(NumArrayLenItCounts, |
| 87 | "Number of trip counts computed with array length"); |
| 88 | STATISTIC(NumTripCountsComputed, |
| 89 | "Number of loops with predictable loop counts"); |
| 90 | STATISTIC(NumTripCountsNotComputed, |
| 91 | "Number of loops without predictable loop counts"); |
| 92 | STATISTIC(NumBruteForceTripCountsComputed, |
| 93 | "Number of loops with trip counts computed by force"); |
| 94 | |
Dan Gohman | 844731a | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 95 | static cl::opt<unsigned> |
Chris Lattner | 3b27d68 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 96 | MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, |
| 97 | cl::desc("Maximum number of iterations SCEV will " |
| 98 | "symbolically execute a constant derived loop"), |
| 99 | cl::init(100)); |
| 100 | |
Dan Gohman | 844731a | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 101 | static RegisterPass<ScalarEvolution> |
| 102 | R("scalar-evolution", "Scalar Evolution Analysis", false, true); |
Devang Patel | 1997473 | 2007-05-03 01:11:54 +0000 | [diff] [blame] | 103 | char ScalarEvolution::ID = 0; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 104 | |
| 105 | //===----------------------------------------------------------------------===// |
| 106 | // SCEV class definitions |
| 107 | //===----------------------------------------------------------------------===// |
| 108 | |
| 109 | //===----------------------------------------------------------------------===// |
| 110 | // Implementation of the SCEV class. |
| 111 | // |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 112 | SCEV::~SCEV() {} |
| 113 | void SCEV::dump() const { |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 114 | print(cerr); |
Nick Lewycky | d1f5fab | 2009-01-16 17:07:22 +0000 | [diff] [blame] | 115 | cerr << '\n'; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 116 | } |
| 117 | |
Reid Spencer | 581b0d4 | 2007-02-28 19:57:34 +0000 | [diff] [blame] | 118 | uint32_t SCEV::getBitWidth() const { |
| 119 | if (const IntegerType* ITy = dyn_cast<IntegerType>(getType())) |
| 120 | return ITy->getBitWidth(); |
| 121 | return 0; |
| 122 | } |
| 123 | |
Dan Gohman | cfeb6a4 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 124 | bool SCEV::isZero() const { |
| 125 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 126 | return SC->getValue()->isZero(); |
| 127 | return false; |
| 128 | } |
| 129 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 130 | |
| 131 | SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {} |
| 132 | |
| 133 | bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const { |
| 134 | assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); |
Misha Brukman | bb2aff1 | 2004-04-05 19:00:46 +0000 | [diff] [blame] | 135 | return false; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 136 | } |
| 137 | |
| 138 | const Type *SCEVCouldNotCompute::getType() const { |
| 139 | assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); |
Misha Brukman | bb2aff1 | 2004-04-05 19:00:46 +0000 | [diff] [blame] | 140 | return 0; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 141 | } |
| 142 | |
| 143 | bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const { |
| 144 | assert(0 && "Attempt to use a SCEVCouldNotCompute object!"); |
| 145 | return false; |
| 146 | } |
| 147 | |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 148 | SCEVHandle SCEVCouldNotCompute:: |
| 149 | replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 150 | const SCEVHandle &Conc, |
| 151 | ScalarEvolution &SE) const { |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 152 | return this; |
| 153 | } |
| 154 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 155 | void SCEVCouldNotCompute::print(std::ostream &OS) const { |
| 156 | OS << "***COULDNOTCOMPUTE***"; |
| 157 | } |
| 158 | |
| 159 | bool SCEVCouldNotCompute::classof(const SCEV *S) { |
| 160 | return S->getSCEVType() == scCouldNotCompute; |
| 161 | } |
| 162 | |
| 163 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 164 | // SCEVConstants - Only allow the creation of one SCEVConstant for any |
| 165 | // particular value. Don't use a SCEVHandle here, or else the object will |
| 166 | // never be deleted! |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 167 | static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 168 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 169 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 170 | SCEVConstant::~SCEVConstant() { |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 171 | SCEVConstants->erase(V); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 172 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 173 | |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 174 | SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) { |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 175 | SCEVConstant *&R = (*SCEVConstants)[V]; |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 176 | if (R == 0) R = new SCEVConstant(V); |
| 177 | return R; |
| 178 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 179 | |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 180 | SCEVHandle ScalarEvolution::getConstant(const APInt& Val) { |
| 181 | return getConstant(ConstantInt::get(Val)); |
Dan Gohman | 9a6ae96 | 2007-07-09 15:25:17 +0000 | [diff] [blame] | 182 | } |
| 183 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 184 | const Type *SCEVConstant::getType() const { return V->getType(); } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 185 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 186 | void SCEVConstant::print(std::ostream &OS) const { |
| 187 | WriteAsOperand(OS, V, false); |
| 188 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 189 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 190 | // SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any |
| 191 | // particular input. Don't use a SCEVHandle here, or else the object will |
| 192 | // never be deleted! |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 193 | static ManagedStatic<std::map<std::pair<SCEV*, const Type*>, |
| 194 | SCEVTruncateExpr*> > SCEVTruncates; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 195 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 196 | SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty) |
| 197 | : SCEV(scTruncate), Op(op), Ty(ty) { |
Chris Lattner | 42a7551 | 2007-01-15 02:27:26 +0000 | [diff] [blame] | 198 | assert(Op->getType()->isInteger() && Ty->isInteger() && |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 199 | "Cannot truncate non-integer value!"); |
Reid Spencer | e7ca042 | 2007-01-08 01:26:33 +0000 | [diff] [blame] | 200 | assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits() |
| 201 | && "This is not a truncating conversion!"); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 202 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 203 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 204 | SCEVTruncateExpr::~SCEVTruncateExpr() { |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 205 | SCEVTruncates->erase(std::make_pair(Op, Ty)); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 206 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 207 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 208 | void SCEVTruncateExpr::print(std::ostream &OS) const { |
| 209 | OS << "(truncate " << *Op << " to " << *Ty << ")"; |
| 210 | } |
| 211 | |
| 212 | // SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any |
| 213 | // particular input. Don't use a SCEVHandle here, or else the object will never |
| 214 | // be deleted! |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 215 | static ManagedStatic<std::map<std::pair<SCEV*, const Type*>, |
| 216 | SCEVZeroExtendExpr*> > SCEVZeroExtends; |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 217 | |
| 218 | SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty) |
Reid Spencer | 48d8a70 | 2006-11-01 21:53:12 +0000 | [diff] [blame] | 219 | : SCEV(scZeroExtend), Op(op), Ty(ty) { |
Chris Lattner | 42a7551 | 2007-01-15 02:27:26 +0000 | [diff] [blame] | 220 | assert(Op->getType()->isInteger() && Ty->isInteger() && |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 221 | "Cannot zero extend non-integer value!"); |
Reid Spencer | e7ca042 | 2007-01-08 01:26:33 +0000 | [diff] [blame] | 222 | assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits() |
| 223 | && "This is not an extending conversion!"); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 224 | } |
| 225 | |
| 226 | SCEVZeroExtendExpr::~SCEVZeroExtendExpr() { |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 227 | SCEVZeroExtends->erase(std::make_pair(Op, Ty)); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 228 | } |
| 229 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 230 | void SCEVZeroExtendExpr::print(std::ostream &OS) const { |
| 231 | OS << "(zeroextend " << *Op << " to " << *Ty << ")"; |
| 232 | } |
| 233 | |
Dan Gohman | d19534a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 234 | // SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any |
| 235 | // particular input. Don't use a SCEVHandle here, or else the object will never |
| 236 | // be deleted! |
| 237 | static ManagedStatic<std::map<std::pair<SCEV*, const Type*>, |
| 238 | SCEVSignExtendExpr*> > SCEVSignExtends; |
| 239 | |
| 240 | SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty) |
| 241 | : SCEV(scSignExtend), Op(op), Ty(ty) { |
| 242 | assert(Op->getType()->isInteger() && Ty->isInteger() && |
| 243 | "Cannot sign extend non-integer value!"); |
| 244 | assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits() |
| 245 | && "This is not an extending conversion!"); |
| 246 | } |
| 247 | |
| 248 | SCEVSignExtendExpr::~SCEVSignExtendExpr() { |
| 249 | SCEVSignExtends->erase(std::make_pair(Op, Ty)); |
| 250 | } |
| 251 | |
Dan Gohman | d19534a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 252 | void SCEVSignExtendExpr::print(std::ostream &OS) const { |
| 253 | OS << "(signextend " << *Op << " to " << *Ty << ")"; |
| 254 | } |
| 255 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 256 | // SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any |
| 257 | // particular input. Don't use a SCEVHandle here, or else the object will never |
| 258 | // be deleted! |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 259 | static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >, |
| 260 | SCEVCommutativeExpr*> > SCEVCommExprs; |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 261 | |
| 262 | SCEVCommutativeExpr::~SCEVCommutativeExpr() { |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 263 | SCEVCommExprs->erase(std::make_pair(getSCEVType(), |
| 264 | std::vector<SCEV*>(Operands.begin(), |
| 265 | Operands.end()))); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 266 | } |
| 267 | |
| 268 | void SCEVCommutativeExpr::print(std::ostream &OS) const { |
| 269 | assert(Operands.size() > 1 && "This plus expr shouldn't exist!"); |
| 270 | const char *OpStr = getOperationStr(); |
| 271 | OS << "(" << *Operands[0]; |
| 272 | for (unsigned i = 1, e = Operands.size(); i != e; ++i) |
| 273 | OS << OpStr << *Operands[i]; |
| 274 | OS << ")"; |
| 275 | } |
| 276 | |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 277 | SCEVHandle SCEVCommutativeExpr:: |
| 278 | replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 279 | const SCEVHandle &Conc, |
| 280 | ScalarEvolution &SE) const { |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 281 | for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 282 | SCEVHandle H = |
| 283 | getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE); |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 284 | if (H != getOperand(i)) { |
| 285 | std::vector<SCEVHandle> NewOps; |
| 286 | NewOps.reserve(getNumOperands()); |
| 287 | for (unsigned j = 0; j != i; ++j) |
| 288 | NewOps.push_back(getOperand(j)); |
| 289 | NewOps.push_back(H); |
| 290 | for (++i; i != e; ++i) |
| 291 | NewOps.push_back(getOperand(i)-> |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 292 | replaceSymbolicValuesWithConcrete(Sym, Conc, SE)); |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 293 | |
| 294 | if (isa<SCEVAddExpr>(this)) |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 295 | return SE.getAddExpr(NewOps); |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 296 | else if (isa<SCEVMulExpr>(this)) |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 297 | return SE.getMulExpr(NewOps); |
Nick Lewycky | c54c561 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 298 | else if (isa<SCEVSMaxExpr>(this)) |
| 299 | return SE.getSMaxExpr(NewOps); |
Nick Lewycky | 3e63076 | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 300 | else if (isa<SCEVUMaxExpr>(this)) |
| 301 | return SE.getUMaxExpr(NewOps); |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 302 | else |
| 303 | assert(0 && "Unknown commutative expr!"); |
| 304 | } |
| 305 | } |
| 306 | return this; |
| 307 | } |
| 308 | |
| 309 | |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 310 | // SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 311 | // input. Don't use a SCEVHandle here, or else the object will never be |
| 312 | // deleted! |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 313 | static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>, |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 314 | SCEVUDivExpr*> > SCEVUDivs; |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 315 | |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 316 | SCEVUDivExpr::~SCEVUDivExpr() { |
| 317 | SCEVUDivs->erase(std::make_pair(LHS, RHS)); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 318 | } |
| 319 | |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 320 | void SCEVUDivExpr::print(std::ostream &OS) const { |
| 321 | OS << "(" << *LHS << " /u " << *RHS << ")"; |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 322 | } |
| 323 | |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 324 | const Type *SCEVUDivExpr::getType() const { |
Reid Spencer | c5b206b | 2006-12-31 05:48:39 +0000 | [diff] [blame] | 325 | return LHS->getType(); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 326 | } |
| 327 | |
| 328 | // SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any |
| 329 | // particular input. Don't use a SCEVHandle here, or else the object will never |
| 330 | // be deleted! |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 331 | static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >, |
| 332 | SCEVAddRecExpr*> > SCEVAddRecExprs; |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 333 | |
| 334 | SCEVAddRecExpr::~SCEVAddRecExpr() { |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 335 | SCEVAddRecExprs->erase(std::make_pair(L, |
| 336 | std::vector<SCEV*>(Operands.begin(), |
| 337 | Operands.end()))); |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 338 | } |
| 339 | |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 340 | SCEVHandle SCEVAddRecExpr:: |
| 341 | replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym, |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 342 | const SCEVHandle &Conc, |
| 343 | ScalarEvolution &SE) const { |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 344 | for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 345 | SCEVHandle H = |
| 346 | getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE); |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 347 | if (H != getOperand(i)) { |
| 348 | std::vector<SCEVHandle> NewOps; |
| 349 | NewOps.reserve(getNumOperands()); |
| 350 | for (unsigned j = 0; j != i; ++j) |
| 351 | NewOps.push_back(getOperand(j)); |
| 352 | NewOps.push_back(H); |
| 353 | for (++i; i != e; ++i) |
| 354 | NewOps.push_back(getOperand(i)-> |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 355 | replaceSymbolicValuesWithConcrete(Sym, Conc, SE)); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 356 | |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 357 | return SE.getAddRecExpr(NewOps, L); |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 358 | } |
| 359 | } |
| 360 | return this; |
| 361 | } |
| 362 | |
| 363 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 364 | bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const { |
| 365 | // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't |
Chris Lattner | ff2006a | 2005-08-16 00:37:01 +0000 | [diff] [blame] | 366 | // contain L and if the start is invariant. |
| 367 | return !QueryLoop->contains(L->getHeader()) && |
| 368 | getOperand(0)->isLoopInvariant(QueryLoop); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 369 | } |
| 370 | |
| 371 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 372 | void SCEVAddRecExpr::print(std::ostream &OS) const { |
| 373 | OS << "{" << *Operands[0]; |
| 374 | for (unsigned i = 1, e = Operands.size(); i != e; ++i) |
| 375 | OS << ",+," << *Operands[i]; |
| 376 | OS << "}<" << L->getHeader()->getName() + ">"; |
| 377 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 378 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 379 | // SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular |
| 380 | // value. Don't use a SCEVHandle here, or else the object will never be |
| 381 | // deleted! |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 382 | static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 383 | |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 384 | SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 385 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 386 | bool SCEVUnknown::isLoopInvariant(const Loop *L) const { |
| 387 | // All non-instruction values are loop invariant. All instructions are loop |
| 388 | // invariant if they are not contained in the specified loop. |
| 389 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 390 | return !L->contains(I->getParent()); |
| 391 | return true; |
| 392 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 393 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 394 | const Type *SCEVUnknown::getType() const { |
| 395 | return V->getType(); |
| 396 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 397 | |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 398 | void SCEVUnknown::print(std::ostream &OS) const { |
| 399 | WriteAsOperand(OS, V, false); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 400 | } |
| 401 | |
Chris Lattner | 8d741b8 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 402 | //===----------------------------------------------------------------------===// |
| 403 | // SCEV Utilities |
| 404 | //===----------------------------------------------------------------------===// |
| 405 | |
| 406 | namespace { |
| 407 | /// SCEVComplexityCompare - Return true if the complexity of the LHS is less |
| 408 | /// than the complexity of the RHS. This comparator is used to canonicalize |
| 409 | /// expressions. |
Chris Lattner | 9525528 | 2006-06-28 23:17:24 +0000 | [diff] [blame] | 410 | struct VISIBILITY_HIDDEN SCEVComplexityCompare { |
Dan Gohman | f7b37b2 | 2008-04-14 18:23:56 +0000 | [diff] [blame] | 411 | bool operator()(const SCEV *LHS, const SCEV *RHS) const { |
Chris Lattner | 8d741b8 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 412 | return LHS->getSCEVType() < RHS->getSCEVType(); |
| 413 | } |
| 414 | }; |
| 415 | } |
| 416 | |
| 417 | /// GroupByComplexity - Given a list of SCEV objects, order them by their |
| 418 | /// complexity, and group objects of the same complexity together by value. |
| 419 | /// When this routine is finished, we know that any duplicates in the vector are |
| 420 | /// consecutive and that complexity is monotonically increasing. |
| 421 | /// |
| 422 | /// Note that we go take special precautions to ensure that we get determinstic |
| 423 | /// results from this routine. In other words, we don't want the results of |
| 424 | /// this to depend on where the addresses of various SCEV objects happened to |
| 425 | /// land in memory. |
| 426 | /// |
| 427 | static void GroupByComplexity(std::vector<SCEVHandle> &Ops) { |
| 428 | if (Ops.size() < 2) return; // Noop |
| 429 | if (Ops.size() == 2) { |
| 430 | // This is the common case, which also happens to be trivially simple. |
| 431 | // Special case it. |
Dan Gohman | f7b37b2 | 2008-04-14 18:23:56 +0000 | [diff] [blame] | 432 | if (SCEVComplexityCompare()(Ops[1], Ops[0])) |
Chris Lattner | 8d741b8 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 433 | std::swap(Ops[0], Ops[1]); |
| 434 | return; |
| 435 | } |
| 436 | |
| 437 | // Do the rough sort by complexity. |
| 438 | std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare()); |
| 439 | |
| 440 | // Now that we are sorted by complexity, group elements of the same |
| 441 | // complexity. Note that this is, at worst, N^2, but the vector is likely to |
| 442 | // be extremely short in practice. Note that we take this approach because we |
| 443 | // do not want to depend on the addresses of the objects we are grouping. |
Chris Lattner | 2d58452 | 2004-06-20 17:01:44 +0000 | [diff] [blame] | 444 | for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { |
Chris Lattner | 8d741b8 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 445 | SCEV *S = Ops[i]; |
| 446 | unsigned Complexity = S->getSCEVType(); |
| 447 | |
| 448 | // If there are any objects of the same complexity and same value as this |
| 449 | // one, group them. |
| 450 | for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { |
| 451 | if (Ops[j] == S) { // Found a duplicate. |
| 452 | // Move it to immediately after i'th element. |
| 453 | std::swap(Ops[i+1], Ops[j]); |
| 454 | ++i; // no need to rescan it. |
Chris Lattner | 541ad5e | 2004-06-20 20:32:16 +0000 | [diff] [blame] | 455 | if (i == e-2) return; // Done! |
Chris Lattner | 8d741b8 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 456 | } |
| 457 | } |
| 458 | } |
| 459 | } |
| 460 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 461 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 462 | |
| 463 | //===----------------------------------------------------------------------===// |
| 464 | // Simple SCEV method implementations |
| 465 | //===----------------------------------------------------------------------===// |
| 466 | |
| 467 | /// getIntegerSCEV - Given an integer or FP type, create a constant for the |
| 468 | /// specified signed integer value and return a SCEV for the constant. |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 469 | SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 470 | Constant *C; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 471 | if (Val == 0) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 472 | C = Constant::getNullValue(Ty); |
| 473 | else if (Ty->isFloatingPoint()) |
Chris Lattner | 02a260a | 2008-04-20 00:41:09 +0000 | [diff] [blame] | 474 | C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle : |
| 475 | APFloat::IEEEdouble, Val)); |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 476 | else |
Reid Spencer | b83eb64 | 2006-10-20 07:07:24 +0000 | [diff] [blame] | 477 | C = ConstantInt::get(Ty, Val); |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 478 | return getUnknown(C); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 479 | } |
| 480 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 481 | /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V |
| 482 | /// |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 483 | SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 484 | if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 485 | return getUnknown(ConstantExpr::getNeg(VC->getValue())); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 486 | |
Nick Lewycky | 178f20a | 2008-02-20 06:58:55 +0000 | [diff] [blame] | 487 | return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType()))); |
Nick Lewycky | 3e63076 | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 488 | } |
| 489 | |
| 490 | /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V |
| 491 | SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) { |
| 492 | if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) |
| 493 | return getUnknown(ConstantExpr::getNot(VC->getValue())); |
| 494 | |
Nick Lewycky | 178f20a | 2008-02-20 06:58:55 +0000 | [diff] [blame] | 495 | SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType())); |
Nick Lewycky | 3e63076 | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 496 | return getMinusSCEV(AllOnes, V); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 497 | } |
| 498 | |
| 499 | /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS. |
| 500 | /// |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 501 | SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS, |
| 502 | const SCEVHandle &RHS) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 503 | // X - Y --> X + -Y |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 504 | return getAddExpr(LHS, getNegativeSCEV(RHS)); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 505 | } |
| 506 | |
| 507 | |
Eli Friedman | b42a626 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 508 | /// BinomialCoefficient - Compute BC(It, K). The result has width W. |
| 509 | // Assume, K > 0. |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 510 | static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K, |
Eli Friedman | b42a626 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 511 | ScalarEvolution &SE, |
| 512 | const IntegerType* ResultTy) { |
| 513 | // Handle the simplest case efficiently. |
| 514 | if (K == 1) |
| 515 | return SE.getTruncateOrZeroExtend(It, ResultTy); |
| 516 | |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 517 | // We are using the following formula for BC(It, K): |
| 518 | // |
| 519 | // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! |
| 520 | // |
Eli Friedman | b42a626 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 521 | // Suppose, W is the bitwidth of the return value. We must be prepared for |
| 522 | // overflow. Hence, we must assure that the result of our computation is |
| 523 | // equal to the accurate one modulo 2^W. Unfortunately, division isn't |
| 524 | // safe in modular arithmetic. |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 525 | // |
Eli Friedman | b42a626 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 526 | // However, this code doesn't use exactly that formula; the formula it uses |
| 527 | // is something like the following, where T is the number of factors of 2 in |
| 528 | // K! (i.e. trailing zeros in the binary representation of K!), and ^ is |
| 529 | // exponentiation: |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 530 | // |
Eli Friedman | b42a626 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 531 | // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 532 | // |
Eli Friedman | b42a626 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 533 | // This formula is trivially equivalent to the previous formula. However, |
| 534 | // this formula can be implemented much more efficiently. The trick is that |
| 535 | // K! / 2^T is odd, and exact division by an odd number *is* safe in modular |
| 536 | // arithmetic. To do exact division in modular arithmetic, all we have |
| 537 | // to do is multiply by the inverse. Therefore, this step can be done at |
| 538 | // width W. |
| 539 | // |
| 540 | // The next issue is how to safely do the division by 2^T. The way this |
| 541 | // is done is by doing the multiplication step at a width of at least W + T |
| 542 | // bits. This way, the bottom W+T bits of the product are accurate. Then, |
| 543 | // when we perform the division by 2^T (which is equivalent to a right shift |
| 544 | // by T), the bottom W bits are accurate. Extra bits are okay; they'll get |
| 545 | // truncated out after the division by 2^T. |
| 546 | // |
| 547 | // In comparison to just directly using the first formula, this technique |
| 548 | // is much more efficient; using the first formula requires W * K bits, |
| 549 | // but this formula less than W + K bits. Also, the first formula requires |
| 550 | // a division step, whereas this formula only requires multiplies and shifts. |
| 551 | // |
| 552 | // It doesn't matter whether the subtraction step is done in the calculation |
| 553 | // width or the input iteration count's width; if the subtraction overflows, |
| 554 | // the result must be zero anyway. We prefer here to do it in the width of |
| 555 | // the induction variable because it helps a lot for certain cases; CodeGen |
| 556 | // isn't smart enough to ignore the overflow, which leads to much less |
| 557 | // efficient code if the width of the subtraction is wider than the native |
| 558 | // register width. |
| 559 | // |
| 560 | // (It's possible to not widen at all by pulling out factors of 2 before |
| 561 | // the multiplication; for example, K=2 can be calculated as |
| 562 | // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires |
| 563 | // extra arithmetic, so it's not an obvious win, and it gets |
| 564 | // much more complicated for K > 3.) |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 565 | |
Eli Friedman | b42a626 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 566 | // Protection from insane SCEVs; this bound is conservative, |
| 567 | // but it probably doesn't matter. |
| 568 | if (K > 1000) |
| 569 | return new SCEVCouldNotCompute(); |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 570 | |
Eli Friedman | b42a626 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 571 | unsigned W = ResultTy->getBitWidth(); |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 572 | |
Eli Friedman | b42a626 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 573 | // Calculate K! / 2^T and T; we divide out the factors of two before |
| 574 | // multiplying for calculating K! / 2^T to avoid overflow. |
| 575 | // Other overflow doesn't matter because we only care about the bottom |
| 576 | // W bits of the result. |
| 577 | APInt OddFactorial(W, 1); |
| 578 | unsigned T = 1; |
| 579 | for (unsigned i = 3; i <= K; ++i) { |
| 580 | APInt Mult(W, i); |
| 581 | unsigned TwoFactors = Mult.countTrailingZeros(); |
| 582 | T += TwoFactors; |
| 583 | Mult = Mult.lshr(TwoFactors); |
| 584 | OddFactorial *= Mult; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 585 | } |
Nick Lewycky | 6f8abf9 | 2008-06-13 04:38:55 +0000 | [diff] [blame] | 586 | |
Eli Friedman | b42a626 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 587 | // We need at least W + T bits for the multiplication step |
Nick Lewycky | 237d873 | 2009-01-25 08:16:27 +0000 | [diff] [blame] | 588 | unsigned CalculationBits = W + T; |
Eli Friedman | b42a626 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 589 | |
| 590 | // Calcuate 2^T, at width T+W. |
| 591 | APInt DivFactor = APInt(CalculationBits, 1).shl(T); |
| 592 | |
| 593 | // Calculate the multiplicative inverse of K! / 2^T; |
| 594 | // this multiplication factor will perform the exact division by |
| 595 | // K! / 2^T. |
| 596 | APInt Mod = APInt::getSignedMinValue(W+1); |
| 597 | APInt MultiplyFactor = OddFactorial.zext(W+1); |
| 598 | MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); |
| 599 | MultiplyFactor = MultiplyFactor.trunc(W); |
| 600 | |
| 601 | // Calculate the product, at width T+W |
| 602 | const IntegerType *CalculationTy = IntegerType::get(CalculationBits); |
| 603 | SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); |
| 604 | for (unsigned i = 1; i != K; ++i) { |
| 605 | SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType())); |
| 606 | Dividend = SE.getMulExpr(Dividend, |
| 607 | SE.getTruncateOrZeroExtend(S, CalculationTy)); |
| 608 | } |
| 609 | |
| 610 | // Divide by 2^T |
| 611 | SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); |
| 612 | |
| 613 | // Truncate the result, and divide by K! / 2^T. |
| 614 | |
| 615 | return SE.getMulExpr(SE.getConstant(MultiplyFactor), |
| 616 | SE.getTruncateOrZeroExtend(DivResult, ResultTy)); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 617 | } |
| 618 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 619 | /// evaluateAtIteration - Return the value of this chain of recurrences at |
| 620 | /// the specified iteration number. We can evaluate this recurrence by |
| 621 | /// multiplying each element in the chain by the binomial coefficient |
| 622 | /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as: |
| 623 | /// |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 624 | /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 625 | /// |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 626 | /// where BC(It, k) stands for binomial coefficient. |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 627 | /// |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 628 | SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It, |
| 629 | ScalarEvolution &SE) const { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 630 | SCEVHandle Result = getStart(); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 631 | for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 632 | // The computation is correct in the face of overflow provided that the |
| 633 | // multiplication is performed _after_ the evaluation of the binomial |
| 634 | // coefficient. |
Nick Lewycky | cb8f1b5 | 2008-10-13 03:58:02 +0000 | [diff] [blame] | 635 | SCEVHandle Coeff = BinomialCoefficient(It, i, SE, |
| 636 | cast<IntegerType>(getType())); |
| 637 | if (isa<SCEVCouldNotCompute>(Coeff)) |
| 638 | return Coeff; |
| 639 | |
| 640 | Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 641 | } |
| 642 | return Result; |
| 643 | } |
| 644 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 645 | //===----------------------------------------------------------------------===// |
| 646 | // SCEV Expression folder implementations |
| 647 | //===----------------------------------------------------------------------===// |
| 648 | |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 649 | SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 650 | if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 651 | return getUnknown( |
Reid Spencer | 315d055 | 2006-12-05 22:39:58 +0000 | [diff] [blame] | 652 | ConstantExpr::getTrunc(SC->getValue(), Ty)); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 653 | |
| 654 | // If the input value is a chrec scev made out of constants, truncate |
| 655 | // all of the constants. |
| 656 | if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { |
| 657 | std::vector<SCEVHandle> Operands; |
| 658 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) |
| 659 | // FIXME: This should allow truncation of other expression types! |
| 660 | if (isa<SCEVConstant>(AddRec->getOperand(i))) |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 661 | Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty)); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 662 | else |
| 663 | break; |
| 664 | if (Operands.size() == AddRec->getNumOperands()) |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 665 | return getAddRecExpr(Operands, AddRec->getLoop()); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 666 | } |
| 667 | |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 668 | SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)]; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 669 | if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty); |
| 670 | return Result; |
| 671 | } |
| 672 | |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 673 | SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 674 | if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 675 | return getUnknown( |
Reid Spencer | d977d86 | 2006-12-12 23:36:14 +0000 | [diff] [blame] | 676 | ConstantExpr::getZExt(SC->getValue(), Ty)); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 677 | |
| 678 | // FIXME: If the input value is a chrec scev, and we can prove that the value |
| 679 | // did not overflow the old, smaller, value, we can zero extend all of the |
| 680 | // operands (often constants). This would allow analysis of something like |
| 681 | // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } |
| 682 | |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 683 | SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)]; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 684 | if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty); |
| 685 | return Result; |
| 686 | } |
| 687 | |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 688 | SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) { |
Dan Gohman | d19534a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 689 | if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 690 | return getUnknown( |
Dan Gohman | d19534a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 691 | ConstantExpr::getSExt(SC->getValue(), Ty)); |
| 692 | |
| 693 | // FIXME: If the input value is a chrec scev, and we can prove that the value |
| 694 | // did not overflow the old, smaller, value, we can sign extend all of the |
| 695 | // operands (often constants). This would allow analysis of something like |
| 696 | // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } |
| 697 | |
| 698 | SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)]; |
| 699 | if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty); |
| 700 | return Result; |
| 701 | } |
| 702 | |
Nick Lewycky | 6f8abf9 | 2008-06-13 04:38:55 +0000 | [diff] [blame] | 703 | /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion |
| 704 | /// of the input value to the specified type. If the type must be |
| 705 | /// extended, it is zero extended. |
| 706 | SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V, |
| 707 | const Type *Ty) { |
| 708 | const Type *SrcTy = V->getType(); |
| 709 | assert(SrcTy->isInteger() && Ty->isInteger() && |
| 710 | "Cannot truncate or zero extend with non-integer arguments!"); |
| 711 | if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits()) |
| 712 | return V; // No conversion |
| 713 | if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()) |
| 714 | return getTruncateExpr(V, Ty); |
| 715 | return getZeroExtendExpr(V, Ty); |
| 716 | } |
| 717 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 718 | // get - Get a canonical add expression, or something simpler if possible. |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 719 | SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 720 | assert(!Ops.empty() && "Cannot get empty add!"); |
Chris Lattner | 627018b | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 721 | if (Ops.size() == 1) return Ops[0]; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 722 | |
| 723 | // Sort by complexity, this groups all similar expression types together. |
Chris Lattner | 8d741b8 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 724 | GroupByComplexity(Ops); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 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; |
Chris Lattner | 627018b | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 730 | assert(Idx < Ops.size()); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 731 | while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
| 732 | // We found two constants, fold them together! |
Nick Lewycky | 3e63076 | 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]); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 739 | } |
| 740 | |
| 741 | // If we are left with a constant zero being added, strip it off. |
Reid Spencer | cae5754 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 742 | if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 743 | Ops.erase(Ops.begin()); |
| 744 | --Idx; |
| 745 | } |
| 746 | } |
| 747 | |
Chris Lattner | 627018b | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 748 | if (Ops.size() == 1) return Ops[0]; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 749 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 758 | SCEVHandle Two = getIntegerSCEV(2, Ty); |
| 759 | SCEVHandle Mul = getMulExpr(Ops[i], Two); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 764 | return getAddExpr(Ops); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 765 | } |
| 766 | |
Dan Gohman | f50cd74 | 2007-06-18 19:30:09 +0000 | [diff] [blame] | 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. |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 786 | return getAddExpr(Ops); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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) |
Chris Lattner | 6a1a78a | 2004-12-04 20:54:32 +0000 | [diff] [blame] | 801 | if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 809 | InnerMul = getMulExpr(MulOps); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 810 | } |
Dan Gohman | 246b256 | 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]); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 823 | return getAddExpr(Ops); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 824 | } |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 825 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 841 | InnerMul1 = getMulExpr(MulOps); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 848 | InnerMul2 = getMulExpr(MulOps); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 849 | } |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 850 | SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2); |
| 851 | SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 856 | return getAddExpr(Ops); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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 | 8dae138 | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 883 | // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 884 | LIOps.push_back(AddRec->getStart()); |
| 885 | |
| 886 | std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end()); |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 887 | AddRecOps[0] = getAddExpr(LIOps); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 888 | |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 889 | SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop()); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 899 | return getAddExpr(Ops); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 918 | NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i)); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 919 | } |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 920 | SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop()); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 927 | return getAddExpr(Ops); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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()); |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 938 | SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr, |
| 939 | SCEVOps)]; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 940 | if (Result == 0) Result = new SCEVAddExpr(Ops); |
| 941 | return Result; |
| 942 | } |
| 943 | |
| 944 | |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 945 | SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 946 | assert(!Ops.empty() && "Cannot get empty mul!"); |
| 947 | |
| 948 | // Sort by complexity, this groups all similar expression types together. |
Chris Lattner | 8d741b8 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 949 | GroupByComplexity(Ops); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 960 | return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), |
| 961 | getMulExpr(LHSC, Add->getOperand(1))); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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 | 3e63076 | 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]); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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; |
Reid Spencer | cae5754 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 979 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 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]; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 991 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1007 | return getMulExpr(Ops); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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 | 8dae138 | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 1031 | // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1037 | NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1042 | NewOps.push_back(getMulExpr(MulOps)); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1043 | } |
| 1044 | } |
| 1045 | |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1046 | SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop()); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1057 | return getMulExpr(Ops); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1070 | SCEVHandle NewStart = getMulExpr(F->getStart(), |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1071 | G->getStart()); |
Dan Gohman | 246b256 | 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()); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1084 | return getMulExpr(Ops); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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()); |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 1095 | SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr, |
| 1096 | SCEVOps)]; |
Chris Lattner | 6a1a78a | 2004-12-04 20:54:32 +0000 | [diff] [blame] | 1097 | if (Result == 0) |
| 1098 | Result = new SCEVMulExpr(Ops); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1099 | return Result; |
| 1100 | } |
| 1101 | |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1102 | SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1103 | if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { |
| 1104 | if (RHSC->getValue()->equalsInt(1)) |
Nick Lewycky | 789558d | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 1105 | return LHS; // X udiv 1 --> x |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1106 | |
| 1107 | if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { |
| 1108 | Constant *LHSCV = LHSC->getValue(); |
| 1109 | Constant *RHSCV = RHSC->getValue(); |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1110 | return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV)); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1111 | } |
| 1112 | } |
| 1113 | |
Nick Lewycky | 789558d | 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 | e3320a1 | 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); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1124 | SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start, |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1132 | return getAddRecExpr(Operands, L); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1133 | } |
| 1134 | |
| 1135 | Operands.push_back(Step); |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1136 | return getAddRecExpr(Operands, L); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1141 | SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands, |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1142 | const Loop *L) { |
| 1143 | if (Operands.size() == 1) return Operands[0]; |
| 1144 | |
Dan Gohman | cfeb6a4 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 1145 | if (Operands.back()->isZero()) { |
| 1146 | Operands.pop_back(); |
Dan Gohman | 8dae138 | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 1147 | return getAddRecExpr(Operands, L); // {X,+,0} --> X |
Dan Gohman | cfeb6a4 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 1148 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1149 | |
Dan Gohman | d9cc749 | 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 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1163 | SCEVAddRecExpr *&Result = |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 1164 | (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(), |
| 1165 | Operands.end()))]; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1166 | if (Result == 0) Result = new SCEVAddRecExpr(Operands, L); |
| 1167 | return Result; |
| 1168 | } |
| 1169 | |
Nick Lewycky | c54c561 | 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 | 3e63076 | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 1192 | ConstantInt *Fold = ConstantInt::get( |
Nick Lewycky | c54c561 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 1193 | APIntOps::smax(LHSC->getValue()->getValue(), |
| 1194 | RHSC->getValue()->getValue())); |
Nick Lewycky | 3e63076 | 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 | c54c561 | 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 | 3e63076 | 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 | c54c561 | 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 | 3e63076 | 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 | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1330 | SCEVHandle ScalarEvolution::getUnknown(Value *V) { |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 1331 | if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1332 | return getConstant(CI); |
Chris Lattner | b336409 | 2006-10-04 21:49:37 +0000 | [diff] [blame] | 1333 | SCEVUnknown *&Result = (*SCEVUnknowns)[V]; |
Chris Lattner | 0a7f98c | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 1334 | if (Result == 0) Result = new SCEVUnknown(V); |
| 1335 | return Result; |
| 1336 | } |
| 1337 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1338 | |
| 1339 | //===----------------------------------------------------------------------===// |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1340 | // ScalarEvolutionsImpl Definition and Implementation |
| 1341 | //===----------------------------------------------------------------------===// |
| 1342 | // |
| 1343 | /// ScalarEvolutionsImpl - This class implements the main driver for the scalar |
| 1344 | /// evolution code. |
| 1345 | /// |
| 1346 | namespace { |
Chris Lattner | 9525528 | 2006-06-28 23:17:24 +0000 | [diff] [blame] | 1347 | struct VISIBILITY_HIDDEN ScalarEvolutionsImpl { |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1348 | /// SE - A reference to the public ScalarEvolution object. |
| 1349 | ScalarEvolution &SE; |
| 1350 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1351 | /// F - The function we are analyzing. |
| 1352 | /// |
| 1353 | Function &F; |
| 1354 | |
| 1355 | /// LI - The loop information for the function we are currently analyzing. |
| 1356 | /// |
| 1357 | LoopInfo &LI; |
| 1358 | |
| 1359 | /// UnknownValue - This SCEV is used to represent unknown trip counts and |
| 1360 | /// things. |
| 1361 | SCEVHandle UnknownValue; |
| 1362 | |
| 1363 | /// Scalars - This is a cache of the scalars we have analyzed so far. |
| 1364 | /// |
| 1365 | std::map<Value*, SCEVHandle> Scalars; |
| 1366 | |
| 1367 | /// IterationCounts - Cache the iteration count of the loops for this |
| 1368 | /// function as they are computed. |
| 1369 | std::map<const Loop*, SCEVHandle> IterationCounts; |
| 1370 | |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1371 | /// ConstantEvolutionLoopExitValue - This map contains entries for all of |
| 1372 | /// the PHI instructions that we attempt to compute constant evolutions for. |
| 1373 | /// This allows us to avoid potentially expensive recomputation of these |
| 1374 | /// properties. An instruction maps to null if we are unable to compute its |
| 1375 | /// exit value. |
| 1376 | std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 1377 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1378 | public: |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1379 | ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li) |
| 1380 | : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {} |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1381 | |
| 1382 | /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the |
| 1383 | /// expression and create a new one. |
| 1384 | SCEVHandle getSCEV(Value *V); |
| 1385 | |
Chris Lattner | a0740fb | 2005-08-09 23:36:33 +0000 | [diff] [blame] | 1386 | /// hasSCEV - Return true if the SCEV for this value has already been |
| 1387 | /// computed. |
| 1388 | bool hasSCEV(Value *V) const { |
| 1389 | return Scalars.count(V); |
| 1390 | } |
| 1391 | |
| 1392 | /// setSCEV - Insert the specified SCEV into the map of current SCEVs for |
| 1393 | /// the specified value. |
| 1394 | void setSCEV(Value *V, const SCEVHandle &H) { |
| 1395 | bool isNew = Scalars.insert(std::make_pair(V, H)).second; |
| 1396 | assert(isNew && "This entry already existed!"); |
Devang Patel | 89d0a4d | 2008-11-11 19:17:41 +0000 | [diff] [blame] | 1397 | isNew = false; |
Chris Lattner | a0740fb | 2005-08-09 23:36:33 +0000 | [diff] [blame] | 1398 | } |
| 1399 | |
| 1400 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1401 | /// getSCEVAtScope - Compute the value of the specified expression within |
| 1402 | /// the indicated loop (which may be null to indicate in no loop). If the |
| 1403 | /// expression cannot be evaluated, return UnknownValue itself. |
| 1404 | SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L); |
| 1405 | |
| 1406 | |
Dan Gohman | c2390b1 | 2009-02-12 22:19:27 +0000 | [diff] [blame^] | 1407 | /// isLoopGuardedByCond - Test whether entry to the loop is protected by |
| 1408 | /// a conditional between LHS and RHS. |
| 1409 | bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred, |
| 1410 | SCEV *LHS, SCEV *RHS); |
| 1411 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1412 | /// hasLoopInvariantIterationCount - Return true if the specified loop has |
| 1413 | /// an analyzable loop-invariant iteration count. |
| 1414 | bool hasLoopInvariantIterationCount(const Loop *L); |
| 1415 | |
| 1416 | /// getIterationCount - If the specified loop has a predictable iteration |
| 1417 | /// count, return it. Note that it is not valid to call this method on a |
| 1418 | /// loop without a loop-invariant iteration count. |
| 1419 | SCEVHandle getIterationCount(const Loop *L); |
| 1420 | |
Dan Gohman | 5cec4db | 2007-06-19 14:28:31 +0000 | [diff] [blame] | 1421 | /// deleteValueFromRecords - This method should be called by the |
| 1422 | /// client before it removes a value from the program, to make sure |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1423 | /// that no dangling references are left around. |
Dan Gohman | 5cec4db | 2007-06-19 14:28:31 +0000 | [diff] [blame] | 1424 | void deleteValueFromRecords(Value *V); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1425 | |
| 1426 | private: |
| 1427 | /// createSCEV - We know that there is no SCEV for the specified value. |
| 1428 | /// Analyze the expression. |
| 1429 | SCEVHandle createSCEV(Value *V); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1430 | |
| 1431 | /// createNodeForPHI - Provide the special handling we need to analyze PHI |
| 1432 | /// SCEVs. |
| 1433 | SCEVHandle createNodeForPHI(PHINode *PN); |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 1434 | |
| 1435 | /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value |
| 1436 | /// for the specified instruction and replaces any references to the |
| 1437 | /// symbolic value SymName with the specified value. This is used during |
| 1438 | /// PHI resolution. |
| 1439 | void ReplaceSymbolicValueWithConcrete(Instruction *I, |
| 1440 | const SCEVHandle &SymName, |
| 1441 | const SCEVHandle &NewVal); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1442 | |
| 1443 | /// ComputeIterationCount - Compute the number of times the specified loop |
| 1444 | /// will iterate. |
| 1445 | SCEVHandle ComputeIterationCount(const Loop *L); |
| 1446 | |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 1447 | /// ComputeLoadConstantCompareIterationCount - Given an exit condition of |
Nick Lewycky | 6e801dc | 2007-11-20 08:44:50 +0000 | [diff] [blame] | 1448 | /// 'icmp op load X, cst', try to see if we can compute the trip count. |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 1449 | SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI, |
| 1450 | Constant *RHS, |
| 1451 | const Loop *L, |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1452 | ICmpInst::Predicate p); |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 1453 | |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 1454 | /// ComputeIterationCountExhaustively - If the trip is known to execute a |
| 1455 | /// constant number of times (the condition evolves only from constants), |
| 1456 | /// try to evaluate a few iterations of the loop until we get the exit |
| 1457 | /// condition gets a value of ExitWhen (true or false). If we cannot |
| 1458 | /// evaluate the trip count of the loop, return UnknownValue. |
| 1459 | SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond, |
| 1460 | bool ExitWhen); |
| 1461 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1462 | /// HowFarToZero - Return the number of times a backedge comparing the |
| 1463 | /// specified value to zero will execute. If not computable, return |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 1464 | /// UnknownValue. |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1465 | SCEVHandle HowFarToZero(SCEV *V, const Loop *L); |
| 1466 | |
| 1467 | /// HowFarToNonZero - Return the number of times a backedge checking the |
| 1468 | /// specified value for nonzero will execute. If not computable, return |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 1469 | /// UnknownValue. |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1470 | SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L); |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1471 | |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 1472 | /// HowManyLessThans - Return the number of times a backedge containing the |
| 1473 | /// specified less-than comparison will execute. If not computable, return |
Nick Lewycky | d6dac0e | 2007-08-06 19:21:00 +0000 | [diff] [blame] | 1474 | /// UnknownValue. isSigned specifies whether the less-than is signed. |
| 1475 | SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, |
Nick Lewycky | 789558d | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 1476 | bool isSigned); |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 1477 | |
Dan Gohman | fd6edef | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 1478 | /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB |
| 1479 | /// (which may not be an immediate predecessor) which has exactly one |
| 1480 | /// successor from which BB is reachable, or null if no such block is |
| 1481 | /// found. |
| 1482 | BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB); |
| 1483 | |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1484 | /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is |
| 1485 | /// in the header of its containing loop, we know the loop executes a |
| 1486 | /// constant number of times, and the PHI node is just a recurrence |
| 1487 | /// involving constants, fold it. |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 1488 | Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 1489 | const Loop *L); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1490 | }; |
| 1491 | } |
| 1492 | |
| 1493 | //===----------------------------------------------------------------------===// |
| 1494 | // Basic SCEV Analysis and PHI Idiom Recognition Code |
| 1495 | // |
| 1496 | |
Dan Gohman | 5cec4db | 2007-06-19 14:28:31 +0000 | [diff] [blame] | 1497 | /// deleteValueFromRecords - This method should be called by the |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1498 | /// client before it removes an instruction from the program, to make sure |
| 1499 | /// that no dangling references are left around. |
Dan Gohman | 5cec4db | 2007-06-19 14:28:31 +0000 | [diff] [blame] | 1500 | void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) { |
| 1501 | SmallVector<Value *, 16> Worklist; |
Nick Lewycky | 9d0332f | 2007-06-06 04:12:20 +0000 | [diff] [blame] | 1502 | |
Dan Gohman | 5cec4db | 2007-06-19 14:28:31 +0000 | [diff] [blame] | 1503 | if (Scalars.erase(V)) { |
| 1504 | if (PHINode *PN = dyn_cast<PHINode>(V)) |
Nick Lewycky | 9d0332f | 2007-06-06 04:12:20 +0000 | [diff] [blame] | 1505 | ConstantEvolutionLoopExitValue.erase(PN); |
Dan Gohman | 5cec4db | 2007-06-19 14:28:31 +0000 | [diff] [blame] | 1506 | Worklist.push_back(V); |
Nick Lewycky | 9d0332f | 2007-06-06 04:12:20 +0000 | [diff] [blame] | 1507 | } |
| 1508 | |
| 1509 | while (!Worklist.empty()) { |
Dan Gohman | 5cec4db | 2007-06-19 14:28:31 +0000 | [diff] [blame] | 1510 | Value *VV = Worklist.back(); |
Nick Lewycky | 9d0332f | 2007-06-06 04:12:20 +0000 | [diff] [blame] | 1511 | Worklist.pop_back(); |
| 1512 | |
Dan Gohman | 5cec4db | 2007-06-19 14:28:31 +0000 | [diff] [blame] | 1513 | for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end(); |
Nick Lewycky | 9d0332f | 2007-06-06 04:12:20 +0000 | [diff] [blame] | 1514 | UI != UE; ++UI) { |
Nick Lewycky | 51e844b | 2007-06-06 11:26:20 +0000 | [diff] [blame] | 1515 | Instruction *Inst = cast<Instruction>(*UI); |
| 1516 | if (Scalars.erase(Inst)) { |
Dan Gohman | 5cec4db | 2007-06-19 14:28:31 +0000 | [diff] [blame] | 1517 | if (PHINode *PN = dyn_cast<PHINode>(VV)) |
Nick Lewycky | 9d0332f | 2007-06-06 04:12:20 +0000 | [diff] [blame] | 1518 | ConstantEvolutionLoopExitValue.erase(PN); |
| 1519 | Worklist.push_back(Inst); |
| 1520 | } |
| 1521 | } |
| 1522 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1523 | } |
| 1524 | |
| 1525 | |
| 1526 | /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the |
| 1527 | /// expression and create a new one. |
| 1528 | SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) { |
| 1529 | assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!"); |
| 1530 | |
| 1531 | std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V); |
| 1532 | if (I != Scalars.end()) return I->second; |
| 1533 | SCEVHandle S = createSCEV(V); |
| 1534 | Scalars.insert(std::make_pair(V, S)); |
| 1535 | return S; |
| 1536 | } |
| 1537 | |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 1538 | /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for |
| 1539 | /// the specified instruction and replaces any references to the symbolic value |
| 1540 | /// SymName with the specified value. This is used during PHI resolution. |
| 1541 | void ScalarEvolutionsImpl:: |
| 1542 | ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName, |
| 1543 | const SCEVHandle &NewVal) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1544 | std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I); |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 1545 | if (SI == Scalars.end()) return; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1546 | |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 1547 | SCEVHandle NV = |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1548 | SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE); |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 1549 | if (NV == SI->second) return; // No change. |
| 1550 | |
| 1551 | SI->second = NV; // Update the scalars map! |
| 1552 | |
| 1553 | // Any instruction values that use this instruction might also need to be |
| 1554 | // updated! |
| 1555 | for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); |
| 1556 | UI != E; ++UI) |
| 1557 | ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal); |
| 1558 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1559 | |
| 1560 | /// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in |
| 1561 | /// a loop header, making it a potential recurrence, or it doesn't. |
| 1562 | /// |
| 1563 | SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) { |
| 1564 | if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized. |
| 1565 | if (const Loop *L = LI.getLoopFor(PN->getParent())) |
| 1566 | if (L->getHeader() == PN->getParent()) { |
| 1567 | // If it lives in the loop header, it has two incoming values, one |
| 1568 | // from outside the loop, and one from inside. |
| 1569 | unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0)); |
| 1570 | unsigned BackEdge = IncomingEdge^1; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 1571 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1572 | // While we are analyzing this PHI node, handle its value symbolically. |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1573 | SCEVHandle SymbolicName = SE.getUnknown(PN); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1574 | assert(Scalars.find(PN) == Scalars.end() && |
| 1575 | "PHI node already processed?"); |
| 1576 | Scalars.insert(std::make_pair(PN, SymbolicName)); |
| 1577 | |
| 1578 | // Using this symbolic name for the PHI, analyze the value coming around |
| 1579 | // the back-edge. |
| 1580 | SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge)); |
| 1581 | |
| 1582 | // NOTE: If BEValue is loop invariant, we know that the PHI node just |
| 1583 | // has a special value for the first iteration of the loop. |
| 1584 | |
| 1585 | // If the value coming around the backedge is an add with the symbolic |
| 1586 | // value we just inserted, then we found a simple induction variable! |
| 1587 | if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { |
| 1588 | // If there is a single occurrence of the symbolic value, replace it |
| 1589 | // with a recurrence. |
| 1590 | unsigned FoundIndex = Add->getNumOperands(); |
| 1591 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) |
| 1592 | if (Add->getOperand(i) == SymbolicName) |
| 1593 | if (FoundIndex == e) { |
| 1594 | FoundIndex = i; |
| 1595 | break; |
| 1596 | } |
| 1597 | |
| 1598 | if (FoundIndex != Add->getNumOperands()) { |
| 1599 | // Create an add with everything but the specified operand. |
| 1600 | std::vector<SCEVHandle> Ops; |
| 1601 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) |
| 1602 | if (i != FoundIndex) |
| 1603 | Ops.push_back(Add->getOperand(i)); |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1604 | SCEVHandle Accum = SE.getAddExpr(Ops); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1605 | |
| 1606 | // This is not a valid addrec if the step amount is varying each |
| 1607 | // loop iteration, but is not itself an addrec in this loop. |
| 1608 | if (Accum->isLoopInvariant(L) || |
| 1609 | (isa<SCEVAddRecExpr>(Accum) && |
| 1610 | cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { |
| 1611 | SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge)); |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1612 | SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1613 | |
| 1614 | // Okay, for the entire analysis of this edge we assumed the PHI |
| 1615 | // to be symbolic. We now need to go back and update all of the |
| 1616 | // entries for the scalars that use the PHI (except for the PHI |
| 1617 | // itself) to use the new analyzed value instead of the "symbolic" |
| 1618 | // value. |
Chris Lattner | 4dc534c | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 1619 | ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1620 | return PHISCEV; |
| 1621 | } |
| 1622 | } |
Chris Lattner | 97156e7 | 2006-04-26 18:34:07 +0000 | [diff] [blame] | 1623 | } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) { |
| 1624 | // Otherwise, this could be a loop like this: |
| 1625 | // i = 0; for (j = 1; ..; ++j) { .... i = j; } |
| 1626 | // In this case, j = {1,+,1} and BEValue is j. |
| 1627 | // Because the other in-value of i (0) fits the evolution of BEValue |
| 1628 | // i really is an addrec evolution. |
| 1629 | if (AddRec->getLoop() == L && AddRec->isAffine()) { |
| 1630 | SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge)); |
| 1631 | |
| 1632 | // If StartVal = j.start - j.stride, we can use StartVal as the |
| 1633 | // initial step of the addrec evolution. |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1634 | if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0), |
| 1635 | AddRec->getOperand(1))) { |
Chris Lattner | 97156e7 | 2006-04-26 18:34:07 +0000 | [diff] [blame] | 1636 | SCEVHandle PHISCEV = |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1637 | SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L); |
Chris Lattner | 97156e7 | 2006-04-26 18:34:07 +0000 | [diff] [blame] | 1638 | |
| 1639 | // Okay, for the entire analysis of this edge we assumed the PHI |
| 1640 | // to be symbolic. We now need to go back and update all of the |
| 1641 | // entries for the scalars that use the PHI (except for the PHI |
| 1642 | // itself) to use the new analyzed value instead of the "symbolic" |
| 1643 | // value. |
| 1644 | ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV); |
| 1645 | return PHISCEV; |
| 1646 | } |
| 1647 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1648 | } |
| 1649 | |
| 1650 | return SymbolicName; |
| 1651 | } |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 1652 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1653 | // If it's not a loop phi, we can't handle it yet. |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1654 | return SE.getUnknown(PN); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1655 | } |
| 1656 | |
Nick Lewycky | 83bb005 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 1657 | /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is |
| 1658 | /// guaranteed to end in (at every loop iteration). It is, at the same time, |
| 1659 | /// the minimum number of times S is divisible by 2. For example, given {4,+,8} |
| 1660 | /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S. |
| 1661 | static uint32_t GetMinTrailingZeros(SCEVHandle S) { |
| 1662 | if (SCEVConstant *C = dyn_cast<SCEVConstant>(S)) |
Chris Lattner | 8314a0c | 2007-11-23 22:36:49 +0000 | [diff] [blame] | 1663 | return C->getValue()->getValue().countTrailingZeros(); |
Chris Lattner | a17f039 | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 1664 | |
Nick Lewycky | 6e801dc | 2007-11-20 08:44:50 +0000 | [diff] [blame] | 1665 | if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) |
Nick Lewycky | 83bb005 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 1666 | return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth()); |
| 1667 | |
| 1668 | if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { |
| 1669 | uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); |
| 1670 | return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes; |
| 1671 | } |
| 1672 | |
| 1673 | if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { |
| 1674 | uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); |
| 1675 | return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes; |
| 1676 | } |
| 1677 | |
Chris Lattner | a17f039 | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 1678 | if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { |
Nick Lewycky | 83bb005 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 1679 | // The result is the min of all operands results. |
| 1680 | uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); |
| 1681 | for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) |
| 1682 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); |
| 1683 | return MinOpRes; |
Chris Lattner | a17f039 | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 1684 | } |
| 1685 | |
| 1686 | if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { |
Nick Lewycky | 83bb005 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 1687 | // The result is the sum of all operands results. |
| 1688 | uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); |
| 1689 | uint32_t BitWidth = M->getBitWidth(); |
| 1690 | for (unsigned i = 1, e = M->getNumOperands(); |
| 1691 | SumOpRes != BitWidth && i != e; ++i) |
| 1692 | SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), |
| 1693 | BitWidth); |
| 1694 | return SumOpRes; |
Chris Lattner | a17f039 | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 1695 | } |
Nick Lewycky | 83bb005 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 1696 | |
Chris Lattner | a17f039 | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 1697 | if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { |
Nick Lewycky | 83bb005 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 1698 | // The result is the min of all operands results. |
| 1699 | uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); |
| 1700 | for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) |
| 1701 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); |
| 1702 | return MinOpRes; |
Chris Lattner | a17f039 | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 1703 | } |
Nick Lewycky | 83bb005 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 1704 | |
Nick Lewycky | c54c561 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 1705 | if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { |
| 1706 | // The result is the min of all operands results. |
| 1707 | uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); |
| 1708 | for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) |
| 1709 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); |
| 1710 | return MinOpRes; |
| 1711 | } |
| 1712 | |
Nick Lewycky | 3e63076 | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 1713 | if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { |
| 1714 | // The result is the min of all operands results. |
| 1715 | uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); |
| 1716 | for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) |
| 1717 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); |
| 1718 | return MinOpRes; |
| 1719 | } |
| 1720 | |
Nick Lewycky | 789558d | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 1721 | // SCEVUDivExpr, SCEVUnknown |
Nick Lewycky | 83bb005 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 1722 | return 0; |
Chris Lattner | a17f039 | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 1723 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1724 | |
| 1725 | /// createSCEV - We know that there is no SCEV for the specified value. |
| 1726 | /// Analyze the expression. |
| 1727 | /// |
| 1728 | SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) { |
Chris Lattner | 42b5e08 | 2007-11-23 08:46:22 +0000 | [diff] [blame] | 1729 | if (!isa<IntegerType>(V->getType())) |
| 1730 | return SE.getUnknown(V); |
| 1731 | |
Dan Gohman | 6c459a2 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 1732 | unsigned Opcode = Instruction::UserOp1; |
| 1733 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 1734 | Opcode = I->getOpcode(); |
| 1735 | else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) |
| 1736 | Opcode = CE->getOpcode(); |
| 1737 | else |
| 1738 | return SE.getUnknown(V); |
Chris Lattner | 2811f2a | 2007-04-02 05:41:38 +0000 | [diff] [blame] | 1739 | |
Dan Gohman | 6c459a2 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 1740 | User *U = cast<User>(V); |
| 1741 | switch (Opcode) { |
| 1742 | case Instruction::Add: |
| 1743 | return SE.getAddExpr(getSCEV(U->getOperand(0)), |
| 1744 | getSCEV(U->getOperand(1))); |
| 1745 | case Instruction::Mul: |
| 1746 | return SE.getMulExpr(getSCEV(U->getOperand(0)), |
| 1747 | getSCEV(U->getOperand(1))); |
| 1748 | case Instruction::UDiv: |
| 1749 | return SE.getUDivExpr(getSCEV(U->getOperand(0)), |
| 1750 | getSCEV(U->getOperand(1))); |
| 1751 | case Instruction::Sub: |
| 1752 | return SE.getMinusSCEV(getSCEV(U->getOperand(0)), |
| 1753 | getSCEV(U->getOperand(1))); |
| 1754 | case Instruction::Or: |
| 1755 | // If the RHS of the Or is a constant, we may have something like: |
| 1756 | // X*4+1 which got turned into X*4|1. Handle this as an Add so loop |
| 1757 | // optimizations will transparently handle this case. |
| 1758 | // |
| 1759 | // In order for this transformation to be safe, the LHS must be of the |
| 1760 | // form X*(2^n) and the Or constant must be less than 2^n. |
| 1761 | if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { |
| 1762 | SCEVHandle LHS = getSCEV(U->getOperand(0)); |
| 1763 | const APInt &CIVal = CI->getValue(); |
| 1764 | if (GetMinTrailingZeros(LHS) >= |
| 1765 | (CIVal.getBitWidth() - CIVal.countLeadingZeros())) |
| 1766 | return SE.getAddExpr(LHS, getSCEV(U->getOperand(1))); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1767 | } |
Dan Gohman | 6c459a2 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 1768 | break; |
| 1769 | case Instruction::Xor: |
Dan Gohman | 6c459a2 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 1770 | if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { |
Nick Lewycky | 01eaf80 | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 1771 | // If the RHS of the xor is a signbit, then this is just an add. |
| 1772 | // Instcombine turns add of signbit into xor as a strength reduction step. |
Dan Gohman | 6c459a2 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 1773 | if (CI->getValue().isSignBit()) |
| 1774 | return SE.getAddExpr(getSCEV(U->getOperand(0)), |
| 1775 | getSCEV(U->getOperand(1))); |
Nick Lewycky | 01eaf80 | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 1776 | |
| 1777 | // If the RHS of xor is -1, then this is a not operation. |
Dan Gohman | 6c459a2 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 1778 | else if (CI->isAllOnesValue()) |
| 1779 | return SE.getNotSCEV(getSCEV(U->getOperand(0))); |
| 1780 | } |
| 1781 | break; |
| 1782 | |
| 1783 | case Instruction::Shl: |
| 1784 | // Turn shift left of a constant amount into a multiply. |
| 1785 | if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) { |
| 1786 | uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth(); |
| 1787 | Constant *X = ConstantInt::get( |
| 1788 | APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth))); |
| 1789 | return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X)); |
| 1790 | } |
| 1791 | break; |
| 1792 | |
Nick Lewycky | 01eaf80 | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 1793 | case Instruction::LShr: |
Nick Lewycky | 789558d | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 1794 | // Turn logical shift right of a constant into a unsigned divide. |
Nick Lewycky | 01eaf80 | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 1795 | if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) { |
| 1796 | uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth(); |
| 1797 | Constant *X = ConstantInt::get( |
| 1798 | APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth))); |
| 1799 | return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X)); |
| 1800 | } |
| 1801 | break; |
| 1802 | |
Dan Gohman | 6c459a2 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 1803 | case Instruction::Trunc: |
| 1804 | return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); |
| 1805 | |
| 1806 | case Instruction::ZExt: |
| 1807 | return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); |
| 1808 | |
| 1809 | case Instruction::SExt: |
| 1810 | return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); |
| 1811 | |
| 1812 | case Instruction::BitCast: |
| 1813 | // BitCasts are no-op casts so we just eliminate the cast. |
| 1814 | if (U->getType()->isInteger() && |
| 1815 | U->getOperand(0)->getType()->isInteger()) |
| 1816 | return getSCEV(U->getOperand(0)); |
| 1817 | break; |
| 1818 | |
| 1819 | case Instruction::PHI: |
| 1820 | return createNodeForPHI(cast<PHINode>(U)); |
| 1821 | |
| 1822 | case Instruction::Select: |
| 1823 | // This could be a smax or umax that was lowered earlier. |
| 1824 | // Try to recover it. |
| 1825 | if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) { |
| 1826 | Value *LHS = ICI->getOperand(0); |
| 1827 | Value *RHS = ICI->getOperand(1); |
| 1828 | switch (ICI->getPredicate()) { |
| 1829 | case ICmpInst::ICMP_SLT: |
| 1830 | case ICmpInst::ICMP_SLE: |
| 1831 | std::swap(LHS, RHS); |
| 1832 | // fall through |
| 1833 | case ICmpInst::ICMP_SGT: |
| 1834 | case ICmpInst::ICMP_SGE: |
| 1835 | if (LHS == U->getOperand(1) && RHS == U->getOperand(2)) |
| 1836 | return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS)); |
| 1837 | else if (LHS == U->getOperand(2) && RHS == U->getOperand(1)) |
Eli Friedman | 1fbffe0 | 2008-07-30 04:36:32 +0000 | [diff] [blame] | 1838 | // ~smax(~x, ~y) == smin(x, y). |
| 1839 | return SE.getNotSCEV(SE.getSMaxExpr( |
| 1840 | SE.getNotSCEV(getSCEV(LHS)), |
| 1841 | SE.getNotSCEV(getSCEV(RHS)))); |
Dan Gohman | 6c459a2 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 1842 | break; |
| 1843 | case ICmpInst::ICMP_ULT: |
| 1844 | case ICmpInst::ICMP_ULE: |
| 1845 | std::swap(LHS, RHS); |
| 1846 | // fall through |
| 1847 | case ICmpInst::ICMP_UGT: |
| 1848 | case ICmpInst::ICMP_UGE: |
| 1849 | if (LHS == U->getOperand(1) && RHS == U->getOperand(2)) |
| 1850 | return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS)); |
| 1851 | else if (LHS == U->getOperand(2) && RHS == U->getOperand(1)) |
| 1852 | // ~umax(~x, ~y) == umin(x, y) |
| 1853 | return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)), |
| 1854 | SE.getNotSCEV(getSCEV(RHS)))); |
| 1855 | break; |
| 1856 | default: |
| 1857 | break; |
| 1858 | } |
| 1859 | } |
| 1860 | |
| 1861 | default: // We cannot analyze this expression. |
| 1862 | break; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1863 | } |
| 1864 | |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 1865 | return SE.getUnknown(V); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1866 | } |
| 1867 | |
| 1868 | |
| 1869 | |
| 1870 | //===----------------------------------------------------------------------===// |
| 1871 | // Iteration Count Computation Code |
| 1872 | // |
| 1873 | |
| 1874 | /// getIterationCount - If the specified loop has a predictable iteration |
| 1875 | /// count, return it. Note that it is not valid to call this method on a |
| 1876 | /// loop without a loop-invariant iteration count. |
| 1877 | SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) { |
| 1878 | std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L); |
| 1879 | if (I == IterationCounts.end()) { |
| 1880 | SCEVHandle ItCount = ComputeIterationCount(L); |
| 1881 | I = IterationCounts.insert(std::make_pair(L, ItCount)).first; |
| 1882 | if (ItCount != UnknownValue) { |
| 1883 | assert(ItCount->isLoopInvariant(L) && |
| 1884 | "Computed trip count isn't loop invariant for loop!"); |
| 1885 | ++NumTripCountsComputed; |
| 1886 | } else if (isa<PHINode>(L->getHeader()->begin())) { |
| 1887 | // Only count loops that have phi nodes as not being computable. |
| 1888 | ++NumTripCountsNotComputed; |
| 1889 | } |
| 1890 | } |
| 1891 | return I->second; |
| 1892 | } |
| 1893 | |
| 1894 | /// ComputeIterationCount - Compute the number of times the specified loop |
| 1895 | /// will iterate. |
| 1896 | SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) { |
| 1897 | // If the loop has a non-one exit block count, we can't analyze it. |
Devang Patel | b7211a2 | 2007-08-21 00:31:24 +0000 | [diff] [blame] | 1898 | SmallVector<BasicBlock*, 8> ExitBlocks; |
Chris Lattner | f1ab4b4 | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 1899 | L->getExitBlocks(ExitBlocks); |
| 1900 | if (ExitBlocks.size() != 1) return UnknownValue; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1901 | |
| 1902 | // Okay, there is one exit block. Try to find the condition that causes the |
| 1903 | // loop to be exited. |
Chris Lattner | f1ab4b4 | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 1904 | BasicBlock *ExitBlock = ExitBlocks[0]; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1905 | |
| 1906 | BasicBlock *ExitingBlock = 0; |
| 1907 | for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock); |
| 1908 | PI != E; ++PI) |
| 1909 | if (L->contains(*PI)) { |
| 1910 | if (ExitingBlock == 0) |
| 1911 | ExitingBlock = *PI; |
| 1912 | else |
| 1913 | return UnknownValue; // More than one block exiting! |
| 1914 | } |
| 1915 | assert(ExitingBlock && "No exits from loop, something is broken!"); |
| 1916 | |
| 1917 | // Okay, we've computed the exiting block. See what condition causes us to |
| 1918 | // exit. |
| 1919 | // |
| 1920 | // FIXME: we should be able to handle switch instructions (with a single exit) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1921 | BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator()); |
| 1922 | if (ExitBr == 0) return UnknownValue; |
| 1923 | assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!"); |
Chris Lattner | 8b0e360 | 2007-01-07 02:24:26 +0000 | [diff] [blame] | 1924 | |
| 1925 | // At this point, we know we have a conditional branch that determines whether |
| 1926 | // the loop is exited. However, we don't know if the branch is executed each |
| 1927 | // time through the loop. If not, then the execution count of the branch will |
| 1928 | // not be equal to the trip count of the loop. |
| 1929 | // |
| 1930 | // Currently we check for this by checking to see if the Exit branch goes to |
| 1931 | // the loop header. If so, we know it will always execute the same number of |
Chris Lattner | 192e403 | 2007-01-14 01:24:47 +0000 | [diff] [blame] | 1932 | // times as the loop. We also handle the case where the exit block *is* the |
| 1933 | // loop header. This is common for un-rotated loops. More extensive analysis |
| 1934 | // could be done to handle more cases here. |
Chris Lattner | 8b0e360 | 2007-01-07 02:24:26 +0000 | [diff] [blame] | 1935 | if (ExitBr->getSuccessor(0) != L->getHeader() && |
Chris Lattner | 192e403 | 2007-01-14 01:24:47 +0000 | [diff] [blame] | 1936 | ExitBr->getSuccessor(1) != L->getHeader() && |
| 1937 | ExitBr->getParent() != L->getHeader()) |
Chris Lattner | 8b0e360 | 2007-01-07 02:24:26 +0000 | [diff] [blame] | 1938 | return UnknownValue; |
| 1939 | |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1940 | ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition()); |
| 1941 | |
Nick Lewycky | 3b71165 | 2008-02-21 08:34:02 +0000 | [diff] [blame] | 1942 | // If it's not an integer comparison then compute it the hard way. |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1943 | // Note that ICmpInst deals with pointer comparisons too so we must check |
| 1944 | // the type of the operand. |
Chris Lattner | 8b0e360 | 2007-01-07 02:24:26 +0000 | [diff] [blame] | 1945 | if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType())) |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 1946 | return ComputeIterationCountExhaustively(L, ExitBr->getCondition(), |
| 1947 | ExitBr->getSuccessor(0) == ExitBlock); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1948 | |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1949 | // If the condition was exit on true, convert the condition to exit on false |
| 1950 | ICmpInst::Predicate Cond; |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 1951 | if (ExitBr->getSuccessor(1) == ExitBlock) |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1952 | Cond = ExitCond->getPredicate(); |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 1953 | else |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1954 | Cond = ExitCond->getInversePredicate(); |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 1955 | |
| 1956 | // Handle common loops like: for (X = "string"; *X; ++X) |
| 1957 | if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) |
| 1958 | if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { |
| 1959 | SCEVHandle ItCnt = |
| 1960 | ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond); |
| 1961 | if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt; |
| 1962 | } |
| 1963 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1964 | SCEVHandle LHS = getSCEV(ExitCond->getOperand(0)); |
| 1965 | SCEVHandle RHS = getSCEV(ExitCond->getOperand(1)); |
| 1966 | |
| 1967 | // Try to evaluate any dependencies out of the loop. |
| 1968 | SCEVHandle Tmp = getSCEVAtScope(LHS, L); |
| 1969 | if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp; |
| 1970 | Tmp = getSCEVAtScope(RHS, L); |
| 1971 | if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp; |
| 1972 | |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1973 | // At this point, we would like to compute how many iterations of the |
| 1974 | // loop the predicate will return true for these inputs. |
Dan Gohman | 70ff4cf | 2008-09-16 18:52:57 +0000 | [diff] [blame] | 1975 | if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) { |
| 1976 | // If there is a loop-invariant, force it into the RHS. |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1977 | std::swap(LHS, RHS); |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 1978 | Cond = ICmpInst::getSwappedPredicate(Cond); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1979 | } |
| 1980 | |
| 1981 | // FIXME: think about handling pointer comparisons! i.e.: |
| 1982 | // while (P != P+100) ++P; |
| 1983 | |
| 1984 | // If we have a comparison of a chrec against a constant, try to use value |
| 1985 | // ranges to answer this query. |
| 1986 | if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) |
| 1987 | if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) |
| 1988 | if (AddRec->getLoop() == L) { |
| 1989 | // Form the comparison range using the constant of the correct type so |
| 1990 | // that the ConstantRange class knows to do a signed or unsigned |
| 1991 | // comparison. |
| 1992 | ConstantInt *CompVal = RHSC->getValue(); |
| 1993 | const Type *RealTy = ExitCond->getOperand(0)->getType(); |
Reid Spencer | 4da4912 | 2006-12-12 05:05:00 +0000 | [diff] [blame] | 1994 | CompVal = dyn_cast<ConstantInt>( |
Reid Spencer | b6ba3e6 | 2006-12-12 09:17:50 +0000 | [diff] [blame] | 1995 | ConstantExpr::getBitCast(CompVal, RealTy)); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1996 | if (CompVal) { |
| 1997 | // Form the constant range. |
Reid Spencer | c6aedf7 | 2007-02-28 22:03:51 +0000 | [diff] [blame] | 1998 | ConstantRange CompRange( |
| 1999 | ICmpInst::makeConstantRange(Cond, CompVal->getValue())); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2000 | |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2001 | SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2002 | if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; |
| 2003 | } |
| 2004 | } |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2005 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2006 | switch (Cond) { |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2007 | case ICmpInst::ICMP_NE: { // while (X != Y) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2008 | // Convert to: while (X-Y != 0) |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2009 | SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L); |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2010 | if (!isa<SCEVCouldNotCompute>(TC)) return TC; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2011 | break; |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2012 | } |
| 2013 | case ICmpInst::ICMP_EQ: { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2014 | // Convert to: while (X-Y == 0) // while (X == Y) |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2015 | SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L); |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2016 | if (!isa<SCEVCouldNotCompute>(TC)) return TC; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2017 | break; |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2018 | } |
| 2019 | case ICmpInst::ICMP_SLT: { |
Nick Lewycky | 789558d | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 2020 | SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true); |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2021 | if (!isa<SCEVCouldNotCompute>(TC)) return TC; |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 2022 | break; |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2023 | } |
| 2024 | case ICmpInst::ICMP_SGT: { |
Eli Friedman | 068acc3 | 2008-07-30 00:04:08 +0000 | [diff] [blame] | 2025 | SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS), |
Nick Lewycky | 789558d | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 2026 | SE.getNotSCEV(RHS), L, true); |
Nick Lewycky | d6dac0e | 2007-08-06 19:21:00 +0000 | [diff] [blame] | 2027 | if (!isa<SCEVCouldNotCompute>(TC)) return TC; |
| 2028 | break; |
| 2029 | } |
| 2030 | case ICmpInst::ICMP_ULT: { |
Nick Lewycky | 789558d | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 2031 | SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false); |
Nick Lewycky | d6dac0e | 2007-08-06 19:21:00 +0000 | [diff] [blame] | 2032 | if (!isa<SCEVCouldNotCompute>(TC)) return TC; |
| 2033 | break; |
| 2034 | } |
| 2035 | case ICmpInst::ICMP_UGT: { |
Dale Johannesen | a0c8fc6 | 2008-04-20 16:58:57 +0000 | [diff] [blame] | 2036 | SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS), |
Nick Lewycky | 789558d | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 2037 | SE.getNotSCEV(RHS), L, false); |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2038 | if (!isa<SCEVCouldNotCompute>(TC)) return TC; |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 2039 | break; |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2040 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2041 | default: |
Chris Lattner | d18d9dc | 2004-04-02 20:26:46 +0000 | [diff] [blame] | 2042 | #if 0 |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 2043 | cerr << "ComputeIterationCount "; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2044 | if (ExitCond->getOperand(0)->getType()->isUnsigned()) |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 2045 | cerr << "[unsigned] "; |
| 2046 | cerr << *LHS << " " |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2047 | << Instruction::getOpcodeName(Instruction::ICmp) |
| 2048 | << " " << *RHS << "\n"; |
Chris Lattner | d18d9dc | 2004-04-02 20:26:46 +0000 | [diff] [blame] | 2049 | #endif |
Chris Lattner | e34c0b4 | 2004-04-03 00:43:03 +0000 | [diff] [blame] | 2050 | break; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2051 | } |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 2052 | return ComputeIterationCountExhaustively(L, ExitCond, |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2053 | ExitBr->getSuccessor(0) == ExitBlock); |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 2054 | } |
| 2055 | |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 2056 | static ConstantInt * |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2057 | EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, |
| 2058 | ScalarEvolution &SE) { |
| 2059 | SCEVHandle InVal = SE.getConstant(C); |
| 2060 | SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE); |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 2061 | assert(isa<SCEVConstant>(Val) && |
| 2062 | "Evaluation of SCEV at constant didn't fold correctly?"); |
| 2063 | return cast<SCEVConstant>(Val)->getValue(); |
| 2064 | } |
| 2065 | |
| 2066 | /// GetAddressedElementFromGlobal - Given a global variable with an initializer |
| 2067 | /// and a GEP expression (missing the pointer index) indexing into it, return |
| 2068 | /// the addressed element of the initializer or null if the index expression is |
| 2069 | /// invalid. |
| 2070 | static Constant * |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2071 | GetAddressedElementFromGlobal(GlobalVariable *GV, |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 2072 | const std::vector<ConstantInt*> &Indices) { |
| 2073 | Constant *Init = GV->getInitializer(); |
| 2074 | for (unsigned i = 0, e = Indices.size(); i != e; ++i) { |
Reid Spencer | b83eb64 | 2006-10-20 07:07:24 +0000 | [diff] [blame] | 2075 | uint64_t Idx = Indices[i]->getZExtValue(); |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 2076 | if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) { |
| 2077 | assert(Idx < CS->getNumOperands() && "Bad struct index!"); |
| 2078 | Init = cast<Constant>(CS->getOperand(Idx)); |
| 2079 | } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) { |
| 2080 | if (Idx >= CA->getNumOperands()) return 0; // Bogus program |
| 2081 | Init = cast<Constant>(CA->getOperand(Idx)); |
| 2082 | } else if (isa<ConstantAggregateZero>(Init)) { |
| 2083 | if (const StructType *STy = dyn_cast<StructType>(Init->getType())) { |
| 2084 | assert(Idx < STy->getNumElements() && "Bad struct index!"); |
| 2085 | Init = Constant::getNullValue(STy->getElementType(Idx)); |
| 2086 | } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) { |
| 2087 | if (Idx >= ATy->getNumElements()) return 0; // Bogus program |
| 2088 | Init = Constant::getNullValue(ATy->getElementType()); |
| 2089 | } else { |
| 2090 | assert(0 && "Unknown constant aggregate type!"); |
| 2091 | } |
| 2092 | return 0; |
| 2093 | } else { |
| 2094 | return 0; // Unknown initializer type |
| 2095 | } |
| 2096 | } |
| 2097 | return Init; |
| 2098 | } |
| 2099 | |
| 2100 | /// ComputeLoadConstantCompareIterationCount - Given an exit condition of |
Nick Lewycky | 08de613 | 2008-05-06 04:03:18 +0000 | [diff] [blame] | 2101 | /// 'icmp op load X, cst', try to see if we can compute the trip count. |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 2102 | SCEVHandle ScalarEvolutionsImpl:: |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2103 | ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS, |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2104 | const Loop *L, |
| 2105 | ICmpInst::Predicate predicate) { |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 2106 | if (LI->isVolatile()) return UnknownValue; |
| 2107 | |
| 2108 | // Check to see if the loaded pointer is a getelementptr of a global. |
| 2109 | GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); |
| 2110 | if (!GEP) return UnknownValue; |
| 2111 | |
| 2112 | // Make sure that it is really a constant global we are gepping, with an |
| 2113 | // initializer, and make sure the first IDX is really 0. |
| 2114 | GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); |
| 2115 | if (!GV || !GV->isConstant() || !GV->hasInitializer() || |
| 2116 | GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || |
| 2117 | !cast<Constant>(GEP->getOperand(1))->isNullValue()) |
| 2118 | return UnknownValue; |
| 2119 | |
| 2120 | // Okay, we allow one non-constant index into the GEP instruction. |
| 2121 | Value *VarIdx = 0; |
| 2122 | std::vector<ConstantInt*> Indexes; |
| 2123 | unsigned VarIdxNum = 0; |
| 2124 | for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) |
| 2125 | if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { |
| 2126 | Indexes.push_back(CI); |
| 2127 | } else if (!isa<ConstantInt>(GEP->getOperand(i))) { |
| 2128 | if (VarIdx) return UnknownValue; // Multiple non-constant idx's. |
| 2129 | VarIdx = GEP->getOperand(i); |
| 2130 | VarIdxNum = i-2; |
| 2131 | Indexes.push_back(0); |
| 2132 | } |
| 2133 | |
| 2134 | // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. |
| 2135 | // Check to see if X is a loop variant variable value now. |
| 2136 | SCEVHandle Idx = getSCEV(VarIdx); |
| 2137 | SCEVHandle Tmp = getSCEVAtScope(Idx, L); |
| 2138 | if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp; |
| 2139 | |
| 2140 | // We can only recognize very limited forms of loop index expressions, in |
| 2141 | // particular, only affine AddRec's like {C1,+,C2}. |
| 2142 | SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); |
| 2143 | if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) || |
| 2144 | !isa<SCEVConstant>(IdxExpr->getOperand(0)) || |
| 2145 | !isa<SCEVConstant>(IdxExpr->getOperand(1))) |
| 2146 | return UnknownValue; |
| 2147 | |
| 2148 | unsigned MaxSteps = MaxBruteForceIterations; |
| 2149 | for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { |
Reid Spencer | b83eb64 | 2006-10-20 07:07:24 +0000 | [diff] [blame] | 2150 | ConstantInt *ItCst = |
Reid Spencer | c5b206b | 2006-12-31 05:48:39 +0000 | [diff] [blame] | 2151 | ConstantInt::get(IdxExpr->getType(), IterationNum); |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2152 | ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE); |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 2153 | |
| 2154 | // Form the GEP offset. |
| 2155 | Indexes[VarIdxNum] = Val; |
| 2156 | |
| 2157 | Constant *Result = GetAddressedElementFromGlobal(GV, Indexes); |
| 2158 | if (Result == 0) break; // Cannot compute! |
| 2159 | |
| 2160 | // Evaluate the condition for this iteration. |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2161 | Result = ConstantExpr::getICmp(predicate, Result, RHS); |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 2162 | if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2163 | if (cast<ConstantInt>(Result)->getValue().isMinValue()) { |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 2164 | #if 0 |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 2165 | cerr << "\n***\n*** Computed loop count " << *ItCst |
| 2166 | << "\n*** From global " << *GV << "*** BB: " << *L->getHeader() |
| 2167 | << "***\n"; |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 2168 | #endif |
| 2169 | ++NumArrayLenItCounts; |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2170 | return SE.getConstant(ItCst); // Found terminating iteration! |
Chris Lattner | 673e02b | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 2171 | } |
| 2172 | } |
| 2173 | return UnknownValue; |
| 2174 | } |
| 2175 | |
| 2176 | |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2177 | /// CanConstantFold - Return true if we can constant fold an instruction of the |
| 2178 | /// specified type, assuming that all operands were constants. |
| 2179 | static bool CanConstantFold(const Instruction *I) { |
Reid Spencer | 832254e | 2007-02-02 02:16:23 +0000 | [diff] [blame] | 2180 | if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2181 | isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I)) |
| 2182 | return true; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2183 | |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2184 | if (const CallInst *CI = dyn_cast<CallInst>(I)) |
| 2185 | if (const Function *F = CI->getCalledFunction()) |
Dan Gohman | fa9b80e | 2008-01-31 01:05:10 +0000 | [diff] [blame] | 2186 | return canConstantFoldCallTo(F); |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2187 | return false; |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 2188 | } |
| 2189 | |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2190 | /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node |
| 2191 | /// in the loop that V is derived from. We allow arbitrary operations along the |
| 2192 | /// way, but the operands of an operation must either be constants or a value |
| 2193 | /// derived from a constant PHI. If this expression does not fit with these |
| 2194 | /// constraints, return null. |
| 2195 | static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { |
| 2196 | // If this is not an instruction, or if this is an instruction outside of the |
| 2197 | // loop, it can't be derived from a loop PHI. |
| 2198 | Instruction *I = dyn_cast<Instruction>(V); |
| 2199 | if (I == 0 || !L->contains(I->getParent())) return 0; |
| 2200 | |
Anton Korobeynikov | ae9f3a3 | 2008-02-20 11:08:44 +0000 | [diff] [blame] | 2201 | if (PHINode *PN = dyn_cast<PHINode>(I)) { |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2202 | if (L->getHeader() == I->getParent()) |
| 2203 | return PN; |
| 2204 | else |
| 2205 | // We don't currently keep track of the control flow needed to evaluate |
| 2206 | // PHIs, so we cannot handle PHIs inside of loops. |
| 2207 | return 0; |
Anton Korobeynikov | ae9f3a3 | 2008-02-20 11:08:44 +0000 | [diff] [blame] | 2208 | } |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2209 | |
| 2210 | // If we won't be able to constant fold this expression even if the operands |
| 2211 | // are constants, return early. |
| 2212 | if (!CanConstantFold(I)) return 0; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2213 | |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2214 | // Otherwise, we can evaluate this instruction if all of its operands are |
| 2215 | // constant or derived from a PHI node themselves. |
| 2216 | PHINode *PHI = 0; |
| 2217 | for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op) |
| 2218 | if (!(isa<Constant>(I->getOperand(Op)) || |
| 2219 | isa<GlobalValue>(I->getOperand(Op)))) { |
| 2220 | PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L); |
| 2221 | if (P == 0) return 0; // Not evolving from PHI |
| 2222 | if (PHI == 0) |
| 2223 | PHI = P; |
| 2224 | else if (PHI != P) |
| 2225 | return 0; // Evolving from multiple different PHIs. |
| 2226 | } |
| 2227 | |
| 2228 | // This is a expression evolving from a constant PHI! |
| 2229 | return PHI; |
| 2230 | } |
| 2231 | |
| 2232 | /// EvaluateExpression - Given an expression that passes the |
| 2233 | /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node |
| 2234 | /// in the loop has the value PHIVal. If we can't fold this expression for some |
| 2235 | /// reason, return null. |
| 2236 | static Constant *EvaluateExpression(Value *V, Constant *PHIVal) { |
| 2237 | if (isa<PHINode>(V)) return PHIVal; |
Reid Spencer | e840434 | 2004-07-18 00:18:30 +0000 | [diff] [blame] | 2238 | if (Constant *C = dyn_cast<Constant>(V)) return C; |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2239 | Instruction *I = cast<Instruction>(V); |
| 2240 | |
| 2241 | std::vector<Constant*> Operands; |
| 2242 | Operands.resize(I->getNumOperands()); |
| 2243 | |
| 2244 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { |
| 2245 | Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal); |
| 2246 | if (Operands[i] == 0) return 0; |
| 2247 | } |
| 2248 | |
Chris Lattner | f286f6f | 2007-12-10 22:53:04 +0000 | [diff] [blame] | 2249 | if (const CmpInst *CI = dyn_cast<CmpInst>(I)) |
| 2250 | return ConstantFoldCompareInstOperands(CI->getPredicate(), |
| 2251 | &Operands[0], Operands.size()); |
| 2252 | else |
| 2253 | return ConstantFoldInstOperands(I->getOpcode(), I->getType(), |
| 2254 | &Operands[0], Operands.size()); |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2255 | } |
| 2256 | |
| 2257 | /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is |
| 2258 | /// in the header of its containing loop, we know the loop executes a |
| 2259 | /// constant number of times, and the PHI node is just a recurrence |
| 2260 | /// involving constants, fold it. |
| 2261 | Constant *ScalarEvolutionsImpl:: |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2262 | getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){ |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2263 | std::map<PHINode*, Constant*>::iterator I = |
| 2264 | ConstantEvolutionLoopExitValue.find(PN); |
| 2265 | if (I != ConstantEvolutionLoopExitValue.end()) |
| 2266 | return I->second; |
| 2267 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2268 | if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations))) |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2269 | return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it. |
| 2270 | |
| 2271 | Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; |
| 2272 | |
| 2273 | // Since the loop is canonicalized, the PHI node must have two entries. One |
| 2274 | // entry must be a constant (coming in from outside of the loop), and the |
| 2275 | // second must be derived from the same PHI. |
| 2276 | bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); |
| 2277 | Constant *StartCST = |
| 2278 | dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge)); |
| 2279 | if (StartCST == 0) |
| 2280 | return RetVal = 0; // Must be a constant. |
| 2281 | |
| 2282 | Value *BEValue = PN->getIncomingValue(SecondIsBackedge); |
| 2283 | PHINode *PN2 = getConstantEvolvingPHI(BEValue, L); |
| 2284 | if (PN2 != PN) |
| 2285 | return RetVal = 0; // Not derived from same PHI. |
| 2286 | |
| 2287 | // Execute the loop symbolically to determine the exit value. |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2288 | if (Its.getActiveBits() >= 32) |
| 2289 | return RetVal = 0; // More than 2^32-1 iterations?? Not doing it! |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2290 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2291 | unsigned NumIterations = Its.getZExtValue(); // must be in range |
| 2292 | unsigned IterationNum = 0; |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2293 | for (Constant *PHIVal = StartCST; ; ++IterationNum) { |
| 2294 | if (IterationNum == NumIterations) |
| 2295 | return RetVal = PHIVal; // Got exit value! |
| 2296 | |
| 2297 | // Compute the value of the PHI node for the next iteration. |
| 2298 | Constant *NextPHI = EvaluateExpression(BEValue, PHIVal); |
| 2299 | if (NextPHI == PHIVal) |
| 2300 | return RetVal = NextPHI; // Stopped evolving! |
| 2301 | if (NextPHI == 0) |
| 2302 | return 0; // Couldn't evaluate! |
| 2303 | PHIVal = NextPHI; |
| 2304 | } |
| 2305 | } |
| 2306 | |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 2307 | /// ComputeIterationCountExhaustively - If the trip is known to execute a |
| 2308 | /// constant number of times (the condition evolves only from constants), |
| 2309 | /// try to evaluate a few iterations of the loop until we get the exit |
| 2310 | /// condition gets a value of ExitWhen (true or false). If we cannot |
| 2311 | /// evaluate the trip count of the loop, return UnknownValue. |
| 2312 | SCEVHandle ScalarEvolutionsImpl:: |
| 2313 | ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) { |
| 2314 | PHINode *PN = getConstantEvolvingPHI(Cond, L); |
| 2315 | if (PN == 0) return UnknownValue; |
| 2316 | |
| 2317 | // Since the loop is canonicalized, the PHI node must have two entries. One |
| 2318 | // entry must be a constant (coming in from outside of the loop), and the |
| 2319 | // second must be derived from the same PHI. |
| 2320 | bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1)); |
| 2321 | Constant *StartCST = |
| 2322 | dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge)); |
| 2323 | if (StartCST == 0) return UnknownValue; // Must be a constant. |
| 2324 | |
| 2325 | Value *BEValue = PN->getIncomingValue(SecondIsBackedge); |
| 2326 | PHINode *PN2 = getConstantEvolvingPHI(BEValue, L); |
| 2327 | if (PN2 != PN) return UnknownValue; // Not derived from same PHI. |
| 2328 | |
| 2329 | // Okay, we find a PHI node that defines the trip count of this loop. Execute |
| 2330 | // the loop symbolically to determine when the condition gets a value of |
| 2331 | // "ExitWhen". |
| 2332 | unsigned IterationNum = 0; |
| 2333 | unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. |
| 2334 | for (Constant *PHIVal = StartCST; |
| 2335 | IterationNum != MaxIterations; ++IterationNum) { |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 2336 | ConstantInt *CondVal = |
| 2337 | dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal)); |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2338 | |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 2339 | // Couldn't symbolically evaluate. |
Chris Lattner | ef3baf0 | 2007-01-12 18:28:58 +0000 | [diff] [blame] | 2340 | if (!CondVal) return UnknownValue; |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 2341 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2342 | if (CondVal->getValue() == uint64_t(ExitWhen)) { |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2343 | ConstantEvolutionLoopExitValue[PN] = PHIVal; |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 2344 | ++NumBruteForceTripCountsComputed; |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2345 | return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum)); |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 2346 | } |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2347 | |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2348 | // Compute the value of the PHI node for the next iteration. |
| 2349 | Constant *NextPHI = EvaluateExpression(BEValue, PHIVal); |
| 2350 | if (NextPHI == 0 || NextPHI == PHIVal) |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 2351 | return UnknownValue; // Couldn't evaluate or not making progress... |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2352 | PHIVal = NextPHI; |
Chris Lattner | 7980fb9 | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 2353 | } |
| 2354 | |
| 2355 | // Too many iterations were needed to evaluate. |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2356 | return UnknownValue; |
| 2357 | } |
| 2358 | |
| 2359 | /// getSCEVAtScope - Compute the value of the specified expression within the |
| 2360 | /// indicated loop (which may be null to indicate in no loop). If the |
| 2361 | /// expression cannot be evaluated, return UnknownValue. |
| 2362 | SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) { |
| 2363 | // FIXME: this should be turned into a virtual method on SCEV! |
| 2364 | |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2365 | if (isa<SCEVConstant>(V)) return V; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2366 | |
Nick Lewycky | 3e63076 | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2367 | // If this instruction is evolved from a constant-evolving PHI, compute the |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2368 | // exit value from the loop without using SCEVs. |
| 2369 | if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { |
| 2370 | if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { |
| 2371 | const Loop *LI = this->LI[I->getParent()]; |
| 2372 | if (LI && LI->getParentLoop() == L) // Looking for loop exit value. |
| 2373 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 2374 | if (PN->getParent() == LI->getHeader()) { |
| 2375 | // Okay, there is no closed form solution for the PHI node. Check |
| 2376 | // to see if the loop that contains it has a known iteration count. |
| 2377 | // If so, we may be able to force computation of the exit value. |
| 2378 | SCEVHandle IterationCount = getIterationCount(LI); |
| 2379 | if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) { |
| 2380 | // Okay, we know how many times the containing loop executes. If |
| 2381 | // this is a constant evolving PHI node, get the final value at |
| 2382 | // the specified iteration number. |
| 2383 | Constant *RV = getConstantEvolutionLoopExitValue(PN, |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2384 | ICC->getValue()->getValue(), |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2385 | LI); |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2386 | if (RV) return SE.getUnknown(RV); |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2387 | } |
| 2388 | } |
| 2389 | |
Reid Spencer | 09906f3 | 2006-12-04 21:33:23 +0000 | [diff] [blame] | 2390 | // Okay, this is an expression that we cannot symbolically evaluate |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2391 | // into a SCEV. Check to see if it's possible to symbolically evaluate |
Reid Spencer | 09906f3 | 2006-12-04 21:33:23 +0000 | [diff] [blame] | 2392 | // the arguments into constants, and if so, try to constant propagate the |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2393 | // result. This is particularly useful for computing loop exit values. |
| 2394 | if (CanConstantFold(I)) { |
| 2395 | std::vector<Constant*> Operands; |
| 2396 | Operands.reserve(I->getNumOperands()); |
| 2397 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { |
| 2398 | Value *Op = I->getOperand(i); |
| 2399 | if (Constant *C = dyn_cast<Constant>(Op)) { |
| 2400 | Operands.push_back(C); |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2401 | } else { |
Chris Lattner | 42b5e08 | 2007-11-23 08:46:22 +0000 | [diff] [blame] | 2402 | // If any of the operands is non-constant and if they are |
| 2403 | // non-integer, don't even try to analyze them with scev techniques. |
| 2404 | if (!isa<IntegerType>(Op->getType())) |
| 2405 | return V; |
| 2406 | |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2407 | SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L); |
| 2408 | if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) |
Reid Spencer | d977d86 | 2006-12-12 23:36:14 +0000 | [diff] [blame] | 2409 | Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(), |
| 2410 | Op->getType(), |
| 2411 | false)); |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2412 | else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) { |
| 2413 | if (Constant *C = dyn_cast<Constant>(SU->getValue())) |
Reid Spencer | d977d86 | 2006-12-12 23:36:14 +0000 | [diff] [blame] | 2414 | Operands.push_back(ConstantExpr::getIntegerCast(C, |
| 2415 | Op->getType(), |
| 2416 | false)); |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2417 | else |
| 2418 | return V; |
| 2419 | } else { |
| 2420 | return V; |
| 2421 | } |
| 2422 | } |
| 2423 | } |
Chris Lattner | f286f6f | 2007-12-10 22:53:04 +0000 | [diff] [blame] | 2424 | |
| 2425 | Constant *C; |
| 2426 | if (const CmpInst *CI = dyn_cast<CmpInst>(I)) |
| 2427 | C = ConstantFoldCompareInstOperands(CI->getPredicate(), |
| 2428 | &Operands[0], Operands.size()); |
| 2429 | else |
| 2430 | C = ConstantFoldInstOperands(I->getOpcode(), I->getType(), |
| 2431 | &Operands[0], Operands.size()); |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2432 | return SE.getUnknown(C); |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2433 | } |
| 2434 | } |
| 2435 | |
| 2436 | // This is some other type of SCEVUnknown, just return it. |
| 2437 | return V; |
| 2438 | } |
| 2439 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2440 | if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { |
| 2441 | // Avoid performing the look-up in the common case where the specified |
| 2442 | // expression has no loop-variant portions. |
| 2443 | for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { |
| 2444 | SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); |
| 2445 | if (OpAtScope != Comm->getOperand(i)) { |
| 2446 | if (OpAtScope == UnknownValue) return UnknownValue; |
| 2447 | // Okay, at least one of these operands is loop variant but might be |
| 2448 | // foldable. Build a new instance of the folded commutative expression. |
Chris Lattner | 3221ad0 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 2449 | std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2450 | NewOps.push_back(OpAtScope); |
| 2451 | |
| 2452 | for (++i; i != e; ++i) { |
| 2453 | OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); |
| 2454 | if (OpAtScope == UnknownValue) return UnknownValue; |
| 2455 | NewOps.push_back(OpAtScope); |
| 2456 | } |
| 2457 | if (isa<SCEVAddExpr>(Comm)) |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2458 | return SE.getAddExpr(NewOps); |
Nick Lewycky | c54c561 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 2459 | if (isa<SCEVMulExpr>(Comm)) |
| 2460 | return SE.getMulExpr(NewOps); |
| 2461 | if (isa<SCEVSMaxExpr>(Comm)) |
| 2462 | return SE.getSMaxExpr(NewOps); |
Nick Lewycky | 3e63076 | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2463 | if (isa<SCEVUMaxExpr>(Comm)) |
| 2464 | return SE.getUMaxExpr(NewOps); |
Nick Lewycky | c54c561 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 2465 | assert(0 && "Unknown commutative SCEV type!"); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2466 | } |
| 2467 | } |
| 2468 | // If we got here, all operands are loop invariant. |
| 2469 | return Comm; |
| 2470 | } |
| 2471 | |
Nick Lewycky | 789558d | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 2472 | if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { |
| 2473 | SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2474 | if (LHS == UnknownValue) return LHS; |
Nick Lewycky | 789558d | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 2475 | SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2476 | if (RHS == UnknownValue) return RHS; |
Nick Lewycky | 789558d | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 2477 | if (LHS == Div->getLHS() && RHS == Div->getRHS()) |
| 2478 | return Div; // must be loop invariant |
Wojciech Matyjewicz | e3320a1 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 2479 | return SE.getUDivExpr(LHS, RHS); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2480 | } |
| 2481 | |
| 2482 | // If this is a loop recurrence for a loop that does not contain L, then we |
| 2483 | // are dealing with the final value computed by the loop. |
| 2484 | if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { |
| 2485 | if (!L || !AddRec->getLoop()->contains(L->getHeader())) { |
| 2486 | // To evaluate this recurrence, we need to know how many times the AddRec |
| 2487 | // loop iterates. Compute this now. |
| 2488 | SCEVHandle IterationCount = getIterationCount(AddRec->getLoop()); |
| 2489 | if (IterationCount == UnknownValue) return UnknownValue; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2490 | |
Eli Friedman | b42a626 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 2491 | // Then, evaluate the AddRec. |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2492 | return AddRec->evaluateAtIteration(IterationCount, SE); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2493 | } |
| 2494 | return UnknownValue; |
| 2495 | } |
| 2496 | |
| 2497 | //assert(0 && "Unknown SCEV type!"); |
| 2498 | return UnknownValue; |
| 2499 | } |
| 2500 | |
Wojciech Matyjewicz | de0f238 | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 2501 | /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the |
| 2502 | /// following equation: |
| 2503 | /// |
| 2504 | /// A * X = B (mod N) |
| 2505 | /// |
| 2506 | /// where N = 2^BW and BW is the common bit width of A and B. The signedness of |
| 2507 | /// A and B isn't important. |
| 2508 | /// |
| 2509 | /// If the equation does not have a solution, SCEVCouldNotCompute is returned. |
| 2510 | static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B, |
| 2511 | ScalarEvolution &SE) { |
| 2512 | uint32_t BW = A.getBitWidth(); |
| 2513 | assert(BW == B.getBitWidth() && "Bit widths must be the same."); |
| 2514 | assert(A != 0 && "A must be non-zero."); |
| 2515 | |
| 2516 | // 1. D = gcd(A, N) |
| 2517 | // |
| 2518 | // The gcd of A and N may have only one prime factor: 2. The number of |
| 2519 | // trailing zeros in A is its multiplicity |
| 2520 | uint32_t Mult2 = A.countTrailingZeros(); |
| 2521 | // D = 2^Mult2 |
| 2522 | |
| 2523 | // 2. Check if B is divisible by D. |
| 2524 | // |
| 2525 | // B is divisible by D if and only if the multiplicity of prime factor 2 for B |
| 2526 | // is not less than multiplicity of this prime factor for D. |
| 2527 | if (B.countTrailingZeros() < Mult2) |
| 2528 | return new SCEVCouldNotCompute(); |
| 2529 | |
| 2530 | // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic |
| 2531 | // modulo (N / D). |
| 2532 | // |
| 2533 | // (N / D) may need BW+1 bits in its representation. Hence, we'll use this |
| 2534 | // bit width during computations. |
| 2535 | APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D |
| 2536 | APInt Mod(BW + 1, 0); |
| 2537 | Mod.set(BW - Mult2); // Mod = N / D |
| 2538 | APInt I = AD.multiplicativeInverse(Mod); |
| 2539 | |
| 2540 | // 4. Compute the minimum unsigned root of the equation: |
| 2541 | // I * (B / D) mod (N / D) |
| 2542 | APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); |
| 2543 | |
| 2544 | // The result is guaranteed to be less than 2^BW so we may truncate it to BW |
| 2545 | // bits. |
| 2546 | return SE.getConstant(Result.trunc(BW)); |
| 2547 | } |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2548 | |
| 2549 | /// SolveQuadraticEquation - Find the roots of the quadratic equation for the |
| 2550 | /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which |
| 2551 | /// might be the same) or two SCEVCouldNotCompute objects. |
| 2552 | /// |
| 2553 | static std::pair<SCEVHandle,SCEVHandle> |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2554 | SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2555 | assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2556 | SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); |
| 2557 | SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); |
| 2558 | SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2559 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2560 | // We currently can only solve this if the coefficients are constants. |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2561 | if (!LC || !MC || !NC) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2562 | SCEV *CNC = new SCEVCouldNotCompute(); |
| 2563 | return std::make_pair(CNC, CNC); |
| 2564 | } |
| 2565 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2566 | uint32_t BitWidth = LC->getValue()->getValue().getBitWidth(); |
Chris Lattner | fe560b8 | 2007-04-15 19:52:49 +0000 | [diff] [blame] | 2567 | const APInt &L = LC->getValue()->getValue(); |
| 2568 | const APInt &M = MC->getValue()->getValue(); |
| 2569 | const APInt &N = NC->getValue()->getValue(); |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2570 | APInt Two(BitWidth, 2); |
| 2571 | APInt Four(BitWidth, 4); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2572 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2573 | { |
| 2574 | using namespace APIntOps; |
Zhou Sheng | 414de4d | 2007-04-07 17:48:27 +0000 | [diff] [blame] | 2575 | const APInt& C = L; |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2576 | // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C |
| 2577 | // The B coefficient is M-N/2 |
| 2578 | APInt B(M); |
| 2579 | B -= sdiv(N,Two); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2580 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2581 | // The A coefficient is N/2 |
Zhou Sheng | 414de4d | 2007-04-07 17:48:27 +0000 | [diff] [blame] | 2582 | APInt A(N.sdiv(Two)); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2583 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2584 | // Compute the B^2-4ac term. |
| 2585 | APInt SqrtTerm(B); |
| 2586 | SqrtTerm *= B; |
| 2587 | SqrtTerm -= Four * (A * C); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2588 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2589 | // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest |
| 2590 | // integer value or else APInt::sqrt() will assert. |
| 2591 | APInt SqrtVal(SqrtTerm.sqrt()); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2592 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2593 | // Compute the two solutions for the quadratic formula. |
| 2594 | // The divisions must be performed as signed divisions. |
| 2595 | APInt NegB(-B); |
Reid Spencer | 3e35c8d | 2007-04-16 02:24:41 +0000 | [diff] [blame] | 2596 | APInt TwoA( A << 1 ); |
Nick Lewycky | 8f4d5eb | 2008-11-03 02:43:49 +0000 | [diff] [blame] | 2597 | if (TwoA.isMinValue()) { |
| 2598 | SCEV *CNC = new SCEVCouldNotCompute(); |
| 2599 | return std::make_pair(CNC, CNC); |
| 2600 | } |
| 2601 | |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2602 | ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA)); |
| 2603 | ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA)); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2604 | |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2605 | return std::make_pair(SE.getConstant(Solution1), |
| 2606 | SE.getConstant(Solution2)); |
Reid Spencer | e8019bb | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 2607 | } // end APIntOps namespace |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2608 | } |
| 2609 | |
| 2610 | /// HowFarToZero - Return the number of times a backedge comparing the specified |
| 2611 | /// value to zero will execute. If not computable, return UnknownValue |
| 2612 | SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) { |
| 2613 | // If the value is a constant |
| 2614 | if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { |
| 2615 | // If the value is already zero, the branch will execute zero times. |
Reid Spencer | cae5754 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 2616 | if (C->getValue()->isZero()) return C; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2617 | return UnknownValue; // Otherwise it will loop infinitely. |
| 2618 | } |
| 2619 | |
| 2620 | SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); |
| 2621 | if (!AddRec || AddRec->getLoop() != L) |
| 2622 | return UnknownValue; |
| 2623 | |
| 2624 | if (AddRec->isAffine()) { |
Wojciech Matyjewicz | de0f238 | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 2625 | // If this is an affine expression, the execution count of this branch is |
| 2626 | // the minimum unsigned root of the following equation: |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2627 | // |
Wojciech Matyjewicz | de0f238 | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 2628 | // Start + Step*N = 0 (mod 2^BW) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2629 | // |
Wojciech Matyjewicz | de0f238 | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 2630 | // equivalent to: |
| 2631 | // |
| 2632 | // Step*N = -Start (mod 2^BW) |
| 2633 | // |
| 2634 | // where BW is the common bit width of Start and Step. |
| 2635 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2636 | // Get the initial value for the loop. |
| 2637 | SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); |
Chris Lattner | 4a2b23e | 2004-10-11 04:07:27 +0000 | [diff] [blame] | 2638 | if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2639 | |
Wojciech Matyjewicz | de0f238 | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 2640 | SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2641 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2642 | if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) { |
Wojciech Matyjewicz | de0f238 | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 2643 | // For now we handle only constant steps. |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2644 | |
Wojciech Matyjewicz | de0f238 | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 2645 | // First, handle unitary steps. |
| 2646 | if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so: |
| 2647 | return SE.getNegativeSCEV(Start); // N = -Start (as unsigned) |
| 2648 | if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so: |
| 2649 | return Start; // N = Start (as unsigned) |
| 2650 | |
| 2651 | // Then, try to solve the above equation provided that Start is constant. |
| 2652 | if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) |
| 2653 | return SolveLinEquationWithOverflow(StepC->getValue()->getValue(), |
| 2654 | -StartC->getValue()->getValue(),SE); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2655 | } |
Chris Lattner | 42a7551 | 2007-01-15 02:27:26 +0000 | [diff] [blame] | 2656 | } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2657 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of |
| 2658 | // the quadratic equation to solve it. |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2659 | std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2660 | SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); |
| 2661 | SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); |
| 2662 | if (R1) { |
Chris Lattner | d18d9dc | 2004-04-02 20:26:46 +0000 | [diff] [blame] | 2663 | #if 0 |
Bill Wendling | e815619 | 2006-12-07 01:30:32 +0000 | [diff] [blame] | 2664 | cerr << "HFTZ: " << *V << " - sol#1: " << *R1 |
| 2665 | << " sol#2: " << *R2 << "\n"; |
Chris Lattner | d18d9dc | 2004-04-02 20:26:46 +0000 | [diff] [blame] | 2666 | #endif |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2667 | // Pick the smallest positive root value. |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 2668 | if (ConstantInt *CB = |
| 2669 | dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2670 | R1->getValue(), R2->getValue()))) { |
Reid Spencer | 579dca1 | 2007-01-12 04:24:46 +0000 | [diff] [blame] | 2671 | if (CB->getZExtValue() == false) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2672 | std::swap(R1, R2); // R1 is the minimum root now. |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2673 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2674 | // We can only use this value if the chrec ends up with an exact zero |
| 2675 | // value at this index. When solving for "X*X != 5", for example, we |
| 2676 | // should not accept a root of 2. |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2677 | SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE); |
Dan Gohman | cfeb6a4 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 2678 | if (Val->isZero()) |
| 2679 | return R1; // We found a quadratic root! |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2680 | } |
| 2681 | } |
| 2682 | } |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2683 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2684 | return UnknownValue; |
| 2685 | } |
| 2686 | |
| 2687 | /// HowFarToNonZero - Return the number of times a backedge checking the |
| 2688 | /// specified value for nonzero will execute. If not computable, return |
| 2689 | /// UnknownValue |
| 2690 | SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) { |
| 2691 | // Loops that look like: while (X == 0) are very strange indeed. We don't |
| 2692 | // handle them yet except for the trivial case. This could be expanded in the |
| 2693 | // future as needed. |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2694 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2695 | // If the value is a constant, check to see if it is known to be non-zero |
| 2696 | // already. If so, the backedge will execute zero times. |
| 2697 | if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { |
Nick Lewycky | 39442af | 2008-02-21 09:14:53 +0000 | [diff] [blame] | 2698 | if (!C->getValue()->isNullValue()) |
| 2699 | return SE.getIntegerSCEV(0, C->getType()); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2700 | return UnknownValue; // Otherwise it will loop infinitely. |
| 2701 | } |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2702 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2703 | // We could implement others, but I really doubt anyone writes loops like |
| 2704 | // this, and if they did, they would already be constant folded. |
| 2705 | return UnknownValue; |
| 2706 | } |
| 2707 | |
Dan Gohman | fd6edef | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 2708 | /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB |
| 2709 | /// (which may not be an immediate predecessor) which has exactly one |
| 2710 | /// successor from which BB is reachable, or null if no such block is |
| 2711 | /// found. |
| 2712 | /// |
| 2713 | BasicBlock * |
| 2714 | ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { |
| 2715 | // If the block has a unique predecessor, the predecessor must have |
| 2716 | // no other successors from which BB is reachable. |
| 2717 | if (BasicBlock *Pred = BB->getSinglePredecessor()) |
| 2718 | return Pred; |
| 2719 | |
| 2720 | // A loop's header is defined to be a block that dominates the loop. |
| 2721 | // If the loop has a preheader, it must be a block that has exactly |
| 2722 | // one successor that can reach BB. This is slightly more strict |
| 2723 | // than necessary, but works if critical edges are split. |
| 2724 | if (Loop *L = LI.getLoopFor(BB)) |
| 2725 | return L->getLoopPreheader(); |
| 2726 | |
| 2727 | return 0; |
| 2728 | } |
| 2729 | |
Dan Gohman | c2390b1 | 2009-02-12 22:19:27 +0000 | [diff] [blame^] | 2730 | /// isLoopGuardedByCond - Test whether entry to the loop is protected by |
Nick Lewycky | 59cff12 | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 2731 | /// a conditional between LHS and RHS. |
Dan Gohman | c2390b1 | 2009-02-12 22:19:27 +0000 | [diff] [blame^] | 2732 | bool ScalarEvolutionsImpl::isLoopGuardedByCond(const Loop *L, |
| 2733 | ICmpInst::Predicate Pred, |
Nick Lewycky | 59cff12 | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 2734 | SCEV *LHS, SCEV *RHS) { |
| 2735 | BasicBlock *Preheader = L->getLoopPreheader(); |
| 2736 | BasicBlock *PreheaderDest = L->getHeader(); |
Nick Lewycky | 59cff12 | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 2737 | |
Dan Gohman | 3837218 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 2738 | // Starting at the preheader, climb up the predecessor chain, as long as |
Dan Gohman | fd6edef | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 2739 | // there are predecessors that can be found that have unique successors |
| 2740 | // leading to the original header. |
| 2741 | for (; Preheader; |
| 2742 | PreheaderDest = Preheader, |
| 2743 | Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) { |
Dan Gohman | 3837218 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 2744 | |
| 2745 | BranchInst *LoopEntryPredicate = |
Nick Lewycky | 59cff12 | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 2746 | dyn_cast<BranchInst>(Preheader->getTerminator()); |
Dan Gohman | 3837218 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 2747 | if (!LoopEntryPredicate || |
| 2748 | LoopEntryPredicate->isUnconditional()) |
| 2749 | continue; |
| 2750 | |
| 2751 | ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition()); |
| 2752 | if (!ICI) continue; |
| 2753 | |
| 2754 | // Now that we found a conditional branch that dominates the loop, check to |
| 2755 | // see if it is the comparison we are looking for. |
| 2756 | Value *PreCondLHS = ICI->getOperand(0); |
| 2757 | Value *PreCondRHS = ICI->getOperand(1); |
| 2758 | ICmpInst::Predicate Cond; |
| 2759 | if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest) |
| 2760 | Cond = ICI->getPredicate(); |
| 2761 | else |
| 2762 | Cond = ICI->getInversePredicate(); |
| 2763 | |
Dan Gohman | c2390b1 | 2009-02-12 22:19:27 +0000 | [diff] [blame^] | 2764 | if (Cond == Pred) |
| 2765 | ; // An exact match. |
| 2766 | else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE) |
| 2767 | ; // The actual condition is beyond sufficient. |
| 2768 | else |
| 2769 | // Check a few special cases. |
| 2770 | switch (Cond) { |
| 2771 | case ICmpInst::ICMP_UGT: |
| 2772 | if (Pred == ICmpInst::ICMP_ULT) { |
| 2773 | std::swap(PreCondLHS, PreCondRHS); |
| 2774 | Cond = ICmpInst::ICMP_ULT; |
| 2775 | break; |
| 2776 | } |
| 2777 | continue; |
| 2778 | case ICmpInst::ICMP_SGT: |
| 2779 | if (Pred == ICmpInst::ICMP_SLT) { |
| 2780 | std::swap(PreCondLHS, PreCondRHS); |
| 2781 | Cond = ICmpInst::ICMP_SLT; |
| 2782 | break; |
| 2783 | } |
| 2784 | continue; |
| 2785 | case ICmpInst::ICMP_NE: |
| 2786 | // Expressions like (x >u 0) are often canonicalized to (x != 0), |
| 2787 | // so check for this case by checking if the NE is comparing against |
| 2788 | // a minimum or maximum constant. |
| 2789 | if (!ICmpInst::isTrueWhenEqual(Pred)) |
| 2790 | if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) { |
| 2791 | const APInt &A = CI->getValue(); |
| 2792 | switch (Pred) { |
| 2793 | case ICmpInst::ICMP_SLT: |
| 2794 | if (A.isMaxSignedValue()) break; |
| 2795 | continue; |
| 2796 | case ICmpInst::ICMP_SGT: |
| 2797 | if (A.isMinSignedValue()) break; |
| 2798 | continue; |
| 2799 | case ICmpInst::ICMP_ULT: |
| 2800 | if (A.isMaxValue()) break; |
| 2801 | continue; |
| 2802 | case ICmpInst::ICMP_UGT: |
| 2803 | if (A.isMinValue()) break; |
| 2804 | continue; |
| 2805 | default: |
| 2806 | continue; |
| 2807 | } |
| 2808 | Cond = ICmpInst::ICMP_NE; |
| 2809 | // NE is symmetric but the original comparison may not be. Swap |
| 2810 | // the operands if necessary so that they match below. |
| 2811 | if (isa<SCEVConstant>(LHS)) |
| 2812 | std::swap(PreCondLHS, PreCondRHS); |
| 2813 | break; |
| 2814 | } |
| 2815 | continue; |
| 2816 | default: |
| 2817 | // We weren't able to reconcile the condition. |
| 2818 | continue; |
| 2819 | } |
Dan Gohman | 3837218 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 2820 | |
| 2821 | if (!PreCondLHS->getType()->isInteger()) continue; |
| 2822 | |
| 2823 | SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS); |
| 2824 | SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS); |
| 2825 | if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) || |
| 2826 | (LHS == SE.getNotSCEV(PreCondRHSSCEV) && |
| 2827 | RHS == SE.getNotSCEV(PreCondLHSSCEV))) |
| 2828 | return true; |
Nick Lewycky | 59cff12 | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 2829 | } |
| 2830 | |
Dan Gohman | 3837218 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 2831 | return false; |
Nick Lewycky | 59cff12 | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 2832 | } |
| 2833 | |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 2834 | /// HowManyLessThans - Return the number of times a backedge containing the |
| 2835 | /// specified less-than comparison will execute. If not computable, return |
| 2836 | /// UnknownValue. |
| 2837 | SCEVHandle ScalarEvolutionsImpl:: |
Nick Lewycky | 789558d | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 2838 | HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) { |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 2839 | // Only handle: "ADDREC < LoopInvariant". |
| 2840 | if (!RHS->isLoopInvariant(L)) return UnknownValue; |
| 2841 | |
| 2842 | SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS); |
| 2843 | if (!AddRec || AddRec->getLoop() != L) |
| 2844 | return UnknownValue; |
| 2845 | |
| 2846 | if (AddRec->isAffine()) { |
Nick Lewycky | 789558d | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 2847 | // FORNOW: We only support unit strides. |
| 2848 | SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType()); |
| 2849 | if (AddRec->getOperand(1) != One) |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 2850 | return UnknownValue; |
| 2851 | |
Nick Lewycky | 789558d | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 2852 | // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant |
| 2853 | // m. So, we count the number of iterations in which {n,+,1} < m is true. |
| 2854 | // Note that we cannot simply return max(m-n,0) because it's not safe to |
Wojciech Matyjewicz | a65ee03 | 2008-02-13 12:21:32 +0000 | [diff] [blame] | 2855 | // treat m-n as signed nor unsigned due to overflow possibility. |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 2856 | |
Wojciech Matyjewicz | 3a4cbe2 | 2008-02-13 11:51:34 +0000 | [diff] [blame] | 2857 | // First, we get the value of the LHS in the first iteration: n |
| 2858 | SCEVHandle Start = AddRec->getOperand(0); |
| 2859 | |
Dan Gohman | c2390b1 | 2009-02-12 22:19:27 +0000 | [diff] [blame^] | 2860 | if (isLoopGuardedByCond(L, |
| 2861 | isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, |
Nick Lewycky | 789558d | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 2862 | SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) { |
| 2863 | // Since we know that the condition is true in order to enter the loop, |
| 2864 | // we know that it will run exactly m-n times. |
| 2865 | return SE.getMinusSCEV(RHS, Start); |
| 2866 | } else { |
| 2867 | // Then, we get the value of the LHS in the first iteration in which the |
| 2868 | // above condition doesn't hold. This equals to max(m,n). |
| 2869 | SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start) |
| 2870 | : SE.getUMaxExpr(RHS, Start); |
Wojciech Matyjewicz | 3a4cbe2 | 2008-02-13 11:51:34 +0000 | [diff] [blame] | 2871 | |
Nick Lewycky | 789558d | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 2872 | // Finally, we subtract these two values to get the number of times the |
| 2873 | // backedge is executed: max(m,n)-n. |
| 2874 | return SE.getMinusSCEV(End, Start); |
Nick Lewycky | 1447f5c | 2008-12-16 08:30:01 +0000 | [diff] [blame] | 2875 | } |
Chris Lattner | db25de4 | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 2876 | } |
| 2877 | |
| 2878 | return UnknownValue; |
| 2879 | } |
| 2880 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2881 | /// getNumIterationsInRange - Return the number of iterations of this loop that |
| 2882 | /// produce values in the specified constant range. Another way of looking at |
| 2883 | /// this is that it returns the first iteration number where the value is not in |
| 2884 | /// the condition, thus computing the exit count. If the iteration count can't |
| 2885 | /// be computed, an instance of SCEVCouldNotCompute is returned. |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2886 | SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range, |
| 2887 | ScalarEvolution &SE) const { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2888 | if (Range.isFullSet()) // Infinite loop. |
| 2889 | return new SCEVCouldNotCompute(); |
| 2890 | |
| 2891 | // If the start is a non-zero constant, shift the range to simplify things. |
| 2892 | if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) |
Reid Spencer | cae5754 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 2893 | if (!SC->getValue()->isZero()) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2894 | std::vector<SCEVHandle> Operands(op_begin(), op_end()); |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2895 | Operands[0] = SE.getIntegerSCEV(0, SC->getType()); |
| 2896 | SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop()); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2897 | if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) |
| 2898 | return ShiftedAddRec->getNumIterationsInRange( |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2899 | Range.subtract(SC->getValue()->getValue()), SE); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2900 | // This is strange and shouldn't happen. |
| 2901 | return new SCEVCouldNotCompute(); |
| 2902 | } |
| 2903 | |
| 2904 | // The only time we can solve this is when we have all constant indices. |
| 2905 | // Otherwise, we cannot determine the overflow conditions. |
| 2906 | for (unsigned i = 0, e = getNumOperands(); i != e; ++i) |
| 2907 | if (!isa<SCEVConstant>(getOperand(i))) |
| 2908 | return new SCEVCouldNotCompute(); |
| 2909 | |
| 2910 | |
| 2911 | // Okay at this point we know that all elements of the chrec are constants and |
| 2912 | // that the start element is zero. |
| 2913 | |
| 2914 | // First check to see if the range contains zero. If not, the first |
| 2915 | // iteration exits. |
Reid Spencer | a6e8a95 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 2916 | if (!Range.contains(APInt(getBitWidth(),0))) |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2917 | return SE.getConstant(ConstantInt::get(getType(),0)); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2918 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2919 | if (isAffine()) { |
| 2920 | // If this is an affine expression then we have this situation: |
| 2921 | // Solve {0,+,A} in Range === Ax in Range |
| 2922 | |
Nick Lewycky | eefdebe | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 2923 | // We know that zero is in the range. If A is positive then we know that |
| 2924 | // the upper value of the range must be the first possible exit value. |
| 2925 | // If A is negative then the lower of the range is the last possible loop |
| 2926 | // value. Also note that we already checked for a full range. |
Reid Spencer | 581b0d4 | 2007-02-28 19:57:34 +0000 | [diff] [blame] | 2927 | APInt One(getBitWidth(),1); |
Nick Lewycky | eefdebe | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 2928 | APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue(); |
| 2929 | APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2930 | |
Nick Lewycky | eefdebe | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 2931 | // The exit value should be (End+A)/A. |
Nick Lewycky | 9a2f931 | 2007-09-27 14:12:54 +0000 | [diff] [blame] | 2932 | APInt ExitVal = (End + A).udiv(A); |
Reid Spencer | c7cd7a0 | 2007-03-01 19:32:33 +0000 | [diff] [blame] | 2933 | ConstantInt *ExitValue = ConstantInt::get(ExitVal); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2934 | |
| 2935 | // Evaluate at the exit value. If we really did fall out of the valid |
| 2936 | // range, then we computed our trip count, otherwise wrap around or other |
| 2937 | // things must have happened. |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2938 | ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); |
Reid Spencer | a6e8a95 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 2939 | if (Range.contains(Val->getValue())) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2940 | return new SCEVCouldNotCompute(); // Something strange happened |
| 2941 | |
| 2942 | // Ensure that the previous value is in the range. This is a sanity check. |
Reid Spencer | 581b0d4 | 2007-02-28 19:57:34 +0000 | [diff] [blame] | 2943 | assert(Range.contains( |
| 2944 | EvaluateConstantChrecAtConstant(this, |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2945 | ConstantInt::get(ExitVal - One), SE)->getValue()) && |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2946 | "Linear scev computation is off in a bad way!"); |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2947 | return SE.getConstant(ExitValue); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2948 | } else if (isQuadratic()) { |
| 2949 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the |
| 2950 | // quadratic equation to solve it. To do this, we must frame our problem in |
| 2951 | // terms of figuring out when zero is crossed, instead of when |
| 2952 | // Range.getUpper() is crossed. |
| 2953 | std::vector<SCEVHandle> NewOps(op_begin(), op_end()); |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2954 | NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); |
| 2955 | SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop()); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2956 | |
| 2957 | // Next, solve the constructed addrec |
| 2958 | std::pair<SCEVHandle,SCEVHandle> Roots = |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2959 | SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2960 | SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); |
| 2961 | SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); |
| 2962 | if (R1) { |
| 2963 | // Pick the smallest positive root value. |
Zhou Sheng | 6b6b6ef | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 2964 | if (ConstantInt *CB = |
| 2965 | dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT, |
Reid Spencer | e4d87aa | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 2966 | R1->getValue(), R2->getValue()))) { |
Reid Spencer | 579dca1 | 2007-01-12 04:24:46 +0000 | [diff] [blame] | 2967 | if (CB->getZExtValue() == false) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2968 | std::swap(R1, R2); // R1 is the minimum root now. |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2969 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2970 | // Make sure the root is not off by one. The returned iteration should |
| 2971 | // not be in the range, but the previous one should be. When solving |
| 2972 | // for "X*X < 5", for example, we should not return a root of 2. |
| 2973 | ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this, |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2974 | R1->getValue(), |
| 2975 | SE); |
Reid Spencer | a6e8a95 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 2976 | if (Range.contains(R1Val->getValue())) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2977 | // The next iteration must be out of the range... |
Dan Gohman | 9a6ae96 | 2007-07-09 15:25:17 +0000 | [diff] [blame] | 2978 | ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2979 | |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2980 | R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); |
Reid Spencer | a6e8a95 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 2981 | if (!Range.contains(R1Val->getValue())) |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2982 | return SE.getConstant(NextVal); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2983 | return new SCEVCouldNotCompute(); // Something strange happened |
| 2984 | } |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2985 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2986 | // If R1 was not in the range, then it is a good return value. Make |
| 2987 | // sure that R1-1 WAS in the range though, just in case. |
Dan Gohman | 9a6ae96 | 2007-07-09 15:25:17 +0000 | [diff] [blame] | 2988 | ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1); |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2989 | R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); |
Reid Spencer | a6e8a95 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 2990 | if (Range.contains(R1Val->getValue())) |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2991 | return R1; |
| 2992 | return new SCEVCouldNotCompute(); // Something strange happened |
| 2993 | } |
| 2994 | } |
| 2995 | } |
| 2996 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2997 | return new SCEVCouldNotCompute(); |
| 2998 | } |
| 2999 | |
| 3000 | |
| 3001 | |
| 3002 | //===----------------------------------------------------------------------===// |
| 3003 | // ScalarEvolution Class Implementation |
| 3004 | //===----------------------------------------------------------------------===// |
| 3005 | |
| 3006 | bool ScalarEvolution::runOnFunction(Function &F) { |
Dan Gohman | 246b256 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 3007 | Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>()); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3008 | return false; |
| 3009 | } |
| 3010 | |
| 3011 | void ScalarEvolution::releaseMemory() { |
| 3012 | delete (ScalarEvolutionsImpl*)Impl; |
| 3013 | Impl = 0; |
| 3014 | } |
| 3015 | |
| 3016 | void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const { |
| 3017 | AU.setPreservesAll(); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3018 | AU.addRequiredTransitive<LoopInfo>(); |
| 3019 | } |
| 3020 | |
| 3021 | SCEVHandle ScalarEvolution::getSCEV(Value *V) const { |
| 3022 | return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V); |
| 3023 | } |
| 3024 | |
Chris Lattner | a0740fb | 2005-08-09 23:36:33 +0000 | [diff] [blame] | 3025 | /// hasSCEV - Return true if the SCEV for this value has already been |
| 3026 | /// computed. |
| 3027 | bool ScalarEvolution::hasSCEV(Value *V) const { |
Chris Lattner | 05bd374 | 2005-08-10 00:59:40 +0000 | [diff] [blame] | 3028 | return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V); |
Chris Lattner | a0740fb | 2005-08-09 23:36:33 +0000 | [diff] [blame] | 3029 | } |
| 3030 | |
| 3031 | |
| 3032 | /// setSCEV - Insert the specified SCEV into the map of current SCEVs for |
| 3033 | /// the specified value. |
| 3034 | void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) { |
| 3035 | ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H); |
| 3036 | } |
| 3037 | |
| 3038 | |
Dan Gohman | c2390b1 | 2009-02-12 22:19:27 +0000 | [diff] [blame^] | 3039 | bool ScalarEvolution::isLoopGuardedByCond(const Loop *L, |
| 3040 | ICmpInst::Predicate Pred, |
| 3041 | SCEV *LHS, SCEV *RHS) { |
| 3042 | return ((ScalarEvolutionsImpl*)Impl)->isLoopGuardedByCond(L, Pred, |
| 3043 | LHS, RHS); |
| 3044 | } |
| 3045 | |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3046 | SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const { |
| 3047 | return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L); |
| 3048 | } |
| 3049 | |
| 3050 | bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const { |
| 3051 | return !isa<SCEVCouldNotCompute>(getIterationCount(L)); |
| 3052 | } |
| 3053 | |
| 3054 | SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const { |
| 3055 | return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L); |
| 3056 | } |
| 3057 | |
Dan Gohman | 5cec4db | 2007-06-19 14:28:31 +0000 | [diff] [blame] | 3058 | void ScalarEvolution::deleteValueFromRecords(Value *V) const { |
| 3059 | return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3060 | } |
| 3061 | |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 3062 | static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE, |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3063 | const Loop *L) { |
| 3064 | // Print all inner loops first |
| 3065 | for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) |
| 3066 | PrintLoopInfo(OS, SE, *I); |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 3067 | |
Nick Lewycky | aeb5e5c | 2008-01-02 02:49:20 +0000 | [diff] [blame] | 3068 | OS << "Loop " << L->getHeader()->getName() << ": "; |
Chris Lattner | f1ab4b4 | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 3069 | |
Devang Patel | b7211a2 | 2007-08-21 00:31:24 +0000 | [diff] [blame] | 3070 | SmallVector<BasicBlock*, 8> ExitBlocks; |
Chris Lattner | f1ab4b4 | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 3071 | L->getExitBlocks(ExitBlocks); |
| 3072 | if (ExitBlocks.size() != 1) |
Nick Lewycky | aeb5e5c | 2008-01-02 02:49:20 +0000 | [diff] [blame] | 3073 | OS << "<multiple exits> "; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3074 | |
| 3075 | if (SE->hasLoopInvariantIterationCount(L)) { |
Nick Lewycky | aeb5e5c | 2008-01-02 02:49:20 +0000 | [diff] [blame] | 3076 | OS << *SE->getIterationCount(L) << " iterations! "; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3077 | } else { |
Nick Lewycky | aeb5e5c | 2008-01-02 02:49:20 +0000 | [diff] [blame] | 3078 | OS << "Unpredictable iteration count. "; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3079 | } |
| 3080 | |
Nick Lewycky | aeb5e5c | 2008-01-02 02:49:20 +0000 | [diff] [blame] | 3081 | OS << "\n"; |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3082 | } |
| 3083 | |
Reid Spencer | ce9653c | 2004-12-07 04:03:45 +0000 | [diff] [blame] | 3084 | void ScalarEvolution::print(std::ostream &OS, const Module* ) const { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3085 | Function &F = ((ScalarEvolutionsImpl*)Impl)->F; |
| 3086 | LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI; |
| 3087 | |
| 3088 | OS << "Classifying expressions for: " << F.getName() << "\n"; |
| 3089 | for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) |
Chris Lattner | 42a7551 | 2007-01-15 02:27:26 +0000 | [diff] [blame] | 3090 | if (I->getType()->isInteger()) { |
Chris Lattner | 6ffe551 | 2004-04-27 15:13:33 +0000 | [diff] [blame] | 3091 | OS << *I; |
Dan Gohman | 8dae138 | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 3092 | OS << " --> "; |
Chris Lattner | 6ffe551 | 2004-04-27 15:13:33 +0000 | [diff] [blame] | 3093 | SCEVHandle SV = getSCEV(&*I); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3094 | SV->print(OS); |
| 3095 | OS << "\t\t"; |
Misha Brukman | 2b37d7c | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 3096 | |
Chris Lattner | 6ffe551 | 2004-04-27 15:13:33 +0000 | [diff] [blame] | 3097 | if (const Loop *L = LI.getLoopFor((*I).getParent())) { |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3098 | OS << "Exits: "; |
Chris Lattner | 6ffe551 | 2004-04-27 15:13:33 +0000 | [diff] [blame] | 3099 | SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop()); |
Chris Lattner | 53e677a | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3100 | if (isa<SCEVCouldNotCompute>(ExitValue)) { |
| 3101 | OS << "<<Unknown>>"; |
| 3102 | } else { |
| 3103 | OS << *ExitValue; |
| 3104 | } |
| 3105 | } |
| 3106 | |
| 3107 | |
| 3108 | OS << "\n"; |
| 3109 | } |
| 3110 | |
| 3111 | OS << "Determining loop execution counts for: " << F.getName() << "\n"; |
| 3112 | for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I) |
| 3113 | PrintLoopInfo(OS, this, *I); |
| 3114 | } |