Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 1 | //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2 | // |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
Chris Lattner | f3ebc3f | 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 | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7 | // |
Chris Lattner | d934c70 | 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 |
Dan Gohman | ef2ae2c | 2009-07-25 16:18:07 +0000 | [diff] [blame] | 17 | // can handle. We only create one SCEV of a particular shape, so |
| 18 | // pointer-comparisons for equality are legal. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 19 | // |
| 20 | // One important aspect of the SCEV objects is that they are never cyclic, even |
| 21 | // if there is a cycle in the dataflow for an expression (ie, a PHI node). If |
| 22 | // the PHI node is one of the idioms that we can represent (e.g., a polynomial |
| 23 | // recurrence) then we represent it directly as a recurrence node, otherwise we |
| 24 | // represent it as a SCEVUnknown node. |
| 25 | // |
| 26 | // In addition to being able to represent expressions of various types, we also |
| 27 | // have folders that are used to build the *canonical* representation for a |
| 28 | // particular expression. These folders are capable of using a variety of |
| 29 | // rewrite rules to simplify the expressions. |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 30 | // |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 31 | // Once the folders are defined, we can implement the more interesting |
| 32 | // higher-level code, such as the code that recognizes PHI nodes of various |
| 33 | // types, computes the execution count of a loop, etc. |
| 34 | // |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 35 | // TODO: We should use these routines and value representations to implement |
| 36 | // dependence analysis! |
| 37 | // |
| 38 | //===----------------------------------------------------------------------===// |
| 39 | // |
| 40 | // There are several good references for the techniques used in this analysis. |
| 41 | // |
| 42 | // Chains of recurrences -- a method to expedite the evaluation |
| 43 | // of closed-form functions |
| 44 | // Olaf Bachmann, Paul S. Wang, Eugene V. Zima |
| 45 | // |
| 46 | // On computational properties of chains of recurrences |
| 47 | // Eugene V. Zima |
| 48 | // |
| 49 | // Symbolic Evaluation of Chains of Recurrences for Loop Optimization |
| 50 | // Robert A. van Engelen |
| 51 | // |
| 52 | // Efficient Symbolic Analysis for Optimizing Compilers |
| 53 | // Robert A. van Engelen |
| 54 | // |
| 55 | // Using the chains of recurrences algebra for data dependence testing and |
| 56 | // induction variable substitution |
| 57 | // MS Thesis, Johnie Birch |
| 58 | // |
| 59 | //===----------------------------------------------------------------------===// |
| 60 | |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 61 | #include "llvm/Analysis/ScalarEvolution.h" |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 62 | #include "llvm/ADT/Optional.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 63 | #include "llvm/ADT/STLExtras.h" |
| 64 | #include "llvm/ADT/SmallPtrSet.h" |
| 65 | #include "llvm/ADT/Statistic.h" |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 66 | #include "llvm/Analysis/AssumptionCache.h" |
John Criswell | fe5f33b | 2005-10-27 15:54:34 +0000 | [diff] [blame] | 67 | #include "llvm/Analysis/ConstantFolding.h" |
Duncan Sands | d06f50e | 2010-11-17 04:18:45 +0000 | [diff] [blame] | 68 | #include "llvm/Analysis/InstructionSimplify.h" |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 69 | #include "llvm/Analysis/LoopInfo.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 70 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Chandler Carruth | 62d4215 | 2015-01-15 02:16:27 +0000 | [diff] [blame] | 71 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Dan Gohman | 1ee696d | 2009-06-16 19:52:01 +0000 | [diff] [blame] | 72 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 8cd041e | 2014-03-04 12:24:34 +0000 | [diff] [blame] | 73 | #include "llvm/IR/ConstantRange.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 74 | #include "llvm/IR/Constants.h" |
| 75 | #include "llvm/IR/DataLayout.h" |
| 76 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 77 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 78 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 79 | #include "llvm/IR/GlobalAlias.h" |
| 80 | #include "llvm/IR/GlobalVariable.h" |
Chandler Carruth | 8394857 | 2014-03-04 10:30:26 +0000 | [diff] [blame] | 81 | #include "llvm/IR/InstIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 82 | #include "llvm/IR/Instructions.h" |
| 83 | #include "llvm/IR/LLVMContext.h" |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 84 | #include "llvm/IR/Metadata.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 85 | #include "llvm/IR/Operator.h" |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 86 | #include "llvm/IR/PatternMatch.h" |
Chris Lattner | 996795b | 2006-06-28 23:17:24 +0000 | [diff] [blame] | 87 | #include "llvm/Support/CommandLine.h" |
David Greene | 2330f78 | 2009-12-23 22:58:38 +0000 | [diff] [blame] | 88 | #include "llvm/Support/Debug.h" |
Torok Edwin | 56d0659 | 2009-07-11 20:10:48 +0000 | [diff] [blame] | 89 | #include "llvm/Support/ErrorHandling.h" |
Chris Lattner | 0a1e993 | 2006-12-19 01:16:02 +0000 | [diff] [blame] | 90 | #include "llvm/Support/MathExtras.h" |
Dan Gohman | e20f824 | 2009-04-21 00:47:46 +0000 | [diff] [blame] | 91 | #include "llvm/Support/raw_ostream.h" |
Sanjoy Das | 5d9a8cb | 2015-09-22 00:10:57 +0000 | [diff] [blame] | 92 | #include "llvm/Support/SaveAndRestore.h" |
Alkis Evlogimenos | a5c04ee | 2004-09-03 18:19:51 +0000 | [diff] [blame] | 93 | #include <algorithm> |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 94 | using namespace llvm; |
| 95 | |
Chandler Carruth | f1221bd | 2014-04-22 02:48:03 +0000 | [diff] [blame] | 96 | #define DEBUG_TYPE "scalar-evolution" |
| 97 | |
Chris Lattner | 57ef942 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 98 | STATISTIC(NumArrayLenItCounts, |
| 99 | "Number of trip counts computed with array length"); |
| 100 | STATISTIC(NumTripCountsComputed, |
| 101 | "Number of loops with predictable loop counts"); |
| 102 | STATISTIC(NumTripCountsNotComputed, |
| 103 | "Number of loops without predictable loop counts"); |
| 104 | STATISTIC(NumBruteForceTripCountsComputed, |
| 105 | "Number of loops with trip counts computed by force"); |
| 106 | |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 107 | static cl::opt<unsigned> |
Chris Lattner | 57ef942 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 108 | MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, |
| 109 | cl::desc("Maximum number of iterations SCEV will " |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 110 | "symbolically execute a constant " |
| 111 | "derived loop"), |
Chris Lattner | 57ef942 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 112 | cl::init(100)); |
| 113 | |
Filipe Cabecinhas | 0da9937 | 2016-04-29 15:22:48 +0000 | [diff] [blame] | 114 | // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 115 | static cl::opt<bool> |
| 116 | VerifySCEV("verify-scev", |
| 117 | cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 118 | static cl::opt<bool> |
| 119 | VerifySCEVMap("verify-scev-maps", |
Jeroen Ketema | e48e393 | 2016-04-12 23:21:46 +0000 | [diff] [blame] | 120 | cl::desc("Verify no dangling value in ScalarEvolution's " |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 121 | "ExprValueMap (slow)")); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 122 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 123 | //===----------------------------------------------------------------------===// |
| 124 | // SCEV class definitions |
| 125 | //===----------------------------------------------------------------------===// |
| 126 | |
| 127 | //===----------------------------------------------------------------------===// |
| 128 | // Implementation of the SCEV class. |
| 129 | // |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 130 | |
Davide Italiano | 2071f4c | 2015-10-25 19:55:24 +0000 | [diff] [blame] | 131 | LLVM_DUMP_METHOD |
| 132 | void SCEV::dump() const { |
| 133 | print(dbgs()); |
| 134 | dbgs() << '\n'; |
| 135 | } |
| 136 | |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 137 | void SCEV::print(raw_ostream &OS) const { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 138 | switch (static_cast<SCEVTypes>(getSCEVType())) { |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 139 | case scConstant: |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 140 | cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 141 | return; |
| 142 | case scTruncate: { |
| 143 | const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); |
| 144 | const SCEV *Op = Trunc->getOperand(); |
| 145 | OS << "(trunc " << *Op->getType() << " " << *Op << " to " |
| 146 | << *Trunc->getType() << ")"; |
| 147 | return; |
| 148 | } |
| 149 | case scZeroExtend: { |
| 150 | const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); |
| 151 | const SCEV *Op = ZExt->getOperand(); |
| 152 | OS << "(zext " << *Op->getType() << " " << *Op << " to " |
| 153 | << *ZExt->getType() << ")"; |
| 154 | return; |
| 155 | } |
| 156 | case scSignExtend: { |
| 157 | const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); |
| 158 | const SCEV *Op = SExt->getOperand(); |
| 159 | OS << "(sext " << *Op->getType() << " " << *Op << " to " |
| 160 | << *SExt->getType() << ")"; |
| 161 | return; |
| 162 | } |
| 163 | case scAddRecExpr: { |
| 164 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); |
| 165 | OS << "{" << *AR->getOperand(0); |
| 166 | for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) |
| 167 | OS << ",+," << *AR->getOperand(i); |
| 168 | OS << "}<"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 169 | if (AR->hasNoUnsignedWrap()) |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 170 | OS << "nuw><"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 171 | if (AR->hasNoSignedWrap()) |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 172 | OS << "nsw><"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 173 | if (AR->hasNoSelfWrap() && |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 174 | !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) |
| 175 | OS << "nw><"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 176 | AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 177 | OS << ">"; |
| 178 | return; |
| 179 | } |
| 180 | case scAddExpr: |
| 181 | case scMulExpr: |
| 182 | case scUMaxExpr: |
| 183 | case scSMaxExpr: { |
| 184 | const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 185 | const char *OpStr = nullptr; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 186 | switch (NAry->getSCEVType()) { |
| 187 | case scAddExpr: OpStr = " + "; break; |
| 188 | case scMulExpr: OpStr = " * "; break; |
| 189 | case scUMaxExpr: OpStr = " umax "; break; |
| 190 | case scSMaxExpr: OpStr = " smax "; break; |
| 191 | } |
| 192 | OS << "("; |
| 193 | for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); |
| 194 | I != E; ++I) { |
| 195 | OS << **I; |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 196 | if (std::next(I) != E) |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 197 | OS << OpStr; |
| 198 | } |
| 199 | OS << ")"; |
Andrew Trick | d912a5b | 2011-11-29 02:06:35 +0000 | [diff] [blame] | 200 | switch (NAry->getSCEVType()) { |
| 201 | case scAddExpr: |
| 202 | case scMulExpr: |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 203 | if (NAry->hasNoUnsignedWrap()) |
Andrew Trick | d912a5b | 2011-11-29 02:06:35 +0000 | [diff] [blame] | 204 | OS << "<nuw>"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 205 | if (NAry->hasNoSignedWrap()) |
Andrew Trick | d912a5b | 2011-11-29 02:06:35 +0000 | [diff] [blame] | 206 | OS << "<nsw>"; |
| 207 | } |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 208 | return; |
| 209 | } |
| 210 | case scUDivExpr: { |
| 211 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); |
| 212 | OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; |
| 213 | return; |
| 214 | } |
| 215 | case scUnknown: { |
| 216 | const SCEVUnknown *U = cast<SCEVUnknown>(this); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 217 | Type *AllocTy; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 218 | if (U->isSizeOf(AllocTy)) { |
| 219 | OS << "sizeof(" << *AllocTy << ")"; |
| 220 | return; |
| 221 | } |
| 222 | if (U->isAlignOf(AllocTy)) { |
| 223 | OS << "alignof(" << *AllocTy << ")"; |
| 224 | return; |
| 225 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 226 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 227 | Type *CTy; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 228 | Constant *FieldNo; |
| 229 | if (U->isOffsetOf(CTy, FieldNo)) { |
| 230 | OS << "offsetof(" << *CTy << ", "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 231 | FieldNo->printAsOperand(OS, false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 232 | OS << ")"; |
| 233 | return; |
| 234 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 235 | |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 236 | // Otherwise just print it normally. |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 237 | U->getValue()->printAsOperand(OS, false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 238 | return; |
| 239 | } |
| 240 | case scCouldNotCompute: |
| 241 | OS << "***COULDNOTCOMPUTE***"; |
| 242 | return; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 243 | } |
| 244 | llvm_unreachable("Unknown SCEV kind!"); |
| 245 | } |
| 246 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 247 | Type *SCEV::getType() const { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 248 | switch (static_cast<SCEVTypes>(getSCEVType())) { |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 249 | case scConstant: |
| 250 | return cast<SCEVConstant>(this)->getType(); |
| 251 | case scTruncate: |
| 252 | case scZeroExtend: |
| 253 | case scSignExtend: |
| 254 | return cast<SCEVCastExpr>(this)->getType(); |
| 255 | case scAddRecExpr: |
| 256 | case scMulExpr: |
| 257 | case scUMaxExpr: |
| 258 | case scSMaxExpr: |
| 259 | return cast<SCEVNAryExpr>(this)->getType(); |
| 260 | case scAddExpr: |
| 261 | return cast<SCEVAddExpr>(this)->getType(); |
| 262 | case scUDivExpr: |
| 263 | return cast<SCEVUDivExpr>(this)->getType(); |
| 264 | case scUnknown: |
| 265 | return cast<SCEVUnknown>(this)->getType(); |
| 266 | case scCouldNotCompute: |
| 267 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 268 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 269 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 270 | } |
| 271 | |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 272 | bool SCEV::isZero() const { |
| 273 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 274 | return SC->getValue()->isZero(); |
| 275 | return false; |
| 276 | } |
| 277 | |
Dan Gohman | ba7f6d8 | 2009-05-18 15:22:39 +0000 | [diff] [blame] | 278 | bool SCEV::isOne() const { |
| 279 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 280 | return SC->getValue()->isOne(); |
| 281 | return false; |
| 282 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 283 | |
Dan Gohman | 18a96bb | 2009-06-24 00:30:26 +0000 | [diff] [blame] | 284 | bool SCEV::isAllOnesValue() const { |
| 285 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 286 | return SC->getValue()->isAllOnesValue(); |
| 287 | return false; |
| 288 | } |
| 289 | |
Andrew Trick | 881a776 | 2012-01-07 00:27:31 +0000 | [diff] [blame] | 290 | /// isNonConstantNegative - Return true if the specified scev is negated, but |
| 291 | /// not a constant. |
| 292 | bool SCEV::isNonConstantNegative() const { |
| 293 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); |
| 294 | if (!Mul) return false; |
| 295 | |
| 296 | // If there is a constant factor, it will be first. |
| 297 | const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); |
| 298 | if (!SC) return false; |
| 299 | |
| 300 | // Return true if the value is negative, this matches things like (-42 * V). |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 301 | return SC->getAPInt().isNegative(); |
Andrew Trick | 881a776 | 2012-01-07 00:27:31 +0000 | [diff] [blame] | 302 | } |
| 303 | |
Owen Anderson | 04052ec | 2009-06-22 21:57:23 +0000 | [diff] [blame] | 304 | SCEVCouldNotCompute::SCEVCouldNotCompute() : |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 305 | SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 306 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 307 | bool SCEVCouldNotCompute::classof(const SCEV *S) { |
| 308 | return S->getSCEVType() == scCouldNotCompute; |
| 309 | } |
| 310 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 311 | const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 312 | FoldingSetNodeID ID; |
| 313 | ID.AddInteger(scConstant); |
| 314 | ID.AddPointer(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 315 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 316 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 317 | SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 318 | UniqueSCEVs.InsertNode(S, IP); |
| 319 | return S; |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 320 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 321 | |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 322 | const SCEV *ScalarEvolution::getConstant(const APInt &Val) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 323 | return getConstant(ConstantInt::get(getContext(), Val)); |
Dan Gohman | 0a76e7f | 2007-07-09 15:25:17 +0000 | [diff] [blame] | 324 | } |
| 325 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 326 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 327 | ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { |
| 328 | IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); |
Dan Gohman | a029cbe | 2010-04-21 16:04:04 +0000 | [diff] [blame] | 329 | return getConstant(ConstantInt::get(ITy, V, isSigned)); |
Dan Gohman | 7ccc52f | 2009-06-15 22:12:54 +0000 | [diff] [blame] | 330 | } |
| 331 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 332 | SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 333 | unsigned SCEVTy, const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 334 | : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 335 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 336 | SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 337 | const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 338 | : SCEVCastExpr(ID, scTruncate, op, ty) { |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 339 | assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && |
| 340 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 341 | "Cannot truncate non-integer value!"); |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 342 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 343 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 344 | SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 345 | const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 346 | : SCEVCastExpr(ID, scZeroExtend, op, ty) { |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 347 | assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && |
| 348 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 349 | "Cannot zero extend non-integer value!"); |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 350 | } |
| 351 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 352 | SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 353 | const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 354 | : SCEVCastExpr(ID, scSignExtend, op, ty) { |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 355 | assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && |
| 356 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 357 | "Cannot sign extend non-integer value!"); |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 358 | } |
| 359 | |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 360 | void SCEVUnknown::deleted() { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 361 | // Clear this SCEVUnknown from various maps. |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 362 | SE->forgetMemoizedResults(this); |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 363 | |
| 364 | // Remove this SCEVUnknown from the uniquing map. |
| 365 | SE->UniqueSCEVs.RemoveNode(this); |
| 366 | |
| 367 | // Release the value. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 368 | setValPtr(nullptr); |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 369 | } |
| 370 | |
| 371 | void SCEVUnknown::allUsesReplacedWith(Value *New) { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 372 | // Clear this SCEVUnknown from various maps. |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 373 | SE->forgetMemoizedResults(this); |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 374 | |
| 375 | // Remove this SCEVUnknown from the uniquing map. |
| 376 | SE->UniqueSCEVs.RemoveNode(this); |
| 377 | |
| 378 | // Update this SCEVUnknown to point to the new value. This is needed |
| 379 | // because there may still be outstanding SCEVs which still point to |
| 380 | // this SCEVUnknown. |
| 381 | setValPtr(New); |
| 382 | } |
| 383 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 384 | bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 385 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 386 | if (VCE->getOpcode() == Instruction::PtrToInt) |
| 387 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 388 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 389 | CE->getOperand(0)->isNullValue() && |
| 390 | CE->getNumOperands() == 2) |
| 391 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) |
| 392 | if (CI->isOne()) { |
| 393 | AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) |
| 394 | ->getElementType(); |
| 395 | return true; |
| 396 | } |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 397 | |
| 398 | return false; |
| 399 | } |
| 400 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 401 | bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 402 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 403 | if (VCE->getOpcode() == Instruction::PtrToInt) |
| 404 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 405 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 406 | CE->getOperand(0)->isNullValue()) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 407 | Type *Ty = |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 408 | cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 409 | if (StructType *STy = dyn_cast<StructType>(Ty)) |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 410 | if (!STy->isPacked() && |
| 411 | CE->getNumOperands() == 3 && |
| 412 | CE->getOperand(1)->isNullValue()) { |
| 413 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) |
| 414 | if (CI->isOne() && |
| 415 | STy->getNumElements() == 2 && |
Duncan Sands | 9dff9be | 2010-02-15 16:12:20 +0000 | [diff] [blame] | 416 | STy->getElementType(0)->isIntegerTy(1)) { |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 417 | AllocTy = STy->getElementType(1); |
| 418 | return true; |
| 419 | } |
| 420 | } |
| 421 | } |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 422 | |
| 423 | return false; |
| 424 | } |
| 425 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 426 | bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 427 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 428 | if (VCE->getOpcode() == Instruction::PtrToInt) |
| 429 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) |
| 430 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 431 | CE->getNumOperands() == 3 && |
| 432 | CE->getOperand(0)->isNullValue() && |
| 433 | CE->getOperand(1)->isNullValue()) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 434 | Type *Ty = |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 435 | cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); |
| 436 | // Ignore vector types here so that ScalarEvolutionExpander doesn't |
| 437 | // emit getelementptrs that index into vectors. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 438 | if (Ty->isStructTy() || Ty->isArrayTy()) { |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 439 | CTy = Ty; |
| 440 | FieldNo = CE->getOperand(2); |
| 441 | return true; |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | return false; |
| 446 | } |
| 447 | |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 448 | //===----------------------------------------------------------------------===// |
| 449 | // SCEV Utilities |
| 450 | //===----------------------------------------------------------------------===// |
| 451 | |
| 452 | namespace { |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 453 | /// SCEVComplexityCompare - Return true if the complexity of the LHS is less |
| 454 | /// than the complexity of the RHS. This comparator is used to canonicalize |
| 455 | /// expressions. |
| 456 | class SCEVComplexityCompare { |
| 457 | const LoopInfo *const LI; |
| 458 | public: |
| 459 | explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {} |
Dan Gohman | 9ba542c | 2009-05-07 14:39:04 +0000 | [diff] [blame] | 460 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 461 | // Return true or false if LHS is less than, or at least RHS, respectively. |
| 462 | bool operator()(const SCEV *LHS, const SCEV *RHS) const { |
| 463 | return compare(LHS, RHS) < 0; |
| 464 | } |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 465 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 466 | // Return negative, zero, or positive, if LHS is less than, equal to, or |
| 467 | // greater than RHS, respectively. A three-way result allows recursive |
| 468 | // comparisons to be more efficient. |
| 469 | int compare(const SCEV *LHS, const SCEV *RHS) const { |
| 470 | // Fast-path: SCEVs are uniqued so we can do a quick equality check. |
| 471 | if (LHS == RHS) |
| 472 | return 0; |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 473 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 474 | // Primarily, sort the SCEVs by their getSCEVType(). |
| 475 | unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); |
| 476 | if (LType != RType) |
| 477 | return (int)LType - (int)RType; |
Dan Gohman | 9ba542c | 2009-05-07 14:39:04 +0000 | [diff] [blame] | 478 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 479 | // Aside from the getSCEVType() ordering, the particular ordering |
| 480 | // isn't very important except that it's beneficial to be consistent, |
| 481 | // so that (a + b) and (b + a) don't end up as different expressions. |
| 482 | switch (static_cast<SCEVTypes>(LType)) { |
| 483 | case scUnknown: { |
| 484 | const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); |
| 485 | const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 486 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 487 | // Sort SCEVUnknown values with some loose heuristics. TODO: This is |
| 488 | // not as complete as it could be. |
| 489 | const Value *LV = LU->getValue(), *RV = RU->getValue(); |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 490 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 491 | // Order pointer values after integer values. This helps SCEVExpander |
| 492 | // form GEPs. |
| 493 | bool LIsPointer = LV->getType()->isPointerTy(), |
| 494 | RIsPointer = RV->getType()->isPointerTy(); |
| 495 | if (LIsPointer != RIsPointer) |
| 496 | return (int)LIsPointer - (int)RIsPointer; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 497 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 498 | // Compare getValueID values. |
| 499 | unsigned LID = LV->getValueID(), |
| 500 | RID = RV->getValueID(); |
| 501 | if (LID != RID) |
| 502 | return (int)LID - (int)RID; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 503 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 504 | // Sort arguments by their position. |
| 505 | if (const Argument *LA = dyn_cast<Argument>(LV)) { |
| 506 | const Argument *RA = cast<Argument>(RV); |
| 507 | unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); |
| 508 | return (int)LArgNo - (int)RArgNo; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 509 | } |
| 510 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 511 | // For instructions, compare their loop depth, and their operand |
| 512 | // count. This is pretty loose. |
| 513 | if (const Instruction *LInst = dyn_cast<Instruction>(LV)) { |
| 514 | const Instruction *RInst = cast<Instruction>(RV); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 515 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 516 | // Compare loop depths. |
| 517 | const BasicBlock *LParent = LInst->getParent(), |
| 518 | *RParent = RInst->getParent(); |
| 519 | if (LParent != RParent) { |
| 520 | unsigned LDepth = LI->getLoopDepth(LParent), |
| 521 | RDepth = LI->getLoopDepth(RParent); |
Dan Gohman | 0c436ab | 2010-08-13 21:24:58 +0000 | [diff] [blame] | 522 | if (LDepth != RDepth) |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 523 | return (int)LDepth - (int)RDepth; |
Dan Gohman | 0c436ab | 2010-08-13 21:24:58 +0000 | [diff] [blame] | 524 | } |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 525 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 526 | // Compare the number of operands. |
| 527 | unsigned LNumOps = LInst->getNumOperands(), |
| 528 | RNumOps = RInst->getNumOperands(); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 529 | return (int)LNumOps - (int)RNumOps; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 530 | } |
| 531 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 532 | return 0; |
| 533 | } |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 534 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 535 | case scConstant: { |
| 536 | const SCEVConstant *LC = cast<SCEVConstant>(LHS); |
| 537 | const SCEVConstant *RC = cast<SCEVConstant>(RHS); |
| 538 | |
| 539 | // Compare constant values. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 540 | const APInt &LA = LC->getAPInt(); |
| 541 | const APInt &RA = RC->getAPInt(); |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 542 | unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); |
| 543 | if (LBitWidth != RBitWidth) |
| 544 | return (int)LBitWidth - (int)RBitWidth; |
| 545 | return LA.ult(RA) ? -1 : 1; |
| 546 | } |
| 547 | |
| 548 | case scAddRecExpr: { |
| 549 | const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); |
| 550 | const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); |
| 551 | |
| 552 | // Compare addrec loop depths. |
| 553 | const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); |
| 554 | if (LLoop != RLoop) { |
| 555 | unsigned LDepth = LLoop->getLoopDepth(), |
| 556 | RDepth = RLoop->getLoopDepth(); |
| 557 | if (LDepth != RDepth) |
| 558 | return (int)LDepth - (int)RDepth; |
| 559 | } |
| 560 | |
| 561 | // Addrec complexity grows with operand count. |
| 562 | unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); |
| 563 | if (LNumOps != RNumOps) |
| 564 | return (int)LNumOps - (int)RNumOps; |
| 565 | |
| 566 | // Lexicographically compare. |
| 567 | for (unsigned i = 0; i != LNumOps; ++i) { |
| 568 | long X = compare(LA->getOperand(i), RA->getOperand(i)); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 569 | if (X != 0) |
| 570 | return X; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 571 | } |
| 572 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 573 | return 0; |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 574 | } |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 575 | |
| 576 | case scAddExpr: |
| 577 | case scMulExpr: |
| 578 | case scSMaxExpr: |
| 579 | case scUMaxExpr: { |
| 580 | const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); |
| 581 | const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); |
| 582 | |
| 583 | // Lexicographically compare n-ary expressions. |
| 584 | unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); |
| 585 | if (LNumOps != RNumOps) |
| 586 | return (int)LNumOps - (int)RNumOps; |
| 587 | |
| 588 | for (unsigned i = 0; i != LNumOps; ++i) { |
| 589 | if (i >= RNumOps) |
| 590 | return 1; |
| 591 | long X = compare(LC->getOperand(i), RC->getOperand(i)); |
| 592 | if (X != 0) |
| 593 | return X; |
| 594 | } |
| 595 | return (int)LNumOps - (int)RNumOps; |
| 596 | } |
| 597 | |
| 598 | case scUDivExpr: { |
| 599 | const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); |
| 600 | const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); |
| 601 | |
| 602 | // Lexicographically compare udiv expressions. |
| 603 | long X = compare(LC->getLHS(), RC->getLHS()); |
| 604 | if (X != 0) |
| 605 | return X; |
| 606 | return compare(LC->getRHS(), RC->getRHS()); |
| 607 | } |
| 608 | |
| 609 | case scTruncate: |
| 610 | case scZeroExtend: |
| 611 | case scSignExtend: { |
| 612 | const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); |
| 613 | const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); |
| 614 | |
| 615 | // Compare cast expressions by operand. |
| 616 | return compare(LC->getOperand(), RC->getOperand()); |
| 617 | } |
| 618 | |
| 619 | case scCouldNotCompute: |
| 620 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
| 621 | } |
| 622 | llvm_unreachable("Unknown SCEV kind!"); |
| 623 | } |
| 624 | }; |
| 625 | } // end anonymous namespace |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 626 | |
| 627 | /// GroupByComplexity - Given a list of SCEV objects, order them by their |
| 628 | /// complexity, and group objects of the same complexity together by value. |
| 629 | /// When this routine is finished, we know that any duplicates in the vector are |
| 630 | /// consecutive and that complexity is monotonically increasing. |
| 631 | /// |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 632 | /// Note that we go take special precautions to ensure that we get deterministic |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 633 | /// results from this routine. In other words, we don't want the results of |
| 634 | /// this to depend on where the addresses of various SCEV objects happened to |
| 635 | /// land in memory. |
| 636 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 637 | static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, |
Dan Gohman | 9ba542c | 2009-05-07 14:39:04 +0000 | [diff] [blame] | 638 | LoopInfo *LI) { |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 639 | if (Ops.size() < 2) return; // Noop |
| 640 | if (Ops.size() == 2) { |
| 641 | // This is the common case, which also happens to be trivially simple. |
| 642 | // Special case it. |
Dan Gohman | 7712d29 | 2010-08-29 15:07:13 +0000 | [diff] [blame] | 643 | const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; |
| 644 | if (SCEVComplexityCompare(LI)(RHS, LHS)) |
| 645 | std::swap(LHS, RHS); |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 646 | return; |
| 647 | } |
| 648 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 649 | // Do the rough sort by complexity. |
| 650 | std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI)); |
| 651 | |
| 652 | // Now that we are sorted by complexity, group elements of the same |
| 653 | // complexity. Note that this is, at worst, N^2, but the vector is likely to |
| 654 | // be extremely short in practice. Note that we take this approach because we |
| 655 | // do not want to depend on the addresses of the objects we are grouping. |
| 656 | for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { |
| 657 | const SCEV *S = Ops[i]; |
| 658 | unsigned Complexity = S->getSCEVType(); |
| 659 | |
| 660 | // If there are any objects of the same complexity and same value as this |
| 661 | // one, group them. |
| 662 | for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { |
| 663 | if (Ops[j] == S) { // Found a duplicate. |
| 664 | // Move it to immediately after i'th element. |
| 665 | std::swap(Ops[i+1], Ops[j]); |
| 666 | ++i; // no need to rescan it. |
| 667 | if (i == e-2) return; // Done! |
| 668 | } |
| 669 | } |
| 670 | } |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 671 | } |
| 672 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 673 | // Returns the size of the SCEV S. |
| 674 | static inline int sizeOfSCEV(const SCEV *S) { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 675 | struct FindSCEVSize { |
| 676 | int Size; |
| 677 | FindSCEVSize() : Size(0) {} |
| 678 | |
| 679 | bool follow(const SCEV *S) { |
| 680 | ++Size; |
| 681 | // Keep looking at all operands of S. |
| 682 | return true; |
| 683 | } |
| 684 | bool isDone() const { |
| 685 | return false; |
| 686 | } |
| 687 | }; |
| 688 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 689 | FindSCEVSize F; |
| 690 | SCEVTraversal<FindSCEVSize> ST(F); |
| 691 | ST.visitAll(S); |
| 692 | return F.Size; |
| 693 | } |
| 694 | |
| 695 | namespace { |
| 696 | |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 697 | struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 698 | public: |
| 699 | // Computes the Quotient and Remainder of the division of Numerator by |
| 700 | // Denominator. |
| 701 | static void divide(ScalarEvolution &SE, const SCEV *Numerator, |
| 702 | const SCEV *Denominator, const SCEV **Quotient, |
| 703 | const SCEV **Remainder) { |
| 704 | assert(Numerator && Denominator && "Uninitialized SCEV"); |
| 705 | |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 706 | SCEVDivision D(SE, Numerator, Denominator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 707 | |
| 708 | // Check for the trivial case here to avoid having to check for it in the |
| 709 | // rest of the code. |
| 710 | if (Numerator == Denominator) { |
| 711 | *Quotient = D.One; |
| 712 | *Remainder = D.Zero; |
| 713 | return; |
| 714 | } |
| 715 | |
| 716 | if (Numerator->isZero()) { |
| 717 | *Quotient = D.Zero; |
| 718 | *Remainder = D.Zero; |
| 719 | return; |
| 720 | } |
| 721 | |
Brendon Cahoon | a57cc8b | 2015-04-20 16:03:28 +0000 | [diff] [blame] | 722 | // A simple case when N/1. The quotient is N. |
| 723 | if (Denominator->isOne()) { |
| 724 | *Quotient = Numerator; |
| 725 | *Remainder = D.Zero; |
| 726 | return; |
| 727 | } |
| 728 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 729 | // Split the Denominator when it is a product. |
| 730 | if (const SCEVMulExpr *T = dyn_cast<const SCEVMulExpr>(Denominator)) { |
| 731 | const SCEV *Q, *R; |
| 732 | *Quotient = Numerator; |
| 733 | for (const SCEV *Op : T->operands()) { |
| 734 | divide(SE, *Quotient, Op, &Q, &R); |
| 735 | *Quotient = Q; |
| 736 | |
| 737 | // Bail out when the Numerator is not divisible by one of the terms of |
| 738 | // the Denominator. |
| 739 | if (!R->isZero()) { |
| 740 | *Quotient = D.Zero; |
| 741 | *Remainder = Numerator; |
| 742 | return; |
| 743 | } |
| 744 | } |
| 745 | *Remainder = D.Zero; |
| 746 | return; |
| 747 | } |
| 748 | |
| 749 | D.visit(Numerator); |
| 750 | *Quotient = D.Quotient; |
| 751 | *Remainder = D.Remainder; |
| 752 | } |
| 753 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 754 | // Except in the trivial case described above, we do not know how to divide |
| 755 | // Expr by Denominator for the following functions with empty implementation. |
| 756 | void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} |
| 757 | void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} |
| 758 | void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} |
| 759 | void visitUDivExpr(const SCEVUDivExpr *Numerator) {} |
| 760 | void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} |
| 761 | void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} |
| 762 | void visitUnknown(const SCEVUnknown *Numerator) {} |
| 763 | void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} |
| 764 | |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 765 | void visitConstant(const SCEVConstant *Numerator) { |
| 766 | if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 767 | APInt NumeratorVal = Numerator->getAPInt(); |
| 768 | APInt DenominatorVal = D->getAPInt(); |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 769 | uint32_t NumeratorBW = NumeratorVal.getBitWidth(); |
| 770 | uint32_t DenominatorBW = DenominatorVal.getBitWidth(); |
| 771 | |
| 772 | if (NumeratorBW > DenominatorBW) |
| 773 | DenominatorVal = DenominatorVal.sext(NumeratorBW); |
| 774 | else if (NumeratorBW < DenominatorBW) |
| 775 | NumeratorVal = NumeratorVal.sext(DenominatorBW); |
| 776 | |
| 777 | APInt QuotientVal(NumeratorVal.getBitWidth(), 0); |
| 778 | APInt RemainderVal(NumeratorVal.getBitWidth(), 0); |
| 779 | APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); |
| 780 | Quotient = SE.getConstant(QuotientVal); |
| 781 | Remainder = SE.getConstant(RemainderVal); |
| 782 | return; |
| 783 | } |
| 784 | } |
| 785 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 786 | void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { |
| 787 | const SCEV *StartQ, *StartR, *StepQ, *StepR; |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 788 | if (!Numerator->isAffine()) |
| 789 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 790 | divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); |
| 791 | divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); |
Brendon Cahoon | f9751ad | 2015-04-22 15:06:40 +0000 | [diff] [blame] | 792 | // Bail out if the types do not match. |
| 793 | Type *Ty = Denominator->getType(); |
| 794 | if (Ty != StartQ->getType() || Ty != StartR->getType() || |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 795 | Ty != StepQ->getType() || Ty != StepR->getType()) |
| 796 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 797 | Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), |
| 798 | Numerator->getNoWrapFlags()); |
| 799 | Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), |
| 800 | Numerator->getNoWrapFlags()); |
| 801 | } |
| 802 | |
| 803 | void visitAddExpr(const SCEVAddExpr *Numerator) { |
| 804 | SmallVector<const SCEV *, 2> Qs, Rs; |
| 805 | Type *Ty = Denominator->getType(); |
| 806 | |
| 807 | for (const SCEV *Op : Numerator->operands()) { |
| 808 | const SCEV *Q, *R; |
| 809 | divide(SE, Op, Denominator, &Q, &R); |
| 810 | |
| 811 | // Bail out if types do not match. |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 812 | if (Ty != Q->getType() || Ty != R->getType()) |
| 813 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 814 | |
| 815 | Qs.push_back(Q); |
| 816 | Rs.push_back(R); |
| 817 | } |
| 818 | |
| 819 | if (Qs.size() == 1) { |
| 820 | Quotient = Qs[0]; |
| 821 | Remainder = Rs[0]; |
| 822 | return; |
| 823 | } |
| 824 | |
| 825 | Quotient = SE.getAddExpr(Qs); |
| 826 | Remainder = SE.getAddExpr(Rs); |
| 827 | } |
| 828 | |
| 829 | void visitMulExpr(const SCEVMulExpr *Numerator) { |
| 830 | SmallVector<const SCEV *, 2> Qs; |
| 831 | Type *Ty = Denominator->getType(); |
| 832 | |
| 833 | bool FoundDenominatorTerm = false; |
| 834 | for (const SCEV *Op : Numerator->operands()) { |
| 835 | // Bail out if types do not match. |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 836 | if (Ty != Op->getType()) |
| 837 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 838 | |
| 839 | if (FoundDenominatorTerm) { |
| 840 | Qs.push_back(Op); |
| 841 | continue; |
| 842 | } |
| 843 | |
| 844 | // Check whether Denominator divides one of the product operands. |
| 845 | const SCEV *Q, *R; |
| 846 | divide(SE, Op, Denominator, &Q, &R); |
| 847 | if (!R->isZero()) { |
| 848 | Qs.push_back(Op); |
| 849 | continue; |
| 850 | } |
| 851 | |
| 852 | // Bail out if types do not match. |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 853 | if (Ty != Q->getType()) |
| 854 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 855 | |
| 856 | FoundDenominatorTerm = true; |
| 857 | Qs.push_back(Q); |
| 858 | } |
| 859 | |
| 860 | if (FoundDenominatorTerm) { |
| 861 | Remainder = Zero; |
| 862 | if (Qs.size() == 1) |
| 863 | Quotient = Qs[0]; |
| 864 | else |
| 865 | Quotient = SE.getMulExpr(Qs); |
| 866 | return; |
| 867 | } |
| 868 | |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 869 | if (!isa<SCEVUnknown>(Denominator)) |
| 870 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 871 | |
| 872 | // The Remainder is obtained by replacing Denominator by 0 in Numerator. |
| 873 | ValueToValueMap RewriteMap; |
| 874 | RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = |
| 875 | cast<SCEVConstant>(Zero)->getValue(); |
| 876 | Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); |
| 877 | |
| 878 | if (Remainder->isZero()) { |
| 879 | // The Quotient is obtained by replacing Denominator by 1 in Numerator. |
| 880 | RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = |
| 881 | cast<SCEVConstant>(One)->getValue(); |
| 882 | Quotient = |
| 883 | SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); |
| 884 | return; |
| 885 | } |
| 886 | |
| 887 | // Quotient is (Numerator - Remainder) divided by Denominator. |
| 888 | const SCEV *Q, *R; |
| 889 | const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 890 | // This SCEV does not seem to simplify: fail the division here. |
| 891 | if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) |
| 892 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 893 | divide(SE, Diff, Denominator, &Q, &R); |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 894 | if (R != Zero) |
| 895 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 896 | Quotient = Q; |
| 897 | } |
| 898 | |
| 899 | private: |
David Majnemer | 5d2670c | 2014-11-17 11:27:45 +0000 | [diff] [blame] | 900 | SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, |
| 901 | const SCEV *Denominator) |
| 902 | : SE(S), Denominator(Denominator) { |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 903 | Zero = SE.getZero(Denominator->getType()); |
| 904 | One = SE.getOne(Denominator->getType()); |
David Majnemer | 5d2670c | 2014-11-17 11:27:45 +0000 | [diff] [blame] | 905 | |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 906 | // We generally do not know how to divide Expr by Denominator. We |
| 907 | // initialize the division to a "cannot divide" state to simplify the rest |
| 908 | // of the code. |
| 909 | cannotDivide(Numerator); |
| 910 | } |
| 911 | |
| 912 | // Convenience function for giving up on the division. We set the quotient to |
| 913 | // be equal to zero and the remainder to be equal to the numerator. |
| 914 | void cannotDivide(const SCEV *Numerator) { |
David Majnemer | 5d2670c | 2014-11-17 11:27:45 +0000 | [diff] [blame] | 915 | Quotient = Zero; |
| 916 | Remainder = Numerator; |
| 917 | } |
| 918 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 919 | ScalarEvolution &SE; |
| 920 | const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; |
David Majnemer | 32b8ccf | 2014-11-16 20:35:19 +0000 | [diff] [blame] | 921 | }; |
| 922 | |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 923 | } |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 924 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 925 | //===----------------------------------------------------------------------===// |
| 926 | // Simple SCEV method implementations |
| 927 | //===----------------------------------------------------------------------===// |
| 928 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 929 | /// BinomialCoefficient - Compute BC(It, K). The result has width W. |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 930 | /// Assume, K > 0. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 931 | static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, |
Dan Gohman | 32291b1 | 2009-07-21 00:38:55 +0000 | [diff] [blame] | 932 | ScalarEvolution &SE, |
Nick Lewycky | 702cf1e | 2011-09-06 06:39:54 +0000 | [diff] [blame] | 933 | Type *ResultTy) { |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 934 | // Handle the simplest case efficiently. |
| 935 | if (K == 1) |
| 936 | return SE.getTruncateOrZeroExtend(It, ResultTy); |
| 937 | |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 938 | // We are using the following formula for BC(It, K): |
| 939 | // |
| 940 | // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! |
| 941 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 942 | // Suppose, W is the bitwidth of the return value. We must be prepared for |
| 943 | // overflow. Hence, we must assure that the result of our computation is |
| 944 | // equal to the accurate one modulo 2^W. Unfortunately, division isn't |
| 945 | // safe in modular arithmetic. |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 946 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 947 | // However, this code doesn't use exactly that formula; the formula it uses |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 948 | // is something like the following, where T is the number of factors of 2 in |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 949 | // K! (i.e. trailing zeros in the binary representation of K!), and ^ is |
| 950 | // exponentiation: |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 951 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 952 | // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 953 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 954 | // This formula is trivially equivalent to the previous formula. However, |
| 955 | // this formula can be implemented much more efficiently. The trick is that |
| 956 | // K! / 2^T is odd, and exact division by an odd number *is* safe in modular |
| 957 | // arithmetic. To do exact division in modular arithmetic, all we have |
| 958 | // to do is multiply by the inverse. Therefore, this step can be done at |
| 959 | // width W. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 960 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 961 | // The next issue is how to safely do the division by 2^T. The way this |
| 962 | // is done is by doing the multiplication step at a width of at least W + T |
| 963 | // bits. This way, the bottom W+T bits of the product are accurate. Then, |
| 964 | // when we perform the division by 2^T (which is equivalent to a right shift |
| 965 | // by T), the bottom W bits are accurate. Extra bits are okay; they'll get |
| 966 | // truncated out after the division by 2^T. |
| 967 | // |
| 968 | // In comparison to just directly using the first formula, this technique |
| 969 | // is much more efficient; using the first formula requires W * K bits, |
| 970 | // but this formula less than W + K bits. Also, the first formula requires |
| 971 | // a division step, whereas this formula only requires multiplies and shifts. |
| 972 | // |
| 973 | // It doesn't matter whether the subtraction step is done in the calculation |
| 974 | // width or the input iteration count's width; if the subtraction overflows, |
| 975 | // the result must be zero anyway. We prefer here to do it in the width of |
| 976 | // the induction variable because it helps a lot for certain cases; CodeGen |
| 977 | // isn't smart enough to ignore the overflow, which leads to much less |
| 978 | // efficient code if the width of the subtraction is wider than the native |
| 979 | // register width. |
| 980 | // |
| 981 | // (It's possible to not widen at all by pulling out factors of 2 before |
| 982 | // the multiplication; for example, K=2 can be calculated as |
| 983 | // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires |
| 984 | // extra arithmetic, so it's not an obvious win, and it gets |
| 985 | // much more complicated for K > 3.) |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 986 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 987 | // Protection from insane SCEVs; this bound is conservative, |
| 988 | // but it probably doesn't matter. |
| 989 | if (K > 1000) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 990 | return SE.getCouldNotCompute(); |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 991 | |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 992 | unsigned W = SE.getTypeSizeInBits(ResultTy); |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 993 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 994 | // Calculate K! / 2^T and T; we divide out the factors of two before |
| 995 | // multiplying for calculating K! / 2^T to avoid overflow. |
| 996 | // Other overflow doesn't matter because we only care about the bottom |
| 997 | // W bits of the result. |
| 998 | APInt OddFactorial(W, 1); |
| 999 | unsigned T = 1; |
| 1000 | for (unsigned i = 3; i <= K; ++i) { |
| 1001 | APInt Mult(W, i); |
| 1002 | unsigned TwoFactors = Mult.countTrailingZeros(); |
| 1003 | T += TwoFactors; |
| 1004 | Mult = Mult.lshr(TwoFactors); |
| 1005 | OddFactorial *= Mult; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1006 | } |
Nick Lewycky | ed169d5 | 2008-06-13 04:38:55 +0000 | [diff] [blame] | 1007 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1008 | // We need at least W + T bits for the multiplication step |
Nick Lewycky | 21add8f | 2009-01-25 08:16:27 +0000 | [diff] [blame] | 1009 | unsigned CalculationBits = W + T; |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1010 | |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 1011 | // Calculate 2^T, at width T+W. |
Benjamin Kramer | fc3ea6f | 2013-07-11 16:05:50 +0000 | [diff] [blame] | 1012 | APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1013 | |
| 1014 | // Calculate the multiplicative inverse of K! / 2^T; |
| 1015 | // this multiplication factor will perform the exact division by |
| 1016 | // K! / 2^T. |
| 1017 | APInt Mod = APInt::getSignedMinValue(W+1); |
| 1018 | APInt MultiplyFactor = OddFactorial.zext(W+1); |
| 1019 | MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); |
| 1020 | MultiplyFactor = MultiplyFactor.trunc(W); |
| 1021 | |
| 1022 | // Calculate the product, at width T+W |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1023 | IntegerType *CalculationTy = IntegerType::get(SE.getContext(), |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1024 | CalculationBits); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1025 | const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1026 | for (unsigned i = 1; i != K; ++i) { |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 1027 | const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1028 | Dividend = SE.getMulExpr(Dividend, |
| 1029 | SE.getTruncateOrZeroExtend(S, CalculationTy)); |
| 1030 | } |
| 1031 | |
| 1032 | // Divide by 2^T |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1033 | const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1034 | |
| 1035 | // Truncate the result, and divide by K! / 2^T. |
| 1036 | |
| 1037 | return SE.getMulExpr(SE.getConstant(MultiplyFactor), |
| 1038 | SE.getTruncateOrZeroExtend(DivResult, ResultTy)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1039 | } |
| 1040 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1041 | /// evaluateAtIteration - Return the value of this chain of recurrences at |
| 1042 | /// the specified iteration number. We can evaluate this recurrence by |
| 1043 | /// multiplying each element in the chain by the binomial coefficient |
| 1044 | /// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as: |
| 1045 | /// |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1046 | /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1047 | /// |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1048 | /// where BC(It, k) stands for binomial coefficient. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1049 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1050 | const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, |
Dan Gohman | 32291b1 | 2009-07-21 00:38:55 +0000 | [diff] [blame] | 1051 | ScalarEvolution &SE) const { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1052 | const SCEV *Result = getStart(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1053 | for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1054 | // The computation is correct in the face of overflow provided that the |
| 1055 | // multiplication is performed _after_ the evaluation of the binomial |
| 1056 | // coefficient. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1057 | const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); |
Nick Lewycky | 707663e | 2008-10-13 03:58:02 +0000 | [diff] [blame] | 1058 | if (isa<SCEVCouldNotCompute>(Coeff)) |
| 1059 | return Coeff; |
| 1060 | |
| 1061 | Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1062 | } |
| 1063 | return Result; |
| 1064 | } |
| 1065 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1066 | //===----------------------------------------------------------------------===// |
| 1067 | // SCEV Expression folder implementations |
| 1068 | //===----------------------------------------------------------------------===// |
| 1069 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1070 | const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1071 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1072 | assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1073 | "This is not a truncating conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1074 | assert(isSCEVable(Ty) && |
| 1075 | "This is not a conversion to a SCEVable type!"); |
| 1076 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1077 | |
Dan Gohman | 3a302cb | 2009-07-13 20:50:19 +0000 | [diff] [blame] | 1078 | FoldingSetNodeID ID; |
| 1079 | ID.AddInteger(scTruncate); |
| 1080 | ID.AddPointer(Op); |
| 1081 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1082 | void *IP = nullptr; |
Dan Gohman | 3a302cb | 2009-07-13 20:50:19 +0000 | [diff] [blame] | 1083 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1084 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1085 | // Fold if the operand is constant. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1086 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
Dan Gohman | 8d7576e | 2009-06-24 00:38:39 +0000 | [diff] [blame] | 1087 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1088 | cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1089 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1090 | // trunc(trunc(x)) --> trunc(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1091 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1092 | return getTruncateExpr(ST->getOperand(), Ty); |
| 1093 | |
Nick Lewycky | b4d9f7a | 2009-04-23 05:15:08 +0000 | [diff] [blame] | 1094 | // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1095 | if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) |
Nick Lewycky | b4d9f7a | 2009-04-23 05:15:08 +0000 | [diff] [blame] | 1096 | return getTruncateOrSignExtend(SS->getOperand(), Ty); |
| 1097 | |
| 1098 | // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1099 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
Nick Lewycky | b4d9f7a | 2009-04-23 05:15:08 +0000 | [diff] [blame] | 1100 | return getTruncateOrZeroExtend(SZ->getOperand(), Ty); |
| 1101 | |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1102 | // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can |
Nick Lewycky | 2ce2832 | 2015-03-20 02:52:23 +0000 | [diff] [blame] | 1103 | // eliminate all the truncates, or we replace other casts with truncates. |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1104 | if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { |
| 1105 | SmallVector<const SCEV *, 4> Operands; |
| 1106 | bool hasTrunc = false; |
| 1107 | for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { |
| 1108 | const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); |
Nick Lewycky | be8af48 | 2015-03-20 02:25:00 +0000 | [diff] [blame] | 1109 | if (!isa<SCEVCastExpr>(SA->getOperand(i))) |
| 1110 | hasTrunc = isa<SCEVTruncateExpr>(S); |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1111 | Operands.push_back(S); |
| 1112 | } |
| 1113 | if (!hasTrunc) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1114 | return getAddExpr(Operands); |
Nick Lewycky | d9e6b4a | 2011-01-26 08:40:22 +0000 | [diff] [blame] | 1115 | UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1116 | } |
| 1117 | |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1118 | // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can |
Nick Lewycky | be8af48 | 2015-03-20 02:25:00 +0000 | [diff] [blame] | 1119 | // eliminate all the truncates, or we replace other casts with truncates. |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1120 | if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { |
| 1121 | SmallVector<const SCEV *, 4> Operands; |
| 1122 | bool hasTrunc = false; |
| 1123 | for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { |
| 1124 | const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); |
Nick Lewycky | be8af48 | 2015-03-20 02:25:00 +0000 | [diff] [blame] | 1125 | if (!isa<SCEVCastExpr>(SM->getOperand(i))) |
| 1126 | hasTrunc = isa<SCEVTruncateExpr>(S); |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1127 | Operands.push_back(S); |
| 1128 | } |
| 1129 | if (!hasTrunc) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1130 | return getMulExpr(Operands); |
Nick Lewycky | d9e6b4a | 2011-01-26 08:40:22 +0000 | [diff] [blame] | 1131 | UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1132 | } |
| 1133 | |
Dan Gohman | 5a728c9 | 2009-06-18 16:24:47 +0000 | [diff] [blame] | 1134 | // If the input value is a chrec scev, truncate the chrec's operands. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1135 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1136 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 1137 | for (const SCEV *Op : AddRec->operands()) |
| 1138 | Operands.push_back(getTruncateExpr(Op, Ty)); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1139 | return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1140 | } |
| 1141 | |
Dan Gohman | 89dd42a | 2010-06-25 18:47:08 +0000 | [diff] [blame] | 1142 | // The cast wasn't folded; create an explicit cast node. We can reuse |
| 1143 | // the existing insert position since if we get here, we won't have |
| 1144 | // made any changes which would invalidate it. |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1145 | SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), |
| 1146 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1147 | UniqueSCEVs.InsertNode(S, IP); |
| 1148 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1149 | } |
| 1150 | |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1151 | // Get the limit of a recurrence such that incrementing by Step cannot cause |
| 1152 | // signed overflow as long as the value of the recurrence within the |
| 1153 | // loop does not exceed this limit before incrementing. |
| 1154 | static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, |
| 1155 | ICmpInst::Predicate *Pred, |
| 1156 | ScalarEvolution *SE) { |
| 1157 | unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); |
| 1158 | if (SE->isKnownPositive(Step)) { |
| 1159 | *Pred = ICmpInst::ICMP_SLT; |
| 1160 | return SE->getConstant(APInt::getSignedMinValue(BitWidth) - |
| 1161 | SE->getSignedRange(Step).getSignedMax()); |
| 1162 | } |
| 1163 | if (SE->isKnownNegative(Step)) { |
| 1164 | *Pred = ICmpInst::ICMP_SGT; |
| 1165 | return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - |
| 1166 | SE->getSignedRange(Step).getSignedMin()); |
| 1167 | } |
| 1168 | return nullptr; |
| 1169 | } |
| 1170 | |
| 1171 | // Get the limit of a recurrence such that incrementing by Step cannot cause |
| 1172 | // unsigned overflow as long as the value of the recurrence within the loop does |
| 1173 | // not exceed this limit before incrementing. |
| 1174 | static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, |
| 1175 | ICmpInst::Predicate *Pred, |
| 1176 | ScalarEvolution *SE) { |
| 1177 | unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); |
| 1178 | *Pred = ICmpInst::ICMP_ULT; |
| 1179 | |
| 1180 | return SE->getConstant(APInt::getMinValue(BitWidth) - |
| 1181 | SE->getUnsignedRange(Step).getUnsignedMax()); |
| 1182 | } |
| 1183 | |
| 1184 | namespace { |
| 1185 | |
| 1186 | struct ExtendOpTraitsBase { |
| 1187 | typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *); |
| 1188 | }; |
| 1189 | |
| 1190 | // Used to make code generic over signed and unsigned overflow. |
| 1191 | template <typename ExtendOp> struct ExtendOpTraits { |
| 1192 | // Members present: |
| 1193 | // |
| 1194 | // static const SCEV::NoWrapFlags WrapType; |
| 1195 | // |
| 1196 | // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; |
| 1197 | // |
| 1198 | // static const SCEV *getOverflowLimitForStep(const SCEV *Step, |
| 1199 | // ICmpInst::Predicate *Pred, |
| 1200 | // ScalarEvolution *SE); |
| 1201 | }; |
| 1202 | |
| 1203 | template <> |
| 1204 | struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { |
| 1205 | static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; |
| 1206 | |
| 1207 | static const GetExtendExprTy GetExtendExpr; |
| 1208 | |
| 1209 | static const SCEV *getOverflowLimitForStep(const SCEV *Step, |
| 1210 | ICmpInst::Predicate *Pred, |
| 1211 | ScalarEvolution *SE) { |
| 1212 | return getSignedOverflowLimitForStep(Step, Pred, SE); |
| 1213 | } |
| 1214 | }; |
| 1215 | |
Sanjoy Das | c1065b9 | 2015-02-18 08:03:22 +0000 | [diff] [blame] | 1216 | const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1217 | SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; |
| 1218 | |
| 1219 | template <> |
| 1220 | struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { |
| 1221 | static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; |
| 1222 | |
| 1223 | static const GetExtendExprTy GetExtendExpr; |
| 1224 | |
| 1225 | static const SCEV *getOverflowLimitForStep(const SCEV *Step, |
| 1226 | ICmpInst::Predicate *Pred, |
| 1227 | ScalarEvolution *SE) { |
| 1228 | return getUnsignedOverflowLimitForStep(Step, Pred, SE); |
| 1229 | } |
| 1230 | }; |
| 1231 | |
Sanjoy Das | c1065b9 | 2015-02-18 08:03:22 +0000 | [diff] [blame] | 1232 | const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1233 | SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 1234 | } |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1235 | |
| 1236 | // The recurrence AR has been shown to have no signed/unsigned wrap or something |
| 1237 | // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as |
| 1238 | // easily prove NSW/NUW for its preincrement or postincrement sibling. This |
| 1239 | // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + |
| 1240 | // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the |
| 1241 | // expression "Step + sext/zext(PreIncAR)" is congruent with |
| 1242 | // "sext/zext(PostIncAR)" |
| 1243 | template <typename ExtendOpTy> |
| 1244 | static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, |
| 1245 | ScalarEvolution *SE) { |
| 1246 | auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; |
| 1247 | auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; |
| 1248 | |
| 1249 | const Loop *L = AR->getLoop(); |
| 1250 | const SCEV *Start = AR->getStart(); |
| 1251 | const SCEV *Step = AR->getStepRecurrence(*SE); |
| 1252 | |
| 1253 | // Check for a simple looking step prior to loop entry. |
| 1254 | const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); |
| 1255 | if (!SA) |
| 1256 | return nullptr; |
| 1257 | |
| 1258 | // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV |
| 1259 | // subtraction is expensive. For this purpose, perform a quick and dirty |
| 1260 | // difference, by checking for Step in the operand list. |
| 1261 | SmallVector<const SCEV *, 4> DiffOps; |
| 1262 | for (const SCEV *Op : SA->operands()) |
| 1263 | if (Op != Step) |
| 1264 | DiffOps.push_back(Op); |
| 1265 | |
| 1266 | if (DiffOps.size() == SA->getNumOperands()) |
| 1267 | return nullptr; |
| 1268 | |
| 1269 | // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + |
| 1270 | // `Step`: |
| 1271 | |
| 1272 | // 1. NSW/NUW flags on the step increment. |
Sanjoy Das | 0714e3e | 2015-10-23 06:33:47 +0000 | [diff] [blame] | 1273 | auto PreStartFlags = |
| 1274 | ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); |
| 1275 | const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1276 | const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( |
| 1277 | SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); |
| 1278 | |
Sanjoy Das | b14010d | 2015-02-24 01:02:42 +0000 | [diff] [blame] | 1279 | // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies |
| 1280 | // "S+X does not sign/unsign-overflow". |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1281 | // |
| 1282 | |
Sanjoy Das | b14010d | 2015-02-24 01:02:42 +0000 | [diff] [blame] | 1283 | const SCEV *BECount = SE->getBackedgeTakenCount(L); |
| 1284 | if (PreAR && PreAR->getNoWrapFlags(WrapType) && |
| 1285 | !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1286 | return PreStart; |
| 1287 | |
| 1288 | // 2. Direct overflow check on the step operation's expression. |
| 1289 | unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); |
| 1290 | Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); |
| 1291 | const SCEV *OperandExtendedStart = |
| 1292 | SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy), |
| 1293 | (SE->*GetExtendExpr)(Step, WideTy)); |
| 1294 | if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) { |
| 1295 | if (PreAR && AR->getNoWrapFlags(WrapType)) { |
| 1296 | // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW |
| 1297 | // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then |
| 1298 | // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. |
| 1299 | const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); |
| 1300 | } |
| 1301 | return PreStart; |
| 1302 | } |
| 1303 | |
| 1304 | // 3. Loop precondition. |
| 1305 | ICmpInst::Predicate Pred; |
| 1306 | const SCEV *OverflowLimit = |
| 1307 | ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); |
| 1308 | |
| 1309 | if (OverflowLimit && |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 1310 | SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1311 | return PreStart; |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 1312 | |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1313 | return nullptr; |
| 1314 | } |
| 1315 | |
| 1316 | // Get the normalized zero or sign extended expression for this AddRec's Start. |
| 1317 | template <typename ExtendOpTy> |
| 1318 | static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, |
| 1319 | ScalarEvolution *SE) { |
| 1320 | auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; |
| 1321 | |
| 1322 | const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE); |
| 1323 | if (!PreStart) |
| 1324 | return (SE->*GetExtendExpr)(AR->getStart(), Ty); |
| 1325 | |
| 1326 | return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty), |
| 1327 | (SE->*GetExtendExpr)(PreStart, Ty)); |
| 1328 | } |
| 1329 | |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1330 | // Try to prove away overflow by looking at "nearby" add recurrences. A |
| 1331 | // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it |
| 1332 | // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. |
| 1333 | // |
| 1334 | // Formally: |
| 1335 | // |
| 1336 | // {S,+,X} == {S-T,+,X} + T |
| 1337 | // => Ext({S,+,X}) == Ext({S-T,+,X} + T) |
| 1338 | // |
| 1339 | // If ({S-T,+,X} + T) does not overflow ... (1) |
| 1340 | // |
| 1341 | // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) |
| 1342 | // |
| 1343 | // If {S-T,+,X} does not overflow ... (2) |
| 1344 | // |
| 1345 | // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) |
| 1346 | // == {Ext(S-T)+Ext(T),+,Ext(X)} |
| 1347 | // |
| 1348 | // If (S-T)+T does not overflow ... (3) |
| 1349 | // |
| 1350 | // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} |
| 1351 | // == {Ext(S),+,Ext(X)} == LHS |
| 1352 | // |
| 1353 | // Thus, if (1), (2) and (3) are true for some T, then |
| 1354 | // Ext({S,+,X}) == {Ext(S),+,Ext(X)} |
| 1355 | // |
| 1356 | // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) |
| 1357 | // does not overflow" restricted to the 0th iteration. Therefore we only need |
| 1358 | // to check for (1) and (2). |
| 1359 | // |
| 1360 | // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T |
| 1361 | // is `Delta` (defined below). |
| 1362 | // |
| 1363 | template <typename ExtendOpTy> |
| 1364 | bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, |
| 1365 | const SCEV *Step, |
| 1366 | const Loop *L) { |
| 1367 | auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; |
| 1368 | |
| 1369 | // We restrict `Start` to a constant to prevent SCEV from spending too much |
| 1370 | // time here. It is correct (but more expensive) to continue with a |
| 1371 | // non-constant `Start` and do a general SCEV subtraction to compute |
| 1372 | // `PreStart` below. |
| 1373 | // |
| 1374 | const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); |
| 1375 | if (!StartC) |
| 1376 | return false; |
| 1377 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1378 | APInt StartAI = StartC->getAPInt(); |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1379 | |
| 1380 | for (unsigned Delta : {-2, -1, 1, 2}) { |
| 1381 | const SCEV *PreStart = getConstant(StartAI - Delta); |
| 1382 | |
Sanjoy Das | 4280110 | 2015-10-23 06:57:21 +0000 | [diff] [blame] | 1383 | FoldingSetNodeID ID; |
| 1384 | ID.AddInteger(scAddRecExpr); |
| 1385 | ID.AddPointer(PreStart); |
| 1386 | ID.AddPointer(Step); |
| 1387 | ID.AddPointer(L); |
| 1388 | void *IP = nullptr; |
| 1389 | const auto *PreAR = |
| 1390 | static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 1391 | |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1392 | // Give up if we don't already have the add recurrence we need because |
| 1393 | // actually constructing an add recurrence is relatively expensive. |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1394 | if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) |
| 1395 | const SCEV *DeltaS = getConstant(StartC->getType(), Delta); |
| 1396 | ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; |
| 1397 | const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( |
| 1398 | DeltaS, &Pred, this); |
| 1399 | if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) |
| 1400 | return true; |
| 1401 | } |
| 1402 | } |
| 1403 | |
| 1404 | return false; |
| 1405 | } |
| 1406 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1407 | const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1408 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1409 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
Dan Gohman | c1c2ba7 | 2009-04-16 19:25:55 +0000 | [diff] [blame] | 1410 | "This is not an extending conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1411 | assert(isSCEVable(Ty) && |
| 1412 | "This is not a conversion to a SCEVable type!"); |
| 1413 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | c1c2ba7 | 2009-04-16 19:25:55 +0000 | [diff] [blame] | 1414 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1415 | // Fold if the operand is constant. |
Dan Gohman | 5235cc2 | 2010-06-24 16:47:03 +0000 | [diff] [blame] | 1416 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
| 1417 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1418 | cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1419 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1420 | // zext(zext(x)) --> zext(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1421 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1422 | return getZeroExtendExpr(SZ->getOperand(), Ty); |
| 1423 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1424 | // Before doing any expensive analysis, check to see if we've already |
| 1425 | // computed a SCEV for this Op and Ty. |
| 1426 | FoldingSetNodeID ID; |
| 1427 | ID.AddInteger(scZeroExtend); |
| 1428 | ID.AddPointer(Op); |
| 1429 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1430 | void *IP = nullptr; |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1431 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1432 | |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1433 | // zext(trunc(x)) --> zext(x) or x or trunc(x) |
| 1434 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { |
| 1435 | // It's possible the bits taken off by the truncate were all zero bits. If |
| 1436 | // so, we should be able to simplify this further. |
| 1437 | const SCEV *X = ST->getOperand(); |
| 1438 | ConstantRange CR = getUnsignedRange(X); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1439 | unsigned TruncBits = getTypeSizeInBits(ST->getType()); |
| 1440 | unsigned NewBits = getTypeSizeInBits(Ty); |
| 1441 | if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( |
Nick Lewycky | d4192f7 | 2011-01-23 20:06:05 +0000 | [diff] [blame] | 1442 | CR.zextOrTrunc(NewBits))) |
| 1443 | return getTruncateOrZeroExtend(X, Ty); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1444 | } |
| 1445 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1446 | // If the input value is a chrec scev, and we can prove that the value |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1447 | // did not overflow the old, smaller, value, we can zero extend all of the |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1448 | // operands (often constants). This allows analysis of something like |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1449 | // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1450 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1451 | if (AR->isAffine()) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1452 | const SCEV *Start = AR->getStart(); |
| 1453 | const SCEV *Step = AR->getStepRecurrence(*this); |
| 1454 | unsigned BitWidth = getTypeSizeInBits(AR->getType()); |
| 1455 | const Loop *L = AR->getLoop(); |
| 1456 | |
Sanjoy Das | 724f5cf | 2016-03-03 18:31:29 +0000 | [diff] [blame] | 1457 | if (!AR->hasNoUnsignedWrap()) { |
| 1458 | auto NewFlags = proveNoWrapViaConstantRanges(AR); |
| 1459 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); |
| 1460 | } |
| 1461 | |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1462 | // If we have special knowledge that this addrec won't overflow, |
| 1463 | // we don't need to do any further analysis. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1464 | if (AR->hasNoUnsignedWrap()) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1465 | return getAddRecExpr( |
| 1466 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1467 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1468 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1469 | // Check whether the backedge-taken count is SCEVCouldNotCompute. |
| 1470 | // Note that this serves two purposes: It filters out loops that are |
| 1471 | // simply not analyzable, and it covers the case where this code is |
| 1472 | // being called from within backedge-taken count analysis, such that |
| 1473 | // attempting to ask for the backedge-taken count would likely result |
| 1474 | // in infinite recursion. In the later case, the analysis code will |
| 1475 | // cope with a conservative value, and it will take care to purge |
| 1476 | // that value once it has finished. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1477 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1478 | if (!isa<SCEVCouldNotCompute>(MaxBECount)) { |
Dan Gohman | 95c5b0e | 2009-04-29 01:54:20 +0000 | [diff] [blame] | 1479 | // Manually compute the final value for AR, checking for |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1480 | // overflow. |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1481 | |
| 1482 | // Check whether the backedge-taken count can be losslessly casted to |
| 1483 | // the addrec's type. The count is always unsigned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1484 | const SCEV *CastedMaxBECount = |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1485 | getTruncateOrZeroExtend(MaxBECount, Start->getType()); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1486 | const SCEV *RecastedMaxBECount = |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1487 | getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); |
| 1488 | if (MaxBECount == RecastedMaxBECount) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1489 | Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1490 | // Check whether Start+Step*MaxBECount has no unsigned overflow. |
Dan Gohman | 007f504 | 2010-02-24 19:31:06 +0000 | [diff] [blame] | 1491 | const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1492 | const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy); |
| 1493 | const SCEV *WideStart = getZeroExtendExpr(Start, WideTy); |
| 1494 | const SCEV *WideMaxBECount = |
| 1495 | getZeroExtendExpr(CastedMaxBECount, WideTy); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1496 | const SCEV *OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1497 | getAddExpr(WideStart, |
| 1498 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1499 | getZeroExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1500 | if (ZAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1501 | // Cache knowledge of AR NUW, which is propagated to this AddRec. |
| 1502 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1503 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1504 | return getAddRecExpr( |
| 1505 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1506 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1507 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1508 | // Similar to above, only this time treat the step value as signed. |
| 1509 | // This covers loops that count down. |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1510 | OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1511 | getAddExpr(WideStart, |
| 1512 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1513 | getSignExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1514 | if (ZAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1515 | // Cache knowledge of AR NW, which is propagated to this AddRec. |
| 1516 | // Negative step causes unsigned wrap, but it still can't self-wrap. |
| 1517 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1518 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1519 | return getAddRecExpr( |
| 1520 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1521 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1522 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1523 | } |
Sanjoy Das | f5d40d5 | 2016-05-17 17:51:14 +0000 | [diff] [blame] | 1524 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1525 | |
Sanjoy Das | f5d40d5 | 2016-05-17 17:51:14 +0000 | [diff] [blame] | 1526 | // Normally, in the cases we can prove no-overflow via a |
| 1527 | // backedge guarding condition, we can also compute a backedge |
| 1528 | // taken count for the loop. The exceptions are assumptions and |
| 1529 | // guards present in the loop -- SCEV is not great at exploiting |
| 1530 | // these to compute max backedge taken counts, but can still use |
| 1531 | // these to prove lack of overflow. Use this fact to avoid |
| 1532 | // doing extra work that may not pay off. |
| 1533 | if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || |
| 1534 | !AC.assumptions().empty()) { |
| 1535 | // If the backedge is guarded by a comparison with the pre-inc |
| 1536 | // value the addrec is safe. Also, if the entry is guarded by |
| 1537 | // a comparison with the start value and the backedge is |
| 1538 | // guarded by a comparison with the post-inc value, the addrec |
| 1539 | // is safe. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1540 | if (isKnownPositive(Step)) { |
| 1541 | const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - |
| 1542 | getUnsignedRange(Step).getUnsignedMax()); |
| 1543 | if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || |
Dan Gohman | b50349a | 2010-04-11 19:27:13 +0000 | [diff] [blame] | 1544 | (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1545 | isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1546 | AR->getPostIncExpr(*this), N))) { |
Sanjoy Das | f5d40d5 | 2016-05-17 17:51:14 +0000 | [diff] [blame] | 1547 | // Cache knowledge of AR NUW, which is propagated to this |
| 1548 | // AddRec. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1549 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1550 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1551 | return getAddRecExpr( |
| 1552 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1553 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1554 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1555 | } else if (isKnownNegative(Step)) { |
| 1556 | const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - |
| 1557 | getSignedRange(Step).getSignedMin()); |
Dan Gohman | 5f18c54 | 2010-05-04 01:11:15 +0000 | [diff] [blame] | 1558 | if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || |
| 1559 | (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1560 | isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1561 | AR->getPostIncExpr(*this), N))) { |
Sanjoy Das | f5d40d5 | 2016-05-17 17:51:14 +0000 | [diff] [blame] | 1562 | // Cache knowledge of AR NW, which is propagated to this |
| 1563 | // AddRec. Negative step causes unsigned wrap, but it |
| 1564 | // still can't self-wrap. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1565 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
| 1566 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1567 | return getAddRecExpr( |
| 1568 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1569 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1570 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1571 | } |
| 1572 | } |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1573 | |
| 1574 | if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { |
| 1575 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
| 1576 | return getAddRecExpr( |
| 1577 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1578 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
| 1579 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1580 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1581 | |
Sanjoy Das | eeca9f6 | 2015-10-22 19:57:38 +0000 | [diff] [blame] | 1582 | if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { |
| 1583 | // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1584 | if (SA->hasNoUnsignedWrap()) { |
Sanjoy Das | eeca9f6 | 2015-10-22 19:57:38 +0000 | [diff] [blame] | 1585 | // If the addition does not unsign overflow then we can, by definition, |
| 1586 | // commute the zero extension with the addition operation. |
| 1587 | SmallVector<const SCEV *, 4> Ops; |
| 1588 | for (const auto *Op : SA->operands()) |
| 1589 | Ops.push_back(getZeroExtendExpr(Op, Ty)); |
| 1590 | return getAddExpr(Ops, SCEV::FlagNUW); |
| 1591 | } |
| 1592 | } |
| 1593 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1594 | // The cast wasn't folded; create an explicit cast node. |
| 1595 | // Recompute the insert position, as it may have been invalidated. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1596 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1597 | SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), |
| 1598 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1599 | UniqueSCEVs.InsertNode(S, IP); |
| 1600 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1601 | } |
| 1602 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1603 | const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1604 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1605 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1606 | "This is not an extending conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1607 | assert(isSCEVable(Ty) && |
| 1608 | "This is not a conversion to a SCEVable type!"); |
| 1609 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1610 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1611 | // Fold if the operand is constant. |
Dan Gohman | 5235cc2 | 2010-06-24 16:47:03 +0000 | [diff] [blame] | 1612 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
| 1613 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1614 | cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1615 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1616 | // sext(sext(x)) --> sext(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1617 | if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1618 | return getSignExtendExpr(SS->getOperand(), Ty); |
| 1619 | |
Nick Lewycky | e9ea75e | 2011-01-19 15:56:12 +0000 | [diff] [blame] | 1620 | // sext(zext(x)) --> zext(x) |
| 1621 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
| 1622 | return getZeroExtendExpr(SZ->getOperand(), Ty); |
| 1623 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1624 | // Before doing any expensive analysis, check to see if we've already |
| 1625 | // computed a SCEV for this Op and Ty. |
| 1626 | FoldingSetNodeID ID; |
| 1627 | ID.AddInteger(scSignExtend); |
| 1628 | ID.AddPointer(Op); |
| 1629 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1630 | void *IP = nullptr; |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1631 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1632 | |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1633 | // sext(trunc(x)) --> sext(x) or x or trunc(x) |
| 1634 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { |
| 1635 | // It's possible the bits taken off by the truncate were all sign bits. If |
| 1636 | // so, we should be able to simplify this further. |
| 1637 | const SCEV *X = ST->getOperand(); |
| 1638 | ConstantRange CR = getSignedRange(X); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1639 | unsigned TruncBits = getTypeSizeInBits(ST->getType()); |
| 1640 | unsigned NewBits = getTypeSizeInBits(Ty); |
| 1641 | if (CR.truncate(TruncBits).signExtend(NewBits).contains( |
Nick Lewycky | d4192f7 | 2011-01-23 20:06:05 +0000 | [diff] [blame] | 1642 | CR.sextOrTrunc(NewBits))) |
| 1643 | return getTruncateOrSignExtend(X, Ty); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1644 | } |
| 1645 | |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1646 | // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1647 | if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1648 | if (SA->getNumOperands() == 2) { |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1649 | auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); |
| 1650 | auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1651 | if (SMul && SC1) { |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1652 | if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1653 | const APInt &C1 = SC1->getAPInt(); |
| 1654 | const APInt &C2 = SC2->getAPInt(); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1655 | if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && |
Michael Zolotukhin | 265dfa4 | 2014-05-26 14:49:46 +0000 | [diff] [blame] | 1656 | C2.ugt(C1) && C2.isPowerOf2()) |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1657 | return getAddExpr(getSignExtendExpr(SC1, Ty), |
| 1658 | getSignExtendExpr(SMul, Ty)); |
| 1659 | } |
| 1660 | } |
| 1661 | } |
Sanjoy Das | a060e60 | 2015-10-22 19:57:25 +0000 | [diff] [blame] | 1662 | |
| 1663 | // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1664 | if (SA->hasNoSignedWrap()) { |
Sanjoy Das | a060e60 | 2015-10-22 19:57:25 +0000 | [diff] [blame] | 1665 | // If the addition does not sign overflow then we can, by definition, |
| 1666 | // commute the sign extension with the addition operation. |
| 1667 | SmallVector<const SCEV *, 4> Ops; |
| 1668 | for (const auto *Op : SA->operands()) |
| 1669 | Ops.push_back(getSignExtendExpr(Op, Ty)); |
| 1670 | return getAddExpr(Ops, SCEV::FlagNSW); |
| 1671 | } |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1672 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1673 | // If the input value is a chrec scev, and we can prove that the value |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1674 | // did not overflow the old, smaller, value, we can sign extend all of the |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1675 | // operands (often constants). This allows analysis of something like |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1676 | // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1677 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1678 | if (AR->isAffine()) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1679 | const SCEV *Start = AR->getStart(); |
| 1680 | const SCEV *Step = AR->getStepRecurrence(*this); |
| 1681 | unsigned BitWidth = getTypeSizeInBits(AR->getType()); |
| 1682 | const Loop *L = AR->getLoop(); |
| 1683 | |
Sanjoy Das | 724f5cf | 2016-03-03 18:31:29 +0000 | [diff] [blame] | 1684 | if (!AR->hasNoSignedWrap()) { |
| 1685 | auto NewFlags = proveNoWrapViaConstantRanges(AR); |
| 1686 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); |
| 1687 | } |
| 1688 | |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1689 | // If we have special knowledge that this addrec won't overflow, |
| 1690 | // we don't need to do any further analysis. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1691 | if (AR->hasNoSignedWrap()) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1692 | return getAddRecExpr( |
| 1693 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1694 | getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW); |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1695 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1696 | // Check whether the backedge-taken count is SCEVCouldNotCompute. |
| 1697 | // Note that this serves two purposes: It filters out loops that are |
| 1698 | // simply not analyzable, and it covers the case where this code is |
| 1699 | // being called from within backedge-taken count analysis, such that |
| 1700 | // attempting to ask for the backedge-taken count would likely result |
| 1701 | // in infinite recursion. In the later case, the analysis code will |
| 1702 | // cope with a conservative value, and it will take care to purge |
| 1703 | // that value once it has finished. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1704 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1705 | if (!isa<SCEVCouldNotCompute>(MaxBECount)) { |
Dan Gohman | 95c5b0e | 2009-04-29 01:54:20 +0000 | [diff] [blame] | 1706 | // Manually compute the final value for AR, checking for |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1707 | // overflow. |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1708 | |
| 1709 | // Check whether the backedge-taken count can be losslessly casted to |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1710 | // the addrec's type. The count is always unsigned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1711 | const SCEV *CastedMaxBECount = |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1712 | getTruncateOrZeroExtend(MaxBECount, Start->getType()); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1713 | const SCEV *RecastedMaxBECount = |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1714 | getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); |
| 1715 | if (MaxBECount == RecastedMaxBECount) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1716 | Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1717 | // Check whether Start+Step*MaxBECount has no signed overflow. |
Dan Gohman | 007f504 | 2010-02-24 19:31:06 +0000 | [diff] [blame] | 1718 | const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1719 | const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy); |
| 1720 | const SCEV *WideStart = getSignExtendExpr(Start, WideTy); |
| 1721 | const SCEV *WideMaxBECount = |
| 1722 | getZeroExtendExpr(CastedMaxBECount, WideTy); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1723 | const SCEV *OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1724 | getAddExpr(WideStart, |
| 1725 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1726 | getSignExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1727 | if (SAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1728 | // Cache knowledge of AR NSW, which is propagated to this AddRec. |
| 1729 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1730 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1731 | return getAddRecExpr( |
| 1732 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1733 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1734 | } |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1735 | // Similar to above, only this time treat the step value as unsigned. |
| 1736 | // This covers loops that count up with an unsigned step. |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1737 | OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1738 | getAddExpr(WideStart, |
| 1739 | getMulExpr(WideMaxBECount, |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1740 | getZeroExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1741 | if (SAdd == OperandExtendedAdd) { |
Sanjoy Das | bf5d870 | 2015-02-09 18:34:55 +0000 | [diff] [blame] | 1742 | // If AR wraps around then |
| 1743 | // |
| 1744 | // abs(Step) * MaxBECount > unsigned-max(AR->getType()) |
| 1745 | // => SAdd != OperandExtendedAdd |
| 1746 | // |
| 1747 | // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> |
| 1748 | // (SAdd == OperandExtendedAdd => AR is NW) |
| 1749 | |
| 1750 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
| 1751 | |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1752 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1753 | return getAddRecExpr( |
| 1754 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1755 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1756 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1757 | } |
Sanjoy Das | 787c246 | 2016-05-11 17:41:26 +0000 | [diff] [blame] | 1758 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1759 | |
Sanjoy Das | 787c246 | 2016-05-11 17:41:26 +0000 | [diff] [blame] | 1760 | // Normally, in the cases we can prove no-overflow via a |
| 1761 | // backedge guarding condition, we can also compute a backedge |
| 1762 | // taken count for the loop. The exceptions are assumptions and |
| 1763 | // guards present in the loop -- SCEV is not great at exploiting |
| 1764 | // these to compute max backedge taken counts, but can still use |
| 1765 | // these to prove lack of overflow. Use this fact to avoid |
| 1766 | // doing extra work that may not pay off. |
| 1767 | |
| 1768 | if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || |
| 1769 | !AC.assumptions().empty()) { |
| 1770 | // If the backedge is guarded by a comparison with the pre-inc |
| 1771 | // value the addrec is safe. Also, if the entry is guarded by |
| 1772 | // a comparison with the start value and the backedge is |
| 1773 | // guarded by a comparison with the post-inc value, the addrec |
| 1774 | // is safe. |
Andrew Trick | 812276e | 2011-05-31 21:17:47 +0000 | [diff] [blame] | 1775 | ICmpInst::Predicate Pred; |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1776 | const SCEV *OverflowLimit = |
| 1777 | getSignedOverflowLimitForStep(Step, &Pred, this); |
Andrew Trick | 812276e | 2011-05-31 21:17:47 +0000 | [diff] [blame] | 1778 | if (OverflowLimit && |
| 1779 | (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || |
| 1780 | (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && |
| 1781 | isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), |
| 1782 | OverflowLimit)))) { |
| 1783 | // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. |
| 1784 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1785 | return getAddRecExpr( |
| 1786 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1787 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1788 | } |
| 1789 | } |
Sanjoy Das | 787c246 | 2016-05-11 17:41:26 +0000 | [diff] [blame] | 1790 | |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1791 | // If Start and Step are constants, check if we can apply this |
| 1792 | // transformation: |
| 1793 | // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1794 | auto *SC1 = dyn_cast<SCEVConstant>(Start); |
| 1795 | auto *SC2 = dyn_cast<SCEVConstant>(Step); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1796 | if (SC1 && SC2) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1797 | const APInt &C1 = SC1->getAPInt(); |
| 1798 | const APInt &C2 = SC2->getAPInt(); |
Michael Zolotukhin | 265dfa4 | 2014-05-26 14:49:46 +0000 | [diff] [blame] | 1799 | if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && |
| 1800 | C2.isPowerOf2()) { |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1801 | Start = getSignExtendExpr(Start, Ty); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 1802 | const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, |
| 1803 | AR->getNoWrapFlags()); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1804 | return getAddExpr(Start, getSignExtendExpr(NewAR, Ty)); |
| 1805 | } |
| 1806 | } |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1807 | |
| 1808 | if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { |
| 1809 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
| 1810 | return getAddRecExpr( |
| 1811 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1812 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
| 1813 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1814 | } |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1815 | |
Sanjoy Das | 11ef606 | 2016-03-03 18:31:23 +0000 | [diff] [blame] | 1816 | // If the input value is provably positive and we could not simplify |
| 1817 | // away the sext build a zext instead. |
| 1818 | if (isKnownNonNegative(Op)) |
| 1819 | return getZeroExtendExpr(Op, Ty); |
| 1820 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1821 | // The cast wasn't folded; create an explicit cast node. |
| 1822 | // Recompute the insert position, as it may have been invalidated. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1823 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1824 | SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), |
| 1825 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1826 | UniqueSCEVs.InsertNode(S, IP); |
| 1827 | return S; |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1828 | } |
| 1829 | |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1830 | /// getAnyExtendExpr - Return a SCEV for the given operand extended with |
| 1831 | /// unspecified bits out to the given type. |
| 1832 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1833 | const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1834 | Type *Ty) { |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1835 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
| 1836 | "This is not an extending conversion!"); |
| 1837 | assert(isSCEVable(Ty) && |
| 1838 | "This is not a conversion to a SCEVable type!"); |
| 1839 | Ty = getEffectiveSCEVType(Ty); |
| 1840 | |
| 1841 | // Sign-extend negative constants. |
| 1842 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1843 | if (SC->getAPInt().isNegative()) |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1844 | return getSignExtendExpr(Op, Ty); |
| 1845 | |
| 1846 | // Peel off a truncate cast. |
| 1847 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1848 | const SCEV *NewOp = T->getOperand(); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1849 | if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) |
| 1850 | return getAnyExtendExpr(NewOp, Ty); |
| 1851 | return getTruncateOrNoop(NewOp, Ty); |
| 1852 | } |
| 1853 | |
| 1854 | // Next try a zext cast. If the cast is folded, use it. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1855 | const SCEV *ZExt = getZeroExtendExpr(Op, Ty); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1856 | if (!isa<SCEVZeroExtendExpr>(ZExt)) |
| 1857 | return ZExt; |
| 1858 | |
| 1859 | // Next try a sext cast. If the cast is folded, use it. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1860 | const SCEV *SExt = getSignExtendExpr(Op, Ty); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1861 | if (!isa<SCEVSignExtendExpr>(SExt)) |
| 1862 | return SExt; |
| 1863 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1864 | // Force the cast to be folded into the operands of an addrec. |
| 1865 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { |
| 1866 | SmallVector<const SCEV *, 4> Ops; |
Tobias Grosser | 924221c | 2014-05-07 06:07:47 +0000 | [diff] [blame] | 1867 | for (const SCEV *Op : AR->operands()) |
| 1868 | Ops.push_back(getAnyExtendExpr(Op, Ty)); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1869 | return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1870 | } |
| 1871 | |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1872 | // If the expression is obviously signed, use the sext cast value. |
| 1873 | if (isa<SCEVSMaxExpr>(Op)) |
| 1874 | return SExt; |
| 1875 | |
| 1876 | // Absent any other information, use the zext cast value. |
| 1877 | return ZExt; |
| 1878 | } |
| 1879 | |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1880 | /// CollectAddOperandsWithScales - Process the given Ops list, which is |
| 1881 | /// a list of operands to be added under the given scale, update the given |
| 1882 | /// map. This is a helper function for getAddRecExpr. As an example of |
| 1883 | /// what it does, given a sequence of operands that would form an add |
| 1884 | /// expression like this: |
| 1885 | /// |
Tobias Grosser | ba49e42 | 2014-03-05 10:37:17 +0000 | [diff] [blame] | 1886 | /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1887 | /// |
| 1888 | /// where A and B are constants, update the map with these values: |
| 1889 | /// |
| 1890 | /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) |
| 1891 | /// |
| 1892 | /// and add 13 + A*B*29 to AccumulatedConstant. |
| 1893 | /// This will allow getAddRecExpr to produce this: |
| 1894 | /// |
| 1895 | /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) |
| 1896 | /// |
| 1897 | /// This form often exposes folding opportunities that are hidden in |
| 1898 | /// the original operand list. |
| 1899 | /// |
Sylvestre Ledru | 91ce36c | 2012-09-27 10:14:43 +0000 | [diff] [blame] | 1900 | /// Return true iff it appears that any interesting folding opportunities |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1901 | /// may be exposed. This helps getAddRecExpr short-circuit extra work in |
| 1902 | /// the common case where no interesting opportunities are present, and |
| 1903 | /// is also used as a check to avoid infinite recursion. |
| 1904 | /// |
| 1905 | static bool |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1906 | CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, |
Craig Topper | 2cd5ff8 | 2013-07-11 16:22:38 +0000 | [diff] [blame] | 1907 | SmallVectorImpl<const SCEV *> &NewOps, |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1908 | APInt &AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1909 | const SCEV *const *Ops, size_t NumOperands, |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1910 | const APInt &Scale, |
| 1911 | ScalarEvolution &SE) { |
| 1912 | bool Interesting = false; |
| 1913 | |
Dan Gohman | 4507304 | 2010-06-18 19:12:32 +0000 | [diff] [blame] | 1914 | // Iterate over the add operands. They are sorted, with constants first. |
| 1915 | unsigned i = 0; |
| 1916 | while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { |
| 1917 | ++i; |
| 1918 | // Pull a buried constant out to the outside. |
| 1919 | if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) |
| 1920 | Interesting = true; |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1921 | AccumulatedConstant += Scale * C->getAPInt(); |
Dan Gohman | 4507304 | 2010-06-18 19:12:32 +0000 | [diff] [blame] | 1922 | } |
| 1923 | |
| 1924 | // Next comes everything else. We're especially interested in multiplies |
| 1925 | // here, but they're in the middle, so just visit the rest with one loop. |
| 1926 | for (; i != NumOperands; ++i) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1927 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); |
| 1928 | if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { |
| 1929 | APInt NewScale = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1930 | Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1931 | if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { |
| 1932 | // A multiplication of a constant with another add; recurse. |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1933 | const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1934 | Interesting |= |
| 1935 | CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1936 | Add->op_begin(), Add->getNumOperands(), |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1937 | NewScale, SE); |
| 1938 | } else { |
| 1939 | // A multiplication of a constant with some other value. Update |
| 1940 | // the map. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1941 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); |
| 1942 | const SCEV *Key = SE.getMulExpr(MulOps); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 1943 | auto Pair = M.insert({Key, NewScale}); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1944 | if (Pair.second) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1945 | NewOps.push_back(Pair.first->first); |
| 1946 | } else { |
| 1947 | Pair.first->second += NewScale; |
| 1948 | // The map already had an entry for this value, which may indicate |
| 1949 | // a folding opportunity. |
| 1950 | Interesting = true; |
| 1951 | } |
| 1952 | } |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1953 | } else { |
| 1954 | // An ordinary operand. Update the map. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1955 | std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 1956 | M.insert({Ops[i], Scale}); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1957 | if (Pair.second) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1958 | NewOps.push_back(Pair.first->first); |
| 1959 | } else { |
| 1960 | Pair.first->second += Scale; |
| 1961 | // The map already had an entry for this value, which may indicate |
| 1962 | // a folding opportunity. |
| 1963 | Interesting = true; |
| 1964 | } |
| 1965 | } |
| 1966 | } |
| 1967 | |
| 1968 | return Interesting; |
| 1969 | } |
| 1970 | |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1971 | // We're trying to construct a SCEV of type `Type' with `Ops' as operands and |
| 1972 | // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of |
| 1973 | // can't-overflow flags for the operation if possible. |
| 1974 | static SCEV::NoWrapFlags |
| 1975 | StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, |
| 1976 | const SmallVectorImpl<const SCEV *> &Ops, |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1977 | SCEV::NoWrapFlags Flags) { |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1978 | using namespace std::placeholders; |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1979 | typedef OverflowingBinaryOperator OBO; |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1980 | |
| 1981 | bool CanAnalyze = |
| 1982 | Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; |
| 1983 | (void)CanAnalyze; |
| 1984 | assert(CanAnalyze && "don't call from other places!"); |
| 1985 | |
| 1986 | int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; |
| 1987 | SCEV::NoWrapFlags SignOrUnsignWrap = |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1988 | ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1989 | |
| 1990 | // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. |
Sanjoy Das | 9b0015f | 2015-11-29 23:40:57 +0000 | [diff] [blame] | 1991 | auto IsKnownNonNegative = [&](const SCEV *S) { |
| 1992 | return SE->isKnownNonNegative(S); |
| 1993 | }; |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1994 | |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 1995 | if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1996 | Flags = |
| 1997 | ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1998 | |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1999 | SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); |
| 2000 | |
| 2001 | if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && |
| 2002 | Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { |
| 2003 | |
| 2004 | // (A + C) --> (A + C)<nsw> if the addition does not sign overflow |
| 2005 | // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow |
| 2006 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2007 | const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2008 | if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { |
Sanjoy Das | 5079f62 | 2016-02-22 16:13:02 +0000 | [diff] [blame] | 2009 | auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 2010 | Instruction::Add, C, OBO::NoSignedWrap); |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2011 | if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) |
| 2012 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); |
| 2013 | } |
| 2014 | if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { |
Sanjoy Das | 5079f62 | 2016-02-22 16:13:02 +0000 | [diff] [blame] | 2015 | auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 2016 | Instruction::Add, C, OBO::NoUnsignedWrap); |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2017 | if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) |
| 2018 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); |
| 2019 | } |
| 2020 | } |
| 2021 | |
| 2022 | return Flags; |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2023 | } |
| 2024 | |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 2025 | /// getAddExpr - Get a canonical add expression, or something simpler if |
| 2026 | /// possible. |
Dan Gohman | 816fe0a | 2009-10-09 00:10:36 +0000 | [diff] [blame] | 2027 | const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2028 | SCEV::NoWrapFlags Flags) { |
| 2029 | assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && |
| 2030 | "only nuw or nsw allowed"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2031 | assert(!Ops.empty() && "Cannot get empty add!"); |
Chris Lattner | 74498e1 | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 2032 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2033 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2034 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2035 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | 9136d9f | 2010-06-18 19:09:27 +0000 | [diff] [blame] | 2036 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2037 | "SCEVAddExpr operand types don't match!"); |
| 2038 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2039 | |
| 2040 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2041 | GroupByComplexity(Ops, &LI); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2042 | |
Sanjoy Das | 6489561 | 2015-10-09 02:44:45 +0000 | [diff] [blame] | 2043 | Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); |
| 2044 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2045 | // If there are any constants, fold them together. |
| 2046 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2047 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2048 | ++Idx; |
Chris Lattner | 74498e1 | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 2049 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2050 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2051 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2052 | Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); |
Dan Gohman | 011cf68 | 2009-06-14 22:53:57 +0000 | [diff] [blame] | 2053 | if (Ops.size() == 2) return Ops[0]; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2054 | Ops.erase(Ops.begin()+1); // Erase the folded element |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2055 | LHSC = cast<SCEVConstant>(Ops[0]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2056 | } |
| 2057 | |
| 2058 | // If we are left with a constant zero being added, strip it off. |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 2059 | if (LHSC->getValue()->isZero()) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2060 | Ops.erase(Ops.begin()); |
| 2061 | --Idx; |
| 2062 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2063 | |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 2064 | if (Ops.size() == 1) return Ops[0]; |
| 2065 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2066 | |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2067 | // Okay, check to see if the same value occurs in the operand list more than |
| 2068 | // once. If so, merge them together into an multiply expression. Since we |
| 2069 | // sorted the list, these values are required to be adjacent. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2070 | Type *Ty = Ops[0]->getType(); |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2071 | bool FoundMatch = false; |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2072 | for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2073 | if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2074 | // Scan ahead to count how many equal operands there are. |
| 2075 | unsigned Count = 2; |
| 2076 | while (i+Count != e && Ops[i+Count] == Ops[i]) |
| 2077 | ++Count; |
| 2078 | // Merge the values into a multiply. |
| 2079 | const SCEV *Scale = getConstant(Ty, Count); |
| 2080 | const SCEV *Mul = getMulExpr(Scale, Ops[i]); |
| 2081 | if (Ops.size() == Count) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2082 | return Mul; |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2083 | Ops[i] = Mul; |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2084 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); |
Dan Gohman | fe22f1d | 2010-08-28 00:39:27 +0000 | [diff] [blame] | 2085 | --i; e -= Count - 1; |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2086 | FoundMatch = true; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2087 | } |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2088 | if (FoundMatch) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2089 | return getAddExpr(Ops, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2090 | |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2091 | // Check for truncates. If all the operands are truncated from the same |
| 2092 | // type, see if factoring out the truncate would permit the result to be |
| 2093 | // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) |
| 2094 | // if the contents of the resulting outer trunc fold to something simple. |
| 2095 | for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { |
| 2096 | const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2097 | Type *DstType = Trunc->getType(); |
| 2098 | Type *SrcType = Trunc->getOperand()->getType(); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2099 | SmallVector<const SCEV *, 8> LargeOps; |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2100 | bool Ok = true; |
| 2101 | // Check all the operands to see if they can be represented in the |
| 2102 | // source type of the truncate. |
| 2103 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) { |
| 2104 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { |
| 2105 | if (T->getOperand()->getType() != SrcType) { |
| 2106 | Ok = false; |
| 2107 | break; |
| 2108 | } |
| 2109 | LargeOps.push_back(T->getOperand()); |
| 2110 | } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { |
Dan Gohman | ff3174e | 2010-04-23 01:51:29 +0000 | [diff] [blame] | 2111 | LargeOps.push_back(getAnyExtendExpr(C, SrcType)); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2112 | } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2113 | SmallVector<const SCEV *, 8> LargeMulOps; |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2114 | for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { |
| 2115 | if (const SCEVTruncateExpr *T = |
| 2116 | dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { |
| 2117 | if (T->getOperand()->getType() != SrcType) { |
| 2118 | Ok = false; |
| 2119 | break; |
| 2120 | } |
| 2121 | LargeMulOps.push_back(T->getOperand()); |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 2122 | } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { |
Dan Gohman | ff3174e | 2010-04-23 01:51:29 +0000 | [diff] [blame] | 2123 | LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2124 | } else { |
| 2125 | Ok = false; |
| 2126 | break; |
| 2127 | } |
| 2128 | } |
| 2129 | if (Ok) |
| 2130 | LargeOps.push_back(getMulExpr(LargeMulOps)); |
| 2131 | } else { |
| 2132 | Ok = false; |
| 2133 | break; |
| 2134 | } |
| 2135 | } |
| 2136 | if (Ok) { |
| 2137 | // Evaluate the expression in the larger type. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2138 | const SCEV *Fold = getAddExpr(LargeOps, Flags); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2139 | // If it folds to something simple, use it. Otherwise, don't. |
| 2140 | if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) |
| 2141 | return getTruncateExpr(Fold, DstType); |
| 2142 | } |
| 2143 | } |
| 2144 | |
| 2145 | // Skip past any other cast SCEVs. |
Dan Gohman | eed125f | 2007-06-18 19:30:09 +0000 | [diff] [blame] | 2146 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) |
| 2147 | ++Idx; |
| 2148 | |
| 2149 | // If there are add operands they would be next. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2150 | if (Idx < Ops.size()) { |
| 2151 | bool DeletedAdd = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2152 | while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2153 | // If we have an add, expand the add operands onto the end of the operands |
| 2154 | // list. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2155 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2156 | Ops.append(Add->op_begin(), Add->op_end()); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2157 | DeletedAdd = true; |
| 2158 | } |
| 2159 | |
| 2160 | // If we deleted at least one add, we added operands to the end of the list, |
| 2161 | // and they are not necessarily sorted. Recurse to resort and resimplify |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 2162 | // any operands we just acquired. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2163 | if (DeletedAdd) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2164 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2165 | } |
| 2166 | |
| 2167 | // Skip over the add expression until we get to a multiply. |
| 2168 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) |
| 2169 | ++Idx; |
| 2170 | |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2171 | // Check to see if there are any folding opportunities present with |
| 2172 | // operands multiplied by constant values. |
| 2173 | if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { |
| 2174 | uint64_t BitWidth = getTypeSizeInBits(Ty); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2175 | DenseMap<const SCEV *, APInt> M; |
| 2176 | SmallVector<const SCEV *, 8> NewOps; |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2177 | APInt AccumulatedConstant(BitWidth, 0); |
| 2178 | if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2179 | Ops.data(), Ops.size(), |
| 2180 | APInt(BitWidth, 1), *this)) { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 2181 | struct APIntCompare { |
| 2182 | bool operator()(const APInt &LHS, const APInt &RHS) const { |
| 2183 | return LHS.ult(RHS); |
| 2184 | } |
| 2185 | }; |
| 2186 | |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2187 | // Some interesting folding opportunity is present, so its worthwhile to |
| 2188 | // re-generate the operands list. Group the operands by constant scale, |
| 2189 | // to avoid multiplying by the same constant scale multiple times. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2190 | std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; |
Sanjoy Das | f25d25a | 2015-10-31 23:21:32 +0000 | [diff] [blame] | 2191 | for (const SCEV *NewOp : NewOps) |
| 2192 | MulOpLists[M.find(NewOp)->second].push_back(NewOp); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2193 | // Re-generate the operands list. |
| 2194 | Ops.clear(); |
| 2195 | if (AccumulatedConstant != 0) |
| 2196 | Ops.push_back(getConstant(AccumulatedConstant)); |
Sanjoy Das | f25d25a | 2015-10-31 23:21:32 +0000 | [diff] [blame] | 2197 | for (auto &MulOp : MulOpLists) |
| 2198 | if (MulOp.first != 0) |
| 2199 | Ops.push_back(getMulExpr(getConstant(MulOp.first), |
| 2200 | getAddExpr(MulOp.second))); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2201 | if (Ops.empty()) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2202 | return getZero(Ty); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2203 | if (Ops.size() == 1) |
| 2204 | return Ops[0]; |
| 2205 | return getAddExpr(Ops); |
| 2206 | } |
| 2207 | } |
| 2208 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2209 | // If we are adding something to a multiply expression, make sure the |
| 2210 | // something is not already an operand of the multiply. If so, merge it into |
| 2211 | // the multiply. |
| 2212 | for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2213 | const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2214 | for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2215 | const SCEV *MulOpSCEV = Mul->getOperand(MulOp); |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2216 | if (isa<SCEVConstant>(MulOpSCEV)) |
| 2217 | continue; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2218 | for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2219 | if (MulOpSCEV == Ops[AddOp]) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2220 | // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2221 | const SCEV *InnerMul = Mul->getOperand(MulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2222 | if (Mul->getNumOperands() != 2) { |
| 2223 | // If the multiply has more than two operands, we must get the |
| 2224 | // Y*Z term. |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2225 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), |
| 2226 | Mul->op_begin()+MulOp); |
| 2227 | MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2228 | InnerMul = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2229 | } |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2230 | const SCEV *One = getOne(Ty); |
Dan Gohman | cf32f2b | 2010-08-13 20:17:14 +0000 | [diff] [blame] | 2231 | const SCEV *AddOne = getAddExpr(One, InnerMul); |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2232 | const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2233 | if (Ops.size() == 2) return OuterMul; |
| 2234 | if (AddOp < Idx) { |
| 2235 | Ops.erase(Ops.begin()+AddOp); |
| 2236 | Ops.erase(Ops.begin()+Idx-1); |
| 2237 | } else { |
| 2238 | Ops.erase(Ops.begin()+Idx); |
| 2239 | Ops.erase(Ops.begin()+AddOp-1); |
| 2240 | } |
| 2241 | Ops.push_back(OuterMul); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2242 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2243 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2244 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2245 | // Check this multiply against other multiplies being added together. |
| 2246 | for (unsigned OtherMulIdx = Idx+1; |
| 2247 | OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); |
| 2248 | ++OtherMulIdx) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2249 | const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2250 | // If MulOp occurs in OtherMul, we can fold the two multiplies |
| 2251 | // together. |
| 2252 | for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); |
| 2253 | OMulOp != e; ++OMulOp) |
| 2254 | if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { |
| 2255 | // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2256 | const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2257 | if (Mul->getNumOperands() != 2) { |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2258 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2259 | Mul->op_begin()+MulOp); |
| 2260 | MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2261 | InnerMul1 = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2262 | } |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2263 | const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2264 | if (OtherMul->getNumOperands() != 2) { |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2265 | SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2266 | OtherMul->op_begin()+OMulOp); |
| 2267 | MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2268 | InnerMul2 = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2269 | } |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2270 | const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2); |
| 2271 | const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2272 | if (Ops.size() == 2) return OuterMul; |
Dan Gohman | aabfc52 | 2010-08-31 22:50:31 +0000 | [diff] [blame] | 2273 | Ops.erase(Ops.begin()+Idx); |
| 2274 | Ops.erase(Ops.begin()+OtherMulIdx-1); |
| 2275 | Ops.push_back(OuterMul); |
| 2276 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2277 | } |
| 2278 | } |
| 2279 | } |
| 2280 | } |
| 2281 | |
| 2282 | // If there are any add recurrences in the operands list, see if any other |
| 2283 | // added values are loop invariant. If so, we can fold them into the |
| 2284 | // recurrence. |
| 2285 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) |
| 2286 | ++Idx; |
| 2287 | |
| 2288 | // Scan over all recurrences, trying to fold loop invariants into them. |
| 2289 | for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { |
| 2290 | // Scan all of the other operands to this add and add them to the vector if |
| 2291 | // they are loop invariant w.r.t. the recurrence. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2292 | SmallVector<const SCEV *, 8> LIOps; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2293 | const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 2294 | const Loop *AddRecLoop = AddRec->getLoop(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2295 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2296 | if (isLoopInvariant(Ops[i], AddRecLoop)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2297 | LIOps.push_back(Ops[i]); |
| 2298 | Ops.erase(Ops.begin()+i); |
| 2299 | --i; --e; |
| 2300 | } |
| 2301 | |
| 2302 | // If we found some loop invariants, fold them into the recurrence. |
| 2303 | if (!LIOps.empty()) { |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 2304 | // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2305 | LIOps.push_back(AddRec->getStart()); |
| 2306 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2307 | SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), |
Dan Gohman | 7a2dab8 | 2009-12-18 03:57:04 +0000 | [diff] [blame] | 2308 | AddRec->op_end()); |
Oleg Ranevskyy | eb4ecca | 2016-05-25 13:01:33 +0000 | [diff] [blame^] | 2309 | // This follows from the fact that the no-wrap flags on the outer add |
| 2310 | // expression are applicable on the 0th iteration, when the add recurrence |
| 2311 | // will be equal to its start value. |
| 2312 | AddRecOps[0] = getAddExpr(LIOps, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2313 | |
Dan Gohman | 1620613 | 2010-06-30 07:16:37 +0000 | [diff] [blame] | 2314 | // Build the new addrec. Propagate the NUW and NSW flags if both the |
Eric Christopher | 23bf3ba | 2011-01-11 09:02:09 +0000 | [diff] [blame] | 2315 | // outer add and the inner addrec are guaranteed to have no overflow. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2316 | // Always propagate NW. |
| 2317 | Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2318 | const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); |
Dan Gohman | 51f1305 | 2009-12-18 18:45:31 +0000 | [diff] [blame] | 2319 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2320 | // If all of the other operands were loop invariant, we are done. |
| 2321 | if (Ops.size() == 1) return NewRec; |
| 2322 | |
Nick Lewycky | db66b82 | 2011-09-06 05:08:09 +0000 | [diff] [blame] | 2323 | // Otherwise, add the folded AddRec by the non-invariant parts. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2324 | for (unsigned i = 0;; ++i) |
| 2325 | if (Ops[i] == AddRec) { |
| 2326 | Ops[i] = NewRec; |
| 2327 | break; |
| 2328 | } |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2329 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2330 | } |
| 2331 | |
| 2332 | // Okay, if there weren't any loop invariants to be folded, check to see if |
| 2333 | // there are multiple AddRec's with the same loop induction variable being |
| 2334 | // added together. If so, we can fold them. |
| 2335 | for (unsigned OtherIdx = Idx+1; |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2336 | OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2337 | ++OtherIdx) |
| 2338 | if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { |
| 2339 | // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> |
| 2340 | SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), |
| 2341 | AddRec->op_end()); |
| 2342 | for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2343 | ++OtherIdx) |
Sanjoy Das | f25d25a | 2015-10-31 23:21:32 +0000 | [diff] [blame] | 2344 | if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2345 | if (OtherAddRec->getLoop() == AddRecLoop) { |
| 2346 | for (unsigned i = 0, e = OtherAddRec->getNumOperands(); |
| 2347 | i != e; ++i) { |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2348 | if (i >= AddRecOps.size()) { |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2349 | AddRecOps.append(OtherAddRec->op_begin()+i, |
| 2350 | OtherAddRec->op_end()); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2351 | break; |
| 2352 | } |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2353 | AddRecOps[i] = getAddExpr(AddRecOps[i], |
| 2354 | OtherAddRec->getOperand(i)); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2355 | } |
| 2356 | Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2357 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2358 | // Step size has changed, so we cannot guarantee no self-wraparound. |
| 2359 | Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2360 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2361 | } |
| 2362 | |
| 2363 | // Otherwise couldn't fold anything into this recurrence. Move onto the |
| 2364 | // next one. |
| 2365 | } |
| 2366 | |
| 2367 | // Okay, it looks like we really DO need an add expr. Check to see if we |
| 2368 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2369 | FoldingSetNodeID ID; |
| 2370 | ID.AddInteger(scAddExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2371 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 2372 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2373 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2374 | SCEVAddExpr *S = |
| 2375 | static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2376 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2377 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 2378 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2379 | S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator), |
| 2380 | O, Ops.size()); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2381 | UniqueSCEVs.InsertNode(S, IP); |
| 2382 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2383 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2384 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2385 | } |
| 2386 | |
Nick Lewycky | 287682e | 2011-10-04 06:51:26 +0000 | [diff] [blame] | 2387 | static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { |
| 2388 | uint64_t k = i*j; |
| 2389 | if (j > 1 && k / j != i) Overflow = true; |
| 2390 | return k; |
| 2391 | } |
| 2392 | |
| 2393 | /// Compute the result of "n choose k", the binomial coefficient. If an |
| 2394 | /// intermediate computation overflows, Overflow will be set and the return will |
Benjamin Kramer | bde9176 | 2012-06-02 10:20:22 +0000 | [diff] [blame] | 2395 | /// be garbage. Overflow is not cleared on absence of overflow. |
Nick Lewycky | 287682e | 2011-10-04 06:51:26 +0000 | [diff] [blame] | 2396 | static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { |
| 2397 | // We use the multiplicative formula: |
| 2398 | // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . |
| 2399 | // At each iteration, we take the n-th term of the numeral and divide by the |
| 2400 | // (k-n)th term of the denominator. This division will always produce an |
| 2401 | // integral result, and helps reduce the chance of overflow in the |
| 2402 | // intermediate computations. However, we can still overflow even when the |
| 2403 | // final result would fit. |
| 2404 | |
| 2405 | if (n == 0 || n == k) return 1; |
| 2406 | if (k > n) return 0; |
| 2407 | |
| 2408 | if (k > n/2) |
| 2409 | k = n-k; |
| 2410 | |
| 2411 | uint64_t r = 1; |
| 2412 | for (uint64_t i = 1; i <= k; ++i) { |
| 2413 | r = umul_ov(r, n-(i-1), Overflow); |
| 2414 | r /= i; |
| 2415 | } |
| 2416 | return r; |
| 2417 | } |
| 2418 | |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2419 | /// Determine if any of the operands in this SCEV are a constant or if |
| 2420 | /// any of the add or multiply expressions in this SCEV contain a constant. |
| 2421 | static bool containsConstantSomewhere(const SCEV *StartExpr) { |
| 2422 | SmallVector<const SCEV *, 4> Ops; |
| 2423 | Ops.push_back(StartExpr); |
| 2424 | while (!Ops.empty()) { |
| 2425 | const SCEV *CurrentExpr = Ops.pop_back_val(); |
| 2426 | if (isa<SCEVConstant>(*CurrentExpr)) |
| 2427 | return true; |
| 2428 | |
| 2429 | if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { |
| 2430 | const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); |
Benjamin Kramer | 6cd780f | 2015-02-17 15:29:18 +0000 | [diff] [blame] | 2431 | Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2432 | } |
| 2433 | } |
| 2434 | return false; |
| 2435 | } |
| 2436 | |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 2437 | /// getMulExpr - Get a canonical multiply expression, or something simpler if |
| 2438 | /// possible. |
Dan Gohman | 816fe0a | 2009-10-09 00:10:36 +0000 | [diff] [blame] | 2439 | const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2440 | SCEV::NoWrapFlags Flags) { |
| 2441 | assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && |
| 2442 | "only nuw or nsw allowed"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2443 | assert(!Ops.empty() && "Cannot get empty mul!"); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2444 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2445 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2446 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2447 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 2448 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2449 | "SCEVMulExpr operand types don't match!"); |
| 2450 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2451 | |
| 2452 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2453 | GroupByComplexity(Ops, &LI); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2454 | |
Sanjoy Das | 6489561 | 2015-10-09 02:44:45 +0000 | [diff] [blame] | 2455 | Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); |
| 2456 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2457 | // If there are any constants, fold them together. |
| 2458 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2459 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2460 | |
| 2461 | // C1*(C2+V) -> C1*C2 + C1*V |
| 2462 | if (Ops.size() == 2) |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2463 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) |
| 2464 | // If any of Add's ops are Adds or Muls with a constant, |
| 2465 | // apply this transformation as well. |
| 2466 | if (Add->getNumOperands() == 2) |
| 2467 | if (containsConstantSomewhere(Add)) |
| 2468 | return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), |
| 2469 | getMulExpr(LHSC, Add->getOperand(1))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2470 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2471 | ++Idx; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2472 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2473 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2474 | ConstantInt *Fold = |
| 2475 | ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2476 | Ops[0] = getConstant(Fold); |
| 2477 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 2478 | if (Ops.size() == 1) return Ops[0]; |
| 2479 | LHSC = cast<SCEVConstant>(Ops[0]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2480 | } |
| 2481 | |
| 2482 | // If we are left with a constant one being multiplied, strip it off. |
| 2483 | if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { |
| 2484 | Ops.erase(Ops.begin()); |
| 2485 | --Idx; |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 2486 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2487 | // If we have a multiply of zero, it will always be zero. |
| 2488 | return Ops[0]; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2489 | } else if (Ops[0]->isAllOnesValue()) { |
| 2490 | // If we have a mul by -1 of an add, try distributing the -1 among the |
| 2491 | // add operands. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2492 | if (Ops.size() == 2) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2493 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { |
| 2494 | SmallVector<const SCEV *, 4> NewOps; |
| 2495 | bool AnyFolded = false; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 2496 | for (const SCEV *AddOp : Add->operands()) { |
| 2497 | const SCEV *Mul = getMulExpr(Ops[0], AddOp); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2498 | if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; |
| 2499 | NewOps.push_back(Mul); |
| 2500 | } |
| 2501 | if (AnyFolded) |
| 2502 | return getAddExpr(NewOps); |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 2503 | } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { |
Andrew Trick | e92dcce | 2011-03-14 17:38:54 +0000 | [diff] [blame] | 2504 | // Negation preserves a recurrence's no self-wrap property. |
| 2505 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 2506 | for (const SCEV *AddRecOp : AddRec->operands()) |
| 2507 | Operands.push_back(getMulExpr(Ops[0], AddRecOp)); |
| 2508 | |
Andrew Trick | e92dcce | 2011-03-14 17:38:54 +0000 | [diff] [blame] | 2509 | return getAddRecExpr(Operands, AddRec->getLoop(), |
| 2510 | AddRec->getNoWrapFlags(SCEV::FlagNW)); |
| 2511 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2512 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2513 | } |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 2514 | |
| 2515 | if (Ops.size() == 1) |
| 2516 | return Ops[0]; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2517 | } |
| 2518 | |
| 2519 | // Skip over the add expression until we get to a multiply. |
| 2520 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) |
| 2521 | ++Idx; |
| 2522 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2523 | // If there are mul operands inline them all into this expression. |
| 2524 | if (Idx < Ops.size()) { |
| 2525 | bool DeletedMul = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2526 | while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2527 | // If we have an mul, expand the mul operands onto the end of the operands |
| 2528 | // list. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2529 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2530 | Ops.append(Mul->op_begin(), Mul->op_end()); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2531 | DeletedMul = true; |
| 2532 | } |
| 2533 | |
| 2534 | // If we deleted at least one mul, we added operands to the end of the list, |
| 2535 | // and they are not necessarily sorted. Recurse to resort and resimplify |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 2536 | // any operands we just acquired. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2537 | if (DeletedMul) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2538 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2539 | } |
| 2540 | |
| 2541 | // If there are any add recurrences in the operands list, see if any other |
| 2542 | // added values are loop invariant. If so, we can fold them into the |
| 2543 | // recurrence. |
| 2544 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) |
| 2545 | ++Idx; |
| 2546 | |
| 2547 | // Scan over all recurrences, trying to fold loop invariants into them. |
| 2548 | for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { |
| 2549 | // Scan all of the other operands to this mul and add them to the vector if |
| 2550 | // they are loop invariant w.r.t. the recurrence. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2551 | SmallVector<const SCEV *, 8> LIOps; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2552 | const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); |
Dan Gohman | 0f2de01 | 2010-08-29 14:55:19 +0000 | [diff] [blame] | 2553 | const Loop *AddRecLoop = AddRec->getLoop(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2554 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2555 | if (isLoopInvariant(Ops[i], AddRecLoop)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2556 | LIOps.push_back(Ops[i]); |
| 2557 | Ops.erase(Ops.begin()+i); |
| 2558 | --i; --e; |
| 2559 | } |
| 2560 | |
| 2561 | // If we found some loop invariants, fold them into the recurrence. |
| 2562 | if (!LIOps.empty()) { |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 2563 | // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2564 | SmallVector<const SCEV *, 4> NewOps; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2565 | NewOps.reserve(AddRec->getNumOperands()); |
Dan Gohman | 8f5954f | 2010-06-17 23:34:09 +0000 | [diff] [blame] | 2566 | const SCEV *Scale = getMulExpr(LIOps); |
| 2567 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) |
| 2568 | NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2569 | |
Dan Gohman | 1620613 | 2010-06-30 07:16:37 +0000 | [diff] [blame] | 2570 | // Build the new addrec. Propagate the NUW and NSW flags if both the |
| 2571 | // outer mul and the inner addrec are guaranteed to have no overflow. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2572 | // |
| 2573 | // No self-wrap cannot be guaranteed after changing the step size, but |
Chris Lattner | 0ab5e2c | 2011-04-15 05:18:47 +0000 | [diff] [blame] | 2574 | // will be inferred if either NUW or NSW is true. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2575 | Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); |
| 2576 | const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2577 | |
| 2578 | // If all of the other operands were loop invariant, we are done. |
| 2579 | if (Ops.size() == 1) return NewRec; |
| 2580 | |
Nick Lewycky | db66b82 | 2011-09-06 05:08:09 +0000 | [diff] [blame] | 2581 | // Otherwise, multiply the folded AddRec by the non-invariant parts. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2582 | for (unsigned i = 0;; ++i) |
| 2583 | if (Ops[i] == AddRec) { |
| 2584 | Ops[i] = NewRec; |
| 2585 | break; |
| 2586 | } |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2587 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2588 | } |
| 2589 | |
| 2590 | // Okay, if there weren't any loop invariants to be folded, check to see if |
| 2591 | // there are multiple AddRec's with the same loop induction variable being |
| 2592 | // multiplied together. If so, we can fold them. |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2593 | |
| 2594 | // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> |
| 2595 | // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ |
| 2596 | // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z |
| 2597 | // ]]],+,...up to x=2n}. |
| 2598 | // Note that the arguments to choose() are always integers with values |
| 2599 | // known at compile time, never SCEV objects. |
| 2600 | // |
| 2601 | // The implementation avoids pointless extra computations when the two |
| 2602 | // addrec's are of different length (mathematically, it's equivalent to |
| 2603 | // an infinite stream of zeros on the right). |
| 2604 | bool OpsModified = false; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2605 | for (unsigned OtherIdx = Idx+1; |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2606 | OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
Nick Lewycky | e0aa54b | 2011-09-06 21:42:18 +0000 | [diff] [blame] | 2607 | ++OtherIdx) { |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2608 | const SCEVAddRecExpr *OtherAddRec = |
| 2609 | dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2610 | if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2611 | continue; |
| 2612 | |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2613 | bool Overflow = false; |
| 2614 | Type *Ty = AddRec->getType(); |
| 2615 | bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; |
| 2616 | SmallVector<const SCEV*, 7> AddRecOps; |
| 2617 | for (int x = 0, xe = AddRec->getNumOperands() + |
| 2618 | OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2619 | const SCEV *Term = getZero(Ty); |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2620 | for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { |
| 2621 | uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); |
| 2622 | for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), |
| 2623 | ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); |
| 2624 | z < ze && !Overflow; ++z) { |
| 2625 | uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); |
| 2626 | uint64_t Coeff; |
| 2627 | if (LargerThan64Bits) |
| 2628 | Coeff = umul_ov(Coeff1, Coeff2, Overflow); |
| 2629 | else |
| 2630 | Coeff = Coeff1*Coeff2; |
| 2631 | const SCEV *CoeffTerm = getConstant(Ty, Coeff); |
| 2632 | const SCEV *Term1 = AddRec->getOperand(y-z); |
| 2633 | const SCEV *Term2 = OtherAddRec->getOperand(z); |
| 2634 | Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2635 | } |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2636 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2637 | AddRecOps.push_back(Term); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2638 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2639 | if (!Overflow) { |
| 2640 | const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), |
| 2641 | SCEV::FlagAnyWrap); |
| 2642 | if (Ops.size() == 2) return NewAddRec; |
| 2643 | Ops[Idx] = NewAddRec; |
| 2644 | Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; |
| 2645 | OpsModified = true; |
| 2646 | AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); |
| 2647 | if (!AddRec) |
| 2648 | break; |
| 2649 | } |
Nick Lewycky | e0aa54b | 2011-09-06 21:42:18 +0000 | [diff] [blame] | 2650 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2651 | if (OpsModified) |
| 2652 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2653 | |
| 2654 | // Otherwise couldn't fold anything into this recurrence. Move onto the |
| 2655 | // next one. |
| 2656 | } |
| 2657 | |
| 2658 | // Okay, it looks like we really DO need an mul expr. Check to see if we |
| 2659 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2660 | FoldingSetNodeID ID; |
| 2661 | ID.AddInteger(scMulExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2662 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 2663 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2664 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2665 | SCEVMulExpr *S = |
| 2666 | static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2667 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2668 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 2669 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2670 | S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), |
| 2671 | O, Ops.size()); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2672 | UniqueSCEVs.InsertNode(S, IP); |
| 2673 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2674 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2675 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2676 | } |
| 2677 | |
Andreas Bolka | 7a5c8db | 2009-08-07 22:55:26 +0000 | [diff] [blame] | 2678 | /// getUDivExpr - Get a canonical unsigned division expression, or something |
| 2679 | /// simpler if possible. |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 2680 | const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, |
| 2681 | const SCEV *RHS) { |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2682 | assert(getEffectiveSCEVType(LHS->getType()) == |
| 2683 | getEffectiveSCEVType(RHS->getType()) && |
| 2684 | "SCEVUDivExpr operand types don't match!"); |
| 2685 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2686 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2687 | if (RHSC->getValue()->equalsInt(1)) |
Dan Gohman | 8a8ad7d | 2009-08-20 16:42:55 +0000 | [diff] [blame] | 2688 | return LHS; // X udiv 1 --> x |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2689 | // If the denominator is zero, the result of the udiv is undefined. Don't |
| 2690 | // try to analyze it, because the resolution chosen here may differ from |
| 2691 | // the resolution chosen in other parts of the compiler. |
| 2692 | if (!RHSC->getValue()->isZero()) { |
| 2693 | // Determine if the division can be folded into the operands of |
| 2694 | // its operands. |
| 2695 | // TODO: Generalize this to non-constants by using known-bits information. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2696 | Type *Ty = LHS->getType(); |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2697 | unsigned LZ = RHSC->getAPInt().countLeadingZeros(); |
Dan Gohman | db764c6 | 2010-08-04 19:52:50 +0000 | [diff] [blame] | 2698 | unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2699 | // For non-power-of-two values, effectively round the value up to the |
| 2700 | // nearest power of two. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2701 | if (!RHSC->getAPInt().isPowerOf2()) |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2702 | ++MaxShiftAmt; |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2703 | IntegerType *ExtTy = |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2704 | IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2705 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) |
| 2706 | if (const SCEVConstant *Step = |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2707 | dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { |
| 2708 | // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2709 | const APInt &StepInt = Step->getAPInt(); |
| 2710 | const APInt &DivInt = RHSC->getAPInt(); |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2711 | if (!StepInt.urem(DivInt) && |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2712 | getZeroExtendExpr(AR, ExtTy) == |
| 2713 | getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), |
| 2714 | getZeroExtendExpr(Step, ExtTy), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2715 | AR->getLoop(), SCEV::FlagAnyWrap)) { |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2716 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 2717 | for (const SCEV *Op : AR->operands()) |
| 2718 | Operands.push_back(getUDivExpr(Op, RHS)); |
| 2719 | return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2720 | } |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2721 | /// Get a canonical UDivExpr for a recurrence. |
| 2722 | /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. |
| 2723 | // We can currently only fold X%N if X is constant. |
| 2724 | const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); |
| 2725 | if (StartC && !DivInt.urem(StepInt) && |
| 2726 | getZeroExtendExpr(AR, ExtTy) == |
| 2727 | getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), |
| 2728 | getZeroExtendExpr(Step, ExtTy), |
| 2729 | AR->getLoop(), SCEV::FlagAnyWrap)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2730 | const APInt &StartInt = StartC->getAPInt(); |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2731 | const APInt &StartRem = StartInt.urem(StepInt); |
| 2732 | if (StartRem != 0) |
| 2733 | LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, |
| 2734 | AR->getLoop(), SCEV::FlagNW); |
| 2735 | } |
| 2736 | } |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2737 | // (A*B)/C --> A*(B/C) if safe and B/C can be folded. |
| 2738 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { |
| 2739 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 2740 | for (const SCEV *Op : M->operands()) |
| 2741 | Operands.push_back(getZeroExtendExpr(Op, ExtTy)); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2742 | if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) |
| 2743 | // Find an operand that's safely divisible. |
| 2744 | for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { |
| 2745 | const SCEV *Op = M->getOperand(i); |
| 2746 | const SCEV *Div = getUDivExpr(Op, RHSC); |
| 2747 | if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { |
| 2748 | Operands = SmallVector<const SCEV *, 4>(M->op_begin(), |
| 2749 | M->op_end()); |
| 2750 | Operands[i] = Div; |
| 2751 | return getMulExpr(Operands); |
| 2752 | } |
| 2753 | } |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2754 | } |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2755 | // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. |
Andrew Trick | 7d1eea8 | 2011-04-27 18:17:36 +0000 | [diff] [blame] | 2756 | if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2757 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 2758 | for (const SCEV *Op : A->operands()) |
| 2759 | Operands.push_back(getZeroExtendExpr(Op, ExtTy)); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2760 | if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { |
| 2761 | Operands.clear(); |
| 2762 | for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { |
| 2763 | const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); |
| 2764 | if (isa<SCEVUDivExpr>(Op) || |
| 2765 | getMulExpr(Op, RHS) != A->getOperand(i)) |
| 2766 | break; |
| 2767 | Operands.push_back(Op); |
| 2768 | } |
| 2769 | if (Operands.size() == A->getNumOperands()) |
| 2770 | return getAddExpr(Operands); |
| 2771 | } |
| 2772 | } |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2773 | |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2774 | // Fold if both operands are constant. |
| 2775 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { |
| 2776 | Constant *LHSCV = LHSC->getValue(); |
| 2777 | Constant *RHSCV = RHSC->getValue(); |
| 2778 | return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, |
| 2779 | RHSCV))); |
| 2780 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2781 | } |
| 2782 | } |
| 2783 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2784 | FoldingSetNodeID ID; |
| 2785 | ID.AddInteger(scUDivExpr); |
| 2786 | ID.AddPointer(LHS); |
| 2787 | ID.AddPointer(RHS); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2788 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2789 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2790 | SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), |
| 2791 | LHS, RHS); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2792 | UniqueSCEVs.InsertNode(S, IP); |
| 2793 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2794 | } |
| 2795 | |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2796 | static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2797 | APInt A = C1->getAPInt().abs(); |
| 2798 | APInt B = C2->getAPInt().abs(); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2799 | uint32_t ABW = A.getBitWidth(); |
| 2800 | uint32_t BBW = B.getBitWidth(); |
| 2801 | |
| 2802 | if (ABW > BBW) |
| 2803 | B = B.zext(ABW); |
| 2804 | else if (ABW < BBW) |
| 2805 | A = A.zext(BBW); |
| 2806 | |
| 2807 | return APIntOps::GreatestCommonDivisor(A, B); |
| 2808 | } |
| 2809 | |
| 2810 | /// getUDivExactExpr - Get a canonical unsigned division expression, or |
| 2811 | /// something simpler if possible. There is no representation for an exact udiv |
| 2812 | /// in SCEV IR, but we can attempt to remove factors from the LHS and RHS. |
| 2813 | /// We can't do this when it's not exact because the udiv may be clearing bits. |
| 2814 | const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, |
| 2815 | const SCEV *RHS) { |
| 2816 | // TODO: we could try to find factors in all sorts of things, but for now we |
| 2817 | // just deal with u/exact (multiply, constant). See SCEVDivision towards the |
| 2818 | // end of this file for inspiration. |
| 2819 | |
| 2820 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); |
| 2821 | if (!Mul) |
| 2822 | return getUDivExpr(LHS, RHS); |
| 2823 | |
| 2824 | if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { |
| 2825 | // If the mulexpr multiplies by a constant, then that constant must be the |
| 2826 | // first element of the mulexpr. |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 2827 | if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2828 | if (LHSCst == RHSCst) { |
| 2829 | SmallVector<const SCEV *, 2> Operands; |
| 2830 | Operands.append(Mul->op_begin() + 1, Mul->op_end()); |
| 2831 | return getMulExpr(Operands); |
| 2832 | } |
| 2833 | |
| 2834 | // We can't just assume that LHSCst divides RHSCst cleanly, it could be |
| 2835 | // that there's a factor provided by one of the other terms. We need to |
| 2836 | // check. |
| 2837 | APInt Factor = gcd(LHSCst, RHSCst); |
| 2838 | if (!Factor.isIntN(1)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2839 | LHSCst = |
| 2840 | cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); |
| 2841 | RHSCst = |
| 2842 | cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2843 | SmallVector<const SCEV *, 2> Operands; |
| 2844 | Operands.push_back(LHSCst); |
| 2845 | Operands.append(Mul->op_begin() + 1, Mul->op_end()); |
| 2846 | LHS = getMulExpr(Operands); |
| 2847 | RHS = RHSCst; |
Nick Lewycky | 629199c | 2014-01-27 10:47:44 +0000 | [diff] [blame] | 2848 | Mul = dyn_cast<SCEVMulExpr>(LHS); |
| 2849 | if (!Mul) |
| 2850 | return getUDivExactExpr(LHS, RHS); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2851 | } |
| 2852 | } |
| 2853 | } |
| 2854 | |
| 2855 | for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { |
| 2856 | if (Mul->getOperand(i) == RHS) { |
| 2857 | SmallVector<const SCEV *, 2> Operands; |
| 2858 | Operands.append(Mul->op_begin(), Mul->op_begin() + i); |
| 2859 | Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); |
| 2860 | return getMulExpr(Operands); |
| 2861 | } |
| 2862 | } |
| 2863 | |
| 2864 | return getUDivExpr(LHS, RHS); |
| 2865 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2866 | |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 2867 | /// getAddRecExpr - Get an add recurrence expression for the specified loop. |
| 2868 | /// Simplify the expression as much as possible. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2869 | const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, |
| 2870 | const Loop *L, |
| 2871 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2872 | SmallVector<const SCEV *, 4> Operands; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2873 | Operands.push_back(Start); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2874 | if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2875 | if (StepChrec->getLoop() == L) { |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2876 | Operands.append(StepChrec->op_begin(), StepChrec->op_end()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2877 | return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2878 | } |
| 2879 | |
| 2880 | Operands.push_back(Step); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2881 | return getAddRecExpr(Operands, L, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2882 | } |
| 2883 | |
Dan Gohman | 4d5435d | 2009-05-24 23:45:28 +0000 | [diff] [blame] | 2884 | /// getAddRecExpr - Get an add recurrence expression for the specified loop. |
| 2885 | /// Simplify the expression as much as possible. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2886 | const SCEV * |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2887 | ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2888 | const Loop *L, SCEV::NoWrapFlags Flags) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2889 | if (Operands.size() == 1) return Operands[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2890 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2891 | Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2892 | for (unsigned i = 1, e = Operands.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 2893 | assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2894 | "SCEVAddRecExpr operand types don't match!"); |
Dan Gohman | d3a32ae | 2010-11-17 20:48:38 +0000 | [diff] [blame] | 2895 | for (unsigned i = 0, e = Operands.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2896 | assert(isLoopInvariant(Operands[i], L) && |
Dan Gohman | d3a32ae | 2010-11-17 20:48:38 +0000 | [diff] [blame] | 2897 | "SCEVAddRecExpr operand is not loop-invariant!"); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2898 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2899 | |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 2900 | if (Operands.back()->isZero()) { |
| 2901 | Operands.pop_back(); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2902 | return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 2903 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2904 | |
Dan Gohman | cf9c64e | 2010-02-19 18:49:22 +0000 | [diff] [blame] | 2905 | // It's tempting to want to call getMaxBackedgeTakenCount count here and |
| 2906 | // use that information to infer NUW and NSW flags. However, computing a |
| 2907 | // BE count requires calling getAddRecExpr, so we may not yet have a |
| 2908 | // meaningful BE count at this point (and if we don't, we'd be stuck |
| 2909 | // with a SCEVCouldNotCompute as the cached BE count). |
| 2910 | |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2911 | Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2912 | |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2913 | // Canonicalize nested AddRecs in by nesting them in order of loop depth. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2914 | if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 2915 | const Loop *NestedLoop = NestedAR->getLoop(); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2916 | if (L->contains(NestedLoop) |
| 2917 | ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) |
| 2918 | : (!NestedLoop->contains(L) && |
| 2919 | DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2920 | SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 2921 | NestedAR->op_end()); |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2922 | Operands[0] = NestedAR->getStart(); |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2923 | // AddRecs require their operands be loop-invariant with respect to their |
| 2924 | // loops. Don't perform this transformation if it would break this |
| 2925 | // requirement. |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 2926 | bool AllInvariant = all_of( |
| 2927 | Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); |
Sanjoy Das | f07d2a7 | 2015-10-18 00:29:23 +0000 | [diff] [blame] | 2928 | |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2929 | if (AllInvariant) { |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2930 | // Create a recurrence for the outer loop with the same step size. |
| 2931 | // |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2932 | // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the |
| 2933 | // inner recurrence has the same property. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2934 | SCEV::NoWrapFlags OuterFlags = |
| 2935 | maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2936 | |
| 2937 | NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 2938 | AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { |
| 2939 | return isLoopInvariant(Op, NestedLoop); |
| 2940 | }); |
Sanjoy Das | f07d2a7 | 2015-10-18 00:29:23 +0000 | [diff] [blame] | 2941 | |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2942 | if (AllInvariant) { |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2943 | // Ok, both add recurrences are valid after the transformation. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2944 | // |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2945 | // The inner recurrence keeps its NW flag but only keeps NUW/NSW if |
| 2946 | // the outer recurrence has the same property. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2947 | SCEV::NoWrapFlags InnerFlags = |
| 2948 | maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2949 | return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); |
| 2950 | } |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2951 | } |
| 2952 | // Reset Operands to its original state. |
| 2953 | Operands[0] = NestedAR; |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2954 | } |
| 2955 | } |
| 2956 | |
Dan Gohman | 8d67d2f | 2010-01-19 22:27:22 +0000 | [diff] [blame] | 2957 | // Okay, it looks like we really DO need an addrec expr. Check to see if we |
| 2958 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2959 | FoldingSetNodeID ID; |
| 2960 | ID.AddInteger(scAddRecExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2961 | for (unsigned i = 0, e = Operands.size(); i != e; ++i) |
| 2962 | ID.AddPointer(Operands[i]); |
| 2963 | ID.AddPointer(L); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2964 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2965 | SCEVAddRecExpr *S = |
| 2966 | static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2967 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2968 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); |
| 2969 | std::uninitialized_copy(Operands.begin(), Operands.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2970 | S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), |
| 2971 | O, Operands.size(), L); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2972 | UniqueSCEVs.InsertNode(S, IP); |
| 2973 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2974 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2975 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2976 | } |
| 2977 | |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 2978 | const SCEV * |
| 2979 | ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr, |
| 2980 | const SmallVectorImpl<const SCEV *> &IndexExprs, |
| 2981 | bool InBounds) { |
| 2982 | // getSCEV(Base)->getType() has the same address space as Base->getType() |
| 2983 | // because SCEV::getType() preserves the address space. |
| 2984 | Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); |
| 2985 | // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP |
| 2986 | // instruction to its SCEV, because the Instruction may be guarded by control |
| 2987 | // flow and the no-overflow bits may not be valid for the expression in any |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 2988 | // context. This can be fixed similarly to how these flags are handled for |
| 2989 | // adds. |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 2990 | SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap; |
| 2991 | |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2992 | const SCEV *TotalOffset = getZero(IntPtrTy); |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 2993 | // The address space is unimportant. The first thing we do on CurTy is getting |
| 2994 | // its element type. |
| 2995 | Type *CurTy = PointerType::getUnqual(PointeeType); |
| 2996 | for (const SCEV *IndexExpr : IndexExprs) { |
| 2997 | // Compute the (potentially symbolic) offset in bytes for this index. |
| 2998 | if (StructType *STy = dyn_cast<StructType>(CurTy)) { |
| 2999 | // For a struct, add the member offset. |
| 3000 | ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); |
| 3001 | unsigned FieldNo = Index->getZExtValue(); |
| 3002 | const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); |
| 3003 | |
| 3004 | // Add the field offset to the running total offset. |
| 3005 | TotalOffset = getAddExpr(TotalOffset, FieldOffset); |
| 3006 | |
| 3007 | // Update CurTy to the type of the field at Index. |
| 3008 | CurTy = STy->getTypeAtIndex(Index); |
| 3009 | } else { |
| 3010 | // Update CurTy to its element type. |
| 3011 | CurTy = cast<SequentialType>(CurTy)->getElementType(); |
| 3012 | // For an array, add the element offset, explicitly scaled. |
| 3013 | const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); |
| 3014 | // Getelementptr indices are signed. |
| 3015 | IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); |
| 3016 | |
| 3017 | // Multiply the index by the element size to compute the element offset. |
| 3018 | const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); |
| 3019 | |
| 3020 | // Add the element offset to the running total offset. |
| 3021 | TotalOffset = getAddExpr(TotalOffset, LocalOffset); |
| 3022 | } |
| 3023 | } |
| 3024 | |
| 3025 | // Add the total offset from all the GEP indices to the base. |
| 3026 | return getAddExpr(BaseExpr, TotalOffset, Wrap); |
| 3027 | } |
| 3028 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3029 | const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, |
| 3030 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3031 | SmallVector<const SCEV *, 2> Ops; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3032 | Ops.push_back(LHS); |
| 3033 | Ops.push_back(RHS); |
| 3034 | return getSMaxExpr(Ops); |
| 3035 | } |
| 3036 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3037 | const SCEV * |
| 3038 | ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3039 | assert(!Ops.empty() && "Cannot get empty smax!"); |
| 3040 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3041 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3042 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3043 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 3044 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3045 | "SCEVSMaxExpr operand types don't match!"); |
| 3046 | #endif |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3047 | |
| 3048 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3049 | GroupByComplexity(Ops, &LI); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3050 | |
| 3051 | // If there are any constants, fold them together. |
| 3052 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3053 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3054 | ++Idx; |
| 3055 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3056 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3057 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 3058 | ConstantInt *Fold = ConstantInt::get( |
| 3059 | getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3060 | Ops[0] = getConstant(Fold); |
| 3061 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 3062 | if (Ops.size() == 1) return Ops[0]; |
| 3063 | LHSC = cast<SCEVConstant>(Ops[0]); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3064 | } |
| 3065 | |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3066 | // If we are left with a constant minimum-int, strip it off. |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3067 | if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { |
| 3068 | Ops.erase(Ops.begin()); |
| 3069 | --Idx; |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3070 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { |
| 3071 | // If we have an smax with a constant maximum-int, it will always be |
| 3072 | // maximum-int. |
| 3073 | return Ops[0]; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3074 | } |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3075 | |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 3076 | if (Ops.size() == 1) return Ops[0]; |
| 3077 | } |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3078 | |
| 3079 | // Find the first SMax |
| 3080 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) |
| 3081 | ++Idx; |
| 3082 | |
| 3083 | // Check to see if one of the operands is an SMax. If so, expand its operands |
| 3084 | // onto our operand list, and recurse to simplify. |
| 3085 | if (Idx < Ops.size()) { |
| 3086 | bool DeletedSMax = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3087 | while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3088 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 3089 | Ops.append(SMax->op_begin(), SMax->op_end()); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3090 | DeletedSMax = true; |
| 3091 | } |
| 3092 | |
| 3093 | if (DeletedSMax) |
| 3094 | return getSMaxExpr(Ops); |
| 3095 | } |
| 3096 | |
| 3097 | // Okay, check to see if the same value occurs in the operand list twice. If |
| 3098 | // so, delete one. Since we sorted the list, these values are required to |
| 3099 | // be adjacent. |
| 3100 | for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) |
Dan Gohman | 7ef0dc2 | 2010-04-13 16:51:03 +0000 | [diff] [blame] | 3101 | // X smax Y smax Y --> X smax Y |
| 3102 | // X smax Y --> X, if X is always greater than Y |
| 3103 | if (Ops[i] == Ops[i+1] || |
| 3104 | isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { |
| 3105 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); |
| 3106 | --i; --e; |
| 3107 | } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3108 | Ops.erase(Ops.begin()+i, Ops.begin()+i+1); |
| 3109 | --i; --e; |
| 3110 | } |
| 3111 | |
| 3112 | if (Ops.size() == 1) return Ops[0]; |
| 3113 | |
| 3114 | assert(!Ops.empty() && "Reduced smax down to nothing!"); |
| 3115 | |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3116 | // Okay, it looks like we really DO need an smax expr. Check to see if we |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3117 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3118 | FoldingSetNodeID ID; |
| 3119 | ID.AddInteger(scSMaxExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3120 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 3121 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3122 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3123 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 3124 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 3125 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 3126 | SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), |
| 3127 | O, Ops.size()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3128 | UniqueSCEVs.InsertNode(S, IP); |
| 3129 | return S; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3130 | } |
| 3131 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3132 | const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, |
| 3133 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3134 | SmallVector<const SCEV *, 2> Ops; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3135 | Ops.push_back(LHS); |
| 3136 | Ops.push_back(RHS); |
| 3137 | return getUMaxExpr(Ops); |
| 3138 | } |
| 3139 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3140 | const SCEV * |
| 3141 | ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3142 | assert(!Ops.empty() && "Cannot get empty umax!"); |
| 3143 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3144 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3145 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3146 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 3147 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3148 | "SCEVUMaxExpr operand types don't match!"); |
| 3149 | #endif |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3150 | |
| 3151 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3152 | GroupByComplexity(Ops, &LI); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3153 | |
| 3154 | // If there are any constants, fold them together. |
| 3155 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3156 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3157 | ++Idx; |
| 3158 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3159 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3160 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 3161 | ConstantInt *Fold = ConstantInt::get( |
| 3162 | getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3163 | Ops[0] = getConstant(Fold); |
| 3164 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 3165 | if (Ops.size() == 1) return Ops[0]; |
| 3166 | LHSC = cast<SCEVConstant>(Ops[0]); |
| 3167 | } |
| 3168 | |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3169 | // If we are left with a constant minimum-int, strip it off. |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3170 | if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { |
| 3171 | Ops.erase(Ops.begin()); |
| 3172 | --Idx; |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3173 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { |
| 3174 | // If we have an umax with a constant maximum-int, it will always be |
| 3175 | // maximum-int. |
| 3176 | return Ops[0]; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3177 | } |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3178 | |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 3179 | if (Ops.size() == 1) return Ops[0]; |
| 3180 | } |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3181 | |
| 3182 | // Find the first UMax |
| 3183 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) |
| 3184 | ++Idx; |
| 3185 | |
| 3186 | // Check to see if one of the operands is a UMax. If so, expand its operands |
| 3187 | // onto our operand list, and recurse to simplify. |
| 3188 | if (Idx < Ops.size()) { |
| 3189 | bool DeletedUMax = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3190 | while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3191 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 3192 | Ops.append(UMax->op_begin(), UMax->op_end()); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3193 | DeletedUMax = true; |
| 3194 | } |
| 3195 | |
| 3196 | if (DeletedUMax) |
| 3197 | return getUMaxExpr(Ops); |
| 3198 | } |
| 3199 | |
| 3200 | // Okay, check to see if the same value occurs in the operand list twice. If |
| 3201 | // so, delete one. Since we sorted the list, these values are required to |
| 3202 | // be adjacent. |
| 3203 | for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) |
Dan Gohman | 7ef0dc2 | 2010-04-13 16:51:03 +0000 | [diff] [blame] | 3204 | // X umax Y umax Y --> X umax Y |
| 3205 | // X umax Y --> X, if X is always greater than Y |
| 3206 | if (Ops[i] == Ops[i+1] || |
| 3207 | isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { |
| 3208 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); |
| 3209 | --i; --e; |
| 3210 | } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3211 | Ops.erase(Ops.begin()+i, Ops.begin()+i+1); |
| 3212 | --i; --e; |
| 3213 | } |
| 3214 | |
| 3215 | if (Ops.size() == 1) return Ops[0]; |
| 3216 | |
| 3217 | assert(!Ops.empty() && "Reduced umax down to nothing!"); |
| 3218 | |
| 3219 | // Okay, it looks like we really DO need a umax expr. Check to see if we |
| 3220 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3221 | FoldingSetNodeID ID; |
| 3222 | ID.AddInteger(scUMaxExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3223 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 3224 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3225 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3226 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 3227 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 3228 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 3229 | SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), |
| 3230 | O, Ops.size()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3231 | UniqueSCEVs.InsertNode(S, IP); |
| 3232 | return S; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3233 | } |
| 3234 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3235 | const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, |
| 3236 | const SCEV *RHS) { |
Dan Gohman | 692b468 | 2009-06-22 03:18:45 +0000 | [diff] [blame] | 3237 | // ~smax(~x, ~y) == smin(x, y). |
| 3238 | return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); |
| 3239 | } |
| 3240 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3241 | const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, |
| 3242 | const SCEV *RHS) { |
Dan Gohman | 692b468 | 2009-06-22 03:18:45 +0000 | [diff] [blame] | 3243 | // ~umax(~x, ~y) == umin(x, y) |
| 3244 | return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); |
| 3245 | } |
| 3246 | |
Matt Arsenault | a90a18e | 2013-09-10 19:55:24 +0000 | [diff] [blame] | 3247 | const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3248 | // We can bypass creating a target-independent |
Dan Gohman | 11862a6 | 2010-04-12 23:03:26 +0000 | [diff] [blame] | 3249 | // constant expression and then folding it back into a ConstantInt. |
| 3250 | // This is just a compile-time optimization. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3251 | return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 3252 | } |
| 3253 | |
Matt Arsenault | a90a18e | 2013-09-10 19:55:24 +0000 | [diff] [blame] | 3254 | const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, |
| 3255 | StructType *STy, |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 3256 | unsigned FieldNo) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3257 | // We can bypass creating a target-independent |
Dan Gohman | 11862a6 | 2010-04-12 23:03:26 +0000 | [diff] [blame] | 3258 | // constant expression and then folding it back into a ConstantInt. |
| 3259 | // This is just a compile-time optimization. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3260 | return getConstant( |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3261 | IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3262 | } |
| 3263 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3264 | const SCEV *ScalarEvolution::getUnknown(Value *V) { |
Dan Gohman | f436bac | 2009-06-24 00:54:57 +0000 | [diff] [blame] | 3265 | // Don't attempt to do anything other than create a SCEVUnknown object |
| 3266 | // here. createSCEV only calls getUnknown after checking for all other |
| 3267 | // interesting possibilities, and any other code that calls getUnknown |
| 3268 | // is doing so in order to hide a value from SCEV canonicalization. |
| 3269 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3270 | FoldingSetNodeID ID; |
| 3271 | ID.AddInteger(scUnknown); |
| 3272 | ID.AddPointer(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3273 | void *IP = nullptr; |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 3274 | if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { |
| 3275 | assert(cast<SCEVUnknown>(S)->getValue() == V && |
| 3276 | "Stale SCEVUnknown in uniquing map!"); |
| 3277 | return S; |
| 3278 | } |
| 3279 | SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, |
| 3280 | FirstUnknown); |
| 3281 | FirstUnknown = cast<SCEVUnknown>(S); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3282 | UniqueSCEVs.InsertNode(S, IP); |
| 3283 | return S; |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 3284 | } |
| 3285 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3286 | //===----------------------------------------------------------------------===// |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3287 | // Basic SCEV Analysis and PHI Idiom Recognition Code |
| 3288 | // |
| 3289 | |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3290 | /// isSCEVable - Test if values of the given type are analyzable within |
| 3291 | /// the SCEV framework. This primarily includes integer types, and it |
| 3292 | /// can optionally include pointer types if the ScalarEvolution class |
| 3293 | /// has access to target-specific information. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3294 | bool ScalarEvolution::isSCEVable(Type *Ty) const { |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3295 | // Integers and pointers are always SCEVable. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3296 | return Ty->isIntegerTy() || Ty->isPointerTy(); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3297 | } |
| 3298 | |
| 3299 | /// getTypeSizeInBits - Return the size in bits of the specified type, |
| 3300 | /// for which isSCEVable must return true. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3301 | uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3302 | assert(isSCEVable(Ty) && "Type is not SCEVable!"); |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3303 | return getDataLayout().getTypeSizeInBits(Ty); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3304 | } |
| 3305 | |
| 3306 | /// getEffectiveSCEVType - Return a type with the same bitwidth as |
| 3307 | /// the given type and which represents how SCEV will treat the given |
| 3308 | /// type, for which isSCEVable must return true. For pointer types, |
| 3309 | /// this is the pointer-sized integer type. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3310 | Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3311 | assert(isSCEVable(Ty) && "Type is not SCEVable!"); |
| 3312 | |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 3313 | if (Ty->isIntegerTy()) |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3314 | return Ty; |
| 3315 | |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3316 | // The only other support type is pointer. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3317 | assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3318 | return getDataLayout().getIntPtrType(Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3319 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3320 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3321 | const SCEV *ScalarEvolution::getCouldNotCompute() { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3322 | return CouldNotCompute.get(); |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 3323 | } |
| 3324 | |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 3325 | |
| 3326 | bool ScalarEvolution::checkValidity(const SCEV *S) const { |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3327 | // Helper class working with SCEVTraversal to figure out if a SCEV contains |
| 3328 | // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne |
| 3329 | // is set iff if find such SCEVUnknown. |
| 3330 | // |
| 3331 | struct FindInvalidSCEVUnknown { |
| 3332 | bool FindOne; |
| 3333 | FindInvalidSCEVUnknown() { FindOne = false; } |
| 3334 | bool follow(const SCEV *S) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 3335 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3336 | case scConstant: |
| 3337 | return false; |
| 3338 | case scUnknown: |
Shuxin Yang | 23773b3 | 2013-07-12 07:25:38 +0000 | [diff] [blame] | 3339 | if (!cast<SCEVUnknown>(S)->getValue()) |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3340 | FindOne = true; |
| 3341 | return false; |
| 3342 | default: |
| 3343 | return true; |
| 3344 | } |
| 3345 | } |
| 3346 | bool isDone() const { return FindOne; } |
| 3347 | }; |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3348 | |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3349 | FindInvalidSCEVUnknown F; |
| 3350 | SCEVTraversal<FindInvalidSCEVUnknown> ST(F); |
| 3351 | ST.visitAll(S); |
| 3352 | |
| 3353 | return !F.FindOne; |
| 3354 | } |
| 3355 | |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3356 | namespace { |
| 3357 | // Helper class working with SCEVTraversal to figure out if a SCEV contains |
| 3358 | // a sub SCEV of scAddRecExpr type. FindInvalidSCEVUnknown::FoundOne is set |
| 3359 | // iff if such sub scAddRecExpr type SCEV is found. |
| 3360 | struct FindAddRecurrence { |
| 3361 | bool FoundOne; |
| 3362 | FindAddRecurrence() : FoundOne(false) {} |
| 3363 | |
| 3364 | bool follow(const SCEV *S) { |
| 3365 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
| 3366 | case scAddRecExpr: |
| 3367 | FoundOne = true; |
| 3368 | case scConstant: |
| 3369 | case scUnknown: |
| 3370 | case scCouldNotCompute: |
| 3371 | return false; |
| 3372 | default: |
| 3373 | return true; |
| 3374 | } |
| 3375 | } |
| 3376 | bool isDone() const { return FoundOne; } |
| 3377 | }; |
| 3378 | } |
| 3379 | |
| 3380 | bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { |
| 3381 | HasRecMapType::iterator I = HasRecMap.find_as(S); |
| 3382 | if (I != HasRecMap.end()) |
| 3383 | return I->second; |
| 3384 | |
| 3385 | FindAddRecurrence F; |
| 3386 | SCEVTraversal<FindAddRecurrence> ST(F); |
| 3387 | ST.visitAll(S); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 3388 | HasRecMap.insert({S, F.FoundOne}); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3389 | return F.FoundOne; |
| 3390 | } |
| 3391 | |
| 3392 | /// getSCEVValues - Return the Value set from S. |
| 3393 | SetVector<Value *> *ScalarEvolution::getSCEVValues(const SCEV *S) { |
| 3394 | ExprValueMapType::iterator SI = ExprValueMap.find_as(S); |
| 3395 | if (SI == ExprValueMap.end()) |
| 3396 | return nullptr; |
| 3397 | #ifndef NDEBUG |
| 3398 | if (VerifySCEVMap) { |
| 3399 | // Check there is no dangling Value in the set returned. |
| 3400 | for (const auto &VE : SI->second) |
| 3401 | assert(ValueExprMap.count(VE)); |
| 3402 | } |
| 3403 | #endif |
| 3404 | return &SI->second; |
| 3405 | } |
| 3406 | |
| 3407 | /// eraseValueFromMap - Erase Value from ValueExprMap and ExprValueMap. |
| 3408 | /// If ValueExprMap.erase(V) is not used together with forgetMemoizedResults(S), |
| 3409 | /// eraseValueFromMap should be used instead to ensure whenever V->S is removed |
| 3410 | /// from ValueExprMap, V is also removed from the set of ExprValueMap[S]. |
| 3411 | void ScalarEvolution::eraseValueFromMap(Value *V) { |
| 3412 | ValueExprMapType::iterator I = ValueExprMap.find_as(V); |
| 3413 | if (I != ValueExprMap.end()) { |
| 3414 | const SCEV *S = I->second; |
| 3415 | SetVector<Value *> *SV = getSCEVValues(S); |
| 3416 | // Remove V from the set of ExprValueMap[S] |
| 3417 | if (SV) |
| 3418 | SV->remove(V); |
| 3419 | ValueExprMap.erase(V); |
| 3420 | } |
| 3421 | } |
| 3422 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3423 | /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the |
| 3424 | /// expression and create a new one. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3425 | const SCEV *ScalarEvolution::getSCEV(Value *V) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3426 | assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3427 | |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3428 | const SCEV *S = getExistingSCEV(V); |
| 3429 | if (S == nullptr) { |
| 3430 | S = createSCEV(V); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3431 | // During PHI resolution, it is possible to create two SCEVs for the same |
| 3432 | // V, so it is needed to double check whether V->S is inserted into |
| 3433 | // ValueExprMap before insert S->V into ExprValueMap. |
| 3434 | std::pair<ValueExprMapType::iterator, bool> Pair = |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 3435 | ValueExprMap.insert({SCEVCallbackVH(V, this), S}); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3436 | if (Pair.second) |
| 3437 | ExprValueMap[S].insert(V); |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3438 | } |
| 3439 | return S; |
| 3440 | } |
| 3441 | |
| 3442 | const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { |
| 3443 | assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); |
| 3444 | |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3445 | ValueExprMapType::iterator I = ValueExprMap.find_as(V); |
| 3446 | if (I != ValueExprMap.end()) { |
| 3447 | const SCEV *S = I->second; |
Shuxin Yang | 23773b3 | 2013-07-12 07:25:38 +0000 | [diff] [blame] | 3448 | if (checkValidity(S)) |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3449 | return S; |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3450 | forgetMemoizedResults(S); |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3451 | ValueExprMap.erase(I); |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3452 | } |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3453 | return nullptr; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3454 | } |
| 3455 | |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3456 | /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V |
| 3457 | /// |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3458 | const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, |
| 3459 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3460 | if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) |
Owen Anderson | 53a5221 | 2009-07-13 04:09:18 +0000 | [diff] [blame] | 3461 | return getConstant( |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 3462 | cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3463 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3464 | Type *Ty = V->getType(); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3465 | Ty = getEffectiveSCEVType(Ty); |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3466 | return getMulExpr( |
| 3467 | V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3468 | } |
| 3469 | |
| 3470 | /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3471 | const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3472 | if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) |
Owen Anderson | 542619e | 2009-07-13 20:58:05 +0000 | [diff] [blame] | 3473 | return getConstant( |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 3474 | cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3475 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3476 | Type *Ty = V->getType(); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3477 | Ty = getEffectiveSCEVType(Ty); |
Owen Anderson | 542619e | 2009-07-13 20:58:05 +0000 | [diff] [blame] | 3478 | const SCEV *AllOnes = |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 3479 | getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3480 | return getMinusSCEV(AllOnes, V); |
| 3481 | } |
| 3482 | |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3483 | /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1. |
Chris Lattner | fc87752 | 2011-01-09 22:26:35 +0000 | [diff] [blame] | 3484 | const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3485 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | 46f00a2 | 2010-07-20 16:53:00 +0000 | [diff] [blame] | 3486 | // Fast path: X - X --> 0. |
| 3487 | if (LHS == RHS) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 3488 | return getZero(LHS->getType()); |
Dan Gohman | 46f00a2 | 2010-07-20 16:53:00 +0000 | [diff] [blame] | 3489 | |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3490 | // We represent LHS - RHS as LHS + (-1)*RHS. This transformation |
| 3491 | // makes it so that we cannot make much use of NUW. |
| 3492 | auto AddFlags = SCEV::FlagAnyWrap; |
| 3493 | const bool RHSIsNotMinSigned = |
| 3494 | !getSignedRange(RHS).getSignedMin().isMinSignedValue(); |
| 3495 | if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { |
| 3496 | // Let M be the minimum representable signed value. Then (-1)*RHS |
| 3497 | // signed-wraps if and only if RHS is M. That can happen even for |
| 3498 | // a NSW subtraction because e.g. (-1)*M signed-wraps even though |
| 3499 | // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + |
| 3500 | // (-1)*RHS, we need to prove that RHS != M. |
| 3501 | // |
| 3502 | // If LHS is non-negative and we know that LHS - RHS does not |
| 3503 | // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap |
| 3504 | // either by proving that RHS > M or that LHS >= 0. |
| 3505 | if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { |
| 3506 | AddFlags = SCEV::FlagNSW; |
| 3507 | } |
| 3508 | } |
| 3509 | |
| 3510 | // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - |
| 3511 | // RHS is NSW and LHS >= 0. |
| 3512 | // |
| 3513 | // The difficulty here is that the NSW flag may have been proven |
| 3514 | // relative to a loop that is to be found in a recurrence in LHS and |
| 3515 | // not in RHS. Applying NSW to (-1)*M may then let the NSW have a |
| 3516 | // larger scope than intended. |
| 3517 | auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; |
| 3518 | |
| 3519 | return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3520 | } |
| 3521 | |
| 3522 | /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the |
| 3523 | /// input value to the specified type. If the type must be extended, it is zero |
| 3524 | /// extended. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3525 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3526 | ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { |
| 3527 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3528 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3529 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3530 | "Cannot truncate or zero extend with non-integer arguments!"); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3531 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3532 | return V; // No conversion |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3533 | if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3534 | return getTruncateExpr(V, Ty); |
| 3535 | return getZeroExtendExpr(V, Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3536 | } |
| 3537 | |
| 3538 | /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the |
| 3539 | /// input value to the specified type. If the type must be extended, it is sign |
| 3540 | /// extended. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3541 | const SCEV * |
| 3542 | ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3543 | Type *Ty) { |
| 3544 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3545 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3546 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3547 | "Cannot truncate or zero extend with non-integer arguments!"); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3548 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3549 | return V; // No conversion |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3550 | if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3551 | return getTruncateExpr(V, Ty); |
| 3552 | return getSignExtendExpr(V, Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3553 | } |
| 3554 | |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3555 | /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the |
| 3556 | /// input value to the specified type. If the type must be extended, it is zero |
| 3557 | /// extended. The conversion must not be narrowing. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3558 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3559 | ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { |
| 3560 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3561 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3562 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3563 | "Cannot noop or zero extend with non-integer arguments!"); |
| 3564 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3565 | "getNoopOrZeroExtend cannot truncate!"); |
| 3566 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3567 | return V; // No conversion |
| 3568 | return getZeroExtendExpr(V, Ty); |
| 3569 | } |
| 3570 | |
| 3571 | /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the |
| 3572 | /// input value to the specified type. If the type must be extended, it is sign |
| 3573 | /// extended. The conversion must not be narrowing. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3574 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3575 | ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { |
| 3576 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3577 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3578 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3579 | "Cannot noop or sign extend with non-integer arguments!"); |
| 3580 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3581 | "getNoopOrSignExtend cannot truncate!"); |
| 3582 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3583 | return V; // No conversion |
| 3584 | return getSignExtendExpr(V, Ty); |
| 3585 | } |
| 3586 | |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 3587 | /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of |
| 3588 | /// the input value to the specified type. If the type must be extended, |
| 3589 | /// it is extended with unspecified bits. The conversion must not be |
| 3590 | /// narrowing. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3591 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3592 | ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { |
| 3593 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3594 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3595 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 3596 | "Cannot noop or any extend with non-integer arguments!"); |
| 3597 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3598 | "getNoopOrAnyExtend cannot truncate!"); |
| 3599 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3600 | return V; // No conversion |
| 3601 | return getAnyExtendExpr(V, Ty); |
| 3602 | } |
| 3603 | |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3604 | /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the |
| 3605 | /// input value to the specified type. The conversion must not be widening. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3606 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3607 | ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { |
| 3608 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3609 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3610 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3611 | "Cannot truncate or noop with non-integer arguments!"); |
| 3612 | assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && |
| 3613 | "getTruncateOrNoop cannot extend!"); |
| 3614 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3615 | return V; // No conversion |
| 3616 | return getTruncateExpr(V, Ty); |
| 3617 | } |
| 3618 | |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 3619 | /// getUMaxFromMismatchedTypes - Promote the operands to the wider of |
| 3620 | /// the types using zero-extension, and then perform a umax operation |
| 3621 | /// with them. |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3622 | const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, |
| 3623 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3624 | const SCEV *PromotedLHS = LHS; |
| 3625 | const SCEV *PromotedRHS = RHS; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 3626 | |
| 3627 | if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) |
| 3628 | PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); |
| 3629 | else |
| 3630 | PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); |
| 3631 | |
| 3632 | return getUMaxExpr(PromotedLHS, PromotedRHS); |
| 3633 | } |
| 3634 | |
Dan Gohman | 2bc2230 | 2009-06-22 15:03:27 +0000 | [diff] [blame] | 3635 | /// getUMinFromMismatchedTypes - Promote the operands to the wider of |
| 3636 | /// the types using zero-extension, and then perform a umin operation |
| 3637 | /// with them. |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3638 | const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, |
| 3639 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3640 | const SCEV *PromotedLHS = LHS; |
| 3641 | const SCEV *PromotedRHS = RHS; |
Dan Gohman | 2bc2230 | 2009-06-22 15:03:27 +0000 | [diff] [blame] | 3642 | |
| 3643 | if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) |
| 3644 | PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); |
| 3645 | else |
| 3646 | PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); |
| 3647 | |
| 3648 | return getUMinExpr(PromotedLHS, PromotedRHS); |
| 3649 | } |
| 3650 | |
Andrew Trick | 87716c9 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 3651 | /// getPointerBase - Transitively follow the chain of pointer-type operands |
| 3652 | /// until reaching a SCEV that does not have a single pointer operand. This |
| 3653 | /// returns a SCEVUnknown pointer for well-formed pointer-type expressions, |
| 3654 | /// but corner cases do exist. |
| 3655 | const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { |
| 3656 | // A pointer operand may evaluate to a nonpointer expression, such as null. |
| 3657 | if (!V->getType()->isPointerTy()) |
| 3658 | return V; |
| 3659 | |
| 3660 | if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { |
| 3661 | return getPointerBase(Cast->getOperand()); |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 3662 | } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3663 | const SCEV *PtrOp = nullptr; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 3664 | for (const SCEV *NAryOp : NAry->operands()) { |
| 3665 | if (NAryOp->getType()->isPointerTy()) { |
Andrew Trick | 87716c9 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 3666 | // Cannot find the base of an expression with multiple pointer operands. |
| 3667 | if (PtrOp) |
| 3668 | return V; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 3669 | PtrOp = NAryOp; |
Andrew Trick | 87716c9 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 3670 | } |
| 3671 | } |
| 3672 | if (!PtrOp) |
| 3673 | return V; |
| 3674 | return getPointerBase(PtrOp); |
| 3675 | } |
| 3676 | return V; |
| 3677 | } |
| 3678 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3679 | /// PushDefUseChildren - Push users of the given Instruction |
| 3680 | /// onto the given Worklist. |
| 3681 | static void |
| 3682 | PushDefUseChildren(Instruction *I, |
| 3683 | SmallVectorImpl<Instruction *> &Worklist) { |
| 3684 | // Push the def-use children onto the Worklist stack. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3685 | for (User *U : I->users()) |
| 3686 | Worklist.push_back(cast<Instruction>(U)); |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3687 | } |
| 3688 | |
| 3689 | /// ForgetSymbolicValue - This looks up computed SCEV values for all |
| 3690 | /// instructions that depend on the given instruction and removes them from |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3691 | /// the ValueExprMapType map if they reference SymName. This is used during PHI |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3692 | /// resolution. |
Sanjoy Das | f1e9cae0 | 2016-03-01 19:28:01 +0000 | [diff] [blame] | 3693 | void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3694 | SmallVector<Instruction *, 16> Worklist; |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3695 | PushDefUseChildren(PN, Worklist); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3696 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3697 | SmallPtrSet<Instruction *, 8> Visited; |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3698 | Visited.insert(PN); |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3699 | while (!Worklist.empty()) { |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3700 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3701 | if (!Visited.insert(I).second) |
| 3702 | continue; |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3703 | |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 3704 | auto It = ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3705 | if (It != ValueExprMap.end()) { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 3706 | const SCEV *Old = It->second; |
| 3707 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3708 | // Short-circuit the def-use traversal if the symbolic name |
| 3709 | // ceases to appear in expressions. |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 3710 | if (Old != SymName && !hasOperand(Old, SymName)) |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3711 | continue; |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3712 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3713 | // SCEVUnknown for a PHI either means that it has an unrecognized |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3714 | // structure, it's a PHI that's in the progress of being computed |
| 3715 | // by createNodeForPHI, or it's a single-value PHI. In the first case, |
| 3716 | // additional loop trip count information isn't going to change anything. |
| 3717 | // In the second case, createNodeForPHI will perform the necessary |
| 3718 | // updates on its own when it gets to that point. In the third, we do |
| 3719 | // want to forget the SCEVUnknown. |
| 3720 | if (!isa<PHINode>(I) || |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 3721 | !isa<SCEVUnknown>(Old) || |
| 3722 | (I != PN && Old == SymName)) { |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 3723 | forgetMemoizedResults(Old); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3724 | ValueExprMap.erase(It); |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 3725 | } |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3726 | } |
| 3727 | |
| 3728 | PushDefUseChildren(I, Worklist); |
| 3729 | } |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3730 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3731 | |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 3732 | namespace { |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3733 | class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { |
| 3734 | public: |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3735 | static const SCEV *rewrite(const SCEV *S, const Loop *L, |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3736 | ScalarEvolution &SE) { |
| 3737 | SCEVInitRewriter Rewriter(L, SE); |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3738 | const SCEV *Result = Rewriter.visit(S); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3739 | return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); |
| 3740 | } |
| 3741 | |
| 3742 | SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) |
| 3743 | : SCEVRewriteVisitor(SE), L(L), Valid(true) {} |
| 3744 | |
| 3745 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { |
| 3746 | if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) |
| 3747 | Valid = false; |
| 3748 | return Expr; |
| 3749 | } |
| 3750 | |
| 3751 | const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { |
| 3752 | // Only allow AddRecExprs for this loop. |
| 3753 | if (Expr->getLoop() == L) |
| 3754 | return Expr->getStart(); |
| 3755 | Valid = false; |
| 3756 | return Expr; |
| 3757 | } |
| 3758 | |
| 3759 | bool isValid() { return Valid; } |
| 3760 | |
| 3761 | private: |
| 3762 | const Loop *L; |
| 3763 | bool Valid; |
| 3764 | }; |
| 3765 | |
| 3766 | class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { |
| 3767 | public: |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3768 | static const SCEV *rewrite(const SCEV *S, const Loop *L, |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3769 | ScalarEvolution &SE) { |
| 3770 | SCEVShiftRewriter Rewriter(L, SE); |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3771 | const SCEV *Result = Rewriter.visit(S); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3772 | return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); |
| 3773 | } |
| 3774 | |
| 3775 | SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) |
| 3776 | : SCEVRewriteVisitor(SE), L(L), Valid(true) {} |
| 3777 | |
| 3778 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { |
| 3779 | // Only allow AddRecExprs for this loop. |
| 3780 | if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) |
| 3781 | Valid = false; |
| 3782 | return Expr; |
| 3783 | } |
| 3784 | |
| 3785 | const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { |
| 3786 | if (Expr->getLoop() == L && Expr->isAffine()) |
| 3787 | return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); |
| 3788 | Valid = false; |
| 3789 | return Expr; |
| 3790 | } |
| 3791 | bool isValid() { return Valid; } |
| 3792 | |
| 3793 | private: |
| 3794 | const Loop *L; |
| 3795 | bool Valid; |
| 3796 | }; |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 3797 | } // end anonymous namespace |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3798 | |
Sanjoy Das | 724f5cf | 2016-03-03 18:31:29 +0000 | [diff] [blame] | 3799 | SCEV::NoWrapFlags |
| 3800 | ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { |
| 3801 | if (!AR->isAffine()) |
| 3802 | return SCEV::FlagAnyWrap; |
| 3803 | |
| 3804 | typedef OverflowingBinaryOperator OBO; |
| 3805 | SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; |
| 3806 | |
| 3807 | if (!AR->hasNoSignedWrap()) { |
| 3808 | ConstantRange AddRecRange = getSignedRange(AR); |
| 3809 | ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); |
| 3810 | |
| 3811 | auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 3812 | Instruction::Add, IncRange, OBO::NoSignedWrap); |
| 3813 | if (NSWRegion.contains(AddRecRange)) |
| 3814 | Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); |
| 3815 | } |
| 3816 | |
| 3817 | if (!AR->hasNoUnsignedWrap()) { |
| 3818 | ConstantRange AddRecRange = getUnsignedRange(AR); |
| 3819 | ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); |
| 3820 | |
| 3821 | auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 3822 | Instruction::Add, IncRange, OBO::NoUnsignedWrap); |
| 3823 | if (NUWRegion.contains(AddRecRange)) |
| 3824 | Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); |
| 3825 | } |
| 3826 | |
| 3827 | return Result; |
| 3828 | } |
| 3829 | |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3830 | namespace { |
| 3831 | /// Represents an abstract binary operation. This may exist as a |
| 3832 | /// normal instruction or constant expression, or may have been |
| 3833 | /// derived from an expression tree. |
| 3834 | struct BinaryOp { |
| 3835 | unsigned Opcode; |
| 3836 | Value *LHS; |
| 3837 | Value *RHS; |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 3838 | bool IsNSW; |
| 3839 | bool IsNUW; |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3840 | |
| 3841 | /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or |
| 3842 | /// constant expression. |
| 3843 | Operator *Op; |
| 3844 | |
| 3845 | explicit BinaryOp(Operator *Op) |
| 3846 | : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 3847 | IsNSW(false), IsNUW(false), Op(Op) { |
| 3848 | if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { |
| 3849 | IsNSW = OBO->hasNoSignedWrap(); |
| 3850 | IsNUW = OBO->hasNoUnsignedWrap(); |
| 3851 | } |
| 3852 | } |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3853 | |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 3854 | explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, |
| 3855 | bool IsNUW = false) |
| 3856 | : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), |
| 3857 | Op(nullptr) {} |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3858 | }; |
| 3859 | } |
| 3860 | |
| 3861 | |
| 3862 | /// Try to map \p V into a BinaryOp, and return \c None on failure. |
Sanjoy Das | f9d88e6 | 2016-04-11 15:26:18 +0000 | [diff] [blame] | 3863 | static Optional<BinaryOp> MatchBinaryOp(Value *V) { |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3864 | auto *Op = dyn_cast<Operator>(V); |
| 3865 | if (!Op) |
| 3866 | return None; |
| 3867 | |
| 3868 | // Implementation detail: all the cleverness here should happen without |
| 3869 | // creating new SCEV expressions -- our caller knowns tricks to avoid creating |
| 3870 | // SCEV expressions when possible, and we should not break that. |
| 3871 | |
| 3872 | switch (Op->getOpcode()) { |
| 3873 | case Instruction::Add: |
| 3874 | case Instruction::Sub: |
| 3875 | case Instruction::Mul: |
| 3876 | case Instruction::UDiv: |
| 3877 | case Instruction::And: |
| 3878 | case Instruction::Or: |
| 3879 | case Instruction::AShr: |
| 3880 | case Instruction::Shl: |
| 3881 | return BinaryOp(Op); |
| 3882 | |
| 3883 | case Instruction::Xor: |
| 3884 | if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) |
| 3885 | // If the RHS of the xor is a signbit, then this is just an add. |
| 3886 | // Instcombine turns add of signbit into xor as a strength reduction step. |
| 3887 | if (RHSC->getValue().isSignBit()) |
| 3888 | return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); |
| 3889 | return BinaryOp(Op); |
| 3890 | |
| 3891 | case Instruction::LShr: |
| 3892 | // Turn logical shift right of a constant into a unsigned divide. |
| 3893 | if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { |
| 3894 | uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); |
| 3895 | |
| 3896 | // If the shift count is not less than the bitwidth, the result of |
| 3897 | // the shift is undefined. Don't try to analyze it, because the |
| 3898 | // resolution chosen here may differ from the resolution chosen in |
| 3899 | // other parts of the compiler. |
| 3900 | if (SA->getValue().ult(BitWidth)) { |
| 3901 | Constant *X = |
| 3902 | ConstantInt::get(SA->getContext(), |
| 3903 | APInt::getOneBitSet(BitWidth, SA->getZExtValue())); |
| 3904 | return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); |
| 3905 | } |
| 3906 | } |
| 3907 | return BinaryOp(Op); |
| 3908 | |
| 3909 | default: |
| 3910 | break; |
| 3911 | } |
| 3912 | |
| 3913 | return None; |
| 3914 | } |
| 3915 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3916 | const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { |
| 3917 | const Loop *L = LI.getLoopFor(PN->getParent()); |
| 3918 | if (!L || L->getHeader() != PN->getParent()) |
| 3919 | return nullptr; |
| 3920 | |
| 3921 | // The loop may have multiple entrances or multiple exits; we can analyze |
| 3922 | // this phi as an addrec if it has a unique entry value and a unique |
| 3923 | // backedge value. |
| 3924 | Value *BEValueV = nullptr, *StartValueV = nullptr; |
| 3925 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 3926 | Value *V = PN->getIncomingValue(i); |
| 3927 | if (L->contains(PN->getIncomingBlock(i))) { |
| 3928 | if (!BEValueV) { |
| 3929 | BEValueV = V; |
| 3930 | } else if (BEValueV != V) { |
| 3931 | BEValueV = nullptr; |
| 3932 | break; |
| 3933 | } |
| 3934 | } else if (!StartValueV) { |
| 3935 | StartValueV = V; |
| 3936 | } else if (StartValueV != V) { |
| 3937 | StartValueV = nullptr; |
| 3938 | break; |
| 3939 | } |
| 3940 | } |
| 3941 | if (BEValueV && StartValueV) { |
| 3942 | // While we are analyzing this PHI node, handle its value symbolically. |
| 3943 | const SCEV *SymbolicName = getUnknown(PN); |
| 3944 | assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && |
| 3945 | "PHI node already processed?"); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 3946 | ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3947 | |
| 3948 | // Using this symbolic name for the PHI, analyze the value coming around |
| 3949 | // the back-edge. |
| 3950 | const SCEV *BEValue = getSCEV(BEValueV); |
| 3951 | |
| 3952 | // NOTE: If BEValue is loop invariant, we know that the PHI node just |
| 3953 | // has a special value for the first iteration of the loop. |
| 3954 | |
| 3955 | // If the value coming around the backedge is an add with the symbolic |
| 3956 | // value we just inserted, then we found a simple induction variable! |
| 3957 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { |
| 3958 | // If there is a single occurrence of the symbolic value, replace it |
| 3959 | // with a recurrence. |
| 3960 | unsigned FoundIndex = Add->getNumOperands(); |
| 3961 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) |
| 3962 | if (Add->getOperand(i) == SymbolicName) |
| 3963 | if (FoundIndex == e) { |
| 3964 | FoundIndex = i; |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 3965 | break; |
| 3966 | } |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3967 | |
| 3968 | if (FoundIndex != Add->getNumOperands()) { |
| 3969 | // Create an add with everything but the specified operand. |
| 3970 | SmallVector<const SCEV *, 8> Ops; |
| 3971 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) |
| 3972 | if (i != FoundIndex) |
| 3973 | Ops.push_back(Add->getOperand(i)); |
| 3974 | const SCEV *Accum = getAddExpr(Ops); |
| 3975 | |
| 3976 | // This is not a valid addrec if the step amount is varying each |
| 3977 | // loop iteration, but is not itself an addrec in this loop. |
| 3978 | if (isLoopInvariant(Accum, L) || |
| 3979 | (isa<SCEVAddRecExpr>(Accum) && |
| 3980 | cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { |
| 3981 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
| 3982 | |
| 3983 | // If the increment doesn't overflow, then neither the addrec nor |
| 3984 | // the post-increment will overflow. |
Sanjoy Das | f9d88e6 | 2016-04-11 15:26:18 +0000 | [diff] [blame] | 3985 | if (auto BO = MatchBinaryOp(BEValueV)) { |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 3986 | if (BO->Opcode == Instruction::Add && BO->LHS == PN) { |
| 3987 | if (BO->IsNUW) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3988 | Flags = setFlags(Flags, SCEV::FlagNUW); |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 3989 | if (BO->IsNSW) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3990 | Flags = setFlags(Flags, SCEV::FlagNSW); |
| 3991 | } |
| 3992 | } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { |
| 3993 | // If the increment is an inbounds GEP, then we know the address |
| 3994 | // space cannot be wrapped around. We cannot make any guarantee |
| 3995 | // about signed or unsigned overflow because pointers are |
| 3996 | // unsigned but we may have a negative index from the base |
| 3997 | // pointer. We can guarantee that no unsigned wrap occurs if the |
| 3998 | // indices form a positive value. |
| 3999 | if (GEP->isInBounds() && GEP->getOperand(0) == PN) { |
| 4000 | Flags = setFlags(Flags, SCEV::FlagNW); |
| 4001 | |
| 4002 | const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); |
| 4003 | if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) |
| 4004 | Flags = setFlags(Flags, SCEV::FlagNUW); |
| 4005 | } |
| 4006 | |
| 4007 | // We cannot transfer nuw and nsw flags from subtraction |
| 4008 | // operations -- sub nuw X, Y is not the same as add nuw X, -Y |
| 4009 | // for instance. |
| 4010 | } |
| 4011 | |
| 4012 | const SCEV *StartVal = getSCEV(StartValueV); |
| 4013 | const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); |
| 4014 | |
| 4015 | // Since the no-wrap flags are on the increment, they apply to the |
| 4016 | // post-incremented value as well. |
| 4017 | if (isLoopInvariant(Accum, L)) |
| 4018 | (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); |
| 4019 | |
| 4020 | // Okay, for the entire analysis of this edge we assumed the PHI |
| 4021 | // to be symbolic. We now need to go back and purge all of the |
| 4022 | // entries for the scalars that use the symbolic expression. |
Sanjoy Das | f1e9cae0 | 2016-03-01 19:28:01 +0000 | [diff] [blame] | 4023 | forgetSymbolicName(PN, SymbolicName); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4024 | ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; |
| 4025 | return PHISCEV; |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 4026 | } |
| 4027 | } |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 4028 | } else { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4029 | // Otherwise, this could be a loop like this: |
| 4030 | // i = 0; for (j = 1; ..; ++j) { .... i = j; } |
| 4031 | // In this case, j = {1,+,1} and BEValue is j. |
| 4032 | // Because the other in-value of i (0) fits the evolution of BEValue |
| 4033 | // i really is an addrec evolution. |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 4034 | // |
| 4035 | // We can generalize this saying that i is the shifted value of BEValue |
| 4036 | // by one iteration: |
| 4037 | // PHI(f(0), f({1,+,1})) --> f({0,+,1}) |
| 4038 | const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); |
| 4039 | const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); |
| 4040 | if (Shifted != getCouldNotCompute() && |
| 4041 | Start != getCouldNotCompute()) { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4042 | const SCEV *StartVal = getSCEV(StartValueV); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 4043 | if (Start == StartVal) { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4044 | // Okay, for the entire analysis of this edge we assumed the PHI |
| 4045 | // to be symbolic. We now need to go back and purge all of the |
| 4046 | // entries for the scalars that use the symbolic expression. |
Sanjoy Das | f1e9cae0 | 2016-03-01 19:28:01 +0000 | [diff] [blame] | 4047 | forgetSymbolicName(PN, SymbolicName); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 4048 | ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; |
| 4049 | return Shifted; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4050 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4051 | } |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 4052 | } |
Tobias Grosser | 934fcf4 | 2016-02-21 18:50:09 +0000 | [diff] [blame] | 4053 | |
| 4054 | // Remove the temporary PHI node SCEV that has been inserted while intending |
| 4055 | // to create an AddRecExpr for this PHI node. We can not keep this temporary |
| 4056 | // as it will prevent later (possibly simpler) SCEV expressions to be added |
| 4057 | // to the ValueExprMap. |
| 4058 | ValueExprMap.erase(PN); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4059 | } |
| 4060 | |
| 4061 | return nullptr; |
| 4062 | } |
| 4063 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4064 | // Checks if the SCEV S is available at BB. S is considered available at BB |
| 4065 | // if S can be materialized at BB without introducing a fault. |
| 4066 | static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, |
| 4067 | BasicBlock *BB) { |
| 4068 | struct CheckAvailable { |
| 4069 | bool TraversalDone = false; |
| 4070 | bool Available = true; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4071 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4072 | const Loop *L = nullptr; // The loop BB is in (can be nullptr) |
| 4073 | BasicBlock *BB = nullptr; |
| 4074 | DominatorTree &DT; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4075 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4076 | CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) |
| 4077 | : L(L), BB(BB), DT(DT) {} |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4078 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4079 | bool setUnavailable() { |
| 4080 | TraversalDone = true; |
| 4081 | Available = false; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4082 | return false; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4083 | } |
| 4084 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4085 | bool follow(const SCEV *S) { |
| 4086 | switch (S->getSCEVType()) { |
| 4087 | case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: |
| 4088 | case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: |
Sanjoy Das | bb5ffc5 | 2015-10-24 05:37:28 +0000 | [diff] [blame] | 4089 | // These expressions are available if their operand(s) is/are. |
| 4090 | return true; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4091 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4092 | case scAddRecExpr: { |
| 4093 | // We allow add recurrences that are on the loop BB is in, or some |
| 4094 | // outer loop. This guarantees availability because the value of the |
| 4095 | // add recurrence at BB is simply the "current" value of the induction |
| 4096 | // variable. We can relax this in the future; for instance an add |
| 4097 | // recurrence on a sibling dominating loop is also available at BB. |
| 4098 | const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); |
| 4099 | if (L && (ARLoop == L || ARLoop->contains(L))) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4100 | return true; |
| 4101 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4102 | return setUnavailable(); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4103 | } |
| 4104 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4105 | case scUnknown: { |
| 4106 | // For SCEVUnknown, we check for simple dominance. |
| 4107 | const auto *SU = cast<SCEVUnknown>(S); |
| 4108 | Value *V = SU->getValue(); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4109 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4110 | if (isa<Argument>(V)) |
| 4111 | return false; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4112 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4113 | if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) |
| 4114 | return false; |
| 4115 | |
| 4116 | return setUnavailable(); |
| 4117 | } |
| 4118 | |
| 4119 | case scUDivExpr: |
| 4120 | case scCouldNotCompute: |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 4121 | // We do not try to smart about these at all. |
| 4122 | return setUnavailable(); |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4123 | } |
| 4124 | llvm_unreachable("switch should be fully covered!"); |
| 4125 | } |
| 4126 | |
| 4127 | bool isDone() { return TraversalDone; } |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4128 | }; |
| 4129 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4130 | CheckAvailable CA(L, BB, DT); |
| 4131 | SCEVTraversal<CheckAvailable> ST(CA); |
| 4132 | |
| 4133 | ST.visitAll(S); |
| 4134 | return CA.Available; |
| 4135 | } |
| 4136 | |
| 4137 | // Try to match a control flow sequence that branches out at BI and merges back |
| 4138 | // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful |
| 4139 | // match. |
| 4140 | static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, |
| 4141 | Value *&C, Value *&LHS, Value *&RHS) { |
| 4142 | C = BI->getCondition(); |
| 4143 | |
| 4144 | BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); |
| 4145 | BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); |
| 4146 | |
| 4147 | if (!LeftEdge.isSingleEdge()) |
| 4148 | return false; |
| 4149 | |
| 4150 | assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); |
| 4151 | |
| 4152 | Use &LeftUse = Merge->getOperandUse(0); |
| 4153 | Use &RightUse = Merge->getOperandUse(1); |
| 4154 | |
| 4155 | if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { |
| 4156 | LHS = LeftUse; |
| 4157 | RHS = RightUse; |
| 4158 | return true; |
| 4159 | } |
| 4160 | |
| 4161 | if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { |
| 4162 | LHS = RightUse; |
| 4163 | RHS = LeftUse; |
| 4164 | return true; |
| 4165 | } |
| 4166 | |
| 4167 | return false; |
| 4168 | } |
| 4169 | |
| 4170 | const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4171 | if (PN->getNumIncomingValues() == 2) { |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4172 | const Loop *L = LI.getLoopFor(PN->getParent()); |
| 4173 | |
Sanjoy Das | 337d478 | 2015-10-31 23:21:40 +0000 | [diff] [blame] | 4174 | // We don't want to break LCSSA, even in a SCEV expression tree. |
| 4175 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
| 4176 | if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) |
| 4177 | return nullptr; |
| 4178 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4179 | // Try to match |
| 4180 | // |
| 4181 | // br %cond, label %left, label %right |
| 4182 | // left: |
| 4183 | // br label %merge |
| 4184 | // right: |
| 4185 | // br label %merge |
| 4186 | // merge: |
| 4187 | // V = phi [ %x, %left ], [ %y, %right ] |
| 4188 | // |
| 4189 | // as "select %cond, %x, %y" |
| 4190 | |
| 4191 | BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); |
| 4192 | assert(IDom && "At least the entry block should dominate PN"); |
| 4193 | |
| 4194 | auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); |
| 4195 | Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; |
| 4196 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4197 | if (BI && BI->isConditional() && |
| 4198 | BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && |
| 4199 | IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && |
| 4200 | IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4201 | return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); |
| 4202 | } |
| 4203 | |
| 4204 | return nullptr; |
| 4205 | } |
| 4206 | |
| 4207 | const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { |
| 4208 | if (const SCEV *S = createAddRecFromPHI(PN)) |
| 4209 | return S; |
| 4210 | |
| 4211 | if (const SCEV *S = createNodeFromSelectLikePHI(PN)) |
| 4212 | return S; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 4213 | |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 4214 | // If the PHI has a single incoming value, follow that value, unless the |
| 4215 | // PHI's incoming blocks are in a different loop, in which case doing so |
| 4216 | // risks breaking LCSSA form. Instcombine would normally zap these, but |
| 4217 | // it doesn't have DominatorTree information, so it may miss cases. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 4218 | if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC)) |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4219 | if (LI.replacementPreservesLCSSAForm(PN, V)) |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 4220 | return getSCEV(V); |
Duncan Sands | 39d77131 | 2010-11-17 20:49:12 +0000 | [diff] [blame] | 4221 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4222 | // If it's not a loop phi, we can't handle it yet. |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4223 | return getUnknown(PN); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4224 | } |
| 4225 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4226 | const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, |
| 4227 | Value *Cond, |
| 4228 | Value *TrueVal, |
| 4229 | Value *FalseVal) { |
Mehdi Amini | 044cb34 | 2015-10-07 18:14:25 +0000 | [diff] [blame] | 4230 | // Handle "constant" branch or select. This can occur for instance when a |
| 4231 | // loop pass transforms an inner loop and moves on to process the outer loop. |
| 4232 | if (auto *CI = dyn_cast<ConstantInt>(Cond)) |
| 4233 | return getSCEV(CI->isOne() ? TrueVal : FalseVal); |
| 4234 | |
Sanjoy Das | d067134 | 2015-10-02 19:39:59 +0000 | [diff] [blame] | 4235 | // Try to match some simple smax or umax patterns. |
| 4236 | auto *ICI = dyn_cast<ICmpInst>(Cond); |
| 4237 | if (!ICI) |
| 4238 | return getUnknown(I); |
| 4239 | |
| 4240 | Value *LHS = ICI->getOperand(0); |
| 4241 | Value *RHS = ICI->getOperand(1); |
| 4242 | |
| 4243 | switch (ICI->getPredicate()) { |
| 4244 | case ICmpInst::ICMP_SLT: |
| 4245 | case ICmpInst::ICMP_SLE: |
| 4246 | std::swap(LHS, RHS); |
| 4247 | // fall through |
| 4248 | case ICmpInst::ICMP_SGT: |
| 4249 | case ICmpInst::ICMP_SGE: |
| 4250 | // a >s b ? a+x : b+x -> smax(a, b)+x |
| 4251 | // a >s b ? b+x : a+x -> smin(a, b)+x |
| 4252 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { |
| 4253 | const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); |
| 4254 | const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); |
| 4255 | const SCEV *LA = getSCEV(TrueVal); |
| 4256 | const SCEV *RA = getSCEV(FalseVal); |
| 4257 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4258 | const SCEV *RDiff = getMinusSCEV(RA, RS); |
| 4259 | if (LDiff == RDiff) |
| 4260 | return getAddExpr(getSMaxExpr(LS, RS), LDiff); |
| 4261 | LDiff = getMinusSCEV(LA, RS); |
| 4262 | RDiff = getMinusSCEV(RA, LS); |
| 4263 | if (LDiff == RDiff) |
| 4264 | return getAddExpr(getSMinExpr(LS, RS), LDiff); |
| 4265 | } |
| 4266 | break; |
| 4267 | case ICmpInst::ICMP_ULT: |
| 4268 | case ICmpInst::ICMP_ULE: |
| 4269 | std::swap(LHS, RHS); |
| 4270 | // fall through |
| 4271 | case ICmpInst::ICMP_UGT: |
| 4272 | case ICmpInst::ICMP_UGE: |
| 4273 | // a >u b ? a+x : b+x -> umax(a, b)+x |
| 4274 | // a >u b ? b+x : a+x -> umin(a, b)+x |
| 4275 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { |
| 4276 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); |
| 4277 | const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); |
| 4278 | const SCEV *LA = getSCEV(TrueVal); |
| 4279 | const SCEV *RA = getSCEV(FalseVal); |
| 4280 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4281 | const SCEV *RDiff = getMinusSCEV(RA, RS); |
| 4282 | if (LDiff == RDiff) |
| 4283 | return getAddExpr(getUMaxExpr(LS, RS), LDiff); |
| 4284 | LDiff = getMinusSCEV(LA, RS); |
| 4285 | RDiff = getMinusSCEV(RA, LS); |
| 4286 | if (LDiff == RDiff) |
| 4287 | return getAddExpr(getUMinExpr(LS, RS), LDiff); |
| 4288 | } |
| 4289 | break; |
| 4290 | case ICmpInst::ICMP_NE: |
| 4291 | // n != 0 ? n+x : 1+x -> umax(n, 1)+x |
| 4292 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && |
| 4293 | isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { |
| 4294 | const SCEV *One = getOne(I->getType()); |
| 4295 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); |
| 4296 | const SCEV *LA = getSCEV(TrueVal); |
| 4297 | const SCEV *RA = getSCEV(FalseVal); |
| 4298 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4299 | const SCEV *RDiff = getMinusSCEV(RA, One); |
| 4300 | if (LDiff == RDiff) |
| 4301 | return getAddExpr(getUMaxExpr(One, LS), LDiff); |
| 4302 | } |
| 4303 | break; |
| 4304 | case ICmpInst::ICMP_EQ: |
| 4305 | // n == 0 ? 1+x : n+x -> umax(n, 1)+x |
| 4306 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && |
| 4307 | isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { |
| 4308 | const SCEV *One = getOne(I->getType()); |
| 4309 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); |
| 4310 | const SCEV *LA = getSCEV(TrueVal); |
| 4311 | const SCEV *RA = getSCEV(FalseVal); |
| 4312 | const SCEV *LDiff = getMinusSCEV(LA, One); |
| 4313 | const SCEV *RDiff = getMinusSCEV(RA, LS); |
| 4314 | if (LDiff == RDiff) |
| 4315 | return getAddExpr(getUMaxExpr(One, LS), LDiff); |
| 4316 | } |
| 4317 | break; |
| 4318 | default: |
| 4319 | break; |
| 4320 | } |
| 4321 | |
| 4322 | return getUnknown(I); |
| 4323 | } |
| 4324 | |
Dan Gohman | ee750d1 | 2009-05-08 20:26:55 +0000 | [diff] [blame] | 4325 | /// createNodeForGEP - Expand GEP instructions into add and multiply |
| 4326 | /// operations. This allows them to be analyzed by regular SCEV code. |
| 4327 | /// |
Dan Gohman | b256ccf | 2009-12-18 02:09:29 +0000 | [diff] [blame] | 4328 | const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { |
Dan Gohman | 30f24fe | 2009-05-09 00:14:52 +0000 | [diff] [blame] | 4329 | // Don't attempt to analyze GEPs over unsized objects. |
Eduard Burtescu | 19eb031 | 2016-01-19 17:28:00 +0000 | [diff] [blame] | 4330 | if (!GEP->getSourceElementType()->isSized()) |
Dan Gohman | 30f24fe | 2009-05-09 00:14:52 +0000 | [diff] [blame] | 4331 | return getUnknown(GEP); |
Matt Arsenault | 4c26590 | 2013-09-27 22:38:23 +0000 | [diff] [blame] | 4332 | |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 4333 | SmallVector<const SCEV *, 4> IndexExprs; |
| 4334 | for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) |
| 4335 | IndexExprs.push_back(getSCEV(*Index)); |
Eduard Burtescu | 19eb031 | 2016-01-19 17:28:00 +0000 | [diff] [blame] | 4336 | return getGEPExpr(GEP->getSourceElementType(), |
| 4337 | getSCEV(GEP->getPointerOperand()), |
| 4338 | IndexExprs, GEP->isInBounds()); |
Dan Gohman | ee750d1 | 2009-05-08 20:26:55 +0000 | [diff] [blame] | 4339 | } |
| 4340 | |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4341 | /// GetMinTrailingZeros - Determine the minimum number of zero bits that S is |
| 4342 | /// guaranteed to end in (at every loop iteration). It is, at the same time, |
| 4343 | /// the minimum number of times S is divisible by 2. For example, given {4,+,8} |
| 4344 | /// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4345 | uint32_t |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4346 | ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4347 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 4348 | return C->getAPInt().countTrailingZeros(); |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4349 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4350 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4351 | return std::min(GetMinTrailingZeros(T->getOperand()), |
| 4352 | (uint32_t)getTypeSizeInBits(T->getType())); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4353 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4354 | if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4355 | uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); |
| 4356 | return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? |
| 4357 | getTypeSizeInBits(E->getType()) : OpRes; |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4358 | } |
| 4359 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4360 | if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4361 | uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); |
| 4362 | return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? |
| 4363 | getTypeSizeInBits(E->getType()) : OpRes; |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4364 | } |
| 4365 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4366 | if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4367 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4368 | uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4369 | for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4370 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4371 | return MinOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4372 | } |
| 4373 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4374 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4375 | // The result is the sum of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4376 | uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); |
| 4377 | uint32_t BitWidth = getTypeSizeInBits(M->getType()); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4378 | for (unsigned i = 1, e = M->getNumOperands(); |
| 4379 | SumOpRes != BitWidth && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4380 | SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4381 | BitWidth); |
| 4382 | return SumOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4383 | } |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4384 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4385 | if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4386 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4387 | uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4388 | for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4389 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4390 | return MinOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4391 | } |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4392 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4393 | if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 4394 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4395 | uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 4396 | for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4397 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 4398 | return MinOpRes; |
| 4399 | } |
| 4400 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4401 | if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 4402 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4403 | uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 4404 | for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4405 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 4406 | return MinOpRes; |
| 4407 | } |
| 4408 | |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4409 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { |
| 4410 | // For a SCEVUnknown, ask ValueTracking. |
| 4411 | unsigned BitWidth = getTypeSizeInBits(U->getType()); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4412 | APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 4413 | computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC, |
| 4414 | nullptr, &DT); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4415 | return Zeros.countTrailingOnes(); |
| 4416 | } |
| 4417 | |
| 4418 | // SCEVUDivExpr |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4419 | return 0; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4420 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4421 | |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 4422 | /// GetRangeFromMetadata - Helper method to assign a range to V from |
| 4423 | /// metadata present in the IR. |
| 4424 | static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { |
Sanjoy Das | a7e1378 | 2015-10-24 05:37:35 +0000 | [diff] [blame] | 4425 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 4426 | if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) |
| 4427 | return getConstantRangeFromMetadata(*MD); |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 4428 | |
| 4429 | return None; |
| 4430 | } |
| 4431 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4432 | /// getRange - Determine the range for a particular SCEV. If SignHint is |
| 4433 | /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges |
| 4434 | /// with a "cleaner" unsigned (resp. signed) representation. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4435 | /// |
| 4436 | ConstantRange |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4437 | ScalarEvolution::getRange(const SCEV *S, |
| 4438 | ScalarEvolution::RangeSignHint SignHint) { |
| 4439 | DenseMap<const SCEV *, ConstantRange> &Cache = |
| 4440 | SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges |
| 4441 | : SignedRanges; |
| 4442 | |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 4443 | // See if we've computed this range already. |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4444 | DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); |
| 4445 | if (I != Cache.end()) |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 4446 | return I->second; |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4447 | |
| 4448 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 4449 | return setRange(C, SignHint, ConstantRange(C->getAPInt())); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4450 | |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4451 | unsigned BitWidth = getTypeSizeInBits(S->getType()); |
| 4452 | ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); |
| 4453 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4454 | // If the value has known zeros, the maximum value will have those known zeros |
| 4455 | // as well. |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4456 | uint32_t TZ = GetMinTrailingZeros(S); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4457 | if (TZ != 0) { |
| 4458 | if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) |
| 4459 | ConservativeResult = |
| 4460 | ConstantRange(APInt::getMinValue(BitWidth), |
| 4461 | APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); |
| 4462 | else |
| 4463 | ConservativeResult = ConstantRange( |
| 4464 | APInt::getSignedMinValue(BitWidth), |
| 4465 | APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); |
| 4466 | } |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4467 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4468 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4469 | ConstantRange X = getRange(Add->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4470 | for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4471 | X = X.add(getRange(Add->getOperand(i), SignHint)); |
| 4472 | return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4473 | } |
| 4474 | |
| 4475 | if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4476 | ConstantRange X = getRange(Mul->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4477 | for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4478 | X = X.multiply(getRange(Mul->getOperand(i), SignHint)); |
| 4479 | return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4480 | } |
| 4481 | |
| 4482 | if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4483 | ConstantRange X = getRange(SMax->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4484 | for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4485 | X = X.smax(getRange(SMax->getOperand(i), SignHint)); |
| 4486 | return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4487 | } |
| 4488 | |
| 4489 | if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4490 | ConstantRange X = getRange(UMax->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4491 | for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4492 | X = X.umax(getRange(UMax->getOperand(i), SignHint)); |
| 4493 | return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4494 | } |
| 4495 | |
| 4496 | if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4497 | ConstantRange X = getRange(UDiv->getLHS(), SignHint); |
| 4498 | ConstantRange Y = getRange(UDiv->getRHS(), SignHint); |
| 4499 | return setRange(UDiv, SignHint, |
| 4500 | ConservativeResult.intersectWith(X.udiv(Y))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4501 | } |
| 4502 | |
| 4503 | if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4504 | ConstantRange X = getRange(ZExt->getOperand(), SignHint); |
| 4505 | return setRange(ZExt, SignHint, |
| 4506 | ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4507 | } |
| 4508 | |
| 4509 | if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4510 | ConstantRange X = getRange(SExt->getOperand(), SignHint); |
| 4511 | return setRange(SExt, SignHint, |
| 4512 | ConservativeResult.intersectWith(X.signExtend(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4513 | } |
| 4514 | |
| 4515 | if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4516 | ConstantRange X = getRange(Trunc->getOperand(), SignHint); |
| 4517 | return setRange(Trunc, SignHint, |
| 4518 | ConservativeResult.intersectWith(X.truncate(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4519 | } |
| 4520 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4521 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4522 | // If there's no unsigned wrap, the value will never be less than its |
| 4523 | // initial value. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 4524 | if (AddRec->hasNoUnsignedWrap()) |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4525 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 4526 | if (!C->getValue()->isZero()) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 4527 | ConservativeResult = ConservativeResult.intersectWith( |
| 4528 | ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4529 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4530 | // If there's no signed wrap, and all the operands have the same sign or |
| 4531 | // zero, the value won't ever change sign. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 4532 | if (AddRec->hasNoSignedWrap()) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4533 | bool AllNonNeg = true; |
| 4534 | bool AllNonPos = true; |
| 4535 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { |
| 4536 | if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; |
| 4537 | if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; |
| 4538 | } |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4539 | if (AllNonNeg) |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 4540 | ConservativeResult = ConservativeResult.intersectWith( |
| 4541 | ConstantRange(APInt(BitWidth, 0), |
| 4542 | APInt::getSignedMinValue(BitWidth))); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4543 | else if (AllNonPos) |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 4544 | ConservativeResult = ConservativeResult.intersectWith( |
| 4545 | ConstantRange(APInt::getSignedMinValue(BitWidth), |
| 4546 | APInt(BitWidth, 1))); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4547 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4548 | |
| 4549 | // TODO: non-affine addrec |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4550 | if (AddRec->isAffine()) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4551 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4552 | if (!isa<SCEVCouldNotCompute>(MaxBECount) && |
| 4553 | getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { |
Sanjoy Das | b765b63 | 2016-03-02 00:57:39 +0000 | [diff] [blame] | 4554 | auto RangeFromAffine = getRangeForAffineAR( |
| 4555 | AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, |
| 4556 | BitWidth); |
| 4557 | if (!RangeFromAffine.isFullSet()) |
| 4558 | ConservativeResult = |
| 4559 | ConservativeResult.intersectWith(RangeFromAffine); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4560 | |
| 4561 | auto RangeFromFactoring = getRangeViaFactoring( |
| 4562 | AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, |
| 4563 | BitWidth); |
| 4564 | if (!RangeFromFactoring.isFullSet()) |
| 4565 | ConservativeResult = |
| 4566 | ConservativeResult.intersectWith(RangeFromFactoring); |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4567 | } |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4568 | } |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4569 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4570 | return setRange(AddRec, SignHint, ConservativeResult); |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4571 | } |
| 4572 | |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4573 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 4574 | // Check if the IR explicitly contains !range metadata. |
| 4575 | Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); |
| 4576 | if (MDRange.hasValue()) |
| 4577 | ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); |
| 4578 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4579 | // Split here to avoid paying the compile-time cost of calling both |
| 4580 | // computeKnownBits and ComputeNumSignBits. This restriction can be lifted |
| 4581 | // if needed. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 4582 | const DataLayout &DL = getDataLayout(); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4583 | if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { |
| 4584 | // For a SCEVUnknown, ask ValueTracking. |
| 4585 | APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4586 | computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4587 | if (Ones != ~Zeros + 1) |
| 4588 | ConservativeResult = |
| 4589 | ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)); |
| 4590 | } else { |
| 4591 | assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && |
| 4592 | "generalize as needed!"); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4593 | unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4594 | if (NS > 1) |
| 4595 | ConservativeResult = ConservativeResult.intersectWith( |
| 4596 | ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), |
| 4597 | APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4598 | } |
| 4599 | |
| 4600 | return setRange(U, SignHint, ConservativeResult); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4601 | } |
| 4602 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4603 | return setRange(S, SignHint, ConservativeResult); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4604 | } |
| 4605 | |
Sanjoy Das | b765b63 | 2016-03-02 00:57:39 +0000 | [diff] [blame] | 4606 | ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, |
| 4607 | const SCEV *Step, |
| 4608 | const SCEV *MaxBECount, |
| 4609 | unsigned BitWidth) { |
| 4610 | assert(!isa<SCEVCouldNotCompute>(MaxBECount) && |
| 4611 | getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && |
| 4612 | "Precondition!"); |
| 4613 | |
| 4614 | ConstantRange Result(BitWidth, /* isFullSet = */ true); |
| 4615 | |
| 4616 | // Check for overflow. This must be done with ConstantRange arithmetic |
| 4617 | // because we could be called from within the ScalarEvolution overflow |
| 4618 | // checking code. |
| 4619 | |
| 4620 | MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); |
| 4621 | ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); |
| 4622 | ConstantRange ZExtMaxBECountRange = |
| 4623 | MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1); |
| 4624 | |
| 4625 | ConstantRange StepSRange = getSignedRange(Step); |
| 4626 | ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1); |
| 4627 | |
| 4628 | ConstantRange StartURange = getUnsignedRange(Start); |
| 4629 | ConstantRange EndURange = |
| 4630 | StartURange.add(MaxBECountRange.multiply(StepSRange)); |
| 4631 | |
| 4632 | // Check for unsigned overflow. |
| 4633 | ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1); |
| 4634 | ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1); |
| 4635 | if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == |
| 4636 | ZExtEndURange) { |
| 4637 | APInt Min = APIntOps::umin(StartURange.getUnsignedMin(), |
| 4638 | EndURange.getUnsignedMin()); |
| 4639 | APInt Max = APIntOps::umax(StartURange.getUnsignedMax(), |
| 4640 | EndURange.getUnsignedMax()); |
| 4641 | bool IsFullRange = Min.isMinValue() && Max.isMaxValue(); |
| 4642 | if (!IsFullRange) |
| 4643 | Result = |
| 4644 | Result.intersectWith(ConstantRange(Min, Max + 1)); |
| 4645 | } |
| 4646 | |
| 4647 | ConstantRange StartSRange = getSignedRange(Start); |
| 4648 | ConstantRange EndSRange = |
| 4649 | StartSRange.add(MaxBECountRange.multiply(StepSRange)); |
| 4650 | |
| 4651 | // Check for signed overflow. This must be done with ConstantRange |
| 4652 | // arithmetic because we could be called from within the ScalarEvolution |
| 4653 | // overflow checking code. |
| 4654 | ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1); |
| 4655 | ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1); |
| 4656 | if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == |
| 4657 | SExtEndSRange) { |
| 4658 | APInt Min = |
| 4659 | APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin()); |
| 4660 | APInt Max = |
| 4661 | APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax()); |
| 4662 | bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue(); |
| 4663 | if (!IsFullRange) |
| 4664 | Result = |
| 4665 | Result.intersectWith(ConstantRange(Min, Max + 1)); |
| 4666 | } |
| 4667 | |
| 4668 | return Result; |
| 4669 | } |
| 4670 | |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4671 | ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, |
| 4672 | const SCEV *Step, |
| 4673 | const SCEV *MaxBECount, |
| 4674 | unsigned BitWidth) { |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4675 | // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) |
| 4676 | // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) |
| 4677 | |
| 4678 | struct SelectPattern { |
| 4679 | Value *Condition = nullptr; |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4680 | APInt TrueValue; |
| 4681 | APInt FalseValue; |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4682 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4683 | explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, |
| 4684 | const SCEV *S) { |
| 4685 | Optional<unsigned> CastOp; |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4686 | APInt Offset(BitWidth, 0); |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4687 | |
| 4688 | assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && |
| 4689 | "Should be!"); |
| 4690 | |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4691 | // Peel off a constant offset: |
| 4692 | if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { |
| 4693 | // In the future we could consider being smarter here and handle |
| 4694 | // {Start+Step,+,Step} too. |
| 4695 | if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) |
| 4696 | return; |
| 4697 | |
| 4698 | Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); |
| 4699 | S = SA->getOperand(1); |
| 4700 | } |
| 4701 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4702 | // Peel off a cast operation |
| 4703 | if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { |
| 4704 | CastOp = SCast->getSCEVType(); |
| 4705 | S = SCast->getOperand(); |
| 4706 | } |
| 4707 | |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4708 | using namespace llvm::PatternMatch; |
| 4709 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4710 | auto *SU = dyn_cast<SCEVUnknown>(S); |
| 4711 | const APInt *TrueVal, *FalseVal; |
| 4712 | if (!SU || |
| 4713 | !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), |
| 4714 | m_APInt(FalseVal)))) { |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4715 | Condition = nullptr; |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4716 | return; |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4717 | } |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4718 | |
| 4719 | TrueValue = *TrueVal; |
| 4720 | FalseValue = *FalseVal; |
| 4721 | |
| 4722 | // Re-apply the cast we peeled off earlier |
| 4723 | if (CastOp.hasValue()) |
| 4724 | switch (*CastOp) { |
| 4725 | default: |
| 4726 | llvm_unreachable("Unknown SCEV cast type!"); |
| 4727 | |
| 4728 | case scTruncate: |
| 4729 | TrueValue = TrueValue.trunc(BitWidth); |
| 4730 | FalseValue = FalseValue.trunc(BitWidth); |
| 4731 | break; |
| 4732 | case scZeroExtend: |
| 4733 | TrueValue = TrueValue.zext(BitWidth); |
| 4734 | FalseValue = FalseValue.zext(BitWidth); |
| 4735 | break; |
| 4736 | case scSignExtend: |
| 4737 | TrueValue = TrueValue.sext(BitWidth); |
| 4738 | FalseValue = FalseValue.sext(BitWidth); |
| 4739 | break; |
| 4740 | } |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4741 | |
| 4742 | // Re-apply the constant offset we peeled off earlier |
| 4743 | TrueValue += Offset; |
| 4744 | FalseValue += Offset; |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4745 | } |
| 4746 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4747 | bool isRecognized() { return Condition != nullptr; } |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4748 | }; |
| 4749 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4750 | SelectPattern StartPattern(*this, BitWidth, Start); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4751 | if (!StartPattern.isRecognized()) |
| 4752 | return ConstantRange(BitWidth, /* isFullSet = */ true); |
| 4753 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4754 | SelectPattern StepPattern(*this, BitWidth, Step); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4755 | if (!StepPattern.isRecognized()) |
| 4756 | return ConstantRange(BitWidth, /* isFullSet = */ true); |
| 4757 | |
| 4758 | if (StartPattern.Condition != StepPattern.Condition) { |
| 4759 | // We don't handle this case today; but we could, by considering four |
| 4760 | // possibilities below instead of two. I'm not sure if there are cases where |
| 4761 | // that will help over what getRange already does, though. |
| 4762 | return ConstantRange(BitWidth, /* isFullSet = */ true); |
| 4763 | } |
| 4764 | |
| 4765 | // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to |
| 4766 | // construct arbitrary general SCEV expressions here. This function is called |
| 4767 | // from deep in the call stack, and calling getSCEV (on a sext instruction, |
| 4768 | // say) can end up caching a suboptimal value. |
| 4769 | |
Sanjoy Das | 6b017a1 | 2016-03-02 02:56:29 +0000 | [diff] [blame] | 4770 | // FIXME: without the explicit `this` receiver below, MSVC errors out with |
| 4771 | // C2352 and C2512 (otherwise it isn't needed). |
| 4772 | |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4773 | const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4774 | const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4775 | const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4776 | const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); |
Sanjoy Das | 62a1c33 | 2016-03-02 02:15:42 +0000 | [diff] [blame] | 4777 | |
Sanjoy Das | 1168f93 | 2016-03-02 02:34:20 +0000 | [diff] [blame] | 4778 | ConstantRange TrueRange = |
Sanjoy Das | eca1b53 | 2016-03-02 02:44:08 +0000 | [diff] [blame] | 4779 | this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); |
Sanjoy Das | 1168f93 | 2016-03-02 02:34:20 +0000 | [diff] [blame] | 4780 | ConstantRange FalseRange = |
Sanjoy Das | eca1b53 | 2016-03-02 02:44:08 +0000 | [diff] [blame] | 4781 | this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4782 | |
| 4783 | return TrueRange.unionWith(FalseRange); |
| 4784 | } |
| 4785 | |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4786 | SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4787 | if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4788 | const BinaryOperator *BinOp = cast<BinaryOperator>(V); |
| 4789 | |
| 4790 | // Return early if there are no flags to propagate to the SCEV. |
| 4791 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
| 4792 | if (BinOp->hasNoUnsignedWrap()) |
| 4793 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); |
| 4794 | if (BinOp->hasNoSignedWrap()) |
| 4795 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); |
Sanjoy Das | dcd3a88 | 2016-03-02 04:52:22 +0000 | [diff] [blame] | 4796 | if (Flags == SCEV::FlagAnyWrap) |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4797 | return SCEV::FlagAnyWrap; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4798 | |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4799 | return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; |
| 4800 | } |
| 4801 | |
| 4802 | bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { |
| 4803 | // Here we check that I is in the header of the innermost loop containing I, |
| 4804 | // since we only deal with instructions in the loop header. The actual loop we |
| 4805 | // need to check later will come from an add recurrence, but getting that |
| 4806 | // requires computing the SCEV of the operands, which can be expensive. This |
| 4807 | // check we can do cheaply to rule out some cases early. |
| 4808 | Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); |
Sanjoy Das | dcd3a88 | 2016-03-02 04:52:22 +0000 | [diff] [blame] | 4809 | if (InnermostContainingLoop == nullptr || |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4810 | InnermostContainingLoop->getHeader() != I->getParent()) |
| 4811 | return false; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4812 | |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4813 | // Only proceed if we can prove that I does not yield poison. |
| 4814 | if (!isKnownNotFullPoison(I)) return false; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4815 | |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4816 | // At this point we know that if I is executed, then it does not wrap |
| 4817 | // according to at least one of NSW or NUW. If I is not executed, then we do |
| 4818 | // not know if the calculation that I represents would wrap. Multiple |
| 4819 | // instructions can map to the same SCEV. If we apply NSW or NUW from I to |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4820 | // the SCEV, we must guarantee no wrapping for that SCEV also when it is |
| 4821 | // derived from other instructions that map to the same SCEV. We cannot make |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4822 | // that guarantee for cases where I is not executed. So we need to find the |
| 4823 | // loop that I is considered in relation to and prove that I is executed for |
| 4824 | // every iteration of that loop. That implies that the value that I |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4825 | // calculates does not wrap anywhere in the loop, so then we can apply the |
| 4826 | // flags to the SCEV. |
| 4827 | // |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4828 | // We check isLoopInvariant to disambiguate in case we are adding recurrences |
| 4829 | // from different loops, so that we know which loop to prove that I is |
| 4830 | // executed in. |
| 4831 | for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { |
| 4832 | const SCEV *Op = getSCEV(I->getOperand(OpIndex)); |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4833 | if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4834 | bool AllOtherOpsLoopInvariant = true; |
| 4835 | for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); |
| 4836 | ++OtherOpIndex) { |
| 4837 | if (OtherOpIndex != OpIndex) { |
| 4838 | const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); |
| 4839 | if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { |
| 4840 | AllOtherOpsLoopInvariant = false; |
| 4841 | break; |
| 4842 | } |
| 4843 | } |
| 4844 | } |
| 4845 | if (AllOtherOpsLoopInvariant && |
| 4846 | isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) |
| 4847 | return true; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4848 | } |
| 4849 | } |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4850 | return false; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4851 | } |
| 4852 | |
| 4853 | /// createSCEV - We know that there is no SCEV for the specified value. Analyze |
| 4854 | /// the expression. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4855 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4856 | const SCEV *ScalarEvolution::createSCEV(Value *V) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 4857 | if (!isSCEVable(V->getType())) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4858 | return getUnknown(V); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 4859 | |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 4860 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 4861 | // Don't attempt to analyze instructions in blocks that aren't |
| 4862 | // reachable. Such instructions don't matter, and they aren't required |
| 4863 | // to obey basic rules for definitions dominating uses which this |
| 4864 | // analysis depends on. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4865 | if (!DT.isReachableFromEntry(I->getParent())) |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 4866 | return getUnknown(V); |
Sanjoy Das | 260ad4d | 2016-03-29 16:40:39 +0000 | [diff] [blame] | 4867 | } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) |
Dan Gohman | f436bac | 2009-06-24 00:54:57 +0000 | [diff] [blame] | 4868 | return getConstant(CI); |
| 4869 | else if (isa<ConstantPointerNull>(V)) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 4870 | return getZero(V->getType()); |
Dan Gohman | f161e06e | 2009-08-25 17:49:57 +0000 | [diff] [blame] | 4871 | else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) |
Sanjoy Das | 5ce3272 | 2016-04-08 00:48:30 +0000 | [diff] [blame] | 4872 | return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); |
Sanjoy Das | 260ad4d | 2016-03-29 16:40:39 +0000 | [diff] [blame] | 4873 | else if (!isa<ConstantExpr>(V)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4874 | return getUnknown(V); |
Chris Lattner | a3e0bb4 | 2007-04-02 05:41:38 +0000 | [diff] [blame] | 4875 | |
Dan Gohman | 80ca01c | 2009-07-17 20:47:02 +0000 | [diff] [blame] | 4876 | Operator *U = cast<Operator>(V); |
Sanjoy Das | f9d88e6 | 2016-04-11 15:26:18 +0000 | [diff] [blame] | 4877 | if (auto BO = MatchBinaryOp(U)) { |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 4878 | switch (BO->Opcode) { |
| 4879 | case Instruction::Add: { |
| 4880 | // The simple thing to do would be to just call getSCEV on both operands |
| 4881 | // and call getAddExpr with the result. However if we're looking at a |
| 4882 | // bunch of things all added together, this can be quite inefficient, |
| 4883 | // because it leads to N-1 getAddExpr calls for N ultimate operands. |
| 4884 | // Instead, gather up all the operands and make a single getAddExpr call. |
| 4885 | // LLVM IR canonical form means we need only traverse the left operands. |
| 4886 | SmallVector<const SCEV *, 4> AddOps; |
| 4887 | do { |
| 4888 | if (BO->Op) { |
| 4889 | if (auto *OpSCEV = getExistingSCEV(BO->Op)) { |
| 4890 | AddOps.push_back(OpSCEV); |
| 4891 | break; |
| 4892 | } |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4893 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 4894 | // If a NUW or NSW flag can be applied to the SCEV for this |
| 4895 | // addition, then compute the SCEV for this addition by itself |
| 4896 | // with a separate call to getAddExpr. We need to do that |
| 4897 | // instead of pushing the operands of the addition onto AddOps, |
| 4898 | // since the flags are only known to apply to this particular |
| 4899 | // addition - they may not apply to other additions that can be |
| 4900 | // formed with operands from AddOps. |
| 4901 | const SCEV *RHS = getSCEV(BO->RHS); |
| 4902 | SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); |
| 4903 | if (Flags != SCEV::FlagAnyWrap) { |
| 4904 | const SCEV *LHS = getSCEV(BO->LHS); |
| 4905 | if (BO->Opcode == Instruction::Sub) |
| 4906 | AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); |
| 4907 | else |
| 4908 | AddOps.push_back(getAddExpr(LHS, RHS, Flags)); |
| 4909 | break; |
| 4910 | } |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 4911 | } |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 4912 | |
| 4913 | if (BO->Opcode == Instruction::Sub) |
| 4914 | AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); |
| 4915 | else |
| 4916 | AddOps.push_back(getSCEV(BO->RHS)); |
| 4917 | |
Sanjoy Das | f9d88e6 | 2016-04-11 15:26:18 +0000 | [diff] [blame] | 4918 | auto NewBO = MatchBinaryOp(BO->LHS); |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 4919 | if (!NewBO || (NewBO->Opcode != Instruction::Add && |
| 4920 | NewBO->Opcode != Instruction::Sub)) { |
| 4921 | AddOps.push_back(getSCEV(BO->LHS)); |
| 4922 | break; |
| 4923 | } |
| 4924 | BO = NewBO; |
| 4925 | } while (true); |
| 4926 | |
| 4927 | return getAddExpr(AddOps); |
| 4928 | } |
| 4929 | |
| 4930 | case Instruction::Mul: { |
| 4931 | SmallVector<const SCEV *, 4> MulOps; |
| 4932 | do { |
| 4933 | if (BO->Op) { |
| 4934 | if (auto *OpSCEV = getExistingSCEV(BO->Op)) { |
| 4935 | MulOps.push_back(OpSCEV); |
| 4936 | break; |
| 4937 | } |
| 4938 | |
| 4939 | SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); |
| 4940 | if (Flags != SCEV::FlagAnyWrap) { |
| 4941 | MulOps.push_back( |
| 4942 | getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); |
| 4943 | break; |
| 4944 | } |
| 4945 | } |
| 4946 | |
| 4947 | MulOps.push_back(getSCEV(BO->RHS)); |
Sanjoy Das | f9d88e6 | 2016-04-11 15:26:18 +0000 | [diff] [blame] | 4948 | auto NewBO = MatchBinaryOp(BO->LHS); |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 4949 | if (!NewBO || NewBO->Opcode != Instruction::Mul) { |
| 4950 | MulOps.push_back(getSCEV(BO->LHS)); |
| 4951 | break; |
| 4952 | } |
| 4953 | BO = NewBO; |
| 4954 | } while (true); |
| 4955 | |
| 4956 | return getMulExpr(MulOps); |
| 4957 | } |
| 4958 | case Instruction::UDiv: |
| 4959 | return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); |
| 4960 | case Instruction::Sub: { |
| 4961 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
| 4962 | if (BO->Op) |
| 4963 | Flags = getNoWrapFlagsFromUB(BO->Op); |
| 4964 | return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); |
| 4965 | } |
| 4966 | case Instruction::And: |
| 4967 | // For an expression like x&255 that merely masks off the high bits, |
| 4968 | // use zext(trunc(x)) as the SCEV expression. |
| 4969 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { |
| 4970 | if (CI->isNullValue()) |
| 4971 | return getSCEV(BO->RHS); |
| 4972 | if (CI->isAllOnesValue()) |
| 4973 | return getSCEV(BO->LHS); |
| 4974 | const APInt &A = CI->getValue(); |
| 4975 | |
| 4976 | // Instcombine's ShrinkDemandedConstant may strip bits out of |
| 4977 | // constants, obscuring what would otherwise be a low-bits mask. |
| 4978 | // Use computeKnownBits to compute what ShrinkDemandedConstant |
| 4979 | // knew about to reconstruct a low-bits mask value. |
| 4980 | unsigned LZ = A.countLeadingZeros(); |
| 4981 | unsigned TZ = A.countTrailingZeros(); |
| 4982 | unsigned BitWidth = A.getBitWidth(); |
| 4983 | APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); |
| 4984 | computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(), |
| 4985 | 0, &AC, nullptr, &DT); |
| 4986 | |
| 4987 | APInt EffectiveMask = |
| 4988 | APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); |
| 4989 | if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) { |
| 4990 | const SCEV *MulCount = getConstant(ConstantInt::get( |
| 4991 | getContext(), APInt::getOneBitSet(BitWidth, TZ))); |
| 4992 | return getMulExpr( |
| 4993 | getZeroExtendExpr( |
| 4994 | getTruncateExpr( |
| 4995 | getUDivExactExpr(getSCEV(BO->LHS), MulCount), |
| 4996 | IntegerType::get(getContext(), BitWidth - LZ - TZ)), |
| 4997 | BO->LHS->getType()), |
| 4998 | MulCount); |
| 4999 | } |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 5000 | } |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5001 | break; |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 5002 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5003 | case Instruction::Or: |
| 5004 | // If the RHS of the Or is a constant, we may have something like: |
| 5005 | // X*4+1 which got turned into X*4|1. Handle this as an Add so loop |
| 5006 | // optimizations will transparently handle this case. |
| 5007 | // |
| 5008 | // In order for this transformation to be safe, the LHS must be of the |
| 5009 | // form X*(2^n) and the Or constant must be less than 2^n. |
| 5010 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { |
| 5011 | const SCEV *LHS = getSCEV(BO->LHS); |
| 5012 | const APInt &CIVal = CI->getValue(); |
| 5013 | if (GetMinTrailingZeros(LHS) >= |
| 5014 | (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { |
| 5015 | // Build a plain add SCEV. |
| 5016 | const SCEV *S = getAddExpr(LHS, getSCEV(CI)); |
| 5017 | // If the LHS of the add was an addrec and it has no-wrap flags, |
| 5018 | // transfer the no-wrap flags, since an or won't introduce a wrap. |
| 5019 | if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { |
| 5020 | const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); |
| 5021 | const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( |
| 5022 | OldAR->getNoWrapFlags()); |
| 5023 | } |
| 5024 | return S; |
| 5025 | } |
| 5026 | } |
| 5027 | break; |
Dan Gohman | 6350296e | 2009-05-18 16:29:04 +0000 | [diff] [blame] | 5028 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5029 | case Instruction::Xor: |
| 5030 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { |
| 5031 | // If the RHS of xor is -1, then this is a not operation. |
| 5032 | if (CI->isAllOnesValue()) |
| 5033 | return getNotSCEV(getSCEV(BO->LHS)); |
Dan Gohman | eddf771 | 2009-06-18 00:00:20 +0000 | [diff] [blame] | 5034 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5035 | // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. |
| 5036 | // This is a variant of the check for xor with -1, and it handles |
| 5037 | // the case where instcombine has trimmed non-demanded bits out |
| 5038 | // of an xor with -1. |
| 5039 | if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) |
| 5040 | if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) |
| 5041 | if (LBO->getOpcode() == Instruction::And && |
| 5042 | LCI->getValue() == CI->getValue()) |
| 5043 | if (const SCEVZeroExtendExpr *Z = |
| 5044 | dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { |
| 5045 | Type *UTy = BO->LHS->getType(); |
| 5046 | const SCEV *Z0 = Z->getOperand(); |
| 5047 | Type *Z0Ty = Z0->getType(); |
| 5048 | unsigned Z0TySize = getTypeSizeInBits(Z0Ty); |
Dan Gohman | eddf771 | 2009-06-18 00:00:20 +0000 | [diff] [blame] | 5049 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5050 | // If C is a low-bits mask, the zero extend is serving to |
| 5051 | // mask off the high bits. Complement the operand and |
| 5052 | // re-apply the zext. |
| 5053 | if (APIntOps::isMask(Z0TySize, CI->getValue())) |
| 5054 | return getZeroExtendExpr(getNotSCEV(Z0), UTy); |
| 5055 | |
| 5056 | // If C is a single bit, it may be in the sign-bit position |
| 5057 | // before the zero-extend. In this case, represent the xor |
| 5058 | // using an add, which is equivalent, and re-apply the zext. |
| 5059 | APInt Trunc = CI->getValue().trunc(Z0TySize); |
| 5060 | if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && |
| 5061 | Trunc.isSignBit()) |
| 5062 | return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), |
| 5063 | UTy); |
| 5064 | } |
| 5065 | } |
| 5066 | break; |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5067 | |
| 5068 | case Instruction::Shl: |
| 5069 | // Turn shift left of a constant amount into a multiply. |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5070 | if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { |
| 5071 | uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 5072 | |
| 5073 | // If the shift count is not less than the bitwidth, the result of |
| 5074 | // the shift is undefined. Don't try to analyze it, because the |
| 5075 | // resolution chosen here may differ from the resolution chosen in |
| 5076 | // other parts of the compiler. |
| 5077 | if (SA->getValue().uge(BitWidth)) |
| 5078 | break; |
| 5079 | |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 5080 | // It is currently not resolved how to interpret NSW for left |
| 5081 | // shift by BitWidth - 1, so we avoid applying flags in that |
| 5082 | // case. Remove this check (or this comment) once the situation |
| 5083 | // is resolved. See |
| 5084 | // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html |
| 5085 | // and http://reviews.llvm.org/D8890 . |
| 5086 | auto Flags = SCEV::FlagAnyWrap; |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5087 | if (BO->Op && SA->getValue().ult(BitWidth - 1)) |
| 5088 | Flags = getNoWrapFlagsFromUB(BO->Op); |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 5089 | |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 5090 | Constant *X = ConstantInt::get(getContext(), |
Benjamin Kramer | fc3ea6f | 2013-07-11 16:05:50 +0000 | [diff] [blame] | 5091 | APInt::getOneBitSet(BitWidth, SA->getZExtValue())); |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5092 | return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5093 | } |
| 5094 | break; |
| 5095 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5096 | case Instruction::AShr: |
| 5097 | // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. |
| 5098 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) |
| 5099 | if (Operator *L = dyn_cast<Operator>(BO->LHS)) |
| 5100 | if (L->getOpcode() == Instruction::Shl && |
| 5101 | L->getOperand(1) == BO->RHS) { |
| 5102 | uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType()); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 5103 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5104 | // If the shift count is not less than the bitwidth, the result of |
| 5105 | // the shift is undefined. Don't try to analyze it, because the |
| 5106 | // resolution chosen here may differ from the resolution chosen in |
| 5107 | // other parts of the compiler. |
| 5108 | if (CI->getValue().uge(BitWidth)) |
| 5109 | break; |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 5110 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5111 | uint64_t Amt = BitWidth - CI->getZExtValue(); |
| 5112 | if (Amt == BitWidth) |
| 5113 | return getSCEV(L->getOperand(0)); // shift by zero --> noop |
| 5114 | return getSignExtendExpr( |
| 5115 | getTruncateExpr(getSCEV(L->getOperand(0)), |
| 5116 | IntegerType::get(getContext(), Amt)), |
| 5117 | BO->LHS->getType()); |
| 5118 | } |
| 5119 | break; |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 5120 | } |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5121 | } |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 5122 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5123 | switch (U->getOpcode()) { |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5124 | case Instruction::Trunc: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5125 | return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5126 | |
| 5127 | case Instruction::ZExt: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5128 | return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5129 | |
| 5130 | case Instruction::SExt: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5131 | return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5132 | |
| 5133 | case Instruction::BitCast: |
| 5134 | // BitCasts are no-op casts so we just eliminate the cast. |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 5135 | if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5136 | return getSCEV(U->getOperand(0)); |
| 5137 | break; |
| 5138 | |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 5139 | // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can |
| 5140 | // lead to pointer expressions which cannot safely be expanded to GEPs, |
| 5141 | // because ScalarEvolution doesn't respect the GEP aliasing rules when |
| 5142 | // simplifying integer expressions. |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 5143 | |
Dan Gohman | ee750d1 | 2009-05-08 20:26:55 +0000 | [diff] [blame] | 5144 | case Instruction::GetElementPtr: |
Dan Gohman | b256ccf | 2009-12-18 02:09:29 +0000 | [diff] [blame] | 5145 | return createNodeForGEP(cast<GEPOperator>(U)); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 5146 | |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5147 | case Instruction::PHI: |
| 5148 | return createNodeForPHI(cast<PHINode>(U)); |
| 5149 | |
| 5150 | case Instruction::Select: |
Sanjoy Das | d067134 | 2015-10-02 19:39:59 +0000 | [diff] [blame] | 5151 | // U can also be a select constant expr, which let fall through. Since |
| 5152 | // createNodeForSelect only works for a condition that is an `ICmpInst`, and |
| 5153 | // constant expressions cannot have instructions as operands, we'd have |
| 5154 | // returned getUnknown for a select constant expressions anyway. |
| 5155 | if (isa<Instruction>(U)) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 5156 | return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), |
| 5157 | U->getOperand(1), U->getOperand(2)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5158 | } |
| 5159 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5160 | return getUnknown(V); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5161 | } |
| 5162 | |
| 5163 | |
| 5164 | |
| 5165 | //===----------------------------------------------------------------------===// |
| 5166 | // Iteration Count Computation Code |
| 5167 | // |
| 5168 | |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5169 | unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) { |
| 5170 | if (BasicBlock *ExitingBB = L->getExitingBlock()) |
| 5171 | return getSmallConstantTripCount(L, ExitingBB); |
| 5172 | |
| 5173 | // No trip count information for multiple exits. |
| 5174 | return 0; |
| 5175 | } |
| 5176 | |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5177 | /// getSmallConstantTripCount - Returns the maximum trip count of this loop as a |
Andrew Trick | e81211f | 2012-01-11 06:52:55 +0000 | [diff] [blame] | 5178 | /// normal unsigned value. Returns 0 if the trip count is unknown or not |
| 5179 | /// constant. Will also return 0 if the maximum trip count is very large (>= |
| 5180 | /// 2^32). |
| 5181 | /// |
| 5182 | /// This "trip count" assumes that control exits via ExitingBlock. More |
| 5183 | /// precisely, it is the number of times that control may reach ExitingBlock |
| 5184 | /// before taking the branch. For loops with multiple exits, it may not be the |
| 5185 | /// number times that the loop header executes because the loop may exit |
| 5186 | /// prematurely via another branch. |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5187 | unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L, |
| 5188 | BasicBlock *ExitingBlock) { |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5189 | assert(ExitingBlock && "Must pass a non-null exiting block!"); |
| 5190 | assert(L->isLoopExiting(ExitingBlock) && |
| 5191 | "Exiting block must actually branch out of the loop!"); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5192 | const SCEVConstant *ExitCount = |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5193 | dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5194 | if (!ExitCount) |
| 5195 | return 0; |
| 5196 | |
| 5197 | ConstantInt *ExitConst = ExitCount->getValue(); |
| 5198 | |
| 5199 | // Guard against huge trip counts. |
| 5200 | if (ExitConst->getValue().getActiveBits() > 32) |
| 5201 | return 0; |
| 5202 | |
| 5203 | // In case of integer overflow, this returns 0, which is correct. |
| 5204 | return ((unsigned)ExitConst->getZExtValue()) + 1; |
| 5205 | } |
| 5206 | |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5207 | unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) { |
| 5208 | if (BasicBlock *ExitingBB = L->getExitingBlock()) |
| 5209 | return getSmallConstantTripMultiple(L, ExitingBB); |
| 5210 | |
| 5211 | // No trip multiple information for multiple exits. |
| 5212 | return 0; |
| 5213 | } |
| 5214 | |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5215 | /// getSmallConstantTripMultiple - Returns the largest constant divisor of the |
| 5216 | /// trip count of this loop as a normal unsigned value, if possible. This |
| 5217 | /// means that the actual trip count is always a multiple of the returned |
| 5218 | /// value (don't forget the trip count could very well be zero as well!). |
| 5219 | /// |
| 5220 | /// Returns 1 if the trip count is unknown or not guaranteed to be the |
| 5221 | /// multiple of a constant (which is also the case if the trip count is simply |
| 5222 | /// constant, use getSmallConstantTripCount for that case), Will also return 1 |
| 5223 | /// if the trip count is very large (>= 2^32). |
Andrew Trick | e81211f | 2012-01-11 06:52:55 +0000 | [diff] [blame] | 5224 | /// |
| 5225 | /// As explained in the comments for getSmallConstantTripCount, this assumes |
| 5226 | /// that control exits the loop via ExitingBlock. |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5227 | unsigned |
| 5228 | ScalarEvolution::getSmallConstantTripMultiple(Loop *L, |
| 5229 | BasicBlock *ExitingBlock) { |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5230 | assert(ExitingBlock && "Must pass a non-null exiting block!"); |
| 5231 | assert(L->isLoopExiting(ExitingBlock) && |
| 5232 | "Exiting block must actually branch out of the loop!"); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5233 | const SCEV *ExitCount = getExitCount(L, ExitingBlock); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5234 | if (ExitCount == getCouldNotCompute()) |
| 5235 | return 1; |
| 5236 | |
| 5237 | // Get the trip count from the BE count by adding 1. |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 5238 | const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType())); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5239 | // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt |
| 5240 | // to factor simple cases. |
| 5241 | if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul)) |
| 5242 | TCMul = Mul->getOperand(0); |
| 5243 | |
| 5244 | const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul); |
| 5245 | if (!MulC) |
| 5246 | return 1; |
| 5247 | |
| 5248 | ConstantInt *Result = MulC->getValue(); |
| 5249 | |
Hal Finkel | 30bd934 | 2012-10-24 19:46:44 +0000 | [diff] [blame] | 5250 | // Guard against huge trip counts (this requires checking |
| 5251 | // for zero to handle the case where the trip count == -1 and the |
| 5252 | // addition wraps). |
| 5253 | if (!Result || Result->getValue().getActiveBits() > 32 || |
| 5254 | Result->getValue().getActiveBits() == 0) |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5255 | return 1; |
| 5256 | |
| 5257 | return (unsigned)Result->getZExtValue(); |
| 5258 | } |
| 5259 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5260 | // getExitCount - Get the expression for the number of loop iterations for which |
Andrew Trick | ee9143a | 2013-05-31 23:34:46 +0000 | [diff] [blame] | 5261 | // this loop is guaranteed not to exit via ExitingBlock. Otherwise return |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5262 | // SCEVCouldNotCompute. |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5263 | const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) { |
| 5264 | return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5265 | } |
| 5266 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5267 | const SCEV * |
| 5268 | ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, |
| 5269 | SCEVUnionPredicate &Preds) { |
| 5270 | return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); |
| 5271 | } |
| 5272 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 5273 | /// getBackedgeTakenCount - If the specified loop has a predictable |
| 5274 | /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute |
| 5275 | /// object. The backedge-taken count is the number of times the loop header |
| 5276 | /// will be branched to from within the loop. This is one less than the |
| 5277 | /// trip count of the loop, since it doesn't count the first iteration, |
| 5278 | /// when the header is branched to from outside the loop. |
| 5279 | /// |
| 5280 | /// Note that it is not valid to call this method on a loop without a |
| 5281 | /// loop-invariant backedge-taken count (see |
| 5282 | /// hasLoopInvariantBackedgeTakenCount). |
| 5283 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5284 | const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5285 | return getBackedgeTakenInfo(L).getExact(this); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5286 | } |
| 5287 | |
| 5288 | /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except |
| 5289 | /// return the least SCEV value that is known never to be less than the |
| 5290 | /// actual backedge taken count. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5291 | const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5292 | return getBackedgeTakenInfo(L).getMax(this); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5293 | } |
| 5294 | |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5295 | /// PushLoopPHIs - Push PHI nodes in the header of the given loop |
| 5296 | /// onto the given Worklist. |
| 5297 | static void |
| 5298 | PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { |
| 5299 | BasicBlock *Header = L->getHeader(); |
| 5300 | |
| 5301 | // Push all Loop-header PHIs onto the Worklist stack. |
| 5302 | for (BasicBlock::iterator I = Header->begin(); |
| 5303 | PHINode *PN = dyn_cast<PHINode>(I); ++I) |
| 5304 | Worklist.push_back(PN); |
| 5305 | } |
| 5306 | |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5307 | const ScalarEvolution::BackedgeTakenInfo & |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5308 | ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { |
| 5309 | auto &BTI = getBackedgeTakenInfo(L); |
| 5310 | if (BTI.hasFullInfo()) |
| 5311 | return BTI; |
| 5312 | |
| 5313 | auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); |
| 5314 | |
| 5315 | if (!Pair.second) |
| 5316 | return Pair.first->second; |
| 5317 | |
| 5318 | BackedgeTakenInfo Result = |
| 5319 | computeBackedgeTakenCount(L, /*AllowPredicates=*/true); |
| 5320 | |
| 5321 | return PredicatedBackedgeTakenCounts.find(L)->second = Result; |
| 5322 | } |
| 5323 | |
| 5324 | const ScalarEvolution::BackedgeTakenInfo & |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5325 | ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5326 | // Initially insert an invalid entry for this loop. If the insertion |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 5327 | // succeeds, proceed to actually compute a backedge-taken count and |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 5328 | // update the value. The temporary CouldNotCompute value tells SCEV |
| 5329 | // code elsewhere that it shouldn't attempt to request a new |
| 5330 | // backedge-taken count, which could result in infinite recursion. |
Dan Gohman | 0daf687 | 2011-05-09 18:44:09 +0000 | [diff] [blame] | 5331 | std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 5332 | BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5333 | if (!Pair.second) |
| 5334 | return Pair.first->second; |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 5335 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5336 | // computeBackedgeTakenCount may allocate memory for its result. Inserting it |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5337 | // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result |
| 5338 | // must be cleared in this scope. |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5339 | BackedgeTakenInfo Result = computeBackedgeTakenCount(L); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5340 | |
| 5341 | if (Result.getExact(this) != getCouldNotCompute()) { |
| 5342 | assert(isLoopInvariant(Result.getExact(this), L) && |
| 5343 | isLoopInvariant(Result.getMax(this), L) && |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5344 | "Computed backedge-taken count isn't loop invariant for loop!"); |
| 5345 | ++NumTripCountsComputed; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5346 | } |
| 5347 | else if (Result.getMax(this) == getCouldNotCompute() && |
| 5348 | isa<PHINode>(L->getHeader()->begin())) { |
| 5349 | // Only count loops that have phi nodes as not being computable. |
| 5350 | ++NumTripCountsNotComputed; |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5351 | } |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5352 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5353 | // Now that we know more about the trip count for this loop, forget any |
| 5354 | // existing SCEV values for PHI nodes in this loop since they are only |
| 5355 | // conservative estimates made without the benefit of trip count |
| 5356 | // information. This is similar to the code in forgetLoop, except that |
| 5357 | // it handles SCEVUnknown PHI nodes specially. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5358 | if (Result.hasAnyInfo()) { |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5359 | SmallVector<Instruction *, 16> Worklist; |
| 5360 | PushLoopPHIs(L, Worklist); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5361 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5362 | SmallPtrSet<Instruction *, 8> Visited; |
| 5363 | while (!Worklist.empty()) { |
| 5364 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5365 | if (!Visited.insert(I).second) |
| 5366 | continue; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5367 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5368 | ValueExprMapType::iterator It = |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 5369 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5370 | if (It != ValueExprMap.end()) { |
| 5371 | const SCEV *Old = It->second; |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 5372 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5373 | // SCEVUnknown for a PHI either means that it has an unrecognized |
| 5374 | // structure, or it's a PHI that's in the progress of being computed |
| 5375 | // by createNodeForPHI. In the former case, additional loop trip |
| 5376 | // count information isn't going to change anything. In the later |
| 5377 | // case, createNodeForPHI will perform the necessary updates on its |
| 5378 | // own when it gets to that point. |
| 5379 | if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { |
| 5380 | forgetMemoizedResults(Old); |
| 5381 | ValueExprMap.erase(It); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5382 | } |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5383 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5384 | ConstantEvolutionLoopExitValue.erase(PN); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5385 | } |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5386 | |
| 5387 | PushDefUseChildren(I, Worklist); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5388 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5389 | } |
Dan Gohman | 6acd95b | 2011-04-25 22:48:29 +0000 | [diff] [blame] | 5390 | |
| 5391 | // Re-lookup the insert position, since the call to |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5392 | // computeBackedgeTakenCount above could result in a |
Dan Gohman | 6acd95b | 2011-04-25 22:48:29 +0000 | [diff] [blame] | 5393 | // recusive call to getBackedgeTakenInfo (on a different |
| 5394 | // loop), which would invalidate the iterator computed |
| 5395 | // earlier. |
| 5396 | return BackedgeTakenCounts.find(L)->second = Result; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5397 | } |
| 5398 | |
Dan Gohman | 880c92a | 2009-10-31 15:04:55 +0000 | [diff] [blame] | 5399 | /// forgetLoop - This method should be called by the client when it has |
| 5400 | /// changed a loop in a way that may effect ScalarEvolution's ability to |
| 5401 | /// compute a trip count, or if the loop is deleted. |
| 5402 | void ScalarEvolution::forgetLoop(const Loop *L) { |
| 5403 | // Drop any stored trip count value. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5404 | auto RemoveLoopFromBackedgeMap = |
| 5405 | [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { |
| 5406 | auto BTCPos = Map.find(L); |
| 5407 | if (BTCPos != Map.end()) { |
| 5408 | BTCPos->second.clear(); |
| 5409 | Map.erase(BTCPos); |
| 5410 | } |
| 5411 | }; |
| 5412 | |
| 5413 | RemoveLoopFromBackedgeMap(BackedgeTakenCounts); |
| 5414 | RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts); |
Dan Gohman | f150572 | 2009-05-02 17:43:35 +0000 | [diff] [blame] | 5415 | |
Dan Gohman | 880c92a | 2009-10-31 15:04:55 +0000 | [diff] [blame] | 5416 | // Drop information about expressions based on loop-header PHIs. |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5417 | SmallVector<Instruction *, 16> Worklist; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5418 | PushLoopPHIs(L, Worklist); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5419 | |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5420 | SmallPtrSet<Instruction *, 8> Visited; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5421 | while (!Worklist.empty()) { |
| 5422 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5423 | if (!Visited.insert(I).second) |
| 5424 | continue; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5425 | |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 5426 | ValueExprMapType::iterator It = |
| 5427 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 5428 | if (It != ValueExprMap.end()) { |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 5429 | forgetMemoizedResults(It->second); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 5430 | ValueExprMap.erase(It); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5431 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5432 | ConstantEvolutionLoopExitValue.erase(PN); |
| 5433 | } |
| 5434 | |
| 5435 | PushDefUseChildren(I, Worklist); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5436 | } |
Dan Gohman | dcb354b | 2010-10-29 20:16:10 +0000 | [diff] [blame] | 5437 | |
| 5438 | // Forget all contained loops too, to avoid dangling entries in the |
| 5439 | // ValuesAtScopes map. |
| 5440 | for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) |
| 5441 | forgetLoop(*I); |
Dan Gohman | 4330034 | 2009-02-17 20:49:49 +0000 | [diff] [blame] | 5442 | } |
| 5443 | |
Eric Christopher | ef6d593 | 2010-07-29 01:25:38 +0000 | [diff] [blame] | 5444 | /// forgetValue - This method should be called by the client when it has |
| 5445 | /// changed a value in a way that may effect its value, or which may |
| 5446 | /// disconnect it from a def-use chain linking it to a loop. |
| 5447 | void ScalarEvolution::forgetValue(Value *V) { |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 5448 | Instruction *I = dyn_cast<Instruction>(V); |
| 5449 | if (!I) return; |
| 5450 | |
| 5451 | // Drop information about expressions based on loop-header PHIs. |
| 5452 | SmallVector<Instruction *, 16> Worklist; |
| 5453 | Worklist.push_back(I); |
| 5454 | |
| 5455 | SmallPtrSet<Instruction *, 8> Visited; |
| 5456 | while (!Worklist.empty()) { |
| 5457 | I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5458 | if (!Visited.insert(I).second) |
| 5459 | continue; |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 5460 | |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 5461 | ValueExprMapType::iterator It = |
| 5462 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 5463 | if (It != ValueExprMap.end()) { |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 5464 | forgetMemoizedResults(It->second); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 5465 | ValueExprMap.erase(It); |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 5466 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5467 | ConstantEvolutionLoopExitValue.erase(PN); |
| 5468 | } |
| 5469 | |
| 5470 | PushDefUseChildren(I, Worklist); |
| 5471 | } |
| 5472 | } |
| 5473 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5474 | /// getExact - Get the exact loop backedge taken count considering all loop |
Sanjoy Das | 135e5b9 | 2015-07-21 20:59:22 +0000 | [diff] [blame] | 5475 | /// exits. A computable result can only be returned for loops with a single |
| 5476 | /// exit. Returning the minimum taken count among all exits is incorrect |
| 5477 | /// because one of the loop's exit limit's may have been skipped. HowFarToZero |
| 5478 | /// assumes that the limit of each loop test is never skipped. This is a valid |
| 5479 | /// assumption as long as the loop exits via that test. For precise results, it |
| 5480 | /// is the caller's responsibility to specify the relevant loop exit using |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5481 | /// getExact(ExitingBlock, SE). |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5482 | const SCEV * |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5483 | ScalarEvolution::BackedgeTakenInfo::getExact( |
| 5484 | ScalarEvolution *SE, SCEVUnionPredicate *Preds) const { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5485 | // If any exits were not computable, the loop is not computable. |
| 5486 | if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute(); |
| 5487 | |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5488 | // We need exactly one computable exit. |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5489 | if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5490 | assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info"); |
| 5491 | |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5492 | const SCEV *BECount = nullptr; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5493 | for (auto &ENT : ExitNotTaken) { |
| 5494 | assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5495 | |
| 5496 | if (!BECount) |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5497 | BECount = ENT.ExactNotTaken; |
| 5498 | else if (BECount != ENT.ExactNotTaken) |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5499 | return SE->getCouldNotCompute(); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5500 | if (Preds && ENT.getPred()) |
| 5501 | Preds->add(ENT.getPred()); |
| 5502 | |
| 5503 | assert((Preds || ENT.hasAlwaysTruePred()) && |
| 5504 | "Predicate should be always true!"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5505 | } |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5506 | |
Andrew Trick | bbb226a | 2011-09-02 21:20:46 +0000 | [diff] [blame] | 5507 | assert(BECount && "Invalid not taken count for loop exit"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5508 | return BECount; |
| 5509 | } |
| 5510 | |
| 5511 | /// getExact - Get the exact not taken count for this loop exit. |
| 5512 | const SCEV * |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5513 | ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5514 | ScalarEvolution *SE) const { |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5515 | for (auto &ENT : ExitNotTaken) |
| 5516 | if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePred()) |
| 5517 | return ENT.ExactNotTaken; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5518 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5519 | return SE->getCouldNotCompute(); |
| 5520 | } |
| 5521 | |
| 5522 | /// getMax - Get the max backedge taken count for the loop. |
| 5523 | const SCEV * |
| 5524 | ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5525 | for (auto &ENT : ExitNotTaken) |
| 5526 | if (!ENT.hasAlwaysTruePred()) |
| 5527 | return SE->getCouldNotCompute(); |
| 5528 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5529 | return Max ? Max : SE->getCouldNotCompute(); |
| 5530 | } |
| 5531 | |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 5532 | bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, |
| 5533 | ScalarEvolution *SE) const { |
| 5534 | if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S)) |
| 5535 | return true; |
| 5536 | |
| 5537 | if (!ExitNotTaken.ExitingBlock) |
| 5538 | return false; |
| 5539 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5540 | for (auto &ENT : ExitNotTaken) |
| 5541 | if (ENT.ExactNotTaken != SE->getCouldNotCompute() && |
| 5542 | SE->hasOperand(ENT.ExactNotTaken, S)) |
Silviu Baranga | a393baf | 2016-04-06 14:06:32 +0000 | [diff] [blame] | 5543 | return true; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5544 | |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 5545 | return false; |
| 5546 | } |
| 5547 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5548 | /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each |
| 5549 | /// computable exit into a persistent ExitNotTakenInfo array. |
| 5550 | ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5551 | SmallVectorImpl<EdgeInfo> &ExitCounts, bool Complete, const SCEV *MaxCount) |
| 5552 | : Max(MaxCount) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5553 | |
| 5554 | if (!Complete) |
| 5555 | ExitNotTaken.setIncomplete(); |
| 5556 | |
| 5557 | unsigned NumExits = ExitCounts.size(); |
| 5558 | if (NumExits == 0) return; |
| 5559 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5560 | ExitNotTaken.ExitingBlock = ExitCounts[0].ExitBlock; |
| 5561 | ExitNotTaken.ExactNotTaken = ExitCounts[0].Taken; |
| 5562 | |
| 5563 | // Determine the number of ExitNotTakenExtras structures that we need. |
| 5564 | unsigned ExtraInfoSize = 0; |
| 5565 | if (NumExits > 1) |
| 5566 | ExtraInfoSize = 1 + std::count_if(std::next(ExitCounts.begin()), |
| 5567 | ExitCounts.end(), [](EdgeInfo &Entry) { |
| 5568 | return !Entry.Pred.isAlwaysTrue(); |
| 5569 | }); |
| 5570 | else if (!ExitCounts[0].Pred.isAlwaysTrue()) |
| 5571 | ExtraInfoSize = 1; |
| 5572 | |
| 5573 | ExitNotTakenExtras *ENT = nullptr; |
| 5574 | |
| 5575 | // Allocate the ExitNotTakenExtras structures and initialize the first |
| 5576 | // element (ExitNotTaken). |
| 5577 | if (ExtraInfoSize > 0) { |
| 5578 | ENT = new ExitNotTakenExtras[ExtraInfoSize]; |
| 5579 | ExitNotTaken.ExtraInfo = &ENT[0]; |
| 5580 | *ExitNotTaken.getPred() = std::move(ExitCounts[0].Pred); |
| 5581 | } |
| 5582 | |
| 5583 | if (NumExits == 1) |
| 5584 | return; |
| 5585 | |
Silviu Baranga | 24dbd2e | 2016-05-13 14:54:50 +0000 | [diff] [blame] | 5586 | assert(ENT && "ExitNotTakenExtras is NULL while having more than one exit"); |
| 5587 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5588 | auto &Exits = ExitNotTaken.ExtraInfo->Exits; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5589 | |
| 5590 | // Handle the rare case of multiple computable exits. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5591 | for (unsigned i = 1, PredPos = 1; i < NumExits; ++i) { |
| 5592 | ExitNotTakenExtras *Ptr = nullptr; |
| 5593 | if (!ExitCounts[i].Pred.isAlwaysTrue()) { |
| 5594 | Ptr = &ENT[PredPos++]; |
| 5595 | Ptr->Pred = std::move(ExitCounts[i].Pred); |
| 5596 | } |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5597 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5598 | Exits.emplace_back(ExitCounts[i].ExitBlock, ExitCounts[i].Taken, Ptr); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5599 | } |
| 5600 | } |
| 5601 | |
| 5602 | /// clear - Invalidate this result and free the ExitNotTakenInfo array. |
| 5603 | void ScalarEvolution::BackedgeTakenInfo::clear() { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5604 | ExitNotTaken.ExitingBlock = nullptr; |
| 5605 | ExitNotTaken.ExactNotTaken = nullptr; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5606 | delete[] ExitNotTaken.ExtraInfo; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5607 | } |
| 5608 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5609 | /// computeBackedgeTakenCount - Compute the number of times the backedge |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 5610 | /// of the specified loop will execute. |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5611 | ScalarEvolution::BackedgeTakenInfo |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5612 | ScalarEvolution::computeBackedgeTakenCount(const Loop *L, |
| 5613 | bool AllowPredicates) { |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 5614 | SmallVector<BasicBlock *, 8> ExitingBlocks; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5615 | L->getExitingBlocks(ExitingBlocks); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5616 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5617 | SmallVector<EdgeInfo, 4> ExitCounts; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5618 | bool CouldComputeBECount = true; |
Andrew Trick | ee5aa7f | 2014-01-15 06:42:11 +0000 | [diff] [blame] | 5619 | BasicBlock *Latch = L->getLoopLatch(); // may be NULL. |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5620 | const SCEV *MustExitMaxBECount = nullptr; |
| 5621 | const SCEV *MayExitMaxBECount = nullptr; |
| 5622 | |
| 5623 | // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts |
| 5624 | // and compute maxBECount. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5625 | // Do a union of all the predicates here. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5626 | for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5627 | BasicBlock *ExitBB = ExitingBlocks[i]; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5628 | ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); |
| 5629 | |
| 5630 | assert((AllowPredicates || EL.Pred.isAlwaysTrue()) && |
| 5631 | "Predicated exit limit when predicates are not allowed!"); |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5632 | |
| 5633 | // 1. For each exit that can be computed, add an entry to ExitCounts. |
| 5634 | // CouldComputeBECount is true only if all exits can be computed. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5635 | if (EL.Exact == getCouldNotCompute()) |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5636 | // We couldn't compute an exact value for this exit, so |
Dan Gohman | 8885b37 | 2009-06-22 21:10:22 +0000 | [diff] [blame] | 5637 | // we won't be able to compute an exact value for the loop. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5638 | CouldComputeBECount = false; |
| 5639 | else |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5640 | ExitCounts.emplace_back(EdgeInfo(ExitBB, EL.Exact, EL.Pred)); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5641 | |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5642 | // 2. Derive the loop's MaxBECount from each exit's max number of |
| 5643 | // non-exiting iterations. Partition the loop exits into two kinds: |
| 5644 | // LoopMustExits and LoopMayExits. |
| 5645 | // |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5646 | // If the exit dominates the loop latch, it is a LoopMustExit otherwise it |
| 5647 | // is a LoopMayExit. If any computable LoopMustExit is found, then |
| 5648 | // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise, |
| 5649 | // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is |
| 5650 | // considered greater than any computable EL.Max. |
| 5651 | if (EL.Max != getCouldNotCompute() && Latch && |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 5652 | DT.dominates(ExitBB, Latch)) { |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5653 | if (!MustExitMaxBECount) |
| 5654 | MustExitMaxBECount = EL.Max; |
| 5655 | else { |
| 5656 | MustExitMaxBECount = |
| 5657 | getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max); |
Andrew Trick | e255359 | 2014-05-22 00:37:03 +0000 | [diff] [blame] | 5658 | } |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5659 | } else if (MayExitMaxBECount != getCouldNotCompute()) { |
| 5660 | if (!MayExitMaxBECount || EL.Max == getCouldNotCompute()) |
| 5661 | MayExitMaxBECount = EL.Max; |
| 5662 | else { |
| 5663 | MayExitMaxBECount = |
| 5664 | getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max); |
| 5665 | } |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5666 | } |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5667 | } |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5668 | const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : |
| 5669 | (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5670 | return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5671 | } |
| 5672 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5673 | ScalarEvolution::ExitLimit |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5674 | ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, |
| 5675 | bool AllowPredicates) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5676 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5677 | // Okay, we've chosen an exiting block. See what condition causes us to exit |
| 5678 | // at this block and remember the exit block and whether all other targets |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5679 | // lead to the loop header. |
| 5680 | bool MustExecuteLoopHeader = true; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5681 | BasicBlock *Exit = nullptr; |
Sanjoy Das | 0ff0787 | 2016-01-19 20:53:46 +0000 | [diff] [blame] | 5682 | for (auto *SBB : successors(ExitingBlock)) |
| 5683 | if (!L->contains(SBB)) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5684 | if (Exit) // Multiple exit successors. |
| 5685 | return getCouldNotCompute(); |
Sanjoy Das | 0ff0787 | 2016-01-19 20:53:46 +0000 | [diff] [blame] | 5686 | Exit = SBB; |
| 5687 | } else if (SBB != L->getHeader()) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5688 | MustExecuteLoopHeader = false; |
| 5689 | } |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 5690 | |
Chris Lattner | 1895485 | 2007-01-07 02:24:26 +0000 | [diff] [blame] | 5691 | // At this point, we know we have a conditional branch that determines whether |
| 5692 | // the loop is exited. However, we don't know if the branch is executed each |
| 5693 | // time through the loop. If not, then the execution count of the branch will |
| 5694 | // not be equal to the trip count of the loop. |
| 5695 | // |
| 5696 | // Currently we check for this by checking to see if the Exit branch goes to |
| 5697 | // the loop header. If so, we know it will always execute the same number of |
Chris Lattner | 5a55476 | 2007-01-14 01:24:47 +0000 | [diff] [blame] | 5698 | // times as the loop. We also handle the case where the exit block *is* the |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5699 | // loop header. This is common for un-rotated loops. |
| 5700 | // |
| 5701 | // If both of those tests fail, walk up the unique predecessor chain to the |
| 5702 | // header, stopping if there is an edge that doesn't exit the loop. If the |
| 5703 | // header is reached, the execution count of the branch will be equal to the |
| 5704 | // trip count of the loop. |
| 5705 | // |
| 5706 | // More extensive analysis could be done to handle more cases here. |
| 5707 | // |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5708 | if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5709 | // The simple checks failed, try climbing the unique predecessor chain |
| 5710 | // up to the header. |
| 5711 | bool Ok = false; |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5712 | for (BasicBlock *BB = ExitingBlock; BB; ) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5713 | BasicBlock *Pred = BB->getUniquePredecessor(); |
| 5714 | if (!Pred) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5715 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5716 | TerminatorInst *PredTerm = Pred->getTerminator(); |
Pete Cooper | ebcd748 | 2015-08-06 20:22:46 +0000 | [diff] [blame] | 5717 | for (const BasicBlock *PredSucc : PredTerm->successors()) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5718 | if (PredSucc == BB) |
| 5719 | continue; |
| 5720 | // If the predecessor has a successor that isn't BB and isn't |
| 5721 | // outside the loop, assume the worst. |
| 5722 | if (L->contains(PredSucc)) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5723 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5724 | } |
| 5725 | if (Pred == L->getHeader()) { |
| 5726 | Ok = true; |
| 5727 | break; |
| 5728 | } |
| 5729 | BB = Pred; |
| 5730 | } |
| 5731 | if (!Ok) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5732 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5733 | } |
| 5734 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5735 | bool IsOnlyExit = (L->getExitingBlock() != nullptr); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5736 | TerminatorInst *Term = ExitingBlock->getTerminator(); |
| 5737 | if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { |
| 5738 | assert(BI->isConditional() && "If unconditional, it can't be in loop!"); |
| 5739 | // Proceed to the next level to examine the exit condition expression. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5740 | return computeExitLimitFromCond( |
| 5741 | L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), |
| 5742 | /*ControlsExit=*/IsOnlyExit, AllowPredicates); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5743 | } |
| 5744 | |
| 5745 | if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5746 | return computeExitLimitFromSingleExitSwitch(L, SI, Exit, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5747 | /*ControlsExit=*/IsOnlyExit); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5748 | |
| 5749 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5750 | } |
| 5751 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5752 | /// computeExitLimitFromCond - Compute the number of times the |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5753 | /// backedge of the specified loop will execute if its exit condition |
| 5754 | /// were a conditional branch of ExitCond, TBB, and FBB. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5755 | /// |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5756 | /// @param ControlsExit is true if ExitCond directly controls the exit |
| 5757 | /// branch. In this case, we can assume that the loop exits only if the |
| 5758 | /// condition is true and can infer that failing to meet the condition prior to |
| 5759 | /// integer wraparound results in undefined behavior. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5760 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5761 | ScalarEvolution::computeExitLimitFromCond(const Loop *L, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5762 | Value *ExitCond, |
| 5763 | BasicBlock *TBB, |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5764 | BasicBlock *FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5765 | bool ControlsExit, |
| 5766 | bool AllowPredicates) { |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 5767 | // Check if the controlling expression for this loop is an And or Or. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5768 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { |
| 5769 | if (BO->getOpcode() == Instruction::And) { |
| 5770 | // Recurse on the operands of the and. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5771 | bool EitherMayExit = L->contains(TBB); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5772 | ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5773 | ControlsExit && !EitherMayExit, |
| 5774 | AllowPredicates); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5775 | ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5776 | ControlsExit && !EitherMayExit, |
| 5777 | AllowPredicates); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5778 | const SCEV *BECount = getCouldNotCompute(); |
| 5779 | const SCEV *MaxBECount = getCouldNotCompute(); |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5780 | if (EitherMayExit) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5781 | // Both conditions must be true for the loop to continue executing. |
| 5782 | // Choose the less conservative count. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5783 | if (EL0.Exact == getCouldNotCompute() || |
| 5784 | EL1.Exact == getCouldNotCompute()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5785 | BECount = getCouldNotCompute(); |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5786 | else |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5787 | BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact); |
| 5788 | if (EL0.Max == getCouldNotCompute()) |
| 5789 | MaxBECount = EL1.Max; |
| 5790 | else if (EL1.Max == getCouldNotCompute()) |
| 5791 | MaxBECount = EL0.Max; |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5792 | else |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5793 | MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5794 | } else { |
Dan Gohman | f7495f2 | 2010-08-11 00:12:36 +0000 | [diff] [blame] | 5795 | // Both conditions must be true at the same time for the loop to exit. |
| 5796 | // For now, be conservative. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5797 | assert(L->contains(FBB) && "Loop block has no successor in loop!"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5798 | if (EL0.Max == EL1.Max) |
| 5799 | MaxBECount = EL0.Max; |
| 5800 | if (EL0.Exact == EL1.Exact) |
| 5801 | BECount = EL0.Exact; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5802 | } |
| 5803 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5804 | SCEVUnionPredicate NP; |
| 5805 | NP.add(&EL0.Pred); |
| 5806 | NP.add(&EL1.Pred); |
Sanjoy Das | 29a4b5d | 2016-01-19 20:53:51 +0000 | [diff] [blame] | 5807 | // There are cases (e.g. PR26207) where computeExitLimitFromCond is able |
| 5808 | // to be more aggressive when computing BECount than when computing |
| 5809 | // MaxBECount. In these cases it is possible for EL0.Exact and EL1.Exact |
| 5810 | // to match, but for EL0.Max and EL1.Max to not. |
| 5811 | if (isa<SCEVCouldNotCompute>(MaxBECount) && |
| 5812 | !isa<SCEVCouldNotCompute>(BECount)) |
| 5813 | MaxBECount = BECount; |
| 5814 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5815 | return ExitLimit(BECount, MaxBECount, NP); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5816 | } |
| 5817 | if (BO->getOpcode() == Instruction::Or) { |
| 5818 | // Recurse on the operands of the or. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5819 | bool EitherMayExit = L->contains(FBB); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5820 | ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5821 | ControlsExit && !EitherMayExit, |
| 5822 | AllowPredicates); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5823 | ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5824 | ControlsExit && !EitherMayExit, |
| 5825 | AllowPredicates); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5826 | const SCEV *BECount = getCouldNotCompute(); |
| 5827 | const SCEV *MaxBECount = getCouldNotCompute(); |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5828 | if (EitherMayExit) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5829 | // Both conditions must be false for the loop to continue executing. |
| 5830 | // Choose the less conservative count. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5831 | if (EL0.Exact == getCouldNotCompute() || |
| 5832 | EL1.Exact == getCouldNotCompute()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5833 | BECount = getCouldNotCompute(); |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5834 | else |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5835 | BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact); |
| 5836 | if (EL0.Max == getCouldNotCompute()) |
| 5837 | MaxBECount = EL1.Max; |
| 5838 | else if (EL1.Max == getCouldNotCompute()) |
| 5839 | MaxBECount = EL0.Max; |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5840 | else |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5841 | MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5842 | } else { |
Dan Gohman | f7495f2 | 2010-08-11 00:12:36 +0000 | [diff] [blame] | 5843 | // Both conditions must be false at the same time for the loop to exit. |
| 5844 | // For now, be conservative. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5845 | assert(L->contains(TBB) && "Loop block has no successor in loop!"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5846 | if (EL0.Max == EL1.Max) |
| 5847 | MaxBECount = EL0.Max; |
| 5848 | if (EL0.Exact == EL1.Exact) |
| 5849 | BECount = EL0.Exact; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5850 | } |
| 5851 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5852 | SCEVUnionPredicate NP; |
| 5853 | NP.add(&EL0.Pred); |
| 5854 | NP.add(&EL1.Pred); |
| 5855 | return ExitLimit(BECount, MaxBECount, NP); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5856 | } |
| 5857 | } |
| 5858 | |
| 5859 | // With an icmp, it may be feasible to compute an exact backedge-taken count. |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 5860 | // Proceed to the next level to examine the icmp. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5861 | if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { |
| 5862 | ExitLimit EL = |
| 5863 | computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); |
| 5864 | if (EL.hasFullInfo() || !AllowPredicates) |
| 5865 | return EL; |
| 5866 | |
| 5867 | // Try again, but use SCEV predicates this time. |
| 5868 | return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, |
| 5869 | /*AllowPredicates=*/true); |
| 5870 | } |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5871 | |
Dan Gohman | 6b1e2a8 | 2010-02-19 18:12:07 +0000 | [diff] [blame] | 5872 | // Check for a constant condition. These are normally stripped out by |
| 5873 | // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to |
| 5874 | // preserve the CFG and is temporarily leaving constant conditions |
| 5875 | // in place. |
| 5876 | if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { |
| 5877 | if (L->contains(FBB) == !CI->getZExtValue()) |
| 5878 | // The backedge is always taken. |
| 5879 | return getCouldNotCompute(); |
| 5880 | else |
| 5881 | // The backedge is never taken. |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 5882 | return getZero(CI->getType()); |
Dan Gohman | 6b1e2a8 | 2010-02-19 18:12:07 +0000 | [diff] [blame] | 5883 | } |
| 5884 | |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 5885 | // If it's not an integer or pointer comparison then compute it the hard way. |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5886 | return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5887 | } |
| 5888 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5889 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5890 | ScalarEvolution::computeExitLimitFromICmp(const Loop *L, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5891 | ICmpInst *ExitCond, |
| 5892 | BasicBlock *TBB, |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5893 | BasicBlock *FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5894 | bool ControlsExit, |
| 5895 | bool AllowPredicates) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5896 | |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5897 | // If the condition was exit on true, convert the condition to exit on false |
| 5898 | ICmpInst::Predicate Cond; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5899 | if (!L->contains(FBB)) |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5900 | Cond = ExitCond->getPredicate(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5901 | else |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5902 | Cond = ExitCond->getInversePredicate(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5903 | |
| 5904 | // Handle common loops like: for (X = "string"; *X; ++X) |
| 5905 | if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) |
| 5906 | if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5907 | ExitLimit ItCnt = |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5908 | computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); |
Dan Gohman | ba82034 | 2010-02-24 17:31:30 +0000 | [diff] [blame] | 5909 | if (ItCnt.hasAnyInfo()) |
| 5910 | return ItCnt; |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5911 | } |
| 5912 | |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 5913 | ExitLimit ShiftEL = computeShiftCompareExitLimit( |
| 5914 | ExitCond->getOperand(0), ExitCond->getOperand(1), L, Cond); |
| 5915 | if (ShiftEL.hasAnyInfo()) |
| 5916 | return ShiftEL; |
| 5917 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5918 | const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); |
| 5919 | const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5920 | |
| 5921 | // Try to evaluate any dependencies out of the loop. |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 5922 | LHS = getSCEVAtScope(LHS, L); |
| 5923 | RHS = getSCEVAtScope(RHS, L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5924 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 5925 | // At this point, we would like to compute how many iterations of the |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5926 | // loop the predicate will return true for these inputs. |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 5927 | if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { |
Dan Gohman | dc5f5cb | 2008-09-16 18:52:57 +0000 | [diff] [blame] | 5928 | // If there is a loop-invariant, force it into the RHS. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5929 | std::swap(LHS, RHS); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5930 | Cond = ICmpInst::getSwappedPredicate(Cond); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5931 | } |
| 5932 | |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 5933 | // Simplify the operands before analyzing them. |
| 5934 | (void)SimplifyICmpOperands(Cond, LHS, RHS); |
| 5935 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5936 | // If we have a comparison of a chrec against a constant, try to use value |
| 5937 | // ranges to answer this query. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 5938 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) |
| 5939 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5940 | if (AddRec->getLoop() == L) { |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 5941 | // Form the constant range. |
| 5942 | ConstantRange CompRange( |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 5943 | ICmpInst::makeConstantRange(Cond, RHSC->getAPInt())); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 5944 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5945 | const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 5946 | if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5947 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 5948 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5949 | switch (Cond) { |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5950 | case ICmpInst::ICMP_NE: { // while (X != Y) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5951 | // Convert to: while (X-Y != 0) |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5952 | ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, |
| 5953 | AllowPredicates); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5954 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5955 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5956 | } |
Dan Gohman | 8a8ad7d | 2009-08-20 16:42:55 +0000 | [diff] [blame] | 5957 | case ICmpInst::ICMP_EQ: { // while (X == Y) |
| 5958 | // Convert to: while (X-Y == 0) |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5959 | ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L); |
| 5960 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5961 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5962 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 5963 | case ICmpInst::ICMP_SLT: |
| 5964 | case ICmpInst::ICMP_ULT: { // while (X < Y) |
| 5965 | bool IsSigned = Cond == ICmpInst::ICMP_SLT; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5966 | ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, |
| 5967 | AllowPredicates); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5968 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 5969 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5970 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 5971 | case ICmpInst::ICMP_SGT: |
| 5972 | case ICmpInst::ICMP_UGT: { // while (X > Y) |
| 5973 | bool IsSigned = Cond == ICmpInst::ICMP_SGT; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5974 | ExitLimit EL = |
| 5975 | HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, |
| 5976 | AllowPredicates); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5977 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 5978 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5979 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5980 | default: |
Chris Lattner | 0defaa1 | 2004-04-03 00:43:03 +0000 | [diff] [blame] | 5981 | break; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5982 | } |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5983 | return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 5984 | } |
| 5985 | |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5986 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5987 | ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5988 | SwitchInst *Switch, |
| 5989 | BasicBlock *ExitingBlock, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5990 | bool ControlsExit) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5991 | assert(!L->contains(ExitingBlock) && "Not an exiting block!"); |
| 5992 | |
| 5993 | // Give up if the exit is the default dest of a switch. |
| 5994 | if (Switch->getDefaultDest() == ExitingBlock) |
| 5995 | return getCouldNotCompute(); |
| 5996 | |
| 5997 | assert(L->contains(Switch->getDefaultDest()) && |
| 5998 | "Default case must not exit the loop!"); |
| 5999 | const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); |
| 6000 | const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); |
| 6001 | |
| 6002 | // while (X != Y) --> while (X-Y != 0) |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 6003 | ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 6004 | if (EL.hasAnyInfo()) |
| 6005 | return EL; |
| 6006 | |
| 6007 | return getCouldNotCompute(); |
| 6008 | } |
| 6009 | |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6010 | static ConstantInt * |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 6011 | EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, |
| 6012 | ScalarEvolution &SE) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6013 | const SCEV *InVal = SE.getConstant(C); |
| 6014 | const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6015 | assert(isa<SCEVConstant>(Val) && |
| 6016 | "Evaluation of SCEV at constant didn't fold correctly?"); |
| 6017 | return cast<SCEVConstant>(Val)->getValue(); |
| 6018 | } |
| 6019 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 6020 | /// computeLoadConstantCompareExitLimit - Given an exit condition of |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6021 | /// 'icmp op load X, cst', try to see if we can compute the backedge |
| 6022 | /// execution count. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6023 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 6024 | ScalarEvolution::computeLoadConstantCompareExitLimit( |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6025 | LoadInst *LI, |
| 6026 | Constant *RHS, |
| 6027 | const Loop *L, |
| 6028 | ICmpInst::Predicate predicate) { |
| 6029 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6030 | if (LI->isVolatile()) return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6031 | |
| 6032 | // Check to see if the loaded pointer is a getelementptr of a global. |
Dan Gohman | ba82034 | 2010-02-24 17:31:30 +0000 | [diff] [blame] | 6033 | // TODO: Use SCEV instead of manually grubbing with GEPs. |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6034 | GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6035 | if (!GEP) return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6036 | |
| 6037 | // Make sure that it is really a constant global we are gepping, with an |
| 6038 | // initializer, and make sure the first IDX is really 0. |
| 6039 | GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); |
Dan Gohman | 5d5bc6d | 2009-08-19 18:20:44 +0000 | [diff] [blame] | 6040 | if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6041 | GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || |
| 6042 | !cast<Constant>(GEP->getOperand(1))->isNullValue()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6043 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6044 | |
| 6045 | // Okay, we allow one non-constant index into the GEP instruction. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6046 | Value *VarIdx = nullptr; |
Chris Lattner | e166a85 | 2012-01-24 05:49:24 +0000 | [diff] [blame] | 6047 | std::vector<Constant*> Indexes; |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6048 | unsigned VarIdxNum = 0; |
| 6049 | for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) |
| 6050 | if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { |
| 6051 | Indexes.push_back(CI); |
| 6052 | } else if (!isa<ConstantInt>(GEP->getOperand(i))) { |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6053 | if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6054 | VarIdx = GEP->getOperand(i); |
| 6055 | VarIdxNum = i-2; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6056 | Indexes.push_back(nullptr); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6057 | } |
| 6058 | |
Andrew Trick | 7004e4b | 2012-03-26 22:33:59 +0000 | [diff] [blame] | 6059 | // Loop-invariant loads may be a byproduct of loop optimization. Skip them. |
| 6060 | if (!VarIdx) |
| 6061 | return getCouldNotCompute(); |
| 6062 | |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6063 | // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. |
| 6064 | // Check to see if X is a loop variant variable value now. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6065 | const SCEV *Idx = getSCEV(VarIdx); |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 6066 | Idx = getSCEVAtScope(Idx, L); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6067 | |
| 6068 | // We can only recognize very limited forms of loop index expressions, in |
| 6069 | // particular, only affine AddRec's like {C1,+,C2}. |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6070 | const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 6071 | if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6072 | !isa<SCEVConstant>(IdxExpr->getOperand(0)) || |
| 6073 | !isa<SCEVConstant>(IdxExpr->getOperand(1))) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6074 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6075 | |
| 6076 | unsigned MaxSteps = MaxBruteForceIterations; |
| 6077 | for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 6078 | ConstantInt *ItCst = ConstantInt::get( |
Owen Anderson | b6b2530 | 2009-07-14 23:09:55 +0000 | [diff] [blame] | 6079 | cast<IntegerType>(IdxExpr->getType()), IterationNum); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6080 | ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6081 | |
| 6082 | // Form the GEP offset. |
| 6083 | Indexes[VarIdxNum] = Val; |
| 6084 | |
Chris Lattner | e166a85 | 2012-01-24 05:49:24 +0000 | [diff] [blame] | 6085 | Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), |
| 6086 | Indexes); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6087 | if (!Result) break; // Cannot compute! |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6088 | |
| 6089 | // Evaluate the condition for this iteration. |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6090 | Result = ConstantExpr::getICmp(predicate, Result, RHS); |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6091 | if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6092 | if (cast<ConstantInt>(Result)->getValue().isMinValue()) { |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6093 | ++NumArrayLenItCounts; |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6094 | return getConstant(ItCst); // Found terminating iteration! |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6095 | } |
| 6096 | } |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6097 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6098 | } |
| 6099 | |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 6100 | ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( |
| 6101 | Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { |
| 6102 | ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); |
| 6103 | if (!RHS) |
| 6104 | return getCouldNotCompute(); |
| 6105 | |
| 6106 | const BasicBlock *Latch = L->getLoopLatch(); |
| 6107 | if (!Latch) |
| 6108 | return getCouldNotCompute(); |
| 6109 | |
| 6110 | const BasicBlock *Predecessor = L->getLoopPredecessor(); |
| 6111 | if (!Predecessor) |
| 6112 | return getCouldNotCompute(); |
| 6113 | |
| 6114 | // Return true if V is of the form "LHS `shift_op` <positive constant>". |
| 6115 | // Return LHS in OutLHS and shift_opt in OutOpCode. |
| 6116 | auto MatchPositiveShift = |
| 6117 | [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { |
| 6118 | |
| 6119 | using namespace PatternMatch; |
| 6120 | |
| 6121 | ConstantInt *ShiftAmt; |
| 6122 | if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) |
| 6123 | OutOpCode = Instruction::LShr; |
| 6124 | else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) |
| 6125 | OutOpCode = Instruction::AShr; |
| 6126 | else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) |
| 6127 | OutOpCode = Instruction::Shl; |
| 6128 | else |
| 6129 | return false; |
| 6130 | |
| 6131 | return ShiftAmt->getValue().isStrictlyPositive(); |
| 6132 | }; |
| 6133 | |
| 6134 | // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in |
| 6135 | // |
| 6136 | // loop: |
| 6137 | // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] |
| 6138 | // %iv.shifted = lshr i32 %iv, <positive constant> |
| 6139 | // |
| 6140 | // Return true on a succesful match. Return the corresponding PHI node (%iv |
| 6141 | // above) in PNOut and the opcode of the shift operation in OpCodeOut. |
| 6142 | auto MatchShiftRecurrence = |
| 6143 | [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { |
| 6144 | Optional<Instruction::BinaryOps> PostShiftOpCode; |
| 6145 | |
| 6146 | { |
| 6147 | Instruction::BinaryOps OpC; |
| 6148 | Value *V; |
| 6149 | |
| 6150 | // If we encounter a shift instruction, "peel off" the shift operation, |
| 6151 | // and remember that we did so. Later when we inspect %iv's backedge |
| 6152 | // value, we will make sure that the backedge value uses the same |
| 6153 | // operation. |
| 6154 | // |
| 6155 | // Note: the peeled shift operation does not have to be the same |
| 6156 | // instruction as the one feeding into the PHI's backedge value. We only |
| 6157 | // really care about it being the same *kind* of shift instruction -- |
| 6158 | // that's all that is required for our later inferences to hold. |
| 6159 | if (MatchPositiveShift(LHS, V, OpC)) { |
| 6160 | PostShiftOpCode = OpC; |
| 6161 | LHS = V; |
| 6162 | } |
| 6163 | } |
| 6164 | |
| 6165 | PNOut = dyn_cast<PHINode>(LHS); |
| 6166 | if (!PNOut || PNOut->getParent() != L->getHeader()) |
| 6167 | return false; |
| 6168 | |
| 6169 | Value *BEValue = PNOut->getIncomingValueForBlock(Latch); |
| 6170 | Value *OpLHS; |
| 6171 | |
| 6172 | return |
| 6173 | // The backedge value for the PHI node must be a shift by a positive |
| 6174 | // amount |
| 6175 | MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && |
| 6176 | |
| 6177 | // of the PHI node itself |
| 6178 | OpLHS == PNOut && |
| 6179 | |
| 6180 | // and the kind of shift should be match the kind of shift we peeled |
| 6181 | // off, if any. |
| 6182 | (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); |
| 6183 | }; |
| 6184 | |
| 6185 | PHINode *PN; |
| 6186 | Instruction::BinaryOps OpCode; |
| 6187 | if (!MatchShiftRecurrence(LHS, PN, OpCode)) |
| 6188 | return getCouldNotCompute(); |
| 6189 | |
| 6190 | const DataLayout &DL = getDataLayout(); |
| 6191 | |
| 6192 | // The key rationale for this optimization is that for some kinds of shift |
| 6193 | // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 |
| 6194 | // within a finite number of iterations. If the condition guarding the |
| 6195 | // backedge (in the sense that the backedge is taken if the condition is true) |
| 6196 | // is false for the value the shift recurrence stabilizes to, then we know |
| 6197 | // that the backedge is taken only a finite number of times. |
| 6198 | |
| 6199 | ConstantInt *StableValue = nullptr; |
| 6200 | switch (OpCode) { |
| 6201 | default: |
| 6202 | llvm_unreachable("Impossible case!"); |
| 6203 | |
| 6204 | case Instruction::AShr: { |
| 6205 | // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most |
| 6206 | // bitwidth(K) iterations. |
| 6207 | Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); |
| 6208 | bool KnownZero, KnownOne; |
| 6209 | ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr, |
| 6210 | Predecessor->getTerminator(), &DT); |
| 6211 | auto *Ty = cast<IntegerType>(RHS->getType()); |
| 6212 | if (KnownZero) |
| 6213 | StableValue = ConstantInt::get(Ty, 0); |
| 6214 | else if (KnownOne) |
| 6215 | StableValue = ConstantInt::get(Ty, -1, true); |
| 6216 | else |
| 6217 | return getCouldNotCompute(); |
| 6218 | |
| 6219 | break; |
| 6220 | } |
| 6221 | case Instruction::LShr: |
| 6222 | case Instruction::Shl: |
| 6223 | // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} |
| 6224 | // stabilize to 0 in at most bitwidth(K) iterations. |
| 6225 | StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); |
| 6226 | break; |
| 6227 | } |
| 6228 | |
| 6229 | auto *Result = |
| 6230 | ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); |
| 6231 | assert(Result->getType()->isIntegerTy(1) && |
| 6232 | "Otherwise cannot be an operand to a branch instruction"); |
| 6233 | |
| 6234 | if (Result->isZeroValue()) { |
| 6235 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
| 6236 | const SCEV *UpperBound = |
| 6237 | getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 6238 | SCEVUnionPredicate P; |
| 6239 | return ExitLimit(getCouldNotCompute(), UpperBound, P); |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 6240 | } |
| 6241 | |
| 6242 | return getCouldNotCompute(); |
| 6243 | } |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6244 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6245 | /// CanConstantFold - Return true if we can constant fold an instruction of the |
| 6246 | /// specified type, assuming that all operands were constants. |
| 6247 | static bool CanConstantFold(const Instruction *I) { |
Reid Spencer | 2341c22 | 2007-02-02 02:16:23 +0000 | [diff] [blame] | 6248 | if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6249 | isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || |
| 6250 | isa<LoadInst>(I)) |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6251 | return true; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6252 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6253 | if (const CallInst *CI = dyn_cast<CallInst>(I)) |
| 6254 | if (const Function *F = CI->getCalledFunction()) |
Dan Gohman | a65951f | 2008-01-31 01:05:10 +0000 | [diff] [blame] | 6255 | return canConstantFoldCallTo(F); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6256 | return false; |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6257 | } |
| 6258 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6259 | /// Determine whether this instruction can constant evolve within this loop |
| 6260 | /// assuming its operands can all constant evolve. |
| 6261 | static bool canConstantEvolve(Instruction *I, const Loop *L) { |
| 6262 | // An instruction outside of the loop can't be derived from a loop PHI. |
| 6263 | if (!L->contains(I)) return false; |
| 6264 | |
| 6265 | if (isa<PHINode>(I)) { |
David Blaikie | 19ef0d3 | 2015-03-24 16:33:19 +0000 | [diff] [blame] | 6266 | // We don't currently keep track of the control flow needed to evaluate |
| 6267 | // PHIs, so we cannot handle PHIs inside of loops. |
| 6268 | return L->getHeader() == I->getParent(); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6269 | } |
| 6270 | |
| 6271 | // If we won't be able to constant fold this expression even if the operands |
| 6272 | // are constants, bail early. |
| 6273 | return CanConstantFold(I); |
| 6274 | } |
| 6275 | |
| 6276 | /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by |
| 6277 | /// recursing through each instruction operand until reaching a loop header phi. |
| 6278 | static PHINode * |
| 6279 | getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6280 | DenseMap<Instruction *, PHINode *> &PHIMap) { |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6281 | |
| 6282 | // Otherwise, we can evaluate this instruction if all of its operands are |
| 6283 | // constant or derived from a PHI node themselves. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6284 | PHINode *PHI = nullptr; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 6285 | for (Value *Op : UseInst->operands()) { |
| 6286 | if (isa<Constant>(Op)) continue; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6287 | |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 6288 | Instruction *OpInst = dyn_cast<Instruction>(Op); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6289 | if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6290 | |
| 6291 | PHINode *P = dyn_cast<PHINode>(OpInst); |
Andrew Trick | 3e8a576 | 2011-10-05 22:06:53 +0000 | [diff] [blame] | 6292 | if (!P) |
| 6293 | // If this operand is already visited, reuse the prior result. |
| 6294 | // We may have P != PHI if this is the deepest point at which the |
| 6295 | // inconsistent paths meet. |
| 6296 | P = PHIMap.lookup(OpInst); |
| 6297 | if (!P) { |
| 6298 | // Recurse and memoize the results, whether a phi is found or not. |
| 6299 | // This recursive call invalidates pointers into PHIMap. |
| 6300 | P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap); |
| 6301 | PHIMap[OpInst] = P; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6302 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6303 | if (!P) |
| 6304 | return nullptr; // Not evolving from PHI |
| 6305 | if (PHI && PHI != P) |
| 6306 | return nullptr; // Evolving from multiple different PHIs. |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6307 | PHI = P; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6308 | } |
| 6309 | // This is a expression evolving from a constant PHI! |
| 6310 | return PHI; |
| 6311 | } |
| 6312 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6313 | /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node |
| 6314 | /// in the loop that V is derived from. We allow arbitrary operations along the |
| 6315 | /// way, but the operands of an operation must either be constants or a value |
| 6316 | /// derived from a constant PHI. If this expression does not fit with these |
| 6317 | /// constraints, return null. |
| 6318 | static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6319 | Instruction *I = dyn_cast<Instruction>(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6320 | if (!I || !canConstantEvolve(I, L)) return nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6321 | |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 6322 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6323 | return PN; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6324 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6325 | // Record non-constant instructions contained by the loop. |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6326 | DenseMap<Instruction *, PHINode *> PHIMap; |
| 6327 | return getConstantEvolvingPHIOperands(I, L, PHIMap); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6328 | } |
| 6329 | |
| 6330 | /// EvaluateExpression - Given an expression that passes the |
| 6331 | /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node |
| 6332 | /// in the loop has the value PHIVal. If we can't fold this expression for some |
| 6333 | /// reason, return null. |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6334 | static Constant *EvaluateExpression(Value *V, const Loop *L, |
| 6335 | DenseMap<Instruction *, Constant *> &Vals, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 6336 | const DataLayout &DL, |
Chad Rosier | e6de63d | 2011-12-01 21:29:16 +0000 | [diff] [blame] | 6337 | const TargetLibraryInfo *TLI) { |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6338 | // Convenient constant check, but redundant for recursive calls. |
Reid Spencer | 30d69a5 | 2004-07-18 00:18:30 +0000 | [diff] [blame] | 6339 | if (Constant *C = dyn_cast<Constant>(V)) return C; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6340 | Instruction *I = dyn_cast<Instruction>(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6341 | if (!I) return nullptr; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6342 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6343 | if (Constant *C = Vals.lookup(I)) return C; |
| 6344 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6345 | // An instruction inside the loop depends on a value outside the loop that we |
| 6346 | // weren't given a mapping for, or a value such as a call inside the loop. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6347 | if (!canConstantEvolve(I, L)) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6348 | |
| 6349 | // An unmapped PHI can be due to a branch or another loop inside this loop, |
| 6350 | // or due to this not being the initial iteration through a loop where we |
| 6351 | // couldn't compute the evolution of this particular PHI last time. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6352 | if (isa<PHINode>(I)) return nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6353 | |
Dan Gohman | f820bd3 | 2010-06-22 13:15:46 +0000 | [diff] [blame] | 6354 | std::vector<Constant*> Operands(I->getNumOperands()); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6355 | |
| 6356 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6357 | Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); |
| 6358 | if (!Operand) { |
Nick Lewycky | a447e0f3 | 2011-10-14 09:38:46 +0000 | [diff] [blame] | 6359 | Operands[i] = dyn_cast<Constant>(I->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6360 | if (!Operands[i]) return nullptr; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6361 | continue; |
| 6362 | } |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 6363 | Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6364 | Vals[Operand] = C; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6365 | if (!C) return nullptr; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6366 | Operands[i] = C; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6367 | } |
| 6368 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6369 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Chris Lattner | cdfb80d | 2009-11-09 23:06:58 +0000 | [diff] [blame] | 6370 | return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 6371 | Operands[1], DL, TLI); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6372 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
| 6373 | if (!LI->isVolatile()) |
Eduard Burtescu | 1423921 | 2016-01-22 01:17:26 +0000 | [diff] [blame] | 6374 | return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6375 | } |
Manuel Jacob | e902459 | 2016-01-21 06:33:22 +0000 | [diff] [blame] | 6376 | return ConstantFoldInstOperands(I, Operands, DL, TLI); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6377 | } |
| 6378 | |
Sanjoy Das | 52bfa0f | 2015-11-02 02:06:01 +0000 | [diff] [blame] | 6379 | |
| 6380 | // If every incoming value to PN except the one for BB is a specific Constant, |
| 6381 | // return that, else return nullptr. |
| 6382 | static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { |
| 6383 | Constant *IncomingVal = nullptr; |
| 6384 | |
| 6385 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 6386 | if (PN->getIncomingBlock(i) == BB) |
| 6387 | continue; |
| 6388 | |
| 6389 | auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); |
| 6390 | if (!CurrentVal) |
| 6391 | return nullptr; |
| 6392 | |
| 6393 | if (IncomingVal != CurrentVal) { |
| 6394 | if (IncomingVal) |
| 6395 | return nullptr; |
| 6396 | IncomingVal = CurrentVal; |
| 6397 | } |
| 6398 | } |
| 6399 | |
| 6400 | return IncomingVal; |
| 6401 | } |
| 6402 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6403 | /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is |
| 6404 | /// in the header of its containing loop, we know the loop executes a |
| 6405 | /// constant number of times, and the PHI node is just a recurrence |
| 6406 | /// involving constants, fold it. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6407 | Constant * |
| 6408 | ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 6409 | const APInt &BEs, |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6410 | const Loop *L) { |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6411 | auto I = ConstantEvolutionLoopExitValue.find(PN); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6412 | if (I != ConstantEvolutionLoopExitValue.end()) |
| 6413 | return I->second; |
| 6414 | |
Dan Gohman | 4ce1fb1 | 2010-04-08 23:03:40 +0000 | [diff] [blame] | 6415 | if (BEs.ugt(MaxBruteForceIterations)) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6416 | return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6417 | |
| 6418 | Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; |
| 6419 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6420 | DenseMap<Instruction *, Constant *> CurrentIterVals; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6421 | BasicBlock *Header = L->getHeader(); |
| 6422 | assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6423 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6424 | BasicBlock *Latch = L->getLoopLatch(); |
| 6425 | if (!Latch) |
| 6426 | return nullptr; |
| 6427 | |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6428 | for (auto &I : *Header) { |
| 6429 | PHINode *PHI = dyn_cast<PHINode>(&I); |
| 6430 | if (!PHI) break; |
Sanjoy Das | 52bfa0f | 2015-11-02 02:06:01 +0000 | [diff] [blame] | 6431 | auto *StartCST = getOtherIncomingValue(PHI, Latch); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6432 | if (!StartCST) continue; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6433 | CurrentIterVals[PHI] = StartCST; |
| 6434 | } |
| 6435 | if (!CurrentIterVals.count(PN)) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6436 | return RetVal = nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6437 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6438 | Value *BEValue = PN->getIncomingValueForBlock(Latch); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6439 | |
| 6440 | // Execute the loop symbolically to determine the exit value. |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6441 | if (BEs.getActiveBits() >= 32) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6442 | return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6443 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6444 | unsigned NumIterations = BEs.getZExtValue(); // must be in range |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6445 | unsigned IterationNum = 0; |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 6446 | const DataLayout &DL = getDataLayout(); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6447 | for (; ; ++IterationNum) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6448 | if (IterationNum == NumIterations) |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6449 | return RetVal = CurrentIterVals[PN]; // Got exit value! |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6450 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6451 | // Compute the value of the PHIs for the next iteration. |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6452 | // EvaluateExpression adds non-phi values to the CurrentIterVals map. |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6453 | DenseMap<Instruction *, Constant *> NextIterVals; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 6454 | Constant *NextPHI = |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6455 | EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6456 | if (!NextPHI) |
| 6457 | return nullptr; // Couldn't evaluate! |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6458 | NextIterVals[PN] = NextPHI; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6459 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6460 | bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; |
| 6461 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6462 | // Also evaluate the other PHI nodes. However, we don't get to stop if we |
| 6463 | // cease to be able to evaluate one of them or if they stop evolving, |
| 6464 | // because that doesn't necessarily prevent us from computing PN. |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6465 | SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6466 | for (const auto &I : CurrentIterVals) { |
| 6467 | PHINode *PHI = dyn_cast<PHINode>(I.first); |
Nick Lewycky | 8e904de | 2011-10-24 05:51:01 +0000 | [diff] [blame] | 6468 | if (!PHI || PHI == PN || PHI->getParent() != Header) continue; |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6469 | PHIsToCompute.emplace_back(PHI, I.second); |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6470 | } |
| 6471 | // We use two distinct loops because EvaluateExpression may invalidate any |
| 6472 | // iterators into CurrentIterVals. |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6473 | for (const auto &I : PHIsToCompute) { |
| 6474 | PHINode *PHI = I.first; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6475 | Constant *&NextPHI = NextIterVals[PHI]; |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6476 | if (!NextPHI) { // Not already computed. |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6477 | Value *BEValue = PHI->getIncomingValueForBlock(Latch); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6478 | NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6479 | } |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6480 | if (NextPHI != I.second) |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6481 | StoppedEvolving = false; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6482 | } |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6483 | |
| 6484 | // If all entries in CurrentIterVals == NextIterVals then we can stop |
| 6485 | // iterating, the loop can't continue to change. |
| 6486 | if (StoppedEvolving) |
| 6487 | return RetVal = CurrentIterVals[PN]; |
| 6488 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6489 | CurrentIterVals.swap(NextIterVals); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6490 | } |
| 6491 | } |
| 6492 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 6493 | const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6494 | Value *Cond, |
| 6495 | bool ExitWhen) { |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6496 | PHINode *PN = getConstantEvolvingPHI(Cond, L); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6497 | if (!PN) return getCouldNotCompute(); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6498 | |
Dan Gohman | 866971e | 2010-06-19 14:17:24 +0000 | [diff] [blame] | 6499 | // If the loop is canonicalized, the PHI will have exactly two entries. |
| 6500 | // That's the only form we support here. |
| 6501 | if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); |
| 6502 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6503 | DenseMap<Instruction *, Constant *> CurrentIterVals; |
| 6504 | BasicBlock *Header = L->getHeader(); |
| 6505 | assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); |
| 6506 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6507 | BasicBlock *Latch = L->getLoopLatch(); |
| 6508 | assert(Latch && "Should follow from NumIncomingValues == 2!"); |
| 6509 | |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6510 | for (auto &I : *Header) { |
| 6511 | PHINode *PHI = dyn_cast<PHINode>(&I); |
| 6512 | if (!PHI) |
| 6513 | break; |
Sanjoy Das | 52bfa0f | 2015-11-02 02:06:01 +0000 | [diff] [blame] | 6514 | auto *StartCST = getOtherIncomingValue(PHI, Latch); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6515 | if (!StartCST) continue; |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6516 | CurrentIterVals[PHI] = StartCST; |
| 6517 | } |
| 6518 | if (!CurrentIterVals.count(PN)) |
| 6519 | return getCouldNotCompute(); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6520 | |
| 6521 | // Okay, we find a PHI node that defines the trip count of this loop. Execute |
| 6522 | // the loop symbolically to determine when the condition gets a value of |
| 6523 | // "ExitWhen". |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 6524 | unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 6525 | const DataLayout &DL = getDataLayout(); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6526 | for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6527 | auto *CondVal = dyn_cast_or_null<ConstantInt>( |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6528 | EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6529 | |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6530 | // Couldn't symbolically evaluate. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6531 | if (!CondVal) return getCouldNotCompute(); |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6532 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6533 | if (CondVal->getValue() == uint64_t(ExitWhen)) { |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6534 | ++NumBruteForceTripCountsComputed; |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 6535 | return getConstant(Type::getInt32Ty(getContext()), IterationNum); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6536 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6537 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6538 | // Update all the PHI nodes for the next iteration. |
| 6539 | DenseMap<Instruction *, Constant *> NextIterVals; |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6540 | |
| 6541 | // Create a list of which PHIs we need to compute. We want to do this before |
| 6542 | // calling EvaluateExpression on them because that may invalidate iterators |
| 6543 | // into CurrentIterVals. |
| 6544 | SmallVector<PHINode *, 8> PHIsToCompute; |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6545 | for (const auto &I : CurrentIterVals) { |
| 6546 | PHINode *PHI = dyn_cast<PHINode>(I.first); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6547 | if (!PHI || PHI->getParent() != Header) continue; |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6548 | PHIsToCompute.push_back(PHI); |
| 6549 | } |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6550 | for (PHINode *PHI : PHIsToCompute) { |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6551 | Constant *&NextPHI = NextIterVals[PHI]; |
| 6552 | if (NextPHI) continue; // Already computed! |
| 6553 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6554 | Value *BEValue = PHI->getIncomingValueForBlock(Latch); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6555 | NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6556 | } |
| 6557 | CurrentIterVals.swap(NextIterVals); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6558 | } |
| 6559 | |
| 6560 | // Too many iterations were needed to evaluate. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6561 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6562 | } |
| 6563 | |
Dan Gohman | 237d9e5 | 2009-09-03 15:00:26 +0000 | [diff] [blame] | 6564 | /// getSCEVAtScope - Return a SCEV expression for the specified value |
Dan Gohman | b81f47d | 2009-05-08 20:38:54 +0000 | [diff] [blame] | 6565 | /// at the specified scope in the program. The L value specifies a loop |
| 6566 | /// nest to evaluate the expression at, where null is the top-level or a |
| 6567 | /// specified loop is immediately inside of the loop. |
| 6568 | /// |
| 6569 | /// This method can be used to compute the exit value for a variable defined |
| 6570 | /// in a loop by querying what the value will hold in the parent loop. |
| 6571 | /// |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 6572 | /// In the case that a relevant loop exit value cannot be computed, the |
| 6573 | /// original value V is returned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6574 | const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 6575 | SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = |
| 6576 | ValuesAtScopes[V]; |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6577 | // Check to see if we've folded this expression at this loop before. |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 6578 | for (auto &LS : Values) |
| 6579 | if (LS.first == L) |
| 6580 | return LS.second ? LS.second : V; |
| 6581 | |
| 6582 | Values.emplace_back(L, nullptr); |
| 6583 | |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6584 | // Otherwise compute it. |
| 6585 | const SCEV *C = computeSCEVAtScope(V, L); |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 6586 | for (auto &LS : reverse(ValuesAtScopes[V])) |
| 6587 | if (LS.first == L) { |
| 6588 | LS.second = C; |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 6589 | break; |
| 6590 | } |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6591 | return C; |
| 6592 | } |
| 6593 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6594 | /// This builds up a Constant using the ConstantExpr interface. That way, we |
| 6595 | /// will return Constants for objects which aren't represented by a |
| 6596 | /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. |
| 6597 | /// Returns NULL if the SCEV isn't representable as a Constant. |
| 6598 | static Constant *BuildConstantFromSCEV(const SCEV *V) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 6599 | switch (static_cast<SCEVTypes>(V->getSCEVType())) { |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6600 | case scCouldNotCompute: |
| 6601 | case scAddRecExpr: |
| 6602 | break; |
| 6603 | case scConstant: |
| 6604 | return cast<SCEVConstant>(V)->getValue(); |
| 6605 | case scUnknown: |
| 6606 | return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); |
| 6607 | case scSignExtend: { |
| 6608 | const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); |
| 6609 | if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) |
| 6610 | return ConstantExpr::getSExt(CastOp, SS->getType()); |
| 6611 | break; |
| 6612 | } |
| 6613 | case scZeroExtend: { |
| 6614 | const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); |
| 6615 | if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) |
| 6616 | return ConstantExpr::getZExt(CastOp, SZ->getType()); |
| 6617 | break; |
| 6618 | } |
| 6619 | case scTruncate: { |
| 6620 | const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); |
| 6621 | if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) |
| 6622 | return ConstantExpr::getTrunc(CastOp, ST->getType()); |
| 6623 | break; |
| 6624 | } |
| 6625 | case scAddExpr: { |
| 6626 | const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); |
| 6627 | if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6628 | if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { |
| 6629 | unsigned AS = PTy->getAddressSpace(); |
| 6630 | Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); |
| 6631 | C = ConstantExpr::getBitCast(C, DestPtrTy); |
| 6632 | } |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6633 | for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { |
| 6634 | Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6635 | if (!C2) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6636 | |
| 6637 | // First pointer! |
| 6638 | if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6639 | unsigned AS = C2->getType()->getPointerAddressSpace(); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6640 | std::swap(C, C2); |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6641 | Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6642 | // The offsets have been converted to bytes. We can add bytes to an |
| 6643 | // i8* by GEP with the byte count in the first index. |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6644 | C = ConstantExpr::getBitCast(C, DestPtrTy); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6645 | } |
| 6646 | |
| 6647 | // Don't bother trying to sum two pointers. We probably can't |
| 6648 | // statically compute a load that results from it anyway. |
| 6649 | if (C2->getType()->isPointerTy()) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6650 | return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6651 | |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6652 | if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { |
| 6653 | if (PTy->getElementType()->isStructTy()) |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6654 | C2 = ConstantExpr::getIntegerCast( |
| 6655 | C2, Type::getInt32Ty(C->getContext()), true); |
David Blaikie | 4a2e73b | 2015-04-02 18:55:32 +0000 | [diff] [blame] | 6656 | C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6657 | } else |
| 6658 | C = ConstantExpr::getAdd(C, C2); |
| 6659 | } |
| 6660 | return C; |
| 6661 | } |
| 6662 | break; |
| 6663 | } |
| 6664 | case scMulExpr: { |
| 6665 | const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); |
| 6666 | if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { |
| 6667 | // Don't bother with pointers at all. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6668 | if (C->getType()->isPointerTy()) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6669 | for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { |
| 6670 | Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6671 | if (!C2 || C2->getType()->isPointerTy()) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6672 | C = ConstantExpr::getMul(C, C2); |
| 6673 | } |
| 6674 | return C; |
| 6675 | } |
| 6676 | break; |
| 6677 | } |
| 6678 | case scUDivExpr: { |
| 6679 | const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); |
| 6680 | if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) |
| 6681 | if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) |
| 6682 | if (LHS->getType() == RHS->getType()) |
| 6683 | return ConstantExpr::getUDiv(LHS, RHS); |
| 6684 | break; |
| 6685 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 6686 | case scSMaxExpr: |
| 6687 | case scUMaxExpr: |
| 6688 | break; // TODO: smax, umax. |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6689 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6690 | return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6691 | } |
| 6692 | |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6693 | const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6694 | if (isa<SCEVConstant>(V)) return V; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6695 | |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 6696 | // If this instruction is evolved from a constant-evolving PHI, compute the |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6697 | // exit value from the loop without using SCEVs. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6698 | if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6699 | if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6700 | const Loop *LI = this->LI[I->getParent()]; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6701 | if (LI && LI->getParentLoop() == L) // Looking for loop exit value. |
| 6702 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 6703 | if (PN->getParent() == LI->getHeader()) { |
| 6704 | // Okay, there is no closed form solution for the PHI node. Check |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6705 | // to see if the loop that contains it has a known backedge-taken |
| 6706 | // count. If so, we may be able to force computation of the exit |
| 6707 | // value. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6708 | const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6709 | if (const SCEVConstant *BTCC = |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6710 | dyn_cast<SCEVConstant>(BackedgeTakenCount)) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6711 | // Okay, we know how many times the containing loop executes. If |
| 6712 | // this is a constant evolving PHI node, get the final value at |
| 6713 | // the specified iteration number. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 6714 | Constant *RV = |
| 6715 | getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); |
Dan Gohman | 9d203c6 | 2009-06-29 21:31:18 +0000 | [diff] [blame] | 6716 | if (RV) return getSCEV(RV); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6717 | } |
| 6718 | } |
| 6719 | |
Reid Spencer | e6328ca | 2006-12-04 21:33:23 +0000 | [diff] [blame] | 6720 | // Okay, this is an expression that we cannot symbolically evaluate |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6721 | // into a SCEV. Check to see if it's possible to symbolically evaluate |
Reid Spencer | e6328ca | 2006-12-04 21:33:23 +0000 | [diff] [blame] | 6722 | // the arguments into constants, and if so, try to constant propagate the |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6723 | // result. This is particularly useful for computing loop exit values. |
| 6724 | if (CanConstantFold(I)) { |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6725 | SmallVector<Constant *, 4> Operands; |
| 6726 | bool MadeImprovement = false; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 6727 | for (Value *Op : I->operands()) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6728 | if (Constant *C = dyn_cast<Constant>(Op)) { |
| 6729 | Operands.push_back(C); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6730 | continue; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6731 | } |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6732 | |
| 6733 | // If any of the operands is non-constant and if they are |
| 6734 | // non-integer and non-pointer, don't even try to analyze them |
| 6735 | // with scev techniques. |
| 6736 | if (!isSCEVable(Op->getType())) |
| 6737 | return V; |
| 6738 | |
| 6739 | const SCEV *OrigV = getSCEV(Op); |
| 6740 | const SCEV *OpV = getSCEVAtScope(OrigV, L); |
| 6741 | MadeImprovement |= OrigV != OpV; |
| 6742 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6743 | Constant *C = BuildConstantFromSCEV(OpV); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6744 | if (!C) return V; |
| 6745 | if (C->getType() != Op->getType()) |
| 6746 | C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, |
| 6747 | Op->getType(), |
| 6748 | false), |
| 6749 | C, Op->getType()); |
| 6750 | Operands.push_back(C); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6751 | } |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6752 | |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6753 | // Check to see if getSCEVAtScope actually made an improvement. |
| 6754 | if (MadeImprovement) { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6755 | Constant *C = nullptr; |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 6756 | const DataLayout &DL = getDataLayout(); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6757 | if (const CmpInst *CI = dyn_cast<CmpInst>(I)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 6758 | C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6759 | Operands[1], DL, &TLI); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6760 | else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { |
| 6761 | if (!LI->isVolatile()) |
Eduard Burtescu | 1423921 | 2016-01-22 01:17:26 +0000 | [diff] [blame] | 6762 | C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6763 | } else |
Manuel Jacob | e902459 | 2016-01-21 06:33:22 +0000 | [diff] [blame] | 6764 | C = ConstantFoldInstOperands(I, Operands, DL, &TLI); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6765 | if (!C) return V; |
Dan Gohman | 4aad750 | 2010-02-24 19:31:47 +0000 | [diff] [blame] | 6766 | return getSCEV(C); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6767 | } |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6768 | } |
| 6769 | } |
| 6770 | |
| 6771 | // This is some other type of SCEVUnknown, just return it. |
| 6772 | return V; |
| 6773 | } |
| 6774 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6775 | if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6776 | // Avoid performing the look-up in the common case where the specified |
| 6777 | // expression has no loop-variant portions. |
| 6778 | for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6779 | const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6780 | if (OpAtScope != Comm->getOperand(i)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6781 | // Okay, at least one of these operands is loop variant but might be |
| 6782 | // foldable. Build a new instance of the folded commutative expression. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6783 | SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), |
| 6784 | Comm->op_begin()+i); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6785 | NewOps.push_back(OpAtScope); |
| 6786 | |
| 6787 | for (++i; i != e; ++i) { |
| 6788 | OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6789 | NewOps.push_back(OpAtScope); |
| 6790 | } |
| 6791 | if (isa<SCEVAddExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6792 | return getAddExpr(NewOps); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 6793 | if (isa<SCEVMulExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6794 | return getMulExpr(NewOps); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 6795 | if (isa<SCEVSMaxExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6796 | return getSMaxExpr(NewOps); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 6797 | if (isa<SCEVUMaxExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6798 | return getUMaxExpr(NewOps); |
Torok Edwin | fbcc663 | 2009-07-14 16:55:14 +0000 | [diff] [blame] | 6799 | llvm_unreachable("Unknown commutative SCEV type!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6800 | } |
| 6801 | } |
| 6802 | // If we got here, all operands are loop invariant. |
| 6803 | return Comm; |
| 6804 | } |
| 6805 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6806 | if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6807 | const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); |
| 6808 | const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); |
Nick Lewycky | 5234830 | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 6809 | if (LHS == Div->getLHS() && RHS == Div->getRHS()) |
| 6810 | return Div; // must be loop invariant |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6811 | return getUDivExpr(LHS, RHS); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6812 | } |
| 6813 | |
| 6814 | // If this is a loop recurrence for a loop that does not contain L, then we |
| 6815 | // are dealing with the final value computed by the loop. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6816 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6817 | // First, attempt to evaluate each operand. |
| 6818 | // Avoid performing the look-up in the common case where the specified |
| 6819 | // expression has no loop-variant portions. |
| 6820 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { |
| 6821 | const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); |
| 6822 | if (OpAtScope == AddRec->getOperand(i)) |
| 6823 | continue; |
| 6824 | |
| 6825 | // Okay, at least one of these operands is loop variant but might be |
| 6826 | // foldable. Build a new instance of the folded commutative expression. |
| 6827 | SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), |
| 6828 | AddRec->op_begin()+i); |
| 6829 | NewOps.push_back(OpAtScope); |
| 6830 | for (++i; i != e; ++i) |
| 6831 | NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); |
| 6832 | |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6833 | const SCEV *FoldedRec = |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6834 | getAddRecExpr(NewOps, AddRec->getLoop(), |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6835 | AddRec->getNoWrapFlags(SCEV::FlagNW)); |
| 6836 | AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); |
Andrew Trick | 01eff82 | 2011-04-27 05:42:17 +0000 | [diff] [blame] | 6837 | // The addrec may be folded to a nonrecurrence, for example, if the |
| 6838 | // induction variable is multiplied by zero after constant folding. Go |
| 6839 | // ahead and return the folded value. |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6840 | if (!AddRec) |
| 6841 | return FoldedRec; |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6842 | break; |
| 6843 | } |
| 6844 | |
| 6845 | // If the scope is outside the addrec's loop, evaluate it by using the |
| 6846 | // loop exit value of the addrec. |
| 6847 | if (!AddRec->getLoop()->contains(L)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6848 | // To evaluate this recurrence, we need to know how many times the AddRec |
| 6849 | // loop iterates. Compute this now. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6850 | const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6851 | if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6852 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 6853 | // Then, evaluate the AddRec. |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6854 | return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6855 | } |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6856 | |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 6857 | return AddRec; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6858 | } |
| 6859 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6860 | if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6861 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 6862 | if (Op == Cast->getOperand()) |
| 6863 | return Cast; // must be loop invariant |
| 6864 | return getZeroExtendExpr(Op, Cast->getType()); |
| 6865 | } |
| 6866 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6867 | if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6868 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 6869 | if (Op == Cast->getOperand()) |
| 6870 | return Cast; // must be loop invariant |
| 6871 | return getSignExtendExpr(Op, Cast->getType()); |
| 6872 | } |
| 6873 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6874 | if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6875 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 6876 | if (Op == Cast->getOperand()) |
| 6877 | return Cast; // must be loop invariant |
| 6878 | return getTruncateExpr(Op, Cast->getType()); |
| 6879 | } |
| 6880 | |
Torok Edwin | fbcc663 | 2009-07-14 16:55:14 +0000 | [diff] [blame] | 6881 | llvm_unreachable("Unknown SCEV type!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6882 | } |
| 6883 | |
Dan Gohman | b81f47d | 2009-05-08 20:38:54 +0000 | [diff] [blame] | 6884 | /// getSCEVAtScope - This is a convenience function which does |
| 6885 | /// getSCEVAtScope(getSCEV(V), L). |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6886 | const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6887 | return getSCEVAtScope(getSCEV(V), L); |
| 6888 | } |
| 6889 | |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6890 | /// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the |
| 6891 | /// following equation: |
| 6892 | /// |
| 6893 | /// A * X = B (mod N) |
| 6894 | /// |
| 6895 | /// where N = 2^BW and BW is the common bit width of A and B. The signedness of |
| 6896 | /// A and B isn't important. |
| 6897 | /// |
| 6898 | /// If the equation does not have a solution, SCEVCouldNotCompute is returned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6899 | static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B, |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6900 | ScalarEvolution &SE) { |
| 6901 | uint32_t BW = A.getBitWidth(); |
| 6902 | assert(BW == B.getBitWidth() && "Bit widths must be the same."); |
| 6903 | assert(A != 0 && "A must be non-zero."); |
| 6904 | |
| 6905 | // 1. D = gcd(A, N) |
| 6906 | // |
| 6907 | // The gcd of A and N may have only one prime factor: 2. The number of |
| 6908 | // trailing zeros in A is its multiplicity |
| 6909 | uint32_t Mult2 = A.countTrailingZeros(); |
| 6910 | // D = 2^Mult2 |
| 6911 | |
| 6912 | // 2. Check if B is divisible by D. |
| 6913 | // |
| 6914 | // B is divisible by D if and only if the multiplicity of prime factor 2 for B |
| 6915 | // is not less than multiplicity of this prime factor for D. |
| 6916 | if (B.countTrailingZeros() < Mult2) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 6917 | return SE.getCouldNotCompute(); |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6918 | |
| 6919 | // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic |
| 6920 | // modulo (N / D). |
| 6921 | // |
| 6922 | // (N / D) may need BW+1 bits in its representation. Hence, we'll use this |
| 6923 | // bit width during computations. |
| 6924 | APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D |
| 6925 | APInt Mod(BW + 1, 0); |
Jay Foad | 25a5e4c | 2010-12-01 08:53:58 +0000 | [diff] [blame] | 6926 | Mod.setBit(BW - Mult2); // Mod = N / D |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6927 | APInt I = AD.multiplicativeInverse(Mod); |
| 6928 | |
| 6929 | // 4. Compute the minimum unsigned root of the equation: |
| 6930 | // I * (B / D) mod (N / D) |
| 6931 | APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); |
| 6932 | |
| 6933 | // The result is guaranteed to be less than 2^BW so we may truncate it to BW |
| 6934 | // bits. |
| 6935 | return SE.getConstant(Result.trunc(BW)); |
| 6936 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6937 | |
| 6938 | /// SolveQuadraticEquation - Find the roots of the quadratic equation for the |
| 6939 | /// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which |
| 6940 | /// might be the same) or two SCEVCouldNotCompute objects. |
| 6941 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6942 | static std::pair<const SCEV *,const SCEV *> |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 6943 | SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6944 | assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6945 | const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); |
| 6946 | const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); |
| 6947 | const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6948 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6949 | // We currently can only solve this if the coefficients are constants. |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6950 | if (!LC || !MC || !NC) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6951 | const SCEV *CNC = SE.getCouldNotCompute(); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 6952 | return {CNC, CNC}; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6953 | } |
| 6954 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 6955 | uint32_t BitWidth = LC->getAPInt().getBitWidth(); |
| 6956 | const APInt &L = LC->getAPInt(); |
| 6957 | const APInt &M = MC->getAPInt(); |
| 6958 | const APInt &N = NC->getAPInt(); |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6959 | APInt Two(BitWidth, 2); |
| 6960 | APInt Four(BitWidth, 4); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6961 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6962 | { |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6963 | using namespace APIntOps; |
Zhou Sheng | 2852d99 | 2007-04-07 17:48:27 +0000 | [diff] [blame] | 6964 | const APInt& C = L; |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6965 | // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C |
| 6966 | // The B coefficient is M-N/2 |
| 6967 | APInt B(M); |
| 6968 | B -= sdiv(N,Two); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6969 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6970 | // The A coefficient is N/2 |
Zhou Sheng | 2852d99 | 2007-04-07 17:48:27 +0000 | [diff] [blame] | 6971 | APInt A(N.sdiv(Two)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6972 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6973 | // Compute the B^2-4ac term. |
| 6974 | APInt SqrtTerm(B); |
| 6975 | SqrtTerm *= B; |
| 6976 | SqrtTerm -= Four * (A * C); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6977 | |
Nick Lewycky | fb78083 | 2012-08-01 09:14:36 +0000 | [diff] [blame] | 6978 | if (SqrtTerm.isNegative()) { |
| 6979 | // The loop is provably infinite. |
| 6980 | const SCEV *CNC = SE.getCouldNotCompute(); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 6981 | return {CNC, CNC}; |
Nick Lewycky | fb78083 | 2012-08-01 09:14:36 +0000 | [diff] [blame] | 6982 | } |
| 6983 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6984 | // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest |
| 6985 | // integer value or else APInt::sqrt() will assert. |
| 6986 | APInt SqrtVal(SqrtTerm.sqrt()); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6987 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6988 | // Compute the two solutions for the quadratic formula. |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6989 | // The divisions must be performed as signed divisions. |
| 6990 | APInt NegB(-B); |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 6991 | APInt TwoA(A << 1); |
Nick Lewycky | 7b14e20 | 2008-11-03 02:43:49 +0000 | [diff] [blame] | 6992 | if (TwoA.isMinValue()) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6993 | const SCEV *CNC = SE.getCouldNotCompute(); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 6994 | return {CNC, CNC}; |
Nick Lewycky | 7b14e20 | 2008-11-03 02:43:49 +0000 | [diff] [blame] | 6995 | } |
| 6996 | |
Owen Anderson | 47db941 | 2009-07-22 00:24:57 +0000 | [diff] [blame] | 6997 | LLVMContext &Context = SE.getContext(); |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 6998 | |
| 6999 | ConstantInt *Solution1 = |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 7000 | ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 7001 | ConstantInt *Solution2 = |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 7002 | ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7003 | |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 7004 | return {SE.getConstant(Solution1), SE.getConstant(Solution2)}; |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 7005 | } // end APIntOps namespace |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7006 | } |
| 7007 | |
| 7008 | /// HowFarToZero - Return the number of times a backedge comparing the specified |
Dan Gohman | 4c720c0 | 2009-06-06 14:37:11 +0000 | [diff] [blame] | 7009 | /// value to zero will execute. If not computable, return CouldNotCompute. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7010 | /// |
| 7011 | /// This is only used for loops with a "x != y" exit test. The exit condition is |
| 7012 | /// now expressed as a single expression, V = x-y. So the exit test is |
| 7013 | /// effectively V != 0. We know and take advantage of the fact that this |
| 7014 | /// expression only being used in a comparison by zero context. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 7015 | ScalarEvolution::ExitLimit |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7016 | ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, |
| 7017 | bool AllowPredicates) { |
| 7018 | SCEVUnionPredicate P; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7019 | // If the value is a constant |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 7020 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7021 | // If the value is already zero, the branch will execute zero times. |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 7022 | if (C->getValue()->isZero()) return C; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7023 | return getCouldNotCompute(); // Otherwise it will loop infinitely. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7024 | } |
| 7025 | |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 7026 | const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7027 | if (!AddRec && AllowPredicates) |
| 7028 | // Try to make this an AddRec using runtime tests, in the first X |
| 7029 | // iterations of this loop, where X is the SCEV expression found by the |
| 7030 | // algorithm below. |
| 7031 | AddRec = convertSCEVToAddRecWithPredicates(V, L, P); |
| 7032 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7033 | if (!AddRec || AddRec->getLoop() != L) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7034 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7035 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7036 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of |
| 7037 | // the quadratic equation to solve it. |
| 7038 | if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { |
| 7039 | std::pair<const SCEV *,const SCEV *> Roots = |
| 7040 | SolveQuadraticEquation(AddRec, *this); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 7041 | const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); |
| 7042 | const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7043 | if (R1 && R2) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7044 | // Pick the smallest positive root value. |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 7045 | if (ConstantInt *CB = |
Chris Lattner | 28f140a | 2011-01-09 22:58:47 +0000 | [diff] [blame] | 7046 | dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT, |
| 7047 | R1->getValue(), |
| 7048 | R2->getValue()))) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 7049 | if (!CB->getZExtValue()) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7050 | std::swap(R1, R2); // R1 is the minimum root now. |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 7051 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7052 | // We can only use this value if the chrec ends up with an exact zero |
| 7053 | // value at this index. When solving for "X*X != 5", for example, we |
| 7054 | // should not accept a root of 2. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 7055 | const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 7056 | if (Val->isZero()) |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7057 | return ExitLimit(R1, R1, P); // We found a quadratic root! |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7058 | } |
| 7059 | } |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7060 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7061 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7062 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7063 | // Otherwise we can only handle this if it is affine. |
| 7064 | if (!AddRec->isAffine()) |
| 7065 | return getCouldNotCompute(); |
| 7066 | |
| 7067 | // If this is an affine expression, the execution count of this branch is |
| 7068 | // the minimum unsigned root of the following equation: |
| 7069 | // |
| 7070 | // Start + Step*N = 0 (mod 2^BW) |
| 7071 | // |
| 7072 | // equivalent to: |
| 7073 | // |
| 7074 | // Step*N = -Start (mod 2^BW) |
| 7075 | // |
| 7076 | // where BW is the common bit width of Start and Step. |
| 7077 | |
| 7078 | // Get the initial value for the loop. |
| 7079 | const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); |
| 7080 | const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); |
| 7081 | |
| 7082 | // For now we handle only constant steps. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7083 | // |
| 7084 | // TODO: Handle a nonconstant Step given AddRec<NUW>. If the |
| 7085 | // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap |
| 7086 | // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. |
| 7087 | // We have not yet seen any such cases. |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7088 | const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 7089 | if (!StepC || StepC->getValue()->equalsInt(0)) |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7090 | return getCouldNotCompute(); |
| 7091 | |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7092 | // For positive steps (counting up until unsigned overflow): |
| 7093 | // N = -Start/Step (as unsigned) |
| 7094 | // For negative steps (counting down to zero): |
| 7095 | // N = Start/-Step |
| 7096 | // First compute the unsigned distance from zero in the direction of Step. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7097 | bool CountDown = StepC->getAPInt().isNegative(); |
Andrew Trick | f1781db | 2011-03-14 17:28:02 +0000 | [diff] [blame] | 7098 | const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7099 | |
| 7100 | // Handle unitary steps, which cannot wraparound. |
Andrew Trick | f1781db | 2011-03-14 17:28:02 +0000 | [diff] [blame] | 7101 | // 1*N = -Start; -1*N = Start (mod 2^BW), so: |
| 7102 | // N = Distance (as unsigned) |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 7103 | if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { |
| 7104 | ConstantRange CR = getUnsignedRange(Start); |
| 7105 | const SCEV *MaxBECount; |
| 7106 | if (!CountDown && CR.getUnsignedMin().isMinValue()) |
| 7107 | // When counting up, the worst starting value is 1, not 0. |
| 7108 | MaxBECount = CR.getUnsignedMax().isMinValue() |
| 7109 | ? getConstant(APInt::getMinValue(CR.getBitWidth())) |
| 7110 | : getConstant(APInt::getMaxValue(CR.getBitWidth())); |
| 7111 | else |
| 7112 | MaxBECount = getConstant(CountDown ? CR.getUnsignedMax() |
| 7113 | : -CR.getUnsignedMin()); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7114 | return ExitLimit(Distance, MaxBECount, P); |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 7115 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 7116 | |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 7117 | // As a special case, handle the instance where Step is a positive power of |
| 7118 | // two. In this case, determining whether Step divides Distance evenly can be |
| 7119 | // done by counting and comparing the number of trailing zeros of Step and |
| 7120 | // Distance. |
| 7121 | if (!CountDown) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7122 | const APInt &StepV = StepC->getAPInt(); |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 7123 | // StepV.isPowerOf2() returns true if StepV is an positive power of two. It |
| 7124 | // also returns true if StepV is maximally negative (eg, INT_MIN), but that |
| 7125 | // case is not handled as this code is guarded by !CountDown. |
| 7126 | if (StepV.isPowerOf2() && |
Sanjoy Das | f3132d3 | 2015-09-10 05:27:38 +0000 | [diff] [blame] | 7127 | GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) { |
| 7128 | // Here we've constrained the equation to be of the form |
| 7129 | // |
| 7130 | // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0) |
| 7131 | // |
| 7132 | // where we're operating on a W bit wide integer domain and k is |
| 7133 | // non-negative. The smallest unsigned solution for X is the trip count. |
| 7134 | // |
| 7135 | // (0) is equivalent to: |
| 7136 | // |
| 7137 | // 2^(N + k) * Distance' - 2^N * X = L * 2^W |
| 7138 | // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N |
| 7139 | // <=> 2^k * Distance' - X = L * 2^(W - N) |
| 7140 | // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1) |
| 7141 | // |
| 7142 | // The smallest X satisfying (1) is unsigned remainder of dividing the LHS |
| 7143 | // by 2^(W - N). |
| 7144 | // |
| 7145 | // <=> X = 2^k * Distance' URem 2^(W - N) ... (2) |
| 7146 | // |
| 7147 | // E.g. say we're solving |
| 7148 | // |
| 7149 | // 2 * Val = 2 * X (in i8) ... (3) |
| 7150 | // |
| 7151 | // then from (2), we get X = Val URem i8 128 (k = 0 in this case). |
| 7152 | // |
| 7153 | // Note: It is tempting to solve (3) by setting X = Val, but Val is not |
| 7154 | // necessarily the smallest unsigned value of X that satisfies (3). |
| 7155 | // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3) |
| 7156 | // is i8 1, not i8 -127 |
| 7157 | |
| 7158 | const auto *ModuloResult = getUDivExactExpr(Distance, Step); |
| 7159 | |
| 7160 | // Since SCEV does not have a URem node, we construct one using a truncate |
| 7161 | // and a zero extend. |
| 7162 | |
| 7163 | unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros(); |
| 7164 | auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth); |
| 7165 | auto *WideTy = Distance->getType(); |
| 7166 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7167 | const SCEV *Limit = |
| 7168 | getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy); |
| 7169 | return ExitLimit(Limit, Limit, P); |
Sanjoy Das | f3132d3 | 2015-09-10 05:27:38 +0000 | [diff] [blame] | 7170 | } |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 7171 | } |
Benjamin Kramer | e75eaca | 2014-03-25 16:25:12 +0000 | [diff] [blame] | 7172 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7173 | // If the condition controls loop exit (the loop exits only if the expression |
| 7174 | // is true) and the addition is no-wrap we can use unsigned divide to |
| 7175 | // compute the backedge count. In this case, the step may not divide the |
| 7176 | // distance, but we don't care because if the condition is "missed" the loop |
| 7177 | // will have undefined behavior due to wrapping. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 7178 | if (ControlsExit && AddRec->hasNoSelfWrap()) { |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7179 | const SCEV *Exact = |
| 7180 | getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7181 | return ExitLimit(Exact, Exact, P); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7182 | } |
Benjamin Kramer | e75eaca | 2014-03-25 16:25:12 +0000 | [diff] [blame] | 7183 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7184 | // Then, try to solve the above equation provided that Start is constant. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7185 | if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) { |
| 7186 | const SCEV *E = SolveLinEquationWithOverflow( |
| 7187 | StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this); |
| 7188 | return ExitLimit(E, E, P); |
| 7189 | } |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7190 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7191 | } |
| 7192 | |
| 7193 | /// HowFarToNonZero - Return the number of times a backedge checking the |
| 7194 | /// specified value for nonzero will execute. If not computable, return |
Dan Gohman | 4c720c0 | 2009-06-06 14:37:11 +0000 | [diff] [blame] | 7195 | /// CouldNotCompute |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 7196 | ScalarEvolution::ExitLimit |
Dan Gohman | ba82034 | 2010-02-24 17:31:30 +0000 | [diff] [blame] | 7197 | ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7198 | // Loops that look like: while (X == 0) are very strange indeed. We don't |
| 7199 | // handle them yet except for the trivial case. This could be expanded in the |
| 7200 | // future as needed. |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7201 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7202 | // If the value is a constant, check to see if it is known to be non-zero |
| 7203 | // already. If so, the backedge will execute zero times. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 7204 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { |
Nick Lewycky | 5a3db14 | 2008-02-21 09:14:53 +0000 | [diff] [blame] | 7205 | if (!C->getValue()->isNullValue()) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 7206 | return getZero(C->getType()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7207 | return getCouldNotCompute(); // Otherwise it will loop infinitely. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7208 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7209 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7210 | // We could implement others, but I really doubt anyone writes loops like |
| 7211 | // this, and if they did, they would already be constant folded. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7212 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7213 | } |
| 7214 | |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7215 | /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB |
| 7216 | /// (which may not be an immediate predecessor) which has exactly one |
| 7217 | /// successor from which BB is reachable, or null if no such block is |
| 7218 | /// found. |
| 7219 | /// |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7220 | std::pair<BasicBlock *, BasicBlock *> |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 7221 | ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { |
Dan Gohman | fa066ef | 2009-04-30 20:48:53 +0000 | [diff] [blame] | 7222 | // If the block has a unique predecessor, then there is no path from the |
| 7223 | // predecessor to the block that does not go through the direct edge |
| 7224 | // from the predecessor to the block. |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7225 | if (BasicBlock *Pred = BB->getSinglePredecessor()) |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 7226 | return {Pred, BB}; |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7227 | |
| 7228 | // A loop's header is defined to be a block that dominates the loop. |
Dan Gohman | 8c77f1a | 2009-05-18 15:36:09 +0000 | [diff] [blame] | 7229 | // If the header has a unique predecessor outside the loop, it must be |
| 7230 | // a block that has exactly one successor that can reach the loop. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7231 | if (Loop *L = LI.getLoopFor(BB)) |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 7232 | return {L->getLoopPredecessor(), L->getHeader()}; |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7233 | |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 7234 | return {nullptr, nullptr}; |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7235 | } |
| 7236 | |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7237 | /// HasSameValue - SCEV structural equivalence is usually sufficient for |
| 7238 | /// testing whether two expressions are equal, however for the purposes of |
| 7239 | /// looking for a condition guarding a loop, it can be useful to be a little |
| 7240 | /// more general, since a front-end may have replicated the controlling |
| 7241 | /// expression. |
| 7242 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 7243 | static bool HasSameValue(const SCEV *A, const SCEV *B) { |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7244 | // Quick check to see if they are the same SCEV. |
| 7245 | if (A == B) return true; |
| 7246 | |
Sanjoy Das | f1090b6 | 2015-09-27 21:09:48 +0000 | [diff] [blame] | 7247 | auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { |
| 7248 | // Not all instructions that are "identical" compute the same value. For |
| 7249 | // instance, two distinct alloca instructions allocating the same type are |
| 7250 | // identical and do not read memory; but compute distinct values. |
| 7251 | return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); |
| 7252 | }; |
| 7253 | |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7254 | // Otherwise, if they're both SCEVUnknown, it's possible that they hold |
| 7255 | // two different instructions with the same value. Check for this case. |
| 7256 | if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) |
| 7257 | if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) |
| 7258 | if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) |
| 7259 | if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) |
Sanjoy Das | f1090b6 | 2015-09-27 21:09:48 +0000 | [diff] [blame] | 7260 | if (ComputesEqualValues(AI, BI)) |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7261 | return true; |
| 7262 | |
| 7263 | // Otherwise assume they may have a different value. |
| 7264 | return false; |
| 7265 | } |
| 7266 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7267 | /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with |
Sylvestre Ledru | 91ce36c | 2012-09-27 10:14:43 +0000 | [diff] [blame] | 7268 | /// predicate Pred. Return true iff any changes were made. |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7269 | /// |
| 7270 | bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7271 | const SCEV *&LHS, const SCEV *&RHS, |
| 7272 | unsigned Depth) { |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7273 | bool Changed = false; |
| 7274 | |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7275 | // If we hit the max recursion limit bail out. |
| 7276 | if (Depth >= 3) |
| 7277 | return false; |
| 7278 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7279 | // Canonicalize a constant to the right side. |
| 7280 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { |
| 7281 | // Check for both operands constant. |
| 7282 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { |
| 7283 | if (ConstantExpr::getICmp(Pred, |
| 7284 | LHSC->getValue(), |
| 7285 | RHSC->getValue())->isNullValue()) |
| 7286 | goto trivially_false; |
| 7287 | else |
| 7288 | goto trivially_true; |
| 7289 | } |
| 7290 | // Otherwise swap the operands to put the constant on the right. |
| 7291 | std::swap(LHS, RHS); |
| 7292 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7293 | Changed = true; |
| 7294 | } |
| 7295 | |
| 7296 | // If we're comparing an addrec with a value which is loop-invariant in the |
Dan Gohman | df564ca | 2010-05-03 17:00:11 +0000 | [diff] [blame] | 7297 | // addrec's loop, put the addrec on the left. Also make a dominance check, |
| 7298 | // as both operands could be addrecs loop-invariant in each other's loop. |
| 7299 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { |
| 7300 | const Loop *L = AR->getLoop(); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 7301 | if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7302 | std::swap(LHS, RHS); |
| 7303 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7304 | Changed = true; |
| 7305 | } |
Dan Gohman | df564ca | 2010-05-03 17:00:11 +0000 | [diff] [blame] | 7306 | } |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7307 | |
| 7308 | // If there's a constant operand, canonicalize comparisons with boundary |
| 7309 | // cases, and canonicalize *-or-equal comparisons to regular comparisons. |
| 7310 | if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7311 | const APInt &RA = RC->getAPInt(); |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7312 | switch (Pred) { |
| 7313 | default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); |
| 7314 | case ICmpInst::ICMP_EQ: |
| 7315 | case ICmpInst::ICMP_NE: |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7316 | // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. |
| 7317 | if (!RA) |
| 7318 | if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) |
| 7319 | if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0))) |
Benjamin Kramer | 406a2db | 2012-05-30 18:42:43 +0000 | [diff] [blame] | 7320 | if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && |
| 7321 | ME->getOperand(0)->isAllOnesValue()) { |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7322 | RHS = AE->getOperand(1); |
| 7323 | LHS = ME->getOperand(1); |
| 7324 | Changed = true; |
| 7325 | } |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7326 | break; |
| 7327 | case ICmpInst::ICMP_UGE: |
| 7328 | if ((RA - 1).isMinValue()) { |
| 7329 | Pred = ICmpInst::ICMP_NE; |
| 7330 | RHS = getConstant(RA - 1); |
| 7331 | Changed = true; |
| 7332 | break; |
| 7333 | } |
| 7334 | if (RA.isMaxValue()) { |
| 7335 | Pred = ICmpInst::ICMP_EQ; |
| 7336 | Changed = true; |
| 7337 | break; |
| 7338 | } |
| 7339 | if (RA.isMinValue()) goto trivially_true; |
| 7340 | |
| 7341 | Pred = ICmpInst::ICMP_UGT; |
| 7342 | RHS = getConstant(RA - 1); |
| 7343 | Changed = true; |
| 7344 | break; |
| 7345 | case ICmpInst::ICMP_ULE: |
| 7346 | if ((RA + 1).isMaxValue()) { |
| 7347 | Pred = ICmpInst::ICMP_NE; |
| 7348 | RHS = getConstant(RA + 1); |
| 7349 | Changed = true; |
| 7350 | break; |
| 7351 | } |
| 7352 | if (RA.isMinValue()) { |
| 7353 | Pred = ICmpInst::ICMP_EQ; |
| 7354 | Changed = true; |
| 7355 | break; |
| 7356 | } |
| 7357 | if (RA.isMaxValue()) goto trivially_true; |
| 7358 | |
| 7359 | Pred = ICmpInst::ICMP_ULT; |
| 7360 | RHS = getConstant(RA + 1); |
| 7361 | Changed = true; |
| 7362 | break; |
| 7363 | case ICmpInst::ICMP_SGE: |
| 7364 | if ((RA - 1).isMinSignedValue()) { |
| 7365 | Pred = ICmpInst::ICMP_NE; |
| 7366 | RHS = getConstant(RA - 1); |
| 7367 | Changed = true; |
| 7368 | break; |
| 7369 | } |
| 7370 | if (RA.isMaxSignedValue()) { |
| 7371 | Pred = ICmpInst::ICMP_EQ; |
| 7372 | Changed = true; |
| 7373 | break; |
| 7374 | } |
| 7375 | if (RA.isMinSignedValue()) goto trivially_true; |
| 7376 | |
| 7377 | Pred = ICmpInst::ICMP_SGT; |
| 7378 | RHS = getConstant(RA - 1); |
| 7379 | Changed = true; |
| 7380 | break; |
| 7381 | case ICmpInst::ICMP_SLE: |
| 7382 | if ((RA + 1).isMaxSignedValue()) { |
| 7383 | Pred = ICmpInst::ICMP_NE; |
| 7384 | RHS = getConstant(RA + 1); |
| 7385 | Changed = true; |
| 7386 | break; |
| 7387 | } |
| 7388 | if (RA.isMinSignedValue()) { |
| 7389 | Pred = ICmpInst::ICMP_EQ; |
| 7390 | Changed = true; |
| 7391 | break; |
| 7392 | } |
| 7393 | if (RA.isMaxSignedValue()) goto trivially_true; |
| 7394 | |
| 7395 | Pred = ICmpInst::ICMP_SLT; |
| 7396 | RHS = getConstant(RA + 1); |
| 7397 | Changed = true; |
| 7398 | break; |
| 7399 | case ICmpInst::ICMP_UGT: |
| 7400 | if (RA.isMinValue()) { |
| 7401 | Pred = ICmpInst::ICMP_NE; |
| 7402 | Changed = true; |
| 7403 | break; |
| 7404 | } |
| 7405 | if ((RA + 1).isMaxValue()) { |
| 7406 | Pred = ICmpInst::ICMP_EQ; |
| 7407 | RHS = getConstant(RA + 1); |
| 7408 | Changed = true; |
| 7409 | break; |
| 7410 | } |
| 7411 | if (RA.isMaxValue()) goto trivially_false; |
| 7412 | break; |
| 7413 | case ICmpInst::ICMP_ULT: |
| 7414 | if (RA.isMaxValue()) { |
| 7415 | Pred = ICmpInst::ICMP_NE; |
| 7416 | Changed = true; |
| 7417 | break; |
| 7418 | } |
| 7419 | if ((RA - 1).isMinValue()) { |
| 7420 | Pred = ICmpInst::ICMP_EQ; |
| 7421 | RHS = getConstant(RA - 1); |
| 7422 | Changed = true; |
| 7423 | break; |
| 7424 | } |
| 7425 | if (RA.isMinValue()) goto trivially_false; |
| 7426 | break; |
| 7427 | case ICmpInst::ICMP_SGT: |
| 7428 | if (RA.isMinSignedValue()) { |
| 7429 | Pred = ICmpInst::ICMP_NE; |
| 7430 | Changed = true; |
| 7431 | break; |
| 7432 | } |
| 7433 | if ((RA + 1).isMaxSignedValue()) { |
| 7434 | Pred = ICmpInst::ICMP_EQ; |
| 7435 | RHS = getConstant(RA + 1); |
| 7436 | Changed = true; |
| 7437 | break; |
| 7438 | } |
| 7439 | if (RA.isMaxSignedValue()) goto trivially_false; |
| 7440 | break; |
| 7441 | case ICmpInst::ICMP_SLT: |
| 7442 | if (RA.isMaxSignedValue()) { |
| 7443 | Pred = ICmpInst::ICMP_NE; |
| 7444 | Changed = true; |
| 7445 | break; |
| 7446 | } |
| 7447 | if ((RA - 1).isMinSignedValue()) { |
| 7448 | Pred = ICmpInst::ICMP_EQ; |
| 7449 | RHS = getConstant(RA - 1); |
| 7450 | Changed = true; |
| 7451 | break; |
| 7452 | } |
| 7453 | if (RA.isMinSignedValue()) goto trivially_false; |
| 7454 | break; |
| 7455 | } |
| 7456 | } |
| 7457 | |
| 7458 | // Check for obvious equality. |
| 7459 | if (HasSameValue(LHS, RHS)) { |
| 7460 | if (ICmpInst::isTrueWhenEqual(Pred)) |
| 7461 | goto trivially_true; |
| 7462 | if (ICmpInst::isFalseWhenEqual(Pred)) |
| 7463 | goto trivially_false; |
| 7464 | } |
| 7465 | |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7466 | // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by |
| 7467 | // adding or subtracting 1 from one of the operands. |
| 7468 | switch (Pred) { |
| 7469 | case ICmpInst::ICMP_SLE: |
| 7470 | if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { |
| 7471 | RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7472 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7473 | Pred = ICmpInst::ICMP_SLT; |
| 7474 | Changed = true; |
| 7475 | } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7476 | LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7477 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7478 | Pred = ICmpInst::ICMP_SLT; |
| 7479 | Changed = true; |
| 7480 | } |
| 7481 | break; |
| 7482 | case ICmpInst::ICMP_SGE: |
| 7483 | if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7484 | RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7485 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7486 | Pred = ICmpInst::ICMP_SGT; |
| 7487 | Changed = true; |
| 7488 | } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { |
| 7489 | LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7490 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7491 | Pred = ICmpInst::ICMP_SGT; |
| 7492 | Changed = true; |
| 7493 | } |
| 7494 | break; |
| 7495 | case ICmpInst::ICMP_ULE: |
| 7496 | if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7497 | RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7498 | SCEV::FlagNUW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7499 | Pred = ICmpInst::ICMP_ULT; |
| 7500 | Changed = true; |
| 7501 | } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { |
Peter Collingbourne | c85f4ce | 2015-11-20 01:26:13 +0000 | [diff] [blame] | 7502 | LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7503 | Pred = ICmpInst::ICMP_ULT; |
| 7504 | Changed = true; |
| 7505 | } |
| 7506 | break; |
| 7507 | case ICmpInst::ICMP_UGE: |
| 7508 | if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { |
Peter Collingbourne | c85f4ce | 2015-11-20 01:26:13 +0000 | [diff] [blame] | 7509 | RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7510 | Pred = ICmpInst::ICMP_UGT; |
| 7511 | Changed = true; |
| 7512 | } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7513 | LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7514 | SCEV::FlagNUW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7515 | Pred = ICmpInst::ICMP_UGT; |
| 7516 | Changed = true; |
| 7517 | } |
| 7518 | break; |
| 7519 | default: |
| 7520 | break; |
| 7521 | } |
| 7522 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7523 | // TODO: More simplifications are possible here. |
| 7524 | |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7525 | // Recursively simplify until we either hit a recursion limit or nothing |
| 7526 | // changes. |
| 7527 | if (Changed) |
| 7528 | return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); |
| 7529 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7530 | return Changed; |
| 7531 | |
| 7532 | trivially_true: |
| 7533 | // Return 0 == 0. |
Benjamin Kramer | ddd1b7b | 2010-11-20 18:43:35 +0000 | [diff] [blame] | 7534 | LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7535 | Pred = ICmpInst::ICMP_EQ; |
| 7536 | return true; |
| 7537 | |
| 7538 | trivially_false: |
| 7539 | // Return 0 != 0. |
Benjamin Kramer | ddd1b7b | 2010-11-20 18:43:35 +0000 | [diff] [blame] | 7540 | LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7541 | Pred = ICmpInst::ICMP_NE; |
| 7542 | return true; |
| 7543 | } |
| 7544 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7545 | bool ScalarEvolution::isKnownNegative(const SCEV *S) { |
| 7546 | return getSignedRange(S).getSignedMax().isNegative(); |
| 7547 | } |
| 7548 | |
| 7549 | bool ScalarEvolution::isKnownPositive(const SCEV *S) { |
| 7550 | return getSignedRange(S).getSignedMin().isStrictlyPositive(); |
| 7551 | } |
| 7552 | |
| 7553 | bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { |
| 7554 | return !getSignedRange(S).getSignedMin().isNegative(); |
| 7555 | } |
| 7556 | |
| 7557 | bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { |
| 7558 | return !getSignedRange(S).getSignedMax().isStrictlyPositive(); |
| 7559 | } |
| 7560 | |
| 7561 | bool ScalarEvolution::isKnownNonZero(const SCEV *S) { |
| 7562 | return isKnownNegative(S) || isKnownPositive(S); |
| 7563 | } |
| 7564 | |
| 7565 | bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, |
| 7566 | const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | 36cce7e | 2010-04-24 01:38:36 +0000 | [diff] [blame] | 7567 | // Canonicalize the inputs first. |
| 7568 | (void)SimplifyICmpOperands(Pred, LHS, RHS); |
| 7569 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7570 | // If LHS or RHS is an addrec, check to see if the condition is true in |
| 7571 | // every iteration of the loop. |
Justin Bogner | cbb8438 | 2014-05-23 00:06:56 +0000 | [diff] [blame] | 7572 | // If LHS and RHS are both addrec, both conditions must be true in |
| 7573 | // every iteration of the loop. |
| 7574 | const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); |
| 7575 | const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); |
| 7576 | bool LeftGuarded = false; |
| 7577 | bool RightGuarded = false; |
| 7578 | if (LAR) { |
| 7579 | const Loop *L = LAR->getLoop(); |
| 7580 | if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && |
| 7581 | isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { |
| 7582 | if (!RAR) return true; |
| 7583 | LeftGuarded = true; |
| 7584 | } |
| 7585 | } |
| 7586 | if (RAR) { |
| 7587 | const Loop *L = RAR->getLoop(); |
| 7588 | if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && |
| 7589 | isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { |
| 7590 | if (!LAR) return true; |
| 7591 | RightGuarded = true; |
| 7592 | } |
| 7593 | } |
| 7594 | if (LeftGuarded && RightGuarded) |
| 7595 | return true; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7596 | |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7597 | if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) |
| 7598 | return true; |
| 7599 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7600 | // Otherwise see what can be done with known constant ranges. |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7601 | return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7602 | } |
| 7603 | |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7604 | bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, |
| 7605 | ICmpInst::Predicate Pred, |
| 7606 | bool &Increasing) { |
| 7607 | bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); |
| 7608 | |
| 7609 | #ifndef NDEBUG |
| 7610 | // Verify an invariant: inverting the predicate should turn a monotonically |
| 7611 | // increasing change to a monotonically decreasing one, and vice versa. |
| 7612 | bool IncreasingSwapped; |
| 7613 | bool ResultSwapped = isMonotonicPredicateImpl( |
| 7614 | LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); |
| 7615 | |
| 7616 | assert(Result == ResultSwapped && "should be able to analyze both!"); |
| 7617 | if (ResultSwapped) |
| 7618 | assert(Increasing == !IncreasingSwapped && |
| 7619 | "monotonicity should flip as we flip the predicate"); |
| 7620 | #endif |
| 7621 | |
| 7622 | return Result; |
| 7623 | } |
| 7624 | |
| 7625 | bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, |
| 7626 | ICmpInst::Predicate Pred, |
| 7627 | bool &Increasing) { |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7628 | |
| 7629 | // A zero step value for LHS means the induction variable is essentially a |
| 7630 | // loop invariant value. We don't really depend on the predicate actually |
| 7631 | // flipping from false to true (for increasing predicates, and the other way |
| 7632 | // around for decreasing predicates), all we care about is that *if* the |
| 7633 | // predicate changes then it only changes from false to true. |
| 7634 | // |
| 7635 | // A zero step value in itself is not very useful, but there may be places |
| 7636 | // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be |
| 7637 | // as general as possible. |
| 7638 | |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7639 | switch (Pred) { |
| 7640 | default: |
| 7641 | return false; // Conservative answer |
| 7642 | |
| 7643 | case ICmpInst::ICMP_UGT: |
| 7644 | case ICmpInst::ICMP_UGE: |
| 7645 | case ICmpInst::ICMP_ULT: |
| 7646 | case ICmpInst::ICMP_ULE: |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 7647 | if (!LHS->hasNoUnsignedWrap()) |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7648 | return false; |
| 7649 | |
| 7650 | Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7651 | return true; |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7652 | |
| 7653 | case ICmpInst::ICMP_SGT: |
| 7654 | case ICmpInst::ICMP_SGE: |
| 7655 | case ICmpInst::ICMP_SLT: |
| 7656 | case ICmpInst::ICMP_SLE: { |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 7657 | if (!LHS->hasNoSignedWrap()) |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7658 | return false; |
| 7659 | |
| 7660 | const SCEV *Step = LHS->getStepRecurrence(*this); |
| 7661 | |
| 7662 | if (isKnownNonNegative(Step)) { |
| 7663 | Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; |
| 7664 | return true; |
| 7665 | } |
| 7666 | |
| 7667 | if (isKnownNonPositive(Step)) { |
| 7668 | Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; |
| 7669 | return true; |
| 7670 | } |
| 7671 | |
| 7672 | return false; |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7673 | } |
| 7674 | |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7675 | } |
| 7676 | |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7677 | llvm_unreachable("switch has default clause!"); |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7678 | } |
| 7679 | |
| 7680 | bool ScalarEvolution::isLoopInvariantPredicate( |
| 7681 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, |
| 7682 | ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, |
| 7683 | const SCEV *&InvariantRHS) { |
| 7684 | |
| 7685 | // If there is a loop-invariant, force it into the RHS, otherwise bail out. |
| 7686 | if (!isLoopInvariant(RHS, L)) { |
| 7687 | if (!isLoopInvariant(LHS, L)) |
| 7688 | return false; |
| 7689 | |
| 7690 | std::swap(LHS, RHS); |
| 7691 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7692 | } |
| 7693 | |
| 7694 | const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); |
| 7695 | if (!ArLHS || ArLHS->getLoop() != L) |
| 7696 | return false; |
| 7697 | |
| 7698 | bool Increasing; |
| 7699 | if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) |
| 7700 | return false; |
| 7701 | |
| 7702 | // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to |
| 7703 | // true as the loop iterates, and the backedge is control dependent on |
| 7704 | // "ArLHS `Pred` RHS" == true then we can reason as follows: |
| 7705 | // |
| 7706 | // * if the predicate was false in the first iteration then the predicate |
| 7707 | // is never evaluated again, since the loop exits without taking the |
| 7708 | // backedge. |
| 7709 | // * if the predicate was true in the first iteration then it will |
| 7710 | // continue to be true for all future iterations since it is |
| 7711 | // monotonically increasing. |
| 7712 | // |
| 7713 | // For both the above possibilities, we can replace the loop varying |
| 7714 | // predicate with its value on the first iteration of the loop (which is |
| 7715 | // loop invariant). |
| 7716 | // |
| 7717 | // A similar reasoning applies for a monotonically decreasing predicate, by |
| 7718 | // replacing true with false and false with true in the above two bullets. |
| 7719 | |
| 7720 | auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); |
| 7721 | |
| 7722 | if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) |
| 7723 | return false; |
| 7724 | |
| 7725 | InvariantPred = Pred; |
| 7726 | InvariantLHS = ArLHS->getStart(); |
| 7727 | InvariantRHS = RHS; |
| 7728 | return true; |
| 7729 | } |
| 7730 | |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7731 | bool ScalarEvolution::isKnownPredicateViaConstantRanges( |
| 7732 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7733 | if (HasSameValue(LHS, RHS)) |
| 7734 | return ICmpInst::isTrueWhenEqual(Pred); |
| 7735 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7736 | // This code is split out from isKnownPredicate because it is called from |
| 7737 | // within isLoopEntryGuardedByCond. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7738 | |
Sanjoy Das | 4c7b6d7 | 2016-02-01 20:48:14 +0000 | [diff] [blame] | 7739 | auto CheckRanges = |
| 7740 | [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { |
| 7741 | return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) |
| 7742 | .contains(RangeLHS); |
| 7743 | }; |
| 7744 | |
| 7745 | // The check at the top of the function catches the case where the values are |
| 7746 | // known to be equal. |
| 7747 | if (Pred == CmpInst::ICMP_EQ) |
| 7748 | return false; |
| 7749 | |
| 7750 | if (Pred == CmpInst::ICMP_NE) |
| 7751 | return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || |
| 7752 | CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || |
| 7753 | isKnownNonZero(getMinusSCEV(LHS, RHS)); |
| 7754 | |
| 7755 | if (CmpInst::isSigned(Pred)) |
| 7756 | return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); |
| 7757 | |
| 7758 | return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7759 | } |
| 7760 | |
Sanjoy Das | c1a2977 | 2015-11-05 23:45:38 +0000 | [diff] [blame] | 7761 | bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, |
| 7762 | const SCEV *LHS, |
| 7763 | const SCEV *RHS) { |
| 7764 | |
| 7765 | // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. |
| 7766 | // Return Y via OutY. |
| 7767 | auto MatchBinaryAddToConst = |
| 7768 | [this](const SCEV *Result, const SCEV *X, APInt &OutY, |
| 7769 | SCEV::NoWrapFlags ExpectedFlags) { |
| 7770 | const SCEV *NonConstOp, *ConstOp; |
| 7771 | SCEV::NoWrapFlags FlagsPresent; |
| 7772 | |
| 7773 | if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || |
| 7774 | !isa<SCEVConstant>(ConstOp) || NonConstOp != X) |
| 7775 | return false; |
| 7776 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7777 | OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); |
Sanjoy Das | c1a2977 | 2015-11-05 23:45:38 +0000 | [diff] [blame] | 7778 | return (FlagsPresent & ExpectedFlags) == ExpectedFlags; |
| 7779 | }; |
| 7780 | |
| 7781 | APInt C; |
| 7782 | |
| 7783 | switch (Pred) { |
| 7784 | default: |
| 7785 | break; |
| 7786 | |
| 7787 | case ICmpInst::ICMP_SGE: |
| 7788 | std::swap(LHS, RHS); |
| 7789 | case ICmpInst::ICMP_SLE: |
| 7790 | // X s<= (X + C)<nsw> if C >= 0 |
| 7791 | if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) |
| 7792 | return true; |
| 7793 | |
| 7794 | // (X + C)<nsw> s<= X if C <= 0 |
| 7795 | if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && |
| 7796 | !C.isStrictlyPositive()) |
| 7797 | return true; |
| 7798 | break; |
| 7799 | |
| 7800 | case ICmpInst::ICMP_SGT: |
| 7801 | std::swap(LHS, RHS); |
| 7802 | case ICmpInst::ICMP_SLT: |
| 7803 | // X s< (X + C)<nsw> if C > 0 |
| 7804 | if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && |
| 7805 | C.isStrictlyPositive()) |
| 7806 | return true; |
| 7807 | |
| 7808 | // (X + C)<nsw> s< X if C < 0 |
| 7809 | if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) |
| 7810 | return true; |
| 7811 | break; |
| 7812 | } |
| 7813 | |
| 7814 | return false; |
| 7815 | } |
| 7816 | |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7817 | bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, |
| 7818 | const SCEV *LHS, |
| 7819 | const SCEV *RHS) { |
Sanjoy Das | 10dffcb | 2015-10-08 03:46:00 +0000 | [diff] [blame] | 7820 | if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7821 | return false; |
| 7822 | |
| 7823 | // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on |
| 7824 | // the stack can result in exponential time complexity. |
| 7825 | SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); |
| 7826 | |
| 7827 | // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L |
| 7828 | // |
| 7829 | // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use |
| 7830 | // isKnownPredicate. isKnownPredicate is more powerful, but also more |
| 7831 | // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the |
| 7832 | // interesting cases seen in practice. We can consider "upgrading" L >= 0 to |
| 7833 | // use isKnownPredicate later if needed. |
Alexander Kornienko | 484e48e3 | 2015-11-05 21:07:12 +0000 | [diff] [blame] | 7834 | return isKnownNonNegative(RHS) && |
| 7835 | isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && |
| 7836 | isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7837 | } |
| 7838 | |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 7839 | bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, |
| 7840 | ICmpInst::Predicate Pred, |
| 7841 | const SCEV *LHS, const SCEV *RHS) { |
| 7842 | // No need to even try if we know the module has no guards. |
| 7843 | if (!HasGuards) |
| 7844 | return false; |
| 7845 | |
| 7846 | return any_of(*BB, [&](Instruction &I) { |
| 7847 | using namespace llvm::PatternMatch; |
| 7848 | |
| 7849 | Value *Condition; |
| 7850 | return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( |
| 7851 | m_Value(Condition))) && |
| 7852 | isImpliedCond(Pred, LHS, RHS, Condition, false); |
| 7853 | }); |
| 7854 | } |
| 7855 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7856 | /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is |
| 7857 | /// protected by a conditional between LHS and RHS. This is used to |
| 7858 | /// to eliminate casts. |
| 7859 | bool |
| 7860 | ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, |
| 7861 | ICmpInst::Predicate Pred, |
| 7862 | const SCEV *LHS, const SCEV *RHS) { |
| 7863 | // Interpret a null as meaning no loop, where there is obviously no guard |
| 7864 | // (interprocedural conditions notwithstanding). |
| 7865 | if (!L) return true; |
| 7866 | |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7867 | if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) |
| 7868 | return true; |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 7869 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7870 | BasicBlock *Latch = L->getLoopLatch(); |
| 7871 | if (!Latch) |
| 7872 | return false; |
| 7873 | |
| 7874 | BranchInst *LoopContinuePredicate = |
| 7875 | dyn_cast<BranchInst>(Latch->getTerminator()); |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 7876 | if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && |
| 7877 | isImpliedCond(Pred, LHS, RHS, |
| 7878 | LoopContinuePredicate->getCondition(), |
| 7879 | LoopContinuePredicate->getSuccessor(0) != L->getHeader())) |
| 7880 | return true; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7881 | |
Piotr Padlewski | 0dde00d2 | 2015-09-09 20:47:30 +0000 | [diff] [blame] | 7882 | // We don't want more than one activation of the following loops on the stack |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7883 | // -- that can lead to O(n!) time complexity. |
| 7884 | if (WalkingBEDominatingConds) |
| 7885 | return false; |
| 7886 | |
Sanjoy Das | 5d9a8cb | 2015-09-22 00:10:57 +0000 | [diff] [blame] | 7887 | SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7888 | |
Sanjoy Das | b174f9a | 2015-09-25 23:53:50 +0000 | [diff] [blame] | 7889 | // See if we can exploit a trip count to prove the predicate. |
| 7890 | const auto &BETakenInfo = getBackedgeTakenInfo(L); |
| 7891 | const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); |
| 7892 | if (LatchBECount != getCouldNotCompute()) { |
| 7893 | // We know that Latch branches back to the loop header exactly |
| 7894 | // LatchBECount times. This means the backdege condition at Latch is |
| 7895 | // equivalent to "{0,+,1} u< LatchBECount". |
| 7896 | Type *Ty = LatchBECount->getType(); |
| 7897 | auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); |
| 7898 | const SCEV *LoopCounter = |
| 7899 | getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); |
| 7900 | if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, |
| 7901 | LatchBECount)) |
| 7902 | return true; |
| 7903 | } |
| 7904 | |
Piotr Padlewski | 0dde00d2 | 2015-09-09 20:47:30 +0000 | [diff] [blame] | 7905 | // Check conditions due to any @llvm.assume intrinsics. |
| 7906 | for (auto &AssumeVH : AC.assumptions()) { |
| 7907 | if (!AssumeVH) |
| 7908 | continue; |
| 7909 | auto *CI = cast<CallInst>(AssumeVH); |
| 7910 | if (!DT.dominates(CI, Latch->getTerminator())) |
| 7911 | continue; |
| 7912 | |
| 7913 | if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) |
| 7914 | return true; |
| 7915 | } |
| 7916 | |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7917 | // If the loop is not reachable from the entry block, we risk running into an |
| 7918 | // infinite loop as we walk up into the dom tree. These loops do not matter |
| 7919 | // anyway, so we just return a conservative answer when we see them. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7920 | if (!DT.isReachableFromEntry(L->getHeader())) |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7921 | return false; |
| 7922 | |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 7923 | if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) |
| 7924 | return true; |
| 7925 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7926 | for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; |
| 7927 | DTN != HeaderDTN; DTN = DTN->getIDom()) { |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7928 | |
| 7929 | assert(DTN && "should reach the loop header before reaching the root!"); |
| 7930 | |
| 7931 | BasicBlock *BB = DTN->getBlock(); |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 7932 | if (isImpliedViaGuard(BB, Pred, LHS, RHS)) |
| 7933 | return true; |
| 7934 | |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7935 | BasicBlock *PBB = BB->getSinglePredecessor(); |
| 7936 | if (!PBB) |
| 7937 | continue; |
| 7938 | |
| 7939 | BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); |
| 7940 | if (!ContinuePredicate || !ContinuePredicate->isConditional()) |
| 7941 | continue; |
| 7942 | |
| 7943 | Value *Condition = ContinuePredicate->getCondition(); |
| 7944 | |
| 7945 | // If we have an edge `E` within the loop body that dominates the only |
| 7946 | // latch, the condition guarding `E` also guards the backedge. This |
| 7947 | // reasoning works only for loops with a single latch. |
| 7948 | |
| 7949 | BasicBlockEdge DominatingEdge(PBB, BB); |
| 7950 | if (DominatingEdge.isSingleEdge()) { |
| 7951 | // We're constructively (and conservatively) enumerating edges within the |
| 7952 | // loop body that dominate the latch. The dominator tree better agree |
| 7953 | // with us on this: |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7954 | assert(DT.dominates(DominatingEdge, Latch) && "should be!"); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7955 | |
| 7956 | if (isImpliedCond(Pred, LHS, RHS, Condition, |
| 7957 | BB != ContinuePredicate->getSuccessor(0))) |
| 7958 | return true; |
| 7959 | } |
| 7960 | } |
| 7961 | |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 7962 | return false; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7963 | } |
| 7964 | |
Dan Gohman | b50349a | 2010-04-11 19:27:13 +0000 | [diff] [blame] | 7965 | /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7966 | /// by a conditional between LHS and RHS. This is used to help avoid max |
| 7967 | /// expressions in loop trip counts, and to eliminate casts. |
| 7968 | bool |
Dan Gohman | b50349a | 2010-04-11 19:27:13 +0000 | [diff] [blame] | 7969 | ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, |
| 7970 | ICmpInst::Predicate Pred, |
| 7971 | const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | 9cf09f8 | 2009-05-18 16:03:58 +0000 | [diff] [blame] | 7972 | // Interpret a null as meaning no loop, where there is obviously no guard |
| 7973 | // (interprocedural conditions notwithstanding). |
| 7974 | if (!L) return false; |
| 7975 | |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7976 | if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) |
| 7977 | return true; |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 7978 | |
Dan Gohman | 8c77f1a | 2009-05-18 15:36:09 +0000 | [diff] [blame] | 7979 | // Starting at the loop predecessor, climb up the predecessor chain, as long |
| 7980 | // as there are predecessors that can be found that have unique successors |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7981 | // leading to the original header. |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7982 | for (std::pair<BasicBlock *, BasicBlock *> |
Dan Gohman | 75c6b0b | 2010-06-22 23:43:28 +0000 | [diff] [blame] | 7983 | Pair(L->getLoopPredecessor(), L->getHeader()); |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7984 | Pair.first; |
| 7985 | Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7986 | |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 7987 | if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) |
| 7988 | return true; |
| 7989 | |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7990 | BranchInst *LoopEntryPredicate = |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7991 | dyn_cast<BranchInst>(Pair.first->getTerminator()); |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7992 | if (!LoopEntryPredicate || |
| 7993 | LoopEntryPredicate->isUnconditional()) |
| 7994 | continue; |
| 7995 | |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7996 | if (isImpliedCond(Pred, LHS, RHS, |
| 7997 | LoopEntryPredicate->getCondition(), |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7998 | LoopEntryPredicate->getSuccessor(0) != Pair.second)) |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7999 | return true; |
Nick Lewycky | b5688cc | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 8000 | } |
| 8001 | |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 8002 | // Check conditions due to any @llvm.assume intrinsics. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8003 | for (auto &AssumeVH : AC.assumptions()) { |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 8004 | if (!AssumeVH) |
| 8005 | continue; |
| 8006 | auto *CI = cast<CallInst>(AssumeVH); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8007 | if (!DT.dominates(CI, L->getHeader())) |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 8008 | continue; |
| 8009 | |
| 8010 | if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) |
| 8011 | return true; |
| 8012 | } |
| 8013 | |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 8014 | return false; |
Nick Lewycky | b5688cc | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 8015 | } |
| 8016 | |
Benjamin Kramer | 039b104 | 2015-10-28 13:54:36 +0000 | [diff] [blame] | 8017 | namespace { |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 8018 | /// RAII wrapper to prevent recursive application of isImpliedCond. |
| 8019 | /// ScalarEvolution's PendingLoopPredicates set must be empty unless we are |
| 8020 | /// currently evaluating isImpliedCond. |
| 8021 | struct MarkPendingLoopPredicate { |
| 8022 | Value *Cond; |
| 8023 | DenseSet<Value*> &LoopPreds; |
| 8024 | bool Pending; |
| 8025 | |
| 8026 | MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP) |
| 8027 | : Cond(C), LoopPreds(LP) { |
| 8028 | Pending = !LoopPreds.insert(Cond).second; |
| 8029 | } |
| 8030 | ~MarkPendingLoopPredicate() { |
| 8031 | if (!Pending) |
| 8032 | LoopPreds.erase(Cond); |
| 8033 | } |
| 8034 | }; |
Benjamin Kramer | 039b104 | 2015-10-28 13:54:36 +0000 | [diff] [blame] | 8035 | } // end anonymous namespace |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 8036 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8037 | /// isImpliedCond - Test whether the condition described by Pred, LHS, |
| 8038 | /// and RHS is true whenever the given Cond value evaluates to true. |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8039 | bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8040 | const SCEV *LHS, const SCEV *RHS, |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8041 | Value *FoundCondValue, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8042 | bool Inverse) { |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 8043 | MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates); |
| 8044 | if (Mark.Pending) |
| 8045 | return false; |
| 8046 | |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 8047 | // Recursively handle And and Or conditions. |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8048 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8049 | if (BO->getOpcode() == Instruction::And) { |
| 8050 | if (!Inverse) |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8051 | return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || |
| 8052 | isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8053 | } else if (BO->getOpcode() == Instruction::Or) { |
| 8054 | if (Inverse) |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8055 | return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || |
| 8056 | isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8057 | } |
| 8058 | } |
| 8059 | |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8060 | ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8061 | if (!ICI) return false; |
| 8062 | |
Andrew Trick | fa59403 | 2012-11-29 18:35:13 +0000 | [diff] [blame] | 8063 | // Now that we found a conditional branch that dominates the loop or controls |
| 8064 | // the loop latch. Check to see if it is the comparison we are looking for. |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8065 | ICmpInst::Predicate FoundPred; |
| 8066 | if (Inverse) |
| 8067 | FoundPred = ICI->getInversePredicate(); |
| 8068 | else |
| 8069 | FoundPred = ICI->getPredicate(); |
| 8070 | |
| 8071 | const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); |
| 8072 | const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8073 | |
Sanjoy Das | df1635d | 2015-09-25 19:59:52 +0000 | [diff] [blame] | 8074 | return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); |
| 8075 | } |
| 8076 | |
| 8077 | bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, |
| 8078 | const SCEV *RHS, |
| 8079 | ICmpInst::Predicate FoundPred, |
| 8080 | const SCEV *FoundLHS, |
| 8081 | const SCEV *FoundRHS) { |
Sanjoy Das | 1459883 | 2015-03-26 17:28:26 +0000 | [diff] [blame] | 8082 | // Balance the types. |
| 8083 | if (getTypeSizeInBits(LHS->getType()) < |
| 8084 | getTypeSizeInBits(FoundLHS->getType())) { |
| 8085 | if (CmpInst::isSigned(Pred)) { |
| 8086 | LHS = getSignExtendExpr(LHS, FoundLHS->getType()); |
| 8087 | RHS = getSignExtendExpr(RHS, FoundLHS->getType()); |
| 8088 | } else { |
| 8089 | LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); |
| 8090 | RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); |
| 8091 | } |
| 8092 | } else if (getTypeSizeInBits(LHS->getType()) > |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8093 | getTypeSizeInBits(FoundLHS->getType())) { |
Stepan Dyatkovskiy | 431993b | 2014-01-09 12:26:12 +0000 | [diff] [blame] | 8094 | if (CmpInst::isSigned(FoundPred)) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8095 | FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); |
| 8096 | FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); |
| 8097 | } else { |
| 8098 | FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); |
| 8099 | FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); |
| 8100 | } |
| 8101 | } |
| 8102 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8103 | // Canonicalize the query to match the way instcombine will have |
| 8104 | // canonicalized the comparison. |
Dan Gohman | 3673aa1 | 2010-04-24 01:34:53 +0000 | [diff] [blame] | 8105 | if (SimplifyICmpOperands(Pred, LHS, RHS)) |
| 8106 | if (LHS == RHS) |
Dan Gohman | b5025c7 | 2010-05-03 18:00:24 +0000 | [diff] [blame] | 8107 | return CmpInst::isTrueWhenEqual(Pred); |
Benjamin Kramer | ba11a98 | 2012-11-29 19:07:57 +0000 | [diff] [blame] | 8108 | if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) |
| 8109 | if (FoundLHS == FoundRHS) |
| 8110 | return CmpInst::isFalseWhenEqual(FoundPred); |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8111 | |
| 8112 | // Check to see if we can make the LHS or RHS match. |
| 8113 | if (LHS == FoundRHS || RHS == FoundLHS) { |
| 8114 | if (isa<SCEVConstant>(RHS)) { |
| 8115 | std::swap(FoundLHS, FoundRHS); |
| 8116 | FoundPred = ICmpInst::getSwappedPredicate(FoundPred); |
| 8117 | } else { |
| 8118 | std::swap(LHS, RHS); |
| 8119 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 8120 | } |
| 8121 | } |
| 8122 | |
| 8123 | // Check whether the found predicate is the same as the desired predicate. |
| 8124 | if (FoundPred == Pred) |
| 8125 | return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); |
| 8126 | |
| 8127 | // Check whether swapping the found predicate makes it the same as the |
| 8128 | // desired predicate. |
| 8129 | if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { |
| 8130 | if (isa<SCEVConstant>(RHS)) |
| 8131 | return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); |
| 8132 | else |
| 8133 | return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), |
| 8134 | RHS, LHS, FoundLHS, FoundRHS); |
| 8135 | } |
| 8136 | |
Sanjoy Das | 6e78b17 | 2015-10-22 19:57:34 +0000 | [diff] [blame] | 8137 | // Unsigned comparison is the same as signed comparison when both the operands |
| 8138 | // are non-negative. |
| 8139 | if (CmpInst::isUnsigned(FoundPred) && |
| 8140 | CmpInst::getSignedPredicate(FoundPred) == Pred && |
| 8141 | isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) |
| 8142 | return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); |
| 8143 | |
Sanjoy Das | c5676df | 2014-11-13 00:00:58 +0000 | [diff] [blame] | 8144 | // Check if we can make progress by sharpening ranges. |
| 8145 | if (FoundPred == ICmpInst::ICMP_NE && |
| 8146 | (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { |
| 8147 | |
| 8148 | const SCEVConstant *C = nullptr; |
| 8149 | const SCEV *V = nullptr; |
| 8150 | |
| 8151 | if (isa<SCEVConstant>(FoundLHS)) { |
| 8152 | C = cast<SCEVConstant>(FoundLHS); |
| 8153 | V = FoundRHS; |
| 8154 | } else { |
| 8155 | C = cast<SCEVConstant>(FoundRHS); |
| 8156 | V = FoundLHS; |
| 8157 | } |
| 8158 | |
| 8159 | // The guarding predicate tells us that C != V. If the known range |
| 8160 | // of V is [C, t), we can sharpen the range to [C + 1, t). The |
| 8161 | // range we consider has to correspond to same signedness as the |
| 8162 | // predicate we're interested in folding. |
| 8163 | |
| 8164 | APInt Min = ICmpInst::isSigned(Pred) ? |
| 8165 | getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); |
| 8166 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8167 | if (Min == C->getAPInt()) { |
Sanjoy Das | c5676df | 2014-11-13 00:00:58 +0000 | [diff] [blame] | 8168 | // Given (V >= Min && V != Min) we conclude V >= (Min + 1). |
| 8169 | // This is true even if (Min + 1) wraps around -- in case of |
| 8170 | // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). |
| 8171 | |
| 8172 | APInt SharperMin = Min + 1; |
| 8173 | |
| 8174 | switch (Pred) { |
| 8175 | case ICmpInst::ICMP_SGE: |
| 8176 | case ICmpInst::ICMP_UGE: |
| 8177 | // We know V `Pred` SharperMin. If this implies LHS `Pred` |
| 8178 | // RHS, we're done. |
| 8179 | if (isImpliedCondOperands(Pred, LHS, RHS, V, |
| 8180 | getConstant(SharperMin))) |
| 8181 | return true; |
| 8182 | |
| 8183 | case ICmpInst::ICMP_SGT: |
| 8184 | case ICmpInst::ICMP_UGT: |
| 8185 | // We know from the range information that (V `Pred` Min || |
| 8186 | // V == Min). We know from the guarding condition that !(V |
| 8187 | // == Min). This gives us |
| 8188 | // |
| 8189 | // V `Pred` Min || V == Min && !(V == Min) |
| 8190 | // => V `Pred` Min |
| 8191 | // |
| 8192 | // If V `Pred` Min implies LHS `Pred` RHS, we're done. |
| 8193 | |
| 8194 | if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) |
| 8195 | return true; |
| 8196 | |
| 8197 | default: |
| 8198 | // No change |
| 8199 | break; |
| 8200 | } |
| 8201 | } |
| 8202 | } |
| 8203 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8204 | // Check whether the actual condition is beyond sufficient. |
| 8205 | if (FoundPred == ICmpInst::ICMP_EQ) |
| 8206 | if (ICmpInst::isTrueWhenEqual(Pred)) |
| 8207 | if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8208 | return true; |
| 8209 | if (Pred == ICmpInst::ICMP_NE) |
| 8210 | if (!ICmpInst::isTrueWhenEqual(FoundPred)) |
| 8211 | if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8212 | return true; |
| 8213 | |
| 8214 | // Otherwise assume the worst. |
| 8215 | return false; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8216 | } |
| 8217 | |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8218 | bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, |
| 8219 | const SCEV *&L, const SCEV *&R, |
| 8220 | SCEV::NoWrapFlags &Flags) { |
| 8221 | const auto *AE = dyn_cast<SCEVAddExpr>(Expr); |
| 8222 | if (!AE || AE->getNumOperands() != 2) |
| 8223 | return false; |
| 8224 | |
| 8225 | L = AE->getOperand(0); |
| 8226 | R = AE->getOperand(1); |
| 8227 | Flags = AE->getNoWrapFlags(); |
| 8228 | return true; |
| 8229 | } |
| 8230 | |
| 8231 | bool ScalarEvolution::computeConstantDifference(const SCEV *Less, |
| 8232 | const SCEV *More, |
| 8233 | APInt &C) { |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8234 | // We avoid subtracting expressions here because this function is usually |
| 8235 | // fairly deep in the call stack (i.e. is called many times). |
| 8236 | |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8237 | if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { |
| 8238 | const auto *LAR = cast<SCEVAddRecExpr>(Less); |
| 8239 | const auto *MAR = cast<SCEVAddRecExpr>(More); |
| 8240 | |
| 8241 | if (LAR->getLoop() != MAR->getLoop()) |
| 8242 | return false; |
| 8243 | |
| 8244 | // We look at affine expressions only; not for correctness but to keep |
| 8245 | // getStepRecurrence cheap. |
| 8246 | if (!LAR->isAffine() || !MAR->isAffine()) |
| 8247 | return false; |
| 8248 | |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8249 | if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8250 | return false; |
| 8251 | |
| 8252 | Less = LAR->getStart(); |
| 8253 | More = MAR->getStart(); |
| 8254 | |
| 8255 | // fall through |
| 8256 | } |
| 8257 | |
| 8258 | if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8259 | const auto &M = cast<SCEVConstant>(More)->getAPInt(); |
| 8260 | const auto &L = cast<SCEVConstant>(Less)->getAPInt(); |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8261 | C = M - L; |
| 8262 | return true; |
| 8263 | } |
| 8264 | |
| 8265 | const SCEV *L, *R; |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8266 | SCEV::NoWrapFlags Flags; |
| 8267 | if (splitBinaryAdd(Less, L, R, Flags)) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8268 | if (const auto *LC = dyn_cast<SCEVConstant>(L)) |
| 8269 | if (R == More) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8270 | C = -(LC->getAPInt()); |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8271 | return true; |
| 8272 | } |
| 8273 | |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8274 | if (splitBinaryAdd(More, L, R, Flags)) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8275 | if (const auto *LC = dyn_cast<SCEVConstant>(L)) |
| 8276 | if (R == Less) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8277 | C = LC->getAPInt(); |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8278 | return true; |
| 8279 | } |
| 8280 | |
| 8281 | return false; |
| 8282 | } |
| 8283 | |
| 8284 | bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( |
| 8285 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, |
| 8286 | const SCEV *FoundLHS, const SCEV *FoundRHS) { |
| 8287 | if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) |
| 8288 | return false; |
| 8289 | |
| 8290 | const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); |
| 8291 | if (!AddRecLHS) |
| 8292 | return false; |
| 8293 | |
| 8294 | const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); |
| 8295 | if (!AddRecFoundLHS) |
| 8296 | return false; |
| 8297 | |
| 8298 | // We'd like to let SCEV reason about control dependencies, so we constrain |
| 8299 | // both the inequalities to be about add recurrences on the same loop. This |
| 8300 | // way we can use isLoopEntryGuardedByCond later. |
| 8301 | |
| 8302 | const Loop *L = AddRecFoundLHS->getLoop(); |
| 8303 | if (L != AddRecLHS->getLoop()) |
| 8304 | return false; |
| 8305 | |
| 8306 | // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) |
| 8307 | // |
| 8308 | // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) |
| 8309 | // ... (2) |
| 8310 | // |
| 8311 | // Informal proof for (2), assuming (1) [*]: |
| 8312 | // |
| 8313 | // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] |
| 8314 | // |
| 8315 | // Then |
| 8316 | // |
| 8317 | // FoundLHS s< FoundRHS s< INT_MIN - C |
| 8318 | // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] |
| 8319 | // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] |
| 8320 | // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< |
| 8321 | // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] |
| 8322 | // <=> FoundLHS + C s< FoundRHS + C |
| 8323 | // |
| 8324 | // [*]: (1) can be proved by ruling out overflow. |
| 8325 | // |
| 8326 | // [**]: This can be proved by analyzing all the four possibilities: |
| 8327 | // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and |
| 8328 | // (A s>= 0, B s>= 0). |
| 8329 | // |
| 8330 | // Note: |
| 8331 | // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" |
| 8332 | // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS |
| 8333 | // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS |
| 8334 | // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is |
| 8335 | // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + |
| 8336 | // C)". |
| 8337 | |
| 8338 | APInt LDiff, RDiff; |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8339 | if (!computeConstantDifference(FoundLHS, LHS, LDiff) || |
| 8340 | !computeConstantDifference(FoundRHS, RHS, RDiff) || |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8341 | LDiff != RDiff) |
| 8342 | return false; |
| 8343 | |
| 8344 | if (LDiff == 0) |
| 8345 | return true; |
| 8346 | |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8347 | APInt FoundRHSLimit; |
| 8348 | |
| 8349 | if (Pred == CmpInst::ICMP_ULT) { |
| 8350 | FoundRHSLimit = -RDiff; |
| 8351 | } else { |
| 8352 | assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); |
Sanjoy Das | 4f1c459 | 2015-09-28 21:14:32 +0000 | [diff] [blame] | 8353 | FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - RDiff; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8354 | } |
| 8355 | |
| 8356 | // Try to prove (1) or (2), as needed. |
| 8357 | return isLoopEntryGuardedByCond(L, Pred, FoundRHS, |
| 8358 | getConstant(FoundRHSLimit)); |
| 8359 | } |
| 8360 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8361 | /// isImpliedCondOperands - Test whether the condition described by Pred, |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 8362 | /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8363 | /// and FoundRHS is true. |
| 8364 | bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, |
| 8365 | const SCEV *LHS, const SCEV *RHS, |
| 8366 | const SCEV *FoundLHS, |
| 8367 | const SCEV *FoundRHS) { |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8368 | if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8369 | return true; |
| 8370 | |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8371 | if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8372 | return true; |
| 8373 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8374 | return isImpliedCondOperandsHelper(Pred, LHS, RHS, |
| 8375 | FoundLHS, FoundRHS) || |
| 8376 | // ~x < ~y --> x > y |
| 8377 | isImpliedCondOperandsHelper(Pred, LHS, RHS, |
| 8378 | getNotSCEV(FoundRHS), |
| 8379 | getNotSCEV(FoundLHS)); |
| 8380 | } |
| 8381 | |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8382 | |
| 8383 | /// If Expr computes ~A, return A else return nullptr |
| 8384 | static const SCEV *MatchNotExpr(const SCEV *Expr) { |
| 8385 | const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); |
Sanjoy Das | 16e7ff1 | 2015-10-13 23:28:31 +0000 | [diff] [blame] | 8386 | if (!Add || Add->getNumOperands() != 2 || |
| 8387 | !Add->getOperand(0)->isAllOnesValue()) |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8388 | return nullptr; |
| 8389 | |
| 8390 | const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); |
Sanjoy Das | 16e7ff1 | 2015-10-13 23:28:31 +0000 | [diff] [blame] | 8391 | if (!AddRHS || AddRHS->getNumOperands() != 2 || |
| 8392 | !AddRHS->getOperand(0)->isAllOnesValue()) |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8393 | return nullptr; |
| 8394 | |
| 8395 | return AddRHS->getOperand(1); |
| 8396 | } |
| 8397 | |
| 8398 | |
| 8399 | /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? |
| 8400 | template<typename MaxExprType> |
| 8401 | static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, |
| 8402 | const SCEV *Candidate) { |
| 8403 | const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); |
| 8404 | if (!MaxExpr) return false; |
| 8405 | |
Sanjoy Das | 347d272 | 2015-12-01 07:49:27 +0000 | [diff] [blame] | 8406 | return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8407 | } |
| 8408 | |
| 8409 | |
| 8410 | /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? |
| 8411 | template<typename MaxExprType> |
| 8412 | static bool IsMinConsistingOf(ScalarEvolution &SE, |
| 8413 | const SCEV *MaybeMinExpr, |
| 8414 | const SCEV *Candidate) { |
| 8415 | const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); |
| 8416 | if (!MaybeMaxExpr) |
| 8417 | return false; |
| 8418 | |
| 8419 | return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); |
| 8420 | } |
| 8421 | |
Hal Finkel | a8d205f | 2015-08-19 01:51:51 +0000 | [diff] [blame] | 8422 | static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, |
| 8423 | ICmpInst::Predicate Pred, |
| 8424 | const SCEV *LHS, const SCEV *RHS) { |
| 8425 | |
| 8426 | // If both sides are affine addrecs for the same loop, with equal |
| 8427 | // steps, and we know the recurrences don't wrap, then we only |
| 8428 | // need to check the predicate on the starting values. |
| 8429 | |
| 8430 | if (!ICmpInst::isRelational(Pred)) |
| 8431 | return false; |
| 8432 | |
| 8433 | const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); |
| 8434 | if (!LAR) |
| 8435 | return false; |
| 8436 | const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); |
| 8437 | if (!RAR) |
| 8438 | return false; |
| 8439 | if (LAR->getLoop() != RAR->getLoop()) |
| 8440 | return false; |
| 8441 | if (!LAR->isAffine() || !RAR->isAffine()) |
| 8442 | return false; |
| 8443 | |
| 8444 | if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) |
| 8445 | return false; |
| 8446 | |
Hal Finkel | ff08a2e | 2015-08-19 17:26:07 +0000 | [diff] [blame] | 8447 | SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? |
| 8448 | SCEV::FlagNSW : SCEV::FlagNUW; |
| 8449 | if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) |
Hal Finkel | a8d205f | 2015-08-19 01:51:51 +0000 | [diff] [blame] | 8450 | return false; |
| 8451 | |
| 8452 | return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); |
| 8453 | } |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8454 | |
| 8455 | /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max |
| 8456 | /// expression? |
| 8457 | static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, |
| 8458 | ICmpInst::Predicate Pred, |
| 8459 | const SCEV *LHS, const SCEV *RHS) { |
| 8460 | switch (Pred) { |
| 8461 | default: |
| 8462 | return false; |
| 8463 | |
| 8464 | case ICmpInst::ICMP_SGE: |
| 8465 | std::swap(LHS, RHS); |
| 8466 | // fall through |
| 8467 | case ICmpInst::ICMP_SLE: |
| 8468 | return |
| 8469 | // min(A, ...) <= A |
| 8470 | IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || |
| 8471 | // A <= max(A, ...) |
| 8472 | IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); |
| 8473 | |
| 8474 | case ICmpInst::ICMP_UGE: |
| 8475 | std::swap(LHS, RHS); |
| 8476 | // fall through |
| 8477 | case ICmpInst::ICMP_ULE: |
| 8478 | return |
| 8479 | // min(A, ...) <= A |
| 8480 | IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || |
| 8481 | // A <= max(A, ...) |
| 8482 | IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); |
| 8483 | } |
| 8484 | |
| 8485 | llvm_unreachable("covered switch fell through?!"); |
| 8486 | } |
| 8487 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8488 | /// isImpliedCondOperandsHelper - Test whether the condition described by |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 8489 | /// Pred, LHS, and RHS is true whenever the condition described by Pred, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8490 | /// FoundLHS, and FoundRHS is true. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8491 | bool |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8492 | ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, |
| 8493 | const SCEV *LHS, const SCEV *RHS, |
| 8494 | const SCEV *FoundLHS, |
| 8495 | const SCEV *FoundRHS) { |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8496 | auto IsKnownPredicateFull = |
| 8497 | [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 8498 | return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || |
Sanjoy Das | 1123148 | 2015-10-22 19:57:29 +0000 | [diff] [blame] | 8499 | IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || |
Sanjoy Das | c1a2977 | 2015-11-05 23:45:38 +0000 | [diff] [blame] | 8500 | IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || |
| 8501 | isKnownPredicateViaNoOverflow(Pred, LHS, RHS); |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8502 | }; |
| 8503 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8504 | switch (Pred) { |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8505 | default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); |
| 8506 | case ICmpInst::ICMP_EQ: |
| 8507 | case ICmpInst::ICMP_NE: |
| 8508 | if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) |
| 8509 | return true; |
| 8510 | break; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8511 | case ICmpInst::ICMP_SLT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8512 | case ICmpInst::ICMP_SLE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8513 | if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) && |
| 8514 | IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8515 | return true; |
| 8516 | break; |
| 8517 | case ICmpInst::ICMP_SGT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8518 | case ICmpInst::ICMP_SGE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8519 | if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) && |
| 8520 | IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8521 | return true; |
| 8522 | break; |
| 8523 | case ICmpInst::ICMP_ULT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8524 | case ICmpInst::ICMP_ULE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8525 | if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) && |
| 8526 | IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8527 | return true; |
| 8528 | break; |
| 8529 | case ICmpInst::ICMP_UGT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8530 | case ICmpInst::ICMP_UGE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8531 | if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) && |
| 8532 | IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8533 | return true; |
| 8534 | break; |
| 8535 | } |
| 8536 | |
| 8537 | return false; |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8538 | } |
| 8539 | |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8540 | /// isImpliedCondOperandsViaRanges - helper function for isImpliedCondOperands. |
| 8541 | /// Tries to get cases like "X `sgt` 0 => X - 1 `sgt` -1". |
| 8542 | bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, |
| 8543 | const SCEV *LHS, |
| 8544 | const SCEV *RHS, |
| 8545 | const SCEV *FoundLHS, |
| 8546 | const SCEV *FoundRHS) { |
| 8547 | if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) |
| 8548 | // The restriction on `FoundRHS` be lifted easily -- it exists only to |
| 8549 | // reduce the compile time impact of this optimization. |
| 8550 | return false; |
| 8551 | |
| 8552 | const SCEVAddExpr *AddLHS = dyn_cast<SCEVAddExpr>(LHS); |
| 8553 | if (!AddLHS || AddLHS->getOperand(1) != FoundLHS || |
| 8554 | !isa<SCEVConstant>(AddLHS->getOperand(0))) |
| 8555 | return false; |
| 8556 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8557 | APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8558 | |
| 8559 | // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the |
| 8560 | // antecedent "`FoundLHS` `Pred` `FoundRHS`". |
| 8561 | ConstantRange FoundLHSRange = |
| 8562 | ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); |
| 8563 | |
| 8564 | // Since `LHS` is `FoundLHS` + `AddLHS->getOperand(0)`, we can compute a range |
| 8565 | // for `LHS`: |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8566 | APInt Addend = cast<SCEVConstant>(AddLHS->getOperand(0))->getAPInt(); |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8567 | ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(Addend)); |
| 8568 | |
| 8569 | // We can also compute the range of values for `LHS` that satisfy the |
| 8570 | // consequent, "`LHS` `Pred` `RHS`": |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8571 | APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8572 | ConstantRange SatisfyingLHSRange = |
| 8573 | ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); |
| 8574 | |
| 8575 | // The antecedent implies the consequent if every value of `LHS` that |
| 8576 | // satisfies the antecedent also satisfies the consequent. |
| 8577 | return SatisfyingLHSRange.contains(LHSRange); |
| 8578 | } |
| 8579 | |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8580 | // Verify if an linear IV with positive stride can overflow when in a |
| 8581 | // less-than comparison, knowing the invariant term of the comparison, the |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8582 | // stride and the knowledge of NSW/NUW flags on the recurrence. |
| 8583 | bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, |
| 8584 | bool IsSigned, bool NoWrap) { |
| 8585 | if (NoWrap) return false; |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 8586 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8587 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8588 | const SCEV *One = getOne(Stride->getType()); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 8589 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8590 | if (IsSigned) { |
| 8591 | APInt MaxRHS = getSignedRange(RHS).getSignedMax(); |
| 8592 | APInt MaxValue = APInt::getSignedMaxValue(BitWidth); |
| 8593 | APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) |
| 8594 | .getSignedMax(); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 8595 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8596 | // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! |
| 8597 | return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 8598 | } |
Dan Gohman | 0104842 | 2009-06-21 23:46:38 +0000 | [diff] [blame] | 8599 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8600 | APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); |
| 8601 | APInt MaxValue = APInt::getMaxValue(BitWidth); |
| 8602 | APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) |
| 8603 | .getUnsignedMax(); |
| 8604 | |
| 8605 | // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! |
| 8606 | return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); |
| 8607 | } |
| 8608 | |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8609 | // Verify if an linear IV with negative stride can overflow when in a |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8610 | // greater-than comparison, knowing the invariant term of the comparison, |
| 8611 | // the stride and the knowledge of NSW/NUW flags on the recurrence. |
| 8612 | bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, |
| 8613 | bool IsSigned, bool NoWrap) { |
| 8614 | if (NoWrap) return false; |
| 8615 | |
| 8616 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8617 | const SCEV *One = getOne(Stride->getType()); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8618 | |
| 8619 | if (IsSigned) { |
| 8620 | APInt MinRHS = getSignedRange(RHS).getSignedMin(); |
| 8621 | APInt MinValue = APInt::getSignedMinValue(BitWidth); |
| 8622 | APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) |
| 8623 | .getSignedMax(); |
| 8624 | |
| 8625 | // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! |
| 8626 | return (MinValue + MaxStrideMinusOne).sgt(MinRHS); |
| 8627 | } |
| 8628 | |
| 8629 | APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); |
| 8630 | APInt MinValue = APInt::getMinValue(BitWidth); |
| 8631 | APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) |
| 8632 | .getUnsignedMax(); |
| 8633 | |
| 8634 | // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! |
| 8635 | return (MinValue + MaxStrideMinusOne).ugt(MinRHS); |
| 8636 | } |
| 8637 | |
| 8638 | // Compute the backedge taken count knowing the interval difference, the |
| 8639 | // stride and presence of the equality in the comparison. |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8640 | const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8641 | bool Equality) { |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8642 | const SCEV *One = getOne(Step->getType()); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8643 | Delta = Equality ? getAddExpr(Delta, Step) |
| 8644 | : getAddExpr(Delta, getMinusSCEV(Step, One)); |
| 8645 | return getUDivExpr(Delta, Step); |
Dan Gohman | 0104842 | 2009-06-21 23:46:38 +0000 | [diff] [blame] | 8646 | } |
| 8647 | |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8648 | /// HowManyLessThans - Return the number of times a backedge containing the |
| 8649 | /// specified less-than comparison will execute. If not computable, return |
Dan Gohman | 4c720c0 | 2009-06-06 14:37:11 +0000 | [diff] [blame] | 8650 | /// CouldNotCompute. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 8651 | /// |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8652 | /// @param ControlsExit is true when the LHS < RHS condition directly controls |
| 8653 | /// the branch (loops exits only if condition is true). In this case, we can use |
| 8654 | /// NoWrapFlags to skip overflow checks. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 8655 | ScalarEvolution::ExitLimit |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 8656 | ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS, |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8657 | const Loop *L, bool IsSigned, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8658 | bool ControlsExit, bool AllowPredicates) { |
| 8659 | SCEVUnionPredicate P; |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8660 | // We handle only IV < Invariant |
| 8661 | if (!isLoopInvariant(RHS, L)) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 8662 | return getCouldNotCompute(); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8663 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8664 | const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8665 | if (!IV && AllowPredicates) |
| 8666 | // Try to make this an AddRec using runtime tests, in the first X |
| 8667 | // iterations of this loop, where X is the SCEV expression found by the |
| 8668 | // algorithm below. |
| 8669 | IV = convertSCEVToAddRecWithPredicates(LHS, L, P); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8670 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8671 | // Avoid weird loops |
| 8672 | if (!IV || IV->getLoop() != L || !IV->isAffine()) |
| 8673 | return getCouldNotCompute(); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8674 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8675 | bool NoWrap = ControlsExit && |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8676 | IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); |
Wojciech Matyjewicz | 35545fd | 2008-02-13 11:51:34 +0000 | [diff] [blame] | 8677 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8678 | const SCEV *Stride = IV->getStepRecurrence(*this); |
Wojciech Matyjewicz | 35545fd | 2008-02-13 11:51:34 +0000 | [diff] [blame] | 8679 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8680 | // Avoid negative or zero stride values |
| 8681 | if (!isKnownPositive(Stride)) |
| 8682 | return getCouldNotCompute(); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8683 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8684 | // Avoid proven overflow cases: this will ensure that the backedge taken count |
| 8685 | // will not generate any unsigned overflow. Relaxed no-overflow conditions |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8686 | // exploit NoWrapFlags, allowing to optimize in presence of undefined |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8687 | // behaviors like the case of C language. |
| 8688 | if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) |
| 8689 | return getCouldNotCompute(); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8690 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8691 | ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT |
| 8692 | : ICmpInst::ICMP_ULT; |
| 8693 | const SCEV *Start = IV->getStart(); |
| 8694 | const SCEV *End = RHS; |
Bradley Smith | 9992b16 | 2014-10-31 11:40:32 +0000 | [diff] [blame] | 8695 | if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) { |
| 8696 | const SCEV *Diff = getMinusSCEV(RHS, Start); |
| 8697 | // If we have NoWrap set, then we can assume that the increment won't |
| 8698 | // overflow, in which case if RHS - Start is a constant, we don't need to |
| 8699 | // do a max operation since we can just figure it out statically |
| 8700 | if (NoWrap && isa<SCEVConstant>(Diff)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8701 | APInt D = dyn_cast<const SCEVConstant>(Diff)->getAPInt(); |
Bradley Smith | 9992b16 | 2014-10-31 11:40:32 +0000 | [diff] [blame] | 8702 | if (D.isNegative()) |
| 8703 | End = Start; |
| 8704 | } else |
| 8705 | End = IsSigned ? getSMaxExpr(RHS, Start) |
| 8706 | : getUMaxExpr(RHS, Start); |
| 8707 | } |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 8708 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8709 | const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8710 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8711 | APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() |
| 8712 | : getUnsignedRange(Start).getUnsignedMin(); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 8713 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8714 | APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() |
| 8715 | : getUnsignedRange(Stride).getUnsignedMin(); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8716 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8717 | unsigned BitWidth = getTypeSizeInBits(LHS->getType()); |
| 8718 | APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1) |
| 8719 | : APInt::getMaxValue(BitWidth) - (MinStride - 1); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8720 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8721 | // Although End can be a MAX expression we estimate MaxEnd considering only |
| 8722 | // the case End = RHS. This is safe because in the other case (End - Start) |
| 8723 | // is zero, leading to a zero maximum backedge taken count. |
| 8724 | APInt MaxEnd = |
| 8725 | IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) |
| 8726 | : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); |
| 8727 | |
Arnaud A. de Grandmaison | 75c9e6d | 2014-03-15 22:13:15 +0000 | [diff] [blame] | 8728 | const SCEV *MaxBECount; |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8729 | if (isa<SCEVConstant>(BECount)) |
| 8730 | MaxBECount = BECount; |
| 8731 | else |
| 8732 | MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), |
| 8733 | getConstant(MinStride), false); |
| 8734 | |
| 8735 | if (isa<SCEVCouldNotCompute>(MaxBECount)) |
| 8736 | MaxBECount = BECount; |
| 8737 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8738 | return ExitLimit(BECount, MaxBECount, P); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8739 | } |
| 8740 | |
| 8741 | ScalarEvolution::ExitLimit |
| 8742 | ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS, |
| 8743 | const Loop *L, bool IsSigned, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8744 | bool ControlsExit, bool AllowPredicates) { |
| 8745 | SCEVUnionPredicate P; |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8746 | // We handle only IV > Invariant |
| 8747 | if (!isLoopInvariant(RHS, L)) |
| 8748 | return getCouldNotCompute(); |
| 8749 | |
| 8750 | const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8751 | if (!IV && AllowPredicates) |
| 8752 | // Try to make this an AddRec using runtime tests, in the first X |
| 8753 | // iterations of this loop, where X is the SCEV expression found by the |
| 8754 | // algorithm below. |
| 8755 | IV = convertSCEVToAddRecWithPredicates(LHS, L, P); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8756 | |
| 8757 | // Avoid weird loops |
| 8758 | if (!IV || IV->getLoop() != L || !IV->isAffine()) |
| 8759 | return getCouldNotCompute(); |
| 8760 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8761 | bool NoWrap = ControlsExit && |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8762 | IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); |
| 8763 | |
| 8764 | const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); |
| 8765 | |
| 8766 | // Avoid negative or zero stride values |
| 8767 | if (!isKnownPositive(Stride)) |
| 8768 | return getCouldNotCompute(); |
| 8769 | |
| 8770 | // Avoid proven overflow cases: this will ensure that the backedge taken count |
| 8771 | // will not generate any unsigned overflow. Relaxed no-overflow conditions |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8772 | // exploit NoWrapFlags, allowing to optimize in presence of undefined |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8773 | // behaviors like the case of C language. |
| 8774 | if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) |
| 8775 | return getCouldNotCompute(); |
| 8776 | |
| 8777 | ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT |
| 8778 | : ICmpInst::ICMP_UGT; |
| 8779 | |
| 8780 | const SCEV *Start = IV->getStart(); |
| 8781 | const SCEV *End = RHS; |
Bradley Smith | 9992b16 | 2014-10-31 11:40:32 +0000 | [diff] [blame] | 8782 | if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { |
| 8783 | const SCEV *Diff = getMinusSCEV(RHS, Start); |
| 8784 | // If we have NoWrap set, then we can assume that the increment won't |
| 8785 | // overflow, in which case if RHS - Start is a constant, we don't need to |
| 8786 | // do a max operation since we can just figure it out statically |
| 8787 | if (NoWrap && isa<SCEVConstant>(Diff)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8788 | APInt D = dyn_cast<const SCEVConstant>(Diff)->getAPInt(); |
Bradley Smith | 9992b16 | 2014-10-31 11:40:32 +0000 | [diff] [blame] | 8789 | if (!D.isNegative()) |
| 8790 | End = Start; |
| 8791 | } else |
| 8792 | End = IsSigned ? getSMinExpr(RHS, Start) |
| 8793 | : getUMinExpr(RHS, Start); |
| 8794 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8795 | |
| 8796 | const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); |
| 8797 | |
| 8798 | APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() |
| 8799 | : getUnsignedRange(Start).getUnsignedMax(); |
| 8800 | |
| 8801 | APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() |
| 8802 | : getUnsignedRange(Stride).getUnsignedMin(); |
| 8803 | |
| 8804 | unsigned BitWidth = getTypeSizeInBits(LHS->getType()); |
| 8805 | APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) |
| 8806 | : APInt::getMinValue(BitWidth) + (MinStride - 1); |
| 8807 | |
| 8808 | // Although End can be a MIN expression we estimate MinEnd considering only |
| 8809 | // the case End = RHS. This is safe because in the other case (Start - End) |
| 8810 | // is zero, leading to a zero maximum backedge taken count. |
| 8811 | APInt MinEnd = |
| 8812 | IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) |
| 8813 | : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); |
| 8814 | |
| 8815 | |
| 8816 | const SCEV *MaxBECount = getCouldNotCompute(); |
| 8817 | if (isa<SCEVConstant>(BECount)) |
| 8818 | MaxBECount = BECount; |
| 8819 | else |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8820 | MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8821 | getConstant(MinStride), false); |
| 8822 | |
| 8823 | if (isa<SCEVCouldNotCompute>(MaxBECount)) |
| 8824 | MaxBECount = BECount; |
| 8825 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8826 | return ExitLimit(BECount, MaxBECount, P); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8827 | } |
| 8828 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8829 | /// getNumIterationsInRange - Return the number of iterations of this loop that |
| 8830 | /// produce values in the specified constant range. Another way of looking at |
| 8831 | /// this is that it returns the first iteration number where the value is not in |
| 8832 | /// the condition, thus computing the exit count. If the iteration count can't |
| 8833 | /// be computed, an instance of SCEVCouldNotCompute is returned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 8834 | const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range, |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 8835 | ScalarEvolution &SE) const { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8836 | if (Range.isFullSet()) // Infinite loop. |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8837 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8838 | |
| 8839 | // If the start is a non-zero constant, shift the range to simplify things. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 8840 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 8841 | if (!SC->getValue()->isZero()) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 8842 | SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8843 | Operands[0] = SE.getZero(SC->getType()); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 8844 | const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 8845 | getNoWrapFlags(FlagNW)); |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 8846 | if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8847 | return ShiftedAddRec->getNumIterationsInRange( |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8848 | Range.subtract(SC->getAPInt()), SE); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8849 | // This is strange and shouldn't happen. |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8850 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8851 | } |
| 8852 | |
| 8853 | // The only time we can solve this is when we have all constant indices. |
| 8854 | // Otherwise, we cannot determine the overflow conditions. |
Sanjoy Das | ff3b8b4 | 2015-12-01 07:49:23 +0000 | [diff] [blame] | 8855 | if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) |
Sanjoy Das | f07d2a7 | 2015-10-18 00:29:23 +0000 | [diff] [blame] | 8856 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8857 | |
| 8858 | // Okay at this point we know that all elements of the chrec are constants and |
| 8859 | // that the start element is zero. |
| 8860 | |
| 8861 | // First check to see if the range contains zero. If not, the first |
| 8862 | // iteration exits. |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 8863 | unsigned BitWidth = SE.getTypeSizeInBits(getType()); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 8864 | if (!Range.contains(APInt(BitWidth, 0))) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8865 | return SE.getZero(getType()); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8866 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8867 | if (isAffine()) { |
| 8868 | // If this is an affine expression then we have this situation: |
| 8869 | // Solve {0,+,A} in Range === Ax in Range |
| 8870 | |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 8871 | // We know that zero is in the range. If A is positive then we know that |
| 8872 | // the upper value of the range must be the first possible exit value. |
| 8873 | // If A is negative then the lower of the range is the last possible loop |
| 8874 | // value. Also note that we already checked for a full range. |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 8875 | APInt One(BitWidth,1); |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8876 | APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 8877 | APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8878 | |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 8879 | // The exit value should be (End+A)/A. |
Nick Lewycky | 3934961 | 2007-09-27 14:12:54 +0000 | [diff] [blame] | 8880 | APInt ExitVal = (End + A).udiv(A); |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 8881 | ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8882 | |
| 8883 | // Evaluate at the exit value. If we really did fall out of the valid |
| 8884 | // range, then we computed our trip count, otherwise wrap around or other |
| 8885 | // things must have happened. |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8886 | ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8887 | if (Range.contains(Val->getValue())) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8888 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8889 | |
| 8890 | // Ensure that the previous value is in the range. This is a sanity check. |
Reid Spencer | 3a7e9d8 | 2007-02-28 19:57:34 +0000 | [diff] [blame] | 8891 | assert(Range.contains( |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 8892 | EvaluateConstantChrecAtConstant(this, |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 8893 | ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8894 | "Linear scev computation is off in a bad way!"); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8895 | return SE.getConstant(ExitValue); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8896 | } else if (isQuadratic()) { |
| 8897 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the |
| 8898 | // quadratic equation to solve it. To do this, we must frame our problem in |
| 8899 | // terms of figuring out when zero is crossed, instead of when |
| 8900 | // Range.getUpper() is crossed. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 8901 | SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8902 | NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 8903 | const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), |
| 8904 | // getNoWrapFlags(FlagNW) |
| 8905 | FlagAnyWrap); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8906 | |
| 8907 | // Next, solve the constructed addrec |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 8908 | auto Roots = SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 8909 | const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first); |
| 8910 | const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8911 | if (R1) { |
| 8912 | // Pick the smallest positive root value. |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 8913 | if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( |
| 8914 | ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 8915 | if (!CB->getZExtValue()) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8916 | std::swap(R1, R2); // R1 is the minimum root now. |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8917 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8918 | // Make sure the root is not off by one. The returned iteration should |
| 8919 | // not be in the range, but the previous one should be. When solving |
| 8920 | // for "X*X < 5", for example, we should not return a root of 2. |
| 8921 | ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this, |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8922 | R1->getValue(), |
| 8923 | SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8924 | if (Range.contains(R1Val->getValue())) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8925 | // The next iteration must be out of the range... |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 8926 | ConstantInt *NextVal = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8927 | ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8928 | |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8929 | R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8930 | if (!Range.contains(R1Val->getValue())) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8931 | return SE.getConstant(NextVal); |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8932 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8933 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8934 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8935 | // If R1 was not in the range, then it is a good return value. Make |
| 8936 | // sure that R1-1 WAS in the range though, just in case. |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 8937 | ConstantInt *NextVal = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8938 | ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8939 | R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8940 | if (Range.contains(R1Val->getValue())) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8941 | return R1; |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8942 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8943 | } |
| 8944 | } |
| 8945 | } |
| 8946 | |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8947 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8948 | } |
| 8949 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8950 | namespace { |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 8951 | struct FindUndefs { |
| 8952 | bool Found; |
| 8953 | FindUndefs() : Found(false) {} |
| 8954 | |
| 8955 | bool follow(const SCEV *S) { |
| 8956 | if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) { |
| 8957 | if (isa<UndefValue>(C->getValue())) |
| 8958 | Found = true; |
| 8959 | } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { |
| 8960 | if (isa<UndefValue>(C->getValue())) |
| 8961 | Found = true; |
| 8962 | } |
| 8963 | |
| 8964 | // Keep looking if we haven't found it yet. |
| 8965 | return !Found; |
| 8966 | } |
| 8967 | bool isDone() const { |
| 8968 | // Stop recursion if we have found an undef. |
| 8969 | return Found; |
| 8970 | } |
| 8971 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 8972 | } |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 8973 | |
| 8974 | // Return true when S contains at least an undef value. |
| 8975 | static inline bool |
| 8976 | containsUndefs(const SCEV *S) { |
| 8977 | FindUndefs F; |
| 8978 | SCEVTraversal<FindUndefs> ST(F); |
| 8979 | ST.visitAll(S); |
| 8980 | |
| 8981 | return F.Found; |
| 8982 | } |
| 8983 | |
| 8984 | namespace { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8985 | // Collect all steps of SCEV expressions. |
| 8986 | struct SCEVCollectStrides { |
| 8987 | ScalarEvolution &SE; |
| 8988 | SmallVectorImpl<const SCEV *> &Strides; |
| 8989 | |
| 8990 | SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) |
| 8991 | : SE(SE), Strides(S) {} |
| 8992 | |
| 8993 | bool follow(const SCEV *S) { |
| 8994 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) |
| 8995 | Strides.push_back(AR->getStepRecurrence(SE)); |
| 8996 | return true; |
| 8997 | } |
| 8998 | bool isDone() const { return false; } |
| 8999 | }; |
| 9000 | |
| 9001 | // Collect all SCEVUnknown and SCEVMulExpr expressions. |
| 9002 | struct SCEVCollectTerms { |
| 9003 | SmallVectorImpl<const SCEV *> &Terms; |
| 9004 | |
| 9005 | SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) |
| 9006 | : Terms(T) {} |
| 9007 | |
| 9008 | bool follow(const SCEV *S) { |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9009 | if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) { |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 9010 | if (!containsUndefs(S)) |
| 9011 | Terms.push_back(S); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9012 | |
| 9013 | // Stop recursion: once we collected a term, do not walk its operands. |
| 9014 | return false; |
| 9015 | } |
| 9016 | |
| 9017 | // Keep looking. |
| 9018 | return true; |
| 9019 | } |
| 9020 | bool isDone() const { return false; } |
| 9021 | }; |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9022 | |
| 9023 | // Check if a SCEV contains an AddRecExpr. |
| 9024 | struct SCEVHasAddRec { |
| 9025 | bool &ContainsAddRec; |
| 9026 | |
| 9027 | SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { |
| 9028 | ContainsAddRec = false; |
| 9029 | } |
| 9030 | |
| 9031 | bool follow(const SCEV *S) { |
| 9032 | if (isa<SCEVAddRecExpr>(S)) { |
| 9033 | ContainsAddRec = true; |
| 9034 | |
| 9035 | // Stop recursion: once we collected a term, do not walk its operands. |
| 9036 | return false; |
| 9037 | } |
| 9038 | |
| 9039 | // Keep looking. |
| 9040 | return true; |
| 9041 | } |
| 9042 | bool isDone() const { return false; } |
| 9043 | }; |
| 9044 | |
| 9045 | // Find factors that are multiplied with an expression that (possibly as a |
| 9046 | // subexpression) contains an AddRecExpr. In the expression: |
| 9047 | // |
| 9048 | // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) |
| 9049 | // |
| 9050 | // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" |
| 9051 | // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size |
| 9052 | // parameters as they form a product with an induction variable. |
| 9053 | // |
| 9054 | // This collector expects all array size parameters to be in the same MulExpr. |
| 9055 | // It might be necessary to later add support for collecting parameters that are |
| 9056 | // spread over different nested MulExpr. |
| 9057 | struct SCEVCollectAddRecMultiplies { |
| 9058 | SmallVectorImpl<const SCEV *> &Terms; |
| 9059 | ScalarEvolution &SE; |
| 9060 | |
| 9061 | SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) |
| 9062 | : Terms(T), SE(SE) {} |
| 9063 | |
| 9064 | bool follow(const SCEV *S) { |
| 9065 | if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { |
| 9066 | bool HasAddRec = false; |
| 9067 | SmallVector<const SCEV *, 0> Operands; |
| 9068 | for (auto Op : Mul->operands()) { |
| 9069 | if (isa<SCEVUnknown>(Op)) { |
| 9070 | Operands.push_back(Op); |
| 9071 | } else { |
| 9072 | bool ContainsAddRec; |
| 9073 | SCEVHasAddRec ContiansAddRec(ContainsAddRec); |
| 9074 | visitAll(Op, ContiansAddRec); |
| 9075 | HasAddRec |= ContainsAddRec; |
| 9076 | } |
| 9077 | } |
| 9078 | if (Operands.size() == 0) |
| 9079 | return true; |
| 9080 | |
| 9081 | if (!HasAddRec) |
| 9082 | return false; |
| 9083 | |
| 9084 | Terms.push_back(SE.getMulExpr(Operands)); |
| 9085 | // Stop recursion: once we collected a term, do not walk its operands. |
| 9086 | return false; |
| 9087 | } |
| 9088 | |
| 9089 | // Keep looking. |
| 9090 | return true; |
| 9091 | } |
| 9092 | bool isDone() const { return false; } |
| 9093 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 9094 | } |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9095 | |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9096 | /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in |
| 9097 | /// two places: |
| 9098 | /// 1) The strides of AddRec expressions. |
| 9099 | /// 2) Unknowns that are multiplied with AddRec expressions. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9100 | void ScalarEvolution::collectParametricTerms(const SCEV *Expr, |
| 9101 | SmallVectorImpl<const SCEV *> &Terms) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9102 | SmallVector<const SCEV *, 4> Strides; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9103 | SCEVCollectStrides StrideCollector(*this, Strides); |
| 9104 | visitAll(Expr, StrideCollector); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9105 | |
| 9106 | DEBUG({ |
| 9107 | dbgs() << "Strides:\n"; |
| 9108 | for (const SCEV *S : Strides) |
| 9109 | dbgs() << *S << "\n"; |
| 9110 | }); |
| 9111 | |
| 9112 | for (const SCEV *S : Strides) { |
| 9113 | SCEVCollectTerms TermCollector(Terms); |
| 9114 | visitAll(S, TermCollector); |
| 9115 | } |
| 9116 | |
| 9117 | DEBUG({ |
| 9118 | dbgs() << "Terms:\n"; |
| 9119 | for (const SCEV *T : Terms) |
| 9120 | dbgs() << *T << "\n"; |
| 9121 | }); |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9122 | |
| 9123 | SCEVCollectAddRecMultiplies MulCollector(Terms, *this); |
| 9124 | visitAll(Expr, MulCollector); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9125 | } |
| 9126 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9127 | static bool findArrayDimensionsRec(ScalarEvolution &SE, |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9128 | SmallVectorImpl<const SCEV *> &Terms, |
Sebastian Pop | 47fe7de | 2014-05-09 22:45:07 +0000 | [diff] [blame] | 9129 | SmallVectorImpl<const SCEV *> &Sizes) { |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9130 | int Last = Terms.size() - 1; |
| 9131 | const SCEV *Step = Terms[Last]; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9132 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9133 | // End of recursion. |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9134 | if (Last == 0) { |
| 9135 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9136 | SmallVector<const SCEV *, 2> Qs; |
| 9137 | for (const SCEV *Op : M->operands()) |
| 9138 | if (!isa<SCEVConstant>(Op)) |
| 9139 | Qs.push_back(Op); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9140 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9141 | Step = SE.getMulExpr(Qs); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9142 | } |
| 9143 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9144 | Sizes.push_back(Step); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9145 | return true; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9146 | } |
| 9147 | |
Benjamin Kramer | 8cff45a | 2014-05-10 17:47:18 +0000 | [diff] [blame] | 9148 | for (const SCEV *&Term : Terms) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9149 | // Normalize the terms before the next call to findArrayDimensionsRec. |
| 9150 | const SCEV *Q, *R; |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 9151 | SCEVDivision::divide(SE, Term, Step, &Q, &R); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9152 | |
| 9153 | // Bail out when GCD does not evenly divide one of the terms. |
| 9154 | if (!R->isZero()) |
| 9155 | return false; |
| 9156 | |
Benjamin Kramer | 8cff45a | 2014-05-10 17:47:18 +0000 | [diff] [blame] | 9157 | Term = Q; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9158 | } |
| 9159 | |
Tobias Grosser | 3080cf1 | 2014-05-08 07:55:34 +0000 | [diff] [blame] | 9160 | // Remove all SCEVConstants. |
Tobias Grosser | 1e9db7e | 2014-05-08 21:43:19 +0000 | [diff] [blame] | 9161 | Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) { |
| 9162 | return isa<SCEVConstant>(E); |
| 9163 | }), |
| 9164 | Terms.end()); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9165 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9166 | if (Terms.size() > 0) |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9167 | if (!findArrayDimensionsRec(SE, Terms, Sizes)) |
| 9168 | return false; |
| 9169 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9170 | Sizes.push_back(Step); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9171 | return true; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9172 | } |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9173 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9174 | // Returns true when S contains at least a SCEVUnknown parameter. |
| 9175 | static inline bool |
| 9176 | containsParameters(const SCEV *S) { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 9177 | struct FindParameter { |
| 9178 | bool FoundParameter; |
| 9179 | FindParameter() : FoundParameter(false) {} |
| 9180 | |
| 9181 | bool follow(const SCEV *S) { |
| 9182 | if (isa<SCEVUnknown>(S)) { |
| 9183 | FoundParameter = true; |
| 9184 | // Stop recursion: we found a parameter. |
| 9185 | return false; |
| 9186 | } |
| 9187 | // Keep looking. |
| 9188 | return true; |
| 9189 | } |
| 9190 | bool isDone() const { |
| 9191 | // Stop recursion if we have found a parameter. |
| 9192 | return FoundParameter; |
| 9193 | } |
| 9194 | }; |
| 9195 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9196 | FindParameter F; |
| 9197 | SCEVTraversal<FindParameter> ST(F); |
| 9198 | ST.visitAll(S); |
| 9199 | |
| 9200 | return F.FoundParameter; |
| 9201 | } |
| 9202 | |
| 9203 | // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. |
| 9204 | static inline bool |
| 9205 | containsParameters(SmallVectorImpl<const SCEV *> &Terms) { |
| 9206 | for (const SCEV *T : Terms) |
| 9207 | if (containsParameters(T)) |
| 9208 | return true; |
| 9209 | return false; |
| 9210 | } |
| 9211 | |
| 9212 | // Return the number of product terms in S. |
| 9213 | static inline int numberOfTerms(const SCEV *S) { |
| 9214 | if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) |
| 9215 | return Expr->getNumOperands(); |
| 9216 | return 1; |
| 9217 | } |
| 9218 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9219 | static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { |
| 9220 | if (isa<SCEVConstant>(T)) |
| 9221 | return nullptr; |
| 9222 | |
| 9223 | if (isa<SCEVUnknown>(T)) |
| 9224 | return T; |
| 9225 | |
| 9226 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { |
| 9227 | SmallVector<const SCEV *, 2> Factors; |
| 9228 | for (const SCEV *Op : M->operands()) |
| 9229 | if (!isa<SCEVConstant>(Op)) |
| 9230 | Factors.push_back(Op); |
| 9231 | |
| 9232 | return SE.getMulExpr(Factors); |
| 9233 | } |
| 9234 | |
| 9235 | return T; |
| 9236 | } |
| 9237 | |
| 9238 | /// Return the size of an element read or written by Inst. |
| 9239 | const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { |
| 9240 | Type *Ty; |
| 9241 | if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) |
| 9242 | Ty = Store->getValueOperand()->getType(); |
| 9243 | else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) |
Tobias Grosser | 40ac100 | 2014-06-08 19:21:20 +0000 | [diff] [blame] | 9244 | Ty = Load->getType(); |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9245 | else |
| 9246 | return nullptr; |
| 9247 | |
| 9248 | Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); |
| 9249 | return getSizeOfExpr(ETy, Ty); |
| 9250 | } |
| 9251 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9252 | /// Second step of delinearization: compute the array dimensions Sizes from the |
| 9253 | /// set of Terms extracted from the memory access function of this SCEVAddRec. |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9254 | void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, |
| 9255 | SmallVectorImpl<const SCEV *> &Sizes, |
| 9256 | const SCEV *ElementSize) const { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9257 | |
Sebastian Pop | 5352408 | 2014-05-29 19:44:05 +0000 | [diff] [blame] | 9258 | if (Terms.size() < 1 || !ElementSize) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9259 | return; |
| 9260 | |
| 9261 | // Early return when Terms do not contain parameters: we do not delinearize |
| 9262 | // non parametric SCEVs. |
| 9263 | if (!containsParameters(Terms)) |
| 9264 | return; |
| 9265 | |
| 9266 | DEBUG({ |
| 9267 | dbgs() << "Terms:\n"; |
| 9268 | for (const SCEV *T : Terms) |
| 9269 | dbgs() << *T << "\n"; |
| 9270 | }); |
| 9271 | |
| 9272 | // Remove duplicates. |
| 9273 | std::sort(Terms.begin(), Terms.end()); |
| 9274 | Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); |
| 9275 | |
| 9276 | // Put larger terms first. |
| 9277 | std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { |
| 9278 | return numberOfTerms(LHS) > numberOfTerms(RHS); |
| 9279 | }); |
| 9280 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9281 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
| 9282 | |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9283 | // Try to divide all terms by the element size. If term is not divisible by |
| 9284 | // element size, proceed with the original term. |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9285 | for (const SCEV *&Term : Terms) { |
| 9286 | const SCEV *Q, *R; |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 9287 | SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9288 | if (!Q->isZero()) |
| 9289 | Term = Q; |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9290 | } |
| 9291 | |
| 9292 | SmallVector<const SCEV *, 4> NewTerms; |
| 9293 | |
| 9294 | // Remove constant factors. |
| 9295 | for (const SCEV *T : Terms) |
| 9296 | if (const SCEV *NewT = removeConstantFactors(SE, T)) |
| 9297 | NewTerms.push_back(NewT); |
| 9298 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9299 | DEBUG({ |
| 9300 | dbgs() << "Terms after sorting:\n"; |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9301 | for (const SCEV *T : NewTerms) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9302 | dbgs() << *T << "\n"; |
| 9303 | }); |
| 9304 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9305 | if (NewTerms.empty() || |
| 9306 | !findArrayDimensionsRec(SE, NewTerms, Sizes)) { |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9307 | Sizes.clear(); |
| 9308 | return; |
| 9309 | } |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9310 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9311 | // The last element to be pushed into Sizes is the size of an element. |
| 9312 | Sizes.push_back(ElementSize); |
| 9313 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9314 | DEBUG({ |
| 9315 | dbgs() << "Sizes:\n"; |
| 9316 | for (const SCEV *S : Sizes) |
| 9317 | dbgs() << *S << "\n"; |
| 9318 | }); |
| 9319 | } |
| 9320 | |
| 9321 | /// Third step of delinearization: compute the access functions for the |
| 9322 | /// Subscripts based on the dimensions in Sizes. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9323 | void ScalarEvolution::computeAccessFunctions( |
| 9324 | const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, |
| 9325 | SmallVectorImpl<const SCEV *> &Sizes) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9326 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9327 | // Early exit in case this SCEV is not an affine multivariate function. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9328 | if (Sizes.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9329 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9330 | |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 9331 | if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9332 | if (!AR->isAffine()) |
| 9333 | return; |
| 9334 | |
| 9335 | const SCEV *Res = Expr; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9336 | int Last = Sizes.size() - 1; |
| 9337 | for (int i = Last; i >= 0; i--) { |
| 9338 | const SCEV *Q, *R; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9339 | SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9340 | |
| 9341 | DEBUG({ |
| 9342 | dbgs() << "Res: " << *Res << "\n"; |
| 9343 | dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; |
| 9344 | dbgs() << "Res divided by Sizes[i]:\n"; |
| 9345 | dbgs() << "Quotient: " << *Q << "\n"; |
| 9346 | dbgs() << "Remainder: " << *R << "\n"; |
| 9347 | }); |
| 9348 | |
| 9349 | Res = Q; |
| 9350 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9351 | // Do not record the last subscript corresponding to the size of elements in |
| 9352 | // the array. |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9353 | if (i == Last) { |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9354 | |
| 9355 | // Bail out if the remainder is too complex. |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9356 | if (isa<SCEVAddRecExpr>(R)) { |
| 9357 | Subscripts.clear(); |
| 9358 | Sizes.clear(); |
| 9359 | return; |
| 9360 | } |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9361 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9362 | continue; |
| 9363 | } |
| 9364 | |
| 9365 | // Record the access function for the current subscript. |
| 9366 | Subscripts.push_back(R); |
| 9367 | } |
| 9368 | |
| 9369 | // Also push in last position the remainder of the last division: it will be |
| 9370 | // the access function of the innermost dimension. |
| 9371 | Subscripts.push_back(Res); |
| 9372 | |
| 9373 | std::reverse(Subscripts.begin(), Subscripts.end()); |
| 9374 | |
| 9375 | DEBUG({ |
| 9376 | dbgs() << "Subscripts:\n"; |
| 9377 | for (const SCEV *S : Subscripts) |
| 9378 | dbgs() << *S << "\n"; |
| 9379 | }); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9380 | } |
| 9381 | |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9382 | /// Splits the SCEV into two vectors of SCEVs representing the subscripts and |
| 9383 | /// sizes of an array access. Returns the remainder of the delinearization that |
Sebastian Pop | 7ee1472 | 2013-11-13 22:37:58 +0000 | [diff] [blame] | 9384 | /// is the offset start of the array. The SCEV->delinearize algorithm computes |
| 9385 | /// the multiples of SCEV coefficients: that is a pattern matching of sub |
| 9386 | /// expressions in the stride and base of a SCEV corresponding to the |
| 9387 | /// computation of a GCD (greatest common divisor) of base and stride. When |
| 9388 | /// SCEV->delinearize fails, it returns the SCEV unchanged. |
| 9389 | /// |
| 9390 | /// For example: when analyzing the memory access A[i][j][k] in this loop nest |
| 9391 | /// |
| 9392 | /// void foo(long n, long m, long o, double A[n][m][o]) { |
| 9393 | /// |
| 9394 | /// for (long i = 0; i < n; i++) |
| 9395 | /// for (long j = 0; j < m; j++) |
| 9396 | /// for (long k = 0; k < o; k++) |
| 9397 | /// A[i][j][k] = 1.0; |
| 9398 | /// } |
| 9399 | /// |
| 9400 | /// the delinearization input is the following AddRec SCEV: |
| 9401 | /// |
| 9402 | /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> |
| 9403 | /// |
| 9404 | /// From this SCEV, we are able to say that the base offset of the access is %A |
| 9405 | /// because it appears as an offset that does not divide any of the strides in |
| 9406 | /// the loops: |
| 9407 | /// |
| 9408 | /// CHECK: Base offset: %A |
| 9409 | /// |
| 9410 | /// and then SCEV->delinearize determines the size of some of the dimensions of |
| 9411 | /// the array as these are the multiples by which the strides are happening: |
| 9412 | /// |
| 9413 | /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. |
| 9414 | /// |
| 9415 | /// Note that the outermost dimension remains of UnknownSize because there are |
| 9416 | /// no strides that would help identifying the size of the last dimension: when |
| 9417 | /// the array has been statically allocated, one could compute the size of that |
| 9418 | /// dimension by dividing the overall size of the array by the size of the known |
| 9419 | /// dimensions: %m * %o * 8. |
| 9420 | /// |
| 9421 | /// Finally delinearize provides the access functions for the array reference |
| 9422 | /// that does correspond to A[i][j][k] of the above C testcase: |
| 9423 | /// |
| 9424 | /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] |
| 9425 | /// |
| 9426 | /// The testcases are checking the output of a function pass: |
| 9427 | /// DelinearizationPass that walks through all loads and stores of a function |
| 9428 | /// asking for the SCEV of the memory access with respect to all enclosing |
| 9429 | /// loops, calling SCEV->delinearize on that and printing the results. |
| 9430 | |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9431 | void ScalarEvolution::delinearize(const SCEV *Expr, |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9432 | SmallVectorImpl<const SCEV *> &Subscripts, |
| 9433 | SmallVectorImpl<const SCEV *> &Sizes, |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9434 | const SCEV *ElementSize) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9435 | // First step: collect parametric terms. |
| 9436 | SmallVector<const SCEV *, 4> Terms; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9437 | collectParametricTerms(Expr, Terms); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9438 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9439 | if (Terms.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9440 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9441 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9442 | // Second step: find subscript sizes. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9443 | findArrayDimensions(Terms, Sizes, ElementSize); |
Sebastian Pop | 7ee1472 | 2013-11-13 22:37:58 +0000 | [diff] [blame] | 9444 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9445 | if (Sizes.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9446 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9447 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9448 | // Third step: compute the access functions for each subscript. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9449 | computeAccessFunctions(Expr, Subscripts, Sizes); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9450 | |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9451 | if (Subscripts.empty()) |
| 9452 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9453 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9454 | DEBUG({ |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9455 | dbgs() << "succeeded to delinearize " << *Expr << "\n"; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9456 | dbgs() << "ArrayDecl[UnknownSize]"; |
| 9457 | for (const SCEV *S : Sizes) |
| 9458 | dbgs() << "[" << *S << "]"; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9459 | |
Sebastian Pop | 444621a | 2014-05-09 22:45:02 +0000 | [diff] [blame] | 9460 | dbgs() << "\nArrayRef"; |
| 9461 | for (const SCEV *S : Subscripts) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9462 | dbgs() << "[" << *S << "]"; |
| 9463 | dbgs() << "\n"; |
| 9464 | }); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9465 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9466 | |
| 9467 | //===----------------------------------------------------------------------===// |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9468 | // SCEVCallbackVH Class Implementation |
| 9469 | //===----------------------------------------------------------------------===// |
| 9470 | |
Dan Gohman | d33a090 | 2009-05-19 19:22:47 +0000 | [diff] [blame] | 9471 | void ScalarEvolution::SCEVCallbackVH::deleted() { |
Dan Gohman | dd707af | 2009-07-13 22:20:53 +0000 | [diff] [blame] | 9472 | assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9473 | if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) |
| 9474 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9475 | SE->eraseValueFromMap(getValPtr()); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9476 | // this now dangles! |
| 9477 | } |
| 9478 | |
Dan Gohman | 7a06672 | 2010-07-28 01:09:07 +0000 | [diff] [blame] | 9479 | void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { |
Dan Gohman | dd707af | 2009-07-13 22:20:53 +0000 | [diff] [blame] | 9480 | assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); |
Eric Christopher | ef6d593 | 2010-07-29 01:25:38 +0000 | [diff] [blame] | 9481 | |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9482 | // Forget all the expressions associated with users of the old value, |
| 9483 | // so that future queries will recompute the expressions using the new |
| 9484 | // value. |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 9485 | Value *Old = getValPtr(); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 9486 | SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); |
Dan Gohman | f34f863 | 2009-07-14 14:34:04 +0000 | [diff] [blame] | 9487 | SmallPtrSet<User *, 8> Visited; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9488 | while (!Worklist.empty()) { |
| 9489 | User *U = Worklist.pop_back_val(); |
| 9490 | // Deleting the Old value will cause this to dangle. Postpone |
| 9491 | // that until everything else is done. |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 9492 | if (U == Old) |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9493 | continue; |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 9494 | if (!Visited.insert(U).second) |
Dan Gohman | f34f863 | 2009-07-14 14:34:04 +0000 | [diff] [blame] | 9495 | continue; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9496 | if (PHINode *PN = dyn_cast<PHINode>(U)) |
| 9497 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9498 | SE->eraseValueFromMap(U); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 9499 | Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9500 | } |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 9501 | // Delete the Old value. |
| 9502 | if (PHINode *PN = dyn_cast<PHINode>(Old)) |
| 9503 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9504 | SE->eraseValueFromMap(Old); |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 9505 | // this now dangles! |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9506 | } |
| 9507 | |
Dan Gohman | d33a090 | 2009-05-19 19:22:47 +0000 | [diff] [blame] | 9508 | ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9509 | : CallbackVH(V), SE(se) {} |
| 9510 | |
| 9511 | //===----------------------------------------------------------------------===// |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9512 | // ScalarEvolution Class Implementation |
| 9513 | //===----------------------------------------------------------------------===// |
| 9514 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9515 | ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, |
| 9516 | AssumptionCache &AC, DominatorTree &DT, |
| 9517 | LoopInfo &LI) |
| 9518 | : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), |
| 9519 | CouldNotCompute(new SCEVCouldNotCompute()), |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 9520 | WalkingBEDominatingConds(false), ProvingSplitPredicate(false), |
| 9521 | ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 9522 | FirstUnknown(nullptr) { |
| 9523 | |
| 9524 | // To use guards for proving predicates, we need to scan every instruction in |
| 9525 | // relevant basic blocks, and not just terminators. Doing this is a waste of |
| 9526 | // time if the IR does not actually contain any calls to |
| 9527 | // @llvm.experimental.guard, so do a quick check and remember this beforehand. |
| 9528 | // |
| 9529 | // This pessimizes the case where a pass that preserves ScalarEvolution wants |
| 9530 | // to _add_ guards to the module when there weren't any before, and wants |
| 9531 | // ScalarEvolution to optimize based on those guards. For now we prefer to be |
| 9532 | // efficient in lieu of being smart in that rather obscure case. |
| 9533 | |
| 9534 | auto *GuardDecl = F.getParent()->getFunction( |
| 9535 | Intrinsic::getName(Intrinsic::experimental_guard)); |
| 9536 | HasGuards = GuardDecl && !GuardDecl->use_empty(); |
| 9537 | } |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9538 | |
| 9539 | ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 9540 | : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), |
| 9541 | LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9542 | ValueExprMap(std::move(Arg.ValueExprMap)), |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 9543 | WalkingBEDominatingConds(false), ProvingSplitPredicate(false), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9544 | BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 9545 | PredicatedBackedgeTakenCounts( |
| 9546 | std::move(Arg.PredicatedBackedgeTakenCounts)), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9547 | ConstantEvolutionLoopExitValue( |
| 9548 | std::move(Arg.ConstantEvolutionLoopExitValue)), |
| 9549 | ValuesAtScopes(std::move(Arg.ValuesAtScopes)), |
| 9550 | LoopDispositions(std::move(Arg.LoopDispositions)), |
| 9551 | BlockDispositions(std::move(Arg.BlockDispositions)), |
| 9552 | UnsignedRanges(std::move(Arg.UnsignedRanges)), |
| 9553 | SignedRanges(std::move(Arg.SignedRanges)), |
| 9554 | UniqueSCEVs(std::move(Arg.UniqueSCEVs)), |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9555 | UniquePreds(std::move(Arg.UniquePreds)), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9556 | SCEVAllocator(std::move(Arg.SCEVAllocator)), |
| 9557 | FirstUnknown(Arg.FirstUnknown) { |
| 9558 | Arg.FirstUnknown = nullptr; |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9559 | } |
| 9560 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9561 | ScalarEvolution::~ScalarEvolution() { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 9562 | // Iterate through all the SCEVUnknown instances and call their |
| 9563 | // destructors, so that they release their references to their values. |
Naomi Musgrave | f90c1be | 2015-09-16 23:46:40 +0000 | [diff] [blame] | 9564 | for (SCEVUnknown *U = FirstUnknown; U;) { |
| 9565 | SCEVUnknown *Tmp = U; |
| 9566 | U = U->Next; |
| 9567 | Tmp->~SCEVUnknown(); |
| 9568 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 9569 | FirstUnknown = nullptr; |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 9570 | |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9571 | ExprValueMap.clear(); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 9572 | ValueExprMap.clear(); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9573 | HasRecMap.clear(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 9574 | |
| 9575 | // Free any extra memory created for ExitNotTakenInfo in the unlikely event |
| 9576 | // that a loop had multiple computable exits. |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9577 | for (auto &BTCI : BackedgeTakenCounts) |
| 9578 | BTCI.second.clear(); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 9579 | for (auto &BTCI : PredicatedBackedgeTakenCounts) |
| 9580 | BTCI.second.clear(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 9581 | |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 9582 | assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 9583 | assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 9584 | assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 9585 | } |
| 9586 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9587 | bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 9588 | return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9589 | } |
| 9590 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9591 | static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9592 | const Loop *L) { |
| 9593 | // Print all inner loops first |
| 9594 | for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) |
| 9595 | PrintLoopInfo(OS, SE, *I); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 9596 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9597 | OS << "Loop "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 9598 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9599 | OS << ": "; |
Chris Lattner | d72c3eb | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 9600 | |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 9601 | SmallVector<BasicBlock *, 8> ExitBlocks; |
Chris Lattner | d72c3eb | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 9602 | L->getExitBlocks(ExitBlocks); |
| 9603 | if (ExitBlocks.size() != 1) |
Nick Lewycky | d1200b0 | 2008-01-02 02:49:20 +0000 | [diff] [blame] | 9604 | OS << "<multiple exits> "; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9605 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 9606 | if (SE->hasLoopInvariantBackedgeTakenCount(L)) { |
| 9607 | OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9608 | } else { |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 9609 | OS << "Unpredictable backedge-taken count. "; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9610 | } |
| 9611 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9612 | OS << "\n" |
| 9613 | "Loop "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 9614 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9615 | OS << ": "; |
Dan Gohman | 6994293 | 2009-06-24 00:33:16 +0000 | [diff] [blame] | 9616 | |
| 9617 | if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { |
| 9618 | OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); |
| 9619 | } else { |
| 9620 | OS << "Unpredictable max backedge-taken count. "; |
| 9621 | } |
| 9622 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 9623 | OS << "\n" |
| 9624 | "Loop "; |
| 9625 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
| 9626 | OS << ": "; |
| 9627 | |
| 9628 | SCEVUnionPredicate Pred; |
| 9629 | auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); |
| 9630 | if (!isa<SCEVCouldNotCompute>(PBT)) { |
| 9631 | OS << "Predicated backedge-taken count is " << *PBT << "\n"; |
| 9632 | OS << " Predicates:\n"; |
| 9633 | Pred.print(OS, 4); |
| 9634 | } else { |
| 9635 | OS << "Unpredictable predicated backedge-taken count. "; |
| 9636 | } |
Dan Gohman | 6994293 | 2009-06-24 00:33:16 +0000 | [diff] [blame] | 9637 | OS << "\n"; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9638 | } |
| 9639 | |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9640 | static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { |
| 9641 | switch (LD) { |
| 9642 | case ScalarEvolution::LoopVariant: |
| 9643 | return "Variant"; |
| 9644 | case ScalarEvolution::LoopInvariant: |
| 9645 | return "Invariant"; |
| 9646 | case ScalarEvolution::LoopComputable: |
| 9647 | return "Computable"; |
| 9648 | } |
Simon Pilgrim | 33ae13d | 2016-05-01 15:52:31 +0000 | [diff] [blame] | 9649 | llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9650 | } |
| 9651 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9652 | void ScalarEvolution::print(raw_ostream &OS) const { |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 9653 | // ScalarEvolution's implementation of the print method is to print |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9654 | // out SCEV values of all instructions that are interesting. Doing |
| 9655 | // this potentially causes it to create new SCEV objects though, |
| 9656 | // which technically conflicts with the const qualifier. This isn't |
Dan Gohman | 028e615 | 2009-07-10 20:25:29 +0000 | [diff] [blame] | 9657 | // observable from outside the class though, so casting away the |
| 9658 | // const isn't dangerous. |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 9659 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9660 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9661 | OS << "Classifying expressions for: "; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9662 | F.printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9663 | OS << "\n"; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9664 | for (Instruction &I : instructions(F)) |
| 9665 | if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { |
| 9666 | OS << I << '\n'; |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 9667 | OS << " --> "; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9668 | const SCEV *SV = SE.getSCEV(&I); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9669 | SV->print(OS); |
Sanjoy Das | f257452 | 2015-03-09 21:43:39 +0000 | [diff] [blame] | 9670 | if (!isa<SCEVCouldNotCompute>(SV)) { |
| 9671 | OS << " U: "; |
| 9672 | SE.getUnsignedRange(SV).print(OS); |
| 9673 | OS << " S: "; |
| 9674 | SE.getSignedRange(SV).print(OS); |
| 9675 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 9676 | |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9677 | const Loop *L = LI.getLoopFor(I.getParent()); |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 9678 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 9679 | const SCEV *AtUse = SE.getSCEVAtScope(SV, L); |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 9680 | if (AtUse != SV) { |
| 9681 | OS << " --> "; |
| 9682 | AtUse->print(OS); |
Sanjoy Das | f257452 | 2015-03-09 21:43:39 +0000 | [diff] [blame] | 9683 | if (!isa<SCEVCouldNotCompute>(AtUse)) { |
| 9684 | OS << " U: "; |
| 9685 | SE.getUnsignedRange(AtUse).print(OS); |
| 9686 | OS << " S: "; |
| 9687 | SE.getSignedRange(AtUse).print(OS); |
| 9688 | } |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 9689 | } |
| 9690 | |
| 9691 | if (L) { |
Dan Gohman | 94c468f | 2009-06-18 00:37:45 +0000 | [diff] [blame] | 9692 | OS << "\t\t" "Exits: "; |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 9693 | const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9694 | if (!SE.isLoopInvariant(ExitValue, L)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9695 | OS << "<<Unknown>>"; |
| 9696 | } else { |
| 9697 | OS << *ExitValue; |
| 9698 | } |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9699 | |
| 9700 | bool First = true; |
| 9701 | for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { |
| 9702 | if (First) { |
Sanjoy Das | 013a4ac | 2016-05-03 17:49:57 +0000 | [diff] [blame] | 9703 | OS << "\t\t" "LoopDispositions: { "; |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9704 | First = false; |
| 9705 | } else { |
| 9706 | OS << ", "; |
| 9707 | } |
| 9708 | |
Sanjoy Das | 013a4ac | 2016-05-03 17:49:57 +0000 | [diff] [blame] | 9709 | Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
| 9710 | OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9711 | } |
| 9712 | |
Sanjoy Das | 013a4ac | 2016-05-03 17:49:57 +0000 | [diff] [blame] | 9713 | for (auto *InnerL : depth_first(L)) { |
| 9714 | if (InnerL == L) |
| 9715 | continue; |
| 9716 | if (First) { |
| 9717 | OS << "\t\t" "LoopDispositions: { "; |
| 9718 | First = false; |
| 9719 | } else { |
| 9720 | OS << ", "; |
| 9721 | } |
| 9722 | |
| 9723 | InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
| 9724 | OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); |
| 9725 | } |
| 9726 | |
| 9727 | OS << " }"; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9728 | } |
| 9729 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9730 | OS << "\n"; |
| 9731 | } |
| 9732 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9733 | OS << "Determining loop execution counts for: "; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9734 | F.printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9735 | OS << "\n"; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9736 | for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9737 | PrintLoopInfo(OS, &SE, *I); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9738 | } |
Dan Gohman | e20f824 | 2009-04-21 00:47:46 +0000 | [diff] [blame] | 9739 | |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9740 | ScalarEvolution::LoopDisposition |
| 9741 | ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9742 | auto &Values = LoopDispositions[S]; |
| 9743 | for (auto &V : Values) { |
| 9744 | if (V.getPointer() == L) |
| 9745 | return V.getInt(); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9746 | } |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9747 | Values.emplace_back(L, LoopVariant); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9748 | LoopDisposition D = computeLoopDisposition(S, L); |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9749 | auto &Values2 = LoopDispositions[S]; |
| 9750 | for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { |
| 9751 | if (V.getPointer() == L) { |
| 9752 | V.setInt(D); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9753 | break; |
| 9754 | } |
| 9755 | } |
| 9756 | return D; |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9757 | } |
| 9758 | |
| 9759 | ScalarEvolution::LoopDisposition |
| 9760 | ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9761 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9762 | case scConstant: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9763 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9764 | case scTruncate: |
| 9765 | case scZeroExtend: |
| 9766 | case scSignExtend: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9767 | return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9768 | case scAddRecExpr: { |
| 9769 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); |
| 9770 | |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9771 | // If L is the addrec's loop, it's computable. |
| 9772 | if (AR->getLoop() == L) |
| 9773 | return LoopComputable; |
| 9774 | |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9775 | // Add recurrences are never invariant in the function-body (null loop). |
| 9776 | if (!L) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9777 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9778 | |
| 9779 | // This recurrence is variant w.r.t. L if L contains AR's loop. |
| 9780 | if (L->contains(AR->getLoop())) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9781 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9782 | |
| 9783 | // This recurrence is invariant w.r.t. L if AR's loop contains L. |
| 9784 | if (AR->getLoop()->contains(L)) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9785 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9786 | |
| 9787 | // This recurrence is variant w.r.t. L if any of its operands |
| 9788 | // are variant. |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 9789 | for (auto *Op : AR->operands()) |
| 9790 | if (!isLoopInvariant(Op, L)) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9791 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9792 | |
| 9793 | // Otherwise it's loop-invariant. |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9794 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9795 | } |
| 9796 | case scAddExpr: |
| 9797 | case scMulExpr: |
| 9798 | case scUMaxExpr: |
| 9799 | case scSMaxExpr: { |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9800 | bool HasVarying = false; |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 9801 | for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { |
| 9802 | LoopDisposition D = getLoopDisposition(Op, L); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9803 | if (D == LoopVariant) |
| 9804 | return LoopVariant; |
| 9805 | if (D == LoopComputable) |
| 9806 | HasVarying = true; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9807 | } |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9808 | return HasVarying ? LoopComputable : LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9809 | } |
| 9810 | case scUDivExpr: { |
| 9811 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9812 | LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); |
| 9813 | if (LD == LoopVariant) |
| 9814 | return LoopVariant; |
| 9815 | LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); |
| 9816 | if (RD == LoopVariant) |
| 9817 | return LoopVariant; |
| 9818 | return (LD == LoopInvariant && RD == LoopInvariant) ? |
| 9819 | LoopInvariant : LoopComputable; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9820 | } |
| 9821 | case scUnknown: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9822 | // All non-instruction values are loop invariant. All instructions are loop |
| 9823 | // invariant if they are not contained in the specified loop. |
| 9824 | // Instructions are never considered invariant in the function body |
| 9825 | // (null loop) because they are defined within the "loop". |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 9826 | if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9827 | return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; |
| 9828 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9829 | case scCouldNotCompute: |
| 9830 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9831 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9832 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9833 | } |
| 9834 | |
| 9835 | bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { |
| 9836 | return getLoopDisposition(S, L) == LoopInvariant; |
| 9837 | } |
| 9838 | |
| 9839 | bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { |
| 9840 | return getLoopDisposition(S, L) == LoopComputable; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9841 | } |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9842 | |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9843 | ScalarEvolution::BlockDisposition |
| 9844 | ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9845 | auto &Values = BlockDispositions[S]; |
| 9846 | for (auto &V : Values) { |
| 9847 | if (V.getPointer() == BB) |
| 9848 | return V.getInt(); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9849 | } |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9850 | Values.emplace_back(BB, DoesNotDominateBlock); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9851 | BlockDisposition D = computeBlockDisposition(S, BB); |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9852 | auto &Values2 = BlockDispositions[S]; |
| 9853 | for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { |
| 9854 | if (V.getPointer() == BB) { |
| 9855 | V.setInt(D); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9856 | break; |
| 9857 | } |
| 9858 | } |
| 9859 | return D; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9860 | } |
| 9861 | |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9862 | ScalarEvolution::BlockDisposition |
| 9863 | ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9864 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9865 | case scConstant: |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9866 | return ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9867 | case scTruncate: |
| 9868 | case scZeroExtend: |
| 9869 | case scSignExtend: |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9870 | return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9871 | case scAddRecExpr: { |
| 9872 | // This uses a "dominates" query instead of "properly dominates" query |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9873 | // to test for proper dominance too, because the instruction which |
| 9874 | // produces the addrec's value is a PHI, and a PHI effectively properly |
| 9875 | // dominates its entire containing block. |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9876 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9877 | if (!DT.dominates(AR->getLoop()->getHeader(), BB)) |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9878 | return DoesNotDominateBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9879 | } |
| 9880 | // FALL THROUGH into SCEVNAryExpr handling. |
| 9881 | case scAddExpr: |
| 9882 | case scMulExpr: |
| 9883 | case scUMaxExpr: |
| 9884 | case scSMaxExpr: { |
| 9885 | const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9886 | bool Proper = true; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 9887 | for (const SCEV *NAryOp : NAry->operands()) { |
| 9888 | BlockDisposition D = getBlockDisposition(NAryOp, BB); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9889 | if (D == DoesNotDominateBlock) |
| 9890 | return DoesNotDominateBlock; |
| 9891 | if (D == DominatesBlock) |
| 9892 | Proper = false; |
| 9893 | } |
| 9894 | return Proper ? ProperlyDominatesBlock : DominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9895 | } |
| 9896 | case scUDivExpr: { |
| 9897 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9898 | const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); |
| 9899 | BlockDisposition LD = getBlockDisposition(LHS, BB); |
| 9900 | if (LD == DoesNotDominateBlock) |
| 9901 | return DoesNotDominateBlock; |
| 9902 | BlockDisposition RD = getBlockDisposition(RHS, BB); |
| 9903 | if (RD == DoesNotDominateBlock) |
| 9904 | return DoesNotDominateBlock; |
| 9905 | return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? |
| 9906 | ProperlyDominatesBlock : DominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9907 | } |
| 9908 | case scUnknown: |
| 9909 | if (Instruction *I = |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9910 | dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { |
| 9911 | if (I->getParent() == BB) |
| 9912 | return DominatesBlock; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9913 | if (DT.properlyDominates(I->getParent(), BB)) |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9914 | return ProperlyDominatesBlock; |
| 9915 | return DoesNotDominateBlock; |
| 9916 | } |
| 9917 | return ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9918 | case scCouldNotCompute: |
| 9919 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9920 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9921 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9922 | } |
| 9923 | |
| 9924 | bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { |
| 9925 | return getBlockDisposition(S, BB) >= DominatesBlock; |
| 9926 | } |
| 9927 | |
| 9928 | bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { |
| 9929 | return getBlockDisposition(S, BB) == ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9930 | } |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 9931 | |
| 9932 | bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 9933 | // Search for a SCEV expression node within an expression tree. |
| 9934 | // Implements SCEVTraversal::Visitor. |
| 9935 | struct SCEVSearch { |
| 9936 | const SCEV *Node; |
| 9937 | bool IsFound; |
| 9938 | |
| 9939 | SCEVSearch(const SCEV *N): Node(N), IsFound(false) {} |
| 9940 | |
| 9941 | bool follow(const SCEV *S) { |
| 9942 | IsFound |= (S == Node); |
| 9943 | return !IsFound; |
| 9944 | } |
| 9945 | bool isDone() const { return IsFound; } |
| 9946 | }; |
| 9947 | |
Andrew Trick | 365e31c | 2012-07-13 23:33:03 +0000 | [diff] [blame] | 9948 | SCEVSearch Search(Op); |
| 9949 | visitAll(S, Search); |
| 9950 | return Search.IsFound; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 9951 | } |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 9952 | |
| 9953 | void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { |
| 9954 | ValuesAtScopes.erase(S); |
| 9955 | LoopDispositions.erase(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9956 | BlockDispositions.erase(S); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 9957 | UnsignedRanges.erase(S); |
| 9958 | SignedRanges.erase(S); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9959 | ExprValueMap.erase(S); |
| 9960 | HasRecMap.erase(S); |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 9961 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 9962 | auto RemoveSCEVFromBackedgeMap = |
| 9963 | [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { |
| 9964 | for (auto I = Map.begin(), E = Map.end(); I != E;) { |
| 9965 | BackedgeTakenInfo &BEInfo = I->second; |
| 9966 | if (BEInfo.hasOperand(S, this)) { |
| 9967 | BEInfo.clear(); |
| 9968 | Map.erase(I++); |
| 9969 | } else |
| 9970 | ++I; |
| 9971 | } |
| 9972 | }; |
| 9973 | |
| 9974 | RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); |
| 9975 | RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 9976 | } |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9977 | |
| 9978 | typedef DenseMap<const Loop *, std::string> VerifyMap; |
Benjamin Kramer | 24d270d | 2012-10-27 10:45:01 +0000 | [diff] [blame] | 9979 | |
Alp Toker | cb40291 | 2014-01-24 17:20:08 +0000 | [diff] [blame] | 9980 | /// replaceSubString - Replaces all occurrences of From in Str with To. |
Benjamin Kramer | 24d270d | 2012-10-27 10:45:01 +0000 | [diff] [blame] | 9981 | static void replaceSubString(std::string &Str, StringRef From, StringRef To) { |
| 9982 | size_t Pos = 0; |
| 9983 | while ((Pos = Str.find(From, Pos)) != std::string::npos) { |
| 9984 | Str.replace(Pos, From.size(), To.data(), To.size()); |
| 9985 | Pos += To.size(); |
| 9986 | } |
| 9987 | } |
| 9988 | |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9989 | /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis. |
| 9990 | static void |
| 9991 | getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) { |
Sanjoy Das | 2fbfb25 | 2015-12-23 17:48:14 +0000 | [diff] [blame] | 9992 | std::string &S = Map[L]; |
| 9993 | if (S.empty()) { |
| 9994 | raw_string_ostream OS(S); |
| 9995 | SE.getBackedgeTakenCount(L)->print(OS); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9996 | |
Sanjoy Das | 2fbfb25 | 2015-12-23 17:48:14 +0000 | [diff] [blame] | 9997 | // false and 0 are semantically equivalent. This can happen in dead loops. |
| 9998 | replaceSubString(OS.str(), "false", "0"); |
| 9999 | // Remove wrap flags, their use in SCEV is highly fragile. |
| 10000 | // FIXME: Remove this when SCEV gets smarter about them. |
| 10001 | replaceSubString(OS.str(), "<nw>", ""); |
| 10002 | replaceSubString(OS.str(), "<nsw>", ""); |
| 10003 | replaceSubString(OS.str(), "<nuw>", ""); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10004 | } |
Sanjoy Das | 2fbfb25 | 2015-12-23 17:48:14 +0000 | [diff] [blame] | 10005 | |
JF Bastien | 61ad8b3 | 2015-12-23 18:18:53 +0000 | [diff] [blame] | 10006 | for (auto *R : reverse(*L)) |
| 10007 | getLoopBackedgeTakenCounts(R, Map, SE); // recurse. |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10008 | } |
| 10009 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10010 | void ScalarEvolution::verify() const { |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10011 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
| 10012 | |
| 10013 | // Gather stringified backedge taken counts for all loops using SCEV's caches. |
| 10014 | // FIXME: It would be much better to store actual values instead of strings, |
| 10015 | // but SCEV pointers will change if we drop the caches. |
| 10016 | VerifyMap BackedgeDumpsOld, BackedgeDumpsNew; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10017 | for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10018 | getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE); |
| 10019 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10020 | // Gather stringified backedge taken counts for all loops using a fresh |
| 10021 | // ScalarEvolution object. |
| 10022 | ScalarEvolution SE2(F, TLI, AC, DT, LI); |
| 10023 | for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) |
| 10024 | getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10025 | |
| 10026 | // Now compare whether they're the same with and without caches. This allows |
| 10027 | // verifying that no pass changed the cache. |
| 10028 | assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() && |
| 10029 | "New loops suddenly appeared!"); |
| 10030 | |
| 10031 | for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(), |
| 10032 | OldE = BackedgeDumpsOld.end(), |
| 10033 | NewI = BackedgeDumpsNew.begin(); |
| 10034 | OldI != OldE; ++OldI, ++NewI) { |
| 10035 | assert(OldI->first == NewI->first && "Loop order changed!"); |
| 10036 | |
| 10037 | // Compare the stringified SCEVs. We don't care if undef backedgetaken count |
| 10038 | // changes. |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 10039 | // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10040 | // means that a pass is buggy or SCEV has to learn a new pattern but is |
| 10041 | // usually not harmful. |
| 10042 | if (OldI->second != NewI->second && |
| 10043 | OldI->second.find("undef") == std::string::npos && |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 10044 | NewI->second.find("undef") == std::string::npos && |
| 10045 | OldI->second != "***COULDNOTCOMPUTE***" && |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10046 | NewI->second != "***COULDNOTCOMPUTE***") { |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 10047 | dbgs() << "SCEVValidator: SCEV for loop '" |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10048 | << OldI->first->getHeader()->getName() |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 10049 | << "' changed from '" << OldI->second |
| 10050 | << "' to '" << NewI->second << "'!\n"; |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10051 | std::abort(); |
| 10052 | } |
| 10053 | } |
| 10054 | |
| 10055 | // TODO: Verify more things. |
| 10056 | } |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10057 | |
Chandler Carruth | b4faf13 | 2016-03-11 10:22:49 +0000 | [diff] [blame] | 10058 | char ScalarEvolutionAnalysis::PassID; |
NAKAMURA Takumi | df0cd72 | 2016-02-28 17:17:00 +0000 | [diff] [blame] | 10059 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10060 | ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, |
Chandler Carruth | b47f801 | 2016-03-11 11:05:24 +0000 | [diff] [blame] | 10061 | AnalysisManager<Function> &AM) { |
| 10062 | return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), |
| 10063 | AM.getResult<AssumptionAnalysis>(F), |
| 10064 | AM.getResult<DominatorTreeAnalysis>(F), |
| 10065 | AM.getResult<LoopAnalysis>(F)); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10066 | } |
| 10067 | |
| 10068 | PreservedAnalyses |
Chandler Carruth | b47f801 | 2016-03-11 11:05:24 +0000 | [diff] [blame] | 10069 | ScalarEvolutionPrinterPass::run(Function &F, AnalysisManager<Function> &AM) { |
| 10070 | AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10071 | return PreservedAnalyses::all(); |
| 10072 | } |
| 10073 | |
| 10074 | INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", |
| 10075 | "Scalar Evolution Analysis", false, true) |
| 10076 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) |
| 10077 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
| 10078 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 10079 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
| 10080 | INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", |
| 10081 | "Scalar Evolution Analysis", false, true) |
| 10082 | char ScalarEvolutionWrapperPass::ID = 0; |
| 10083 | |
| 10084 | ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { |
| 10085 | initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); |
| 10086 | } |
| 10087 | |
| 10088 | bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { |
| 10089 | SE.reset(new ScalarEvolution( |
| 10090 | F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), |
| 10091 | getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), |
| 10092 | getAnalysis<DominatorTreeWrapperPass>().getDomTree(), |
| 10093 | getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); |
| 10094 | return false; |
| 10095 | } |
| 10096 | |
| 10097 | void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } |
| 10098 | |
| 10099 | void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { |
| 10100 | SE->print(OS); |
| 10101 | } |
| 10102 | |
| 10103 | void ScalarEvolutionWrapperPass::verifyAnalysis() const { |
| 10104 | if (!VerifySCEV) |
| 10105 | return; |
| 10106 | |
| 10107 | SE->verify(); |
| 10108 | } |
| 10109 | |
| 10110 | void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { |
| 10111 | AU.setPreservesAll(); |
| 10112 | AU.addRequiredTransitive<AssumptionCacheTracker>(); |
| 10113 | AU.addRequiredTransitive<LoopInfoWrapperPass>(); |
| 10114 | AU.addRequiredTransitive<DominatorTreeWrapperPass>(); |
| 10115 | AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); |
| 10116 | } |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10117 | |
| 10118 | const SCEVPredicate * |
| 10119 | ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS, |
| 10120 | const SCEVConstant *RHS) { |
| 10121 | FoldingSetNodeID ID; |
| 10122 | // Unique this node based on the arguments |
| 10123 | ID.AddInteger(SCEVPredicate::P_Equal); |
| 10124 | ID.AddPointer(LHS); |
| 10125 | ID.AddPointer(RHS); |
| 10126 | void *IP = nullptr; |
| 10127 | if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) |
| 10128 | return S; |
| 10129 | SCEVEqualPredicate *Eq = new (SCEVAllocator) |
| 10130 | SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); |
| 10131 | UniquePreds.InsertNode(Eq, IP); |
| 10132 | return Eq; |
| 10133 | } |
| 10134 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10135 | const SCEVPredicate *ScalarEvolution::getWrapPredicate( |
| 10136 | const SCEVAddRecExpr *AR, |
| 10137 | SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { |
| 10138 | FoldingSetNodeID ID; |
| 10139 | // Unique this node based on the arguments |
| 10140 | ID.AddInteger(SCEVPredicate::P_Wrap); |
| 10141 | ID.AddPointer(AR); |
| 10142 | ID.AddInteger(AddedFlags); |
| 10143 | void *IP = nullptr; |
| 10144 | if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) |
| 10145 | return S; |
| 10146 | auto *OF = new (SCEVAllocator) |
| 10147 | SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); |
| 10148 | UniquePreds.InsertNode(OF, IP); |
| 10149 | return OF; |
| 10150 | } |
| 10151 | |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 10152 | namespace { |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10153 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10154 | class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { |
| 10155 | public: |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 10156 | // Rewrites \p S in the context of a loop L and the predicate A. |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10157 | // If Assume is true, rewrite is free to add further predicates to A |
| 10158 | // such that the result will be an AddRecExpr. |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 10159 | static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, |
| 10160 | SCEVUnionPredicate &A, bool Assume) { |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10161 | SCEVPredicateRewriter Rewriter(L, SE, A, Assume); |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 10162 | return Rewriter.visit(S); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10163 | } |
| 10164 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10165 | SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, |
| 10166 | SCEVUnionPredicate &P, bool Assume) |
| 10167 | : SCEVRewriteVisitor(SE), P(P), L(L), Assume(Assume) {} |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10168 | |
| 10169 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { |
| 10170 | auto ExprPreds = P.getPredicatesForExpr(Expr); |
| 10171 | for (auto *Pred : ExprPreds) |
| 10172 | if (const auto *IPred = dyn_cast<const SCEVEqualPredicate>(Pred)) |
| 10173 | if (IPred->getLHS() == Expr) |
| 10174 | return IPred->getRHS(); |
| 10175 | |
| 10176 | return Expr; |
| 10177 | } |
| 10178 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10179 | const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { |
| 10180 | const SCEV *Operand = visit(Expr->getOperand()); |
| 10181 | const SCEVAddRecExpr *AR = dyn_cast<const SCEVAddRecExpr>(Operand); |
| 10182 | if (AR && AR->getLoop() == L && AR->isAffine()) { |
| 10183 | // This couldn't be folded because the operand didn't have the nuw |
| 10184 | // flag. Add the nusw flag as an assumption that we could make. |
| 10185 | const SCEV *Step = AR->getStepRecurrence(SE); |
| 10186 | Type *Ty = Expr->getType(); |
| 10187 | if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) |
| 10188 | return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), |
| 10189 | SE.getSignExtendExpr(Step, Ty), L, |
| 10190 | AR->getNoWrapFlags()); |
| 10191 | } |
| 10192 | return SE.getZeroExtendExpr(Operand, Expr->getType()); |
| 10193 | } |
| 10194 | |
| 10195 | const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { |
| 10196 | const SCEV *Operand = visit(Expr->getOperand()); |
| 10197 | const SCEVAddRecExpr *AR = dyn_cast<const SCEVAddRecExpr>(Operand); |
| 10198 | if (AR && AR->getLoop() == L && AR->isAffine()) { |
| 10199 | // This couldn't be folded because the operand didn't have the nsw |
| 10200 | // flag. Add the nssw flag as an assumption that we could make. |
| 10201 | const SCEV *Step = AR->getStepRecurrence(SE); |
| 10202 | Type *Ty = Expr->getType(); |
| 10203 | if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) |
| 10204 | return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), |
| 10205 | SE.getSignExtendExpr(Step, Ty), L, |
| 10206 | AR->getNoWrapFlags()); |
| 10207 | } |
| 10208 | return SE.getSignExtendExpr(Operand, Expr->getType()); |
| 10209 | } |
| 10210 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10211 | private: |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10212 | bool addOverflowAssumption(const SCEVAddRecExpr *AR, |
| 10213 | SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { |
| 10214 | auto *A = SE.getWrapPredicate(AR, AddedFlags); |
| 10215 | if (!Assume) { |
| 10216 | // Check if we've already made this assumption. |
| 10217 | if (P.implies(A)) |
| 10218 | return true; |
| 10219 | return false; |
| 10220 | } |
| 10221 | P.add(A); |
| 10222 | return true; |
| 10223 | } |
| 10224 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10225 | SCEVUnionPredicate &P; |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10226 | const Loop *L; |
| 10227 | bool Assume; |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10228 | }; |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 10229 | } // end anonymous namespace |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10230 | |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 10231 | const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10232 | SCEVUnionPredicate &Preds) { |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 10233 | return SCEVPredicateRewriter::rewrite(S, L, *this, Preds, false); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10234 | } |
| 10235 | |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 10236 | const SCEVAddRecExpr * |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 10237 | ScalarEvolution::convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, |
| 10238 | SCEVUnionPredicate &Preds) { |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 10239 | SCEVUnionPredicate TransformPreds; |
| 10240 | S = SCEVPredicateRewriter::rewrite(S, L, *this, TransformPreds, true); |
| 10241 | auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); |
| 10242 | |
| 10243 | if (!AddRec) |
| 10244 | return nullptr; |
| 10245 | |
| 10246 | // Since the transformation was successful, we can now transfer the SCEV |
| 10247 | // predicates. |
| 10248 | Preds.add(&TransformPreds); |
| 10249 | return AddRec; |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10250 | } |
| 10251 | |
| 10252 | /// SCEV predicates |
| 10253 | SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, |
| 10254 | SCEVPredicateKind Kind) |
| 10255 | : FastID(ID), Kind(Kind) {} |
| 10256 | |
| 10257 | SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, |
| 10258 | const SCEVUnknown *LHS, |
| 10259 | const SCEVConstant *RHS) |
| 10260 | : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {} |
| 10261 | |
| 10262 | bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { |
| 10263 | const auto *Op = dyn_cast<const SCEVEqualPredicate>(N); |
| 10264 | |
| 10265 | if (!Op) |
| 10266 | return false; |
| 10267 | |
| 10268 | return Op->LHS == LHS && Op->RHS == RHS; |
| 10269 | } |
| 10270 | |
| 10271 | bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } |
| 10272 | |
| 10273 | const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } |
| 10274 | |
| 10275 | void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { |
| 10276 | OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; |
| 10277 | } |
| 10278 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10279 | SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, |
| 10280 | const SCEVAddRecExpr *AR, |
| 10281 | IncrementWrapFlags Flags) |
| 10282 | : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} |
| 10283 | |
| 10284 | const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } |
| 10285 | |
| 10286 | bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { |
| 10287 | const auto *Op = dyn_cast<SCEVWrapPredicate>(N); |
| 10288 | |
| 10289 | return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; |
| 10290 | } |
| 10291 | |
| 10292 | bool SCEVWrapPredicate::isAlwaysTrue() const { |
| 10293 | SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); |
| 10294 | IncrementWrapFlags IFlags = Flags; |
| 10295 | |
| 10296 | if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) |
| 10297 | IFlags = clearFlags(IFlags, IncrementNSSW); |
| 10298 | |
| 10299 | return IFlags == IncrementAnyWrap; |
| 10300 | } |
| 10301 | |
| 10302 | void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { |
| 10303 | OS.indent(Depth) << *getExpr() << " Added Flags: "; |
| 10304 | if (SCEVWrapPredicate::IncrementNUSW & getFlags()) |
| 10305 | OS << "<nusw>"; |
| 10306 | if (SCEVWrapPredicate::IncrementNSSW & getFlags()) |
| 10307 | OS << "<nssw>"; |
| 10308 | OS << "\n"; |
| 10309 | } |
| 10310 | |
| 10311 | SCEVWrapPredicate::IncrementWrapFlags |
| 10312 | SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, |
| 10313 | ScalarEvolution &SE) { |
| 10314 | IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; |
| 10315 | SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); |
| 10316 | |
| 10317 | // We can safely transfer the NSW flag as NSSW. |
| 10318 | if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) |
| 10319 | ImpliedFlags = IncrementNSSW; |
| 10320 | |
| 10321 | if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { |
| 10322 | // If the increment is positive, the SCEV NUW flag will also imply the |
| 10323 | // WrapPredicate NUSW flag. |
| 10324 | if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) |
| 10325 | if (Step->getValue()->getValue().isNonNegative()) |
| 10326 | ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); |
| 10327 | } |
| 10328 | |
| 10329 | return ImpliedFlags; |
| 10330 | } |
| 10331 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10332 | /// Union predicates don't get cached so create a dummy set ID for it. |
| 10333 | SCEVUnionPredicate::SCEVUnionPredicate() |
| 10334 | : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} |
| 10335 | |
| 10336 | bool SCEVUnionPredicate::isAlwaysTrue() const { |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 10337 | return all_of(Preds, |
| 10338 | [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10339 | } |
| 10340 | |
| 10341 | ArrayRef<const SCEVPredicate *> |
| 10342 | SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { |
| 10343 | auto I = SCEVToPreds.find(Expr); |
| 10344 | if (I == SCEVToPreds.end()) |
| 10345 | return ArrayRef<const SCEVPredicate *>(); |
| 10346 | return I->second; |
| 10347 | } |
| 10348 | |
| 10349 | bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { |
| 10350 | if (const auto *Set = dyn_cast<const SCEVUnionPredicate>(N)) |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 10351 | return all_of(Set->Preds, |
| 10352 | [this](const SCEVPredicate *I) { return this->implies(I); }); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10353 | |
| 10354 | auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); |
| 10355 | if (ScevPredsIt == SCEVToPreds.end()) |
| 10356 | return false; |
| 10357 | auto &SCEVPreds = ScevPredsIt->second; |
| 10358 | |
Sanjoy Das | ff3b8b4 | 2015-12-01 07:49:23 +0000 | [diff] [blame] | 10359 | return any_of(SCEVPreds, |
| 10360 | [N](const SCEVPredicate *I) { return I->implies(N); }); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10361 | } |
| 10362 | |
| 10363 | const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } |
| 10364 | |
| 10365 | void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { |
| 10366 | for (auto Pred : Preds) |
| 10367 | Pred->print(OS, Depth); |
| 10368 | } |
| 10369 | |
| 10370 | void SCEVUnionPredicate::add(const SCEVPredicate *N) { |
| 10371 | if (const auto *Set = dyn_cast<const SCEVUnionPredicate>(N)) { |
| 10372 | for (auto Pred : Set->Preds) |
| 10373 | add(Pred); |
| 10374 | return; |
| 10375 | } |
| 10376 | |
| 10377 | if (implies(N)) |
| 10378 | return; |
| 10379 | |
| 10380 | const SCEV *Key = N->getExpr(); |
| 10381 | assert(Key && "Only SCEVUnionPredicate doesn't have an " |
| 10382 | " associated expression!"); |
| 10383 | |
| 10384 | SCEVToPreds[Key].push_back(N); |
| 10385 | Preds.push_back(N); |
| 10386 | } |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10387 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10388 | PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, |
| 10389 | Loop &L) |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 10390 | : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {} |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10391 | |
| 10392 | const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { |
| 10393 | const SCEV *Expr = SE.getSCEV(V); |
| 10394 | RewriteEntry &Entry = RewriteMap[Expr]; |
| 10395 | |
| 10396 | // If we already have an entry and the version matches, return it. |
| 10397 | if (Entry.second && Generation == Entry.first) |
| 10398 | return Entry.second; |
| 10399 | |
| 10400 | // We found an entry but it's stale. Rewrite the stale entry |
| 10401 | // acording to the current predicate. |
| 10402 | if (Entry.second) |
| 10403 | Expr = Entry.second; |
| 10404 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10405 | const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10406 | Entry = {Generation, NewSCEV}; |
| 10407 | |
| 10408 | return NewSCEV; |
| 10409 | } |
| 10410 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 10411 | const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { |
| 10412 | if (!BackedgeCount) { |
| 10413 | SCEVUnionPredicate BackedgePred; |
| 10414 | BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); |
| 10415 | addPredicate(BackedgePred); |
| 10416 | } |
| 10417 | return BackedgeCount; |
| 10418 | } |
| 10419 | |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10420 | void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { |
| 10421 | if (Preds.implies(&Pred)) |
| 10422 | return; |
| 10423 | Preds.add(&Pred); |
| 10424 | updateGeneration(); |
| 10425 | } |
| 10426 | |
| 10427 | const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { |
| 10428 | return Preds; |
| 10429 | } |
| 10430 | |
| 10431 | void PredicatedScalarEvolution::updateGeneration() { |
| 10432 | // If the generation number wrapped recompute everything. |
| 10433 | if (++Generation == 0) { |
| 10434 | for (auto &II : RewriteMap) { |
| 10435 | const SCEV *Rewritten = II.second.second; |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10436 | II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10437 | } |
| 10438 | } |
| 10439 | } |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10440 | |
| 10441 | void PredicatedScalarEvolution::setNoOverflow( |
| 10442 | Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { |
| 10443 | const SCEV *Expr = getSCEV(V); |
| 10444 | const auto *AR = cast<SCEVAddRecExpr>(Expr); |
| 10445 | |
| 10446 | auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); |
| 10447 | |
| 10448 | // Clear the statically implied flags. |
| 10449 | Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); |
| 10450 | addPredicate(*SE.getWrapPredicate(AR, Flags)); |
| 10451 | |
| 10452 | auto II = FlagsMap.insert({V, Flags}); |
| 10453 | if (!II.second) |
| 10454 | II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); |
| 10455 | } |
| 10456 | |
| 10457 | bool PredicatedScalarEvolution::hasNoOverflow( |
| 10458 | Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { |
| 10459 | const SCEV *Expr = getSCEV(V); |
| 10460 | const auto *AR = cast<SCEVAddRecExpr>(Expr); |
| 10461 | |
| 10462 | Flags = SCEVWrapPredicate::clearFlags( |
| 10463 | Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); |
| 10464 | |
| 10465 | auto II = FlagsMap.find(V); |
| 10466 | |
| 10467 | if (II != FlagsMap.end()) |
| 10468 | Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); |
| 10469 | |
| 10470 | return Flags == SCEVWrapPredicate::IncrementAnyWrap; |
| 10471 | } |
| 10472 | |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 10473 | const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10474 | const SCEV *Expr = this->getSCEV(V); |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 10475 | auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, Preds); |
| 10476 | |
| 10477 | if (!New) |
| 10478 | return nullptr; |
| 10479 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10480 | updateGeneration(); |
| 10481 | RewriteMap[SE.getSCEV(V)] = {Generation, New}; |
| 10482 | return New; |
| 10483 | } |
| 10484 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 10485 | PredicatedScalarEvolution::PredicatedScalarEvolution( |
| 10486 | const PredicatedScalarEvolution &Init) |
| 10487 | : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), |
| 10488 | Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10489 | for (auto I = Init.FlagsMap.begin(), E = Init.FlagsMap.end(); I != E; ++I) |
| 10490 | FlagsMap.insert(*I); |
| 10491 | } |
Silviu Baranga | b77365b | 2016-04-14 16:08:45 +0000 | [diff] [blame] | 10492 | |
| 10493 | void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { |
| 10494 | // For each block. |
| 10495 | for (auto *BB : L.getBlocks()) |
| 10496 | for (auto &I : *BB) { |
| 10497 | if (!SE.isSCEVable(I.getType())) |
| 10498 | continue; |
| 10499 | |
| 10500 | auto *Expr = SE.getSCEV(&I); |
| 10501 | auto II = RewriteMap.find(Expr); |
| 10502 | |
| 10503 | if (II == RewriteMap.end()) |
| 10504 | continue; |
| 10505 | |
| 10506 | // Don't print things that are not interesting. |
| 10507 | if (II->second.second == Expr) |
| 10508 | continue; |
| 10509 | |
| 10510 | OS.indent(Depth) << "[PSE]" << I << ":\n"; |
| 10511 | OS.indent(Depth + 2) << *Expr << "\n"; |
| 10512 | OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; |
| 10513 | } |
| 10514 | } |