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" |
Sanjoy Das | c46bceb | 2016-09-27 18:01:42 +0000 | [diff] [blame] | 64 | #include "llvm/ADT/ScopeExit.h" |
Sanjoy Das | 1707869 | 2016-10-31 03:32:43 +0000 | [diff] [blame] | 65 | #include "llvm/ADT/Sequence.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 66 | #include "llvm/ADT/SmallPtrSet.h" |
| 67 | #include "llvm/ADT/Statistic.h" |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 68 | #include "llvm/Analysis/AssumptionCache.h" |
John Criswell | fe5f33b | 2005-10-27 15:54:34 +0000 | [diff] [blame] | 69 | #include "llvm/Analysis/ConstantFolding.h" |
Duncan Sands | d06f50e | 2010-11-17 04:18:45 +0000 | [diff] [blame] | 70 | #include "llvm/Analysis/InstructionSimplify.h" |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 71 | #include "llvm/Analysis/LoopInfo.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 72 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Chandler Carruth | 62d4215 | 2015-01-15 02:16:27 +0000 | [diff] [blame] | 73 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Dan Gohman | 1ee696d | 2009-06-16 19:52:01 +0000 | [diff] [blame] | 74 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 8cd041e | 2014-03-04 12:24:34 +0000 | [diff] [blame] | 75 | #include "llvm/IR/ConstantRange.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 76 | #include "llvm/IR/Constants.h" |
| 77 | #include "llvm/IR/DataLayout.h" |
| 78 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 79 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 80 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 81 | #include "llvm/IR/GlobalAlias.h" |
| 82 | #include "llvm/IR/GlobalVariable.h" |
Chandler Carruth | 8394857 | 2014-03-04 10:30:26 +0000 | [diff] [blame] | 83 | #include "llvm/IR/InstIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 84 | #include "llvm/IR/Instructions.h" |
| 85 | #include "llvm/IR/LLVMContext.h" |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 86 | #include "llvm/IR/Metadata.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 87 | #include "llvm/IR/Operator.h" |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 88 | #include "llvm/IR/PatternMatch.h" |
Chris Lattner | 996795b | 2006-06-28 23:17:24 +0000 | [diff] [blame] | 89 | #include "llvm/Support/CommandLine.h" |
David Greene | 2330f78 | 2009-12-23 22:58:38 +0000 | [diff] [blame] | 90 | #include "llvm/Support/Debug.h" |
Torok Edwin | 56d0659 | 2009-07-11 20:10:48 +0000 | [diff] [blame] | 91 | #include "llvm/Support/ErrorHandling.h" |
Chris Lattner | 0a1e993 | 2006-12-19 01:16:02 +0000 | [diff] [blame] | 92 | #include "llvm/Support/MathExtras.h" |
Dan Gohman | e20f824 | 2009-04-21 00:47:46 +0000 | [diff] [blame] | 93 | #include "llvm/Support/raw_ostream.h" |
Sanjoy Das | 5d9a8cb | 2015-09-22 00:10:57 +0000 | [diff] [blame] | 94 | #include "llvm/Support/SaveAndRestore.h" |
Alkis Evlogimenos | a5c04ee | 2004-09-03 18:19:51 +0000 | [diff] [blame] | 95 | #include <algorithm> |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 96 | using namespace llvm; |
| 97 | |
Chandler Carruth | f1221bd | 2014-04-22 02:48:03 +0000 | [diff] [blame] | 98 | #define DEBUG_TYPE "scalar-evolution" |
| 99 | |
Chris Lattner | 57ef942 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 100 | STATISTIC(NumArrayLenItCounts, |
| 101 | "Number of trip counts computed with array length"); |
| 102 | STATISTIC(NumTripCountsComputed, |
| 103 | "Number of loops with predictable loop counts"); |
| 104 | STATISTIC(NumTripCountsNotComputed, |
| 105 | "Number of loops without predictable loop counts"); |
| 106 | STATISTIC(NumBruteForceTripCountsComputed, |
| 107 | "Number of loops with trip counts computed by force"); |
| 108 | |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 109 | static cl::opt<unsigned> |
Chris Lattner | 57ef942 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 110 | MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, |
| 111 | cl::desc("Maximum number of iterations SCEV will " |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 112 | "symbolically execute a constant " |
| 113 | "derived loop"), |
Chris Lattner | 57ef942 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 114 | cl::init(100)); |
| 115 | |
Filipe Cabecinhas | 0da9937 | 2016-04-29 15:22:48 +0000 | [diff] [blame] | 116 | // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 117 | static cl::opt<bool> |
| 118 | VerifySCEV("verify-scev", |
| 119 | cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 120 | static cl::opt<bool> |
| 121 | VerifySCEVMap("verify-scev-maps", |
Jeroen Ketema | e48e393 | 2016-04-12 23:21:46 +0000 | [diff] [blame] | 122 | cl::desc("Verify no dangling value in ScalarEvolution's " |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 123 | "ExprValueMap (slow)")); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 124 | |
Li Huang | fcfe8cd | 2016-10-20 21:38:39 +0000 | [diff] [blame] | 125 | static cl::opt<unsigned> MulOpsInlineThreshold( |
| 126 | "scev-mulops-inline-threshold", cl::Hidden, |
| 127 | cl::desc("Threshold for inlining multiplication operands into a SCEV"), |
| 128 | cl::init(1000)); |
| 129 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 130 | //===----------------------------------------------------------------------===// |
| 131 | // SCEV class definitions |
| 132 | //===----------------------------------------------------------------------===// |
| 133 | |
| 134 | //===----------------------------------------------------------------------===// |
| 135 | // Implementation of the SCEV class. |
| 136 | // |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 137 | |
Davide Italiano | 2071f4c | 2015-10-25 19:55:24 +0000 | [diff] [blame] | 138 | LLVM_DUMP_METHOD |
| 139 | void SCEV::dump() const { |
| 140 | print(dbgs()); |
| 141 | dbgs() << '\n'; |
| 142 | } |
| 143 | |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 144 | void SCEV::print(raw_ostream &OS) const { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 145 | switch (static_cast<SCEVTypes>(getSCEVType())) { |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 146 | case scConstant: |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 147 | cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 148 | return; |
| 149 | case scTruncate: { |
| 150 | const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); |
| 151 | const SCEV *Op = Trunc->getOperand(); |
| 152 | OS << "(trunc " << *Op->getType() << " " << *Op << " to " |
| 153 | << *Trunc->getType() << ")"; |
| 154 | return; |
| 155 | } |
| 156 | case scZeroExtend: { |
| 157 | const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); |
| 158 | const SCEV *Op = ZExt->getOperand(); |
| 159 | OS << "(zext " << *Op->getType() << " " << *Op << " to " |
| 160 | << *ZExt->getType() << ")"; |
| 161 | return; |
| 162 | } |
| 163 | case scSignExtend: { |
| 164 | const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); |
| 165 | const SCEV *Op = SExt->getOperand(); |
| 166 | OS << "(sext " << *Op->getType() << " " << *Op << " to " |
| 167 | << *SExt->getType() << ")"; |
| 168 | return; |
| 169 | } |
| 170 | case scAddRecExpr: { |
| 171 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); |
| 172 | OS << "{" << *AR->getOperand(0); |
| 173 | for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) |
| 174 | OS << ",+," << *AR->getOperand(i); |
| 175 | OS << "}<"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 176 | if (AR->hasNoUnsignedWrap()) |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 177 | OS << "nuw><"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 178 | if (AR->hasNoSignedWrap()) |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 179 | OS << "nsw><"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 180 | if (AR->hasNoSelfWrap() && |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 181 | !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) |
| 182 | OS << "nw><"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 183 | AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 184 | OS << ">"; |
| 185 | return; |
| 186 | } |
| 187 | case scAddExpr: |
| 188 | case scMulExpr: |
| 189 | case scUMaxExpr: |
| 190 | case scSMaxExpr: { |
| 191 | const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 192 | const char *OpStr = nullptr; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 193 | switch (NAry->getSCEVType()) { |
| 194 | case scAddExpr: OpStr = " + "; break; |
| 195 | case scMulExpr: OpStr = " * "; break; |
| 196 | case scUMaxExpr: OpStr = " umax "; break; |
| 197 | case scSMaxExpr: OpStr = " smax "; break; |
| 198 | } |
| 199 | OS << "("; |
| 200 | for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); |
| 201 | I != E; ++I) { |
| 202 | OS << **I; |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 203 | if (std::next(I) != E) |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 204 | OS << OpStr; |
| 205 | } |
| 206 | OS << ")"; |
Andrew Trick | d912a5b | 2011-11-29 02:06:35 +0000 | [diff] [blame] | 207 | switch (NAry->getSCEVType()) { |
| 208 | case scAddExpr: |
| 209 | case scMulExpr: |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 210 | if (NAry->hasNoUnsignedWrap()) |
Andrew Trick | d912a5b | 2011-11-29 02:06:35 +0000 | [diff] [blame] | 211 | OS << "<nuw>"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 212 | if (NAry->hasNoSignedWrap()) |
Andrew Trick | d912a5b | 2011-11-29 02:06:35 +0000 | [diff] [blame] | 213 | OS << "<nsw>"; |
| 214 | } |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 215 | return; |
| 216 | } |
| 217 | case scUDivExpr: { |
| 218 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); |
| 219 | OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; |
| 220 | return; |
| 221 | } |
| 222 | case scUnknown: { |
| 223 | const SCEVUnknown *U = cast<SCEVUnknown>(this); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 224 | Type *AllocTy; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 225 | if (U->isSizeOf(AllocTy)) { |
| 226 | OS << "sizeof(" << *AllocTy << ")"; |
| 227 | return; |
| 228 | } |
| 229 | if (U->isAlignOf(AllocTy)) { |
| 230 | OS << "alignof(" << *AllocTy << ")"; |
| 231 | return; |
| 232 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 233 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 234 | Type *CTy; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 235 | Constant *FieldNo; |
| 236 | if (U->isOffsetOf(CTy, FieldNo)) { |
| 237 | OS << "offsetof(" << *CTy << ", "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 238 | FieldNo->printAsOperand(OS, false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 239 | OS << ")"; |
| 240 | return; |
| 241 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 242 | |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 243 | // Otherwise just print it normally. |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 244 | U->getValue()->printAsOperand(OS, false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 245 | return; |
| 246 | } |
| 247 | case scCouldNotCompute: |
| 248 | OS << "***COULDNOTCOMPUTE***"; |
| 249 | return; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 250 | } |
| 251 | llvm_unreachable("Unknown SCEV kind!"); |
| 252 | } |
| 253 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 254 | Type *SCEV::getType() const { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 255 | switch (static_cast<SCEVTypes>(getSCEVType())) { |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 256 | case scConstant: |
| 257 | return cast<SCEVConstant>(this)->getType(); |
| 258 | case scTruncate: |
| 259 | case scZeroExtend: |
| 260 | case scSignExtend: |
| 261 | return cast<SCEVCastExpr>(this)->getType(); |
| 262 | case scAddRecExpr: |
| 263 | case scMulExpr: |
| 264 | case scUMaxExpr: |
| 265 | case scSMaxExpr: |
| 266 | return cast<SCEVNAryExpr>(this)->getType(); |
| 267 | case scAddExpr: |
| 268 | return cast<SCEVAddExpr>(this)->getType(); |
| 269 | case scUDivExpr: |
| 270 | return cast<SCEVUDivExpr>(this)->getType(); |
| 271 | case scUnknown: |
| 272 | return cast<SCEVUnknown>(this)->getType(); |
| 273 | case scCouldNotCompute: |
| 274 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 275 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 276 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 277 | } |
| 278 | |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 279 | bool SCEV::isZero() const { |
| 280 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 281 | return SC->getValue()->isZero(); |
| 282 | return false; |
| 283 | } |
| 284 | |
Dan Gohman | ba7f6d8 | 2009-05-18 15:22:39 +0000 | [diff] [blame] | 285 | bool SCEV::isOne() const { |
| 286 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 287 | return SC->getValue()->isOne(); |
| 288 | return false; |
| 289 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 290 | |
Dan Gohman | 18a96bb | 2009-06-24 00:30:26 +0000 | [diff] [blame] | 291 | bool SCEV::isAllOnesValue() const { |
| 292 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 293 | return SC->getValue()->isAllOnesValue(); |
| 294 | return false; |
| 295 | } |
| 296 | |
Andrew Trick | 881a776 | 2012-01-07 00:27:31 +0000 | [diff] [blame] | 297 | bool SCEV::isNonConstantNegative() const { |
| 298 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); |
| 299 | if (!Mul) return false; |
| 300 | |
| 301 | // If there is a constant factor, it will be first. |
| 302 | const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); |
| 303 | if (!SC) return false; |
| 304 | |
| 305 | // 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] | 306 | return SC->getAPInt().isNegative(); |
Andrew Trick | 881a776 | 2012-01-07 00:27:31 +0000 | [diff] [blame] | 307 | } |
| 308 | |
Owen Anderson | 04052ec | 2009-06-22 21:57:23 +0000 | [diff] [blame] | 309 | SCEVCouldNotCompute::SCEVCouldNotCompute() : |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 310 | SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 311 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 312 | bool SCEVCouldNotCompute::classof(const SCEV *S) { |
| 313 | return S->getSCEVType() == scCouldNotCompute; |
| 314 | } |
| 315 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 316 | const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 317 | FoldingSetNodeID ID; |
| 318 | ID.AddInteger(scConstant); |
| 319 | ID.AddPointer(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 320 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 321 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 322 | SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 323 | UniqueSCEVs.InsertNode(S, IP); |
| 324 | return S; |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 325 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 326 | |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 327 | const SCEV *ScalarEvolution::getConstant(const APInt &Val) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 328 | return getConstant(ConstantInt::get(getContext(), Val)); |
Dan Gohman | 0a76e7f | 2007-07-09 15:25:17 +0000 | [diff] [blame] | 329 | } |
| 330 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 331 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 332 | ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { |
| 333 | IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); |
Dan Gohman | a029cbe | 2010-04-21 16:04:04 +0000 | [diff] [blame] | 334 | return getConstant(ConstantInt::get(ITy, V, isSigned)); |
Dan Gohman | 7ccc52f | 2009-06-15 22:12:54 +0000 | [diff] [blame] | 335 | } |
| 336 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 337 | SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 338 | unsigned SCEVTy, const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 339 | : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 340 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 341 | SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 342 | const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 343 | : SCEVCastExpr(ID, scTruncate, op, ty) { |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 344 | assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && |
| 345 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 346 | "Cannot truncate non-integer value!"); |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 347 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 348 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 349 | SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 350 | const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 351 | : SCEVCastExpr(ID, scZeroExtend, op, ty) { |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 352 | assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && |
| 353 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 354 | "Cannot zero extend non-integer value!"); |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 355 | } |
| 356 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 357 | SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 358 | const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 359 | : SCEVCastExpr(ID, scSignExtend, op, ty) { |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 360 | assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && |
| 361 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 362 | "Cannot sign extend non-integer value!"); |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 363 | } |
| 364 | |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 365 | void SCEVUnknown::deleted() { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 366 | // Clear this SCEVUnknown from various maps. |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 367 | SE->forgetMemoizedResults(this); |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 368 | |
| 369 | // Remove this SCEVUnknown from the uniquing map. |
| 370 | SE->UniqueSCEVs.RemoveNode(this); |
| 371 | |
| 372 | // Release the value. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 373 | setValPtr(nullptr); |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 374 | } |
| 375 | |
| 376 | void SCEVUnknown::allUsesReplacedWith(Value *New) { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 377 | // Clear this SCEVUnknown from various maps. |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 378 | SE->forgetMemoizedResults(this); |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 379 | |
| 380 | // Remove this SCEVUnknown from the uniquing map. |
| 381 | SE->UniqueSCEVs.RemoveNode(this); |
| 382 | |
| 383 | // Update this SCEVUnknown to point to the new value. This is needed |
| 384 | // because there may still be outstanding SCEVs which still point to |
| 385 | // this SCEVUnknown. |
| 386 | setValPtr(New); |
| 387 | } |
| 388 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 389 | bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 390 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 391 | if (VCE->getOpcode() == Instruction::PtrToInt) |
| 392 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 393 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 394 | CE->getOperand(0)->isNullValue() && |
| 395 | CE->getNumOperands() == 2) |
| 396 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) |
| 397 | if (CI->isOne()) { |
| 398 | AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) |
| 399 | ->getElementType(); |
| 400 | return true; |
| 401 | } |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 402 | |
| 403 | return false; |
| 404 | } |
| 405 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 406 | bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 407 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 408 | if (VCE->getOpcode() == Instruction::PtrToInt) |
| 409 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 410 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 411 | CE->getOperand(0)->isNullValue()) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 412 | Type *Ty = |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 413 | cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 414 | if (StructType *STy = dyn_cast<StructType>(Ty)) |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 415 | if (!STy->isPacked() && |
| 416 | CE->getNumOperands() == 3 && |
| 417 | CE->getOperand(1)->isNullValue()) { |
| 418 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) |
| 419 | if (CI->isOne() && |
| 420 | STy->getNumElements() == 2 && |
Duncan Sands | 9dff9be | 2010-02-15 16:12:20 +0000 | [diff] [blame] | 421 | STy->getElementType(0)->isIntegerTy(1)) { |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 422 | AllocTy = STy->getElementType(1); |
| 423 | return true; |
| 424 | } |
| 425 | } |
| 426 | } |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 427 | |
| 428 | return false; |
| 429 | } |
| 430 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 431 | bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 432 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 433 | if (VCE->getOpcode() == Instruction::PtrToInt) |
| 434 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) |
| 435 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 436 | CE->getNumOperands() == 3 && |
| 437 | CE->getOperand(0)->isNullValue() && |
| 438 | CE->getOperand(1)->isNullValue()) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 439 | Type *Ty = |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 440 | cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); |
| 441 | // Ignore vector types here so that ScalarEvolutionExpander doesn't |
| 442 | // emit getelementptrs that index into vectors. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 443 | if (Ty->isStructTy() || Ty->isArrayTy()) { |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 444 | CTy = Ty; |
| 445 | FieldNo = CE->getOperand(2); |
| 446 | return true; |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | return false; |
| 451 | } |
| 452 | |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 453 | //===----------------------------------------------------------------------===// |
| 454 | // SCEV Utilities |
| 455 | //===----------------------------------------------------------------------===// |
| 456 | |
Sanjoy Das | 1707869 | 2016-10-31 03:32:43 +0000 | [diff] [blame] | 457 | /// Compare the two values \p LV and \p RV in terms of their "complexity" where |
| 458 | /// "complexity" is a partial (and somewhat ad-hoc) relation used to order |
| 459 | /// operands in SCEV expressions. \p EqCache is a set of pairs of values that |
| 460 | /// have been previously deemed to be "equally complex" by this routine. It is |
| 461 | /// intended to avoid exponential time complexity in cases like: |
| 462 | /// |
| 463 | /// %a = f(%x, %y) |
| 464 | /// %b = f(%a, %a) |
| 465 | /// %c = f(%b, %b) |
| 466 | /// |
| 467 | /// %d = f(%x, %y) |
| 468 | /// %e = f(%d, %d) |
| 469 | /// %f = f(%e, %e) |
| 470 | /// |
| 471 | /// CompareValueComplexity(%f, %c) |
| 472 | /// |
| 473 | /// Since we do not continue running this routine on expression trees once we |
| 474 | /// have seen unequal values, there is no need to track them in the cache. |
| 475 | static int |
| 476 | CompareValueComplexity(SmallSet<std::pair<Value *, Value *>, 8> &EqCache, |
| 477 | const LoopInfo *const LI, Value *LV, Value *RV, |
| 478 | unsigned DepthLeft = 2) { |
| 479 | if (DepthLeft == 0 || EqCache.count({LV, RV})) |
Sanjoy Das | 507dd40 | 2016-10-18 17:45:16 +0000 | [diff] [blame] | 480 | return 0; |
| 481 | |
Sanjoy Das | 9cd877a | 2016-10-18 17:45:13 +0000 | [diff] [blame] | 482 | // Order pointer values after integer values. This helps SCEVExpander form |
| 483 | // GEPs. |
| 484 | bool LIsPointer = LV->getType()->isPointerTy(), |
| 485 | RIsPointer = RV->getType()->isPointerTy(); |
| 486 | if (LIsPointer != RIsPointer) |
| 487 | return (int)LIsPointer - (int)RIsPointer; |
| 488 | |
| 489 | // Compare getValueID values. |
| 490 | unsigned LID = LV->getValueID(), RID = RV->getValueID(); |
| 491 | if (LID != RID) |
| 492 | return (int)LID - (int)RID; |
| 493 | |
| 494 | // Sort arguments by their position. |
Sanjoy Das | b4830a8 | 2016-10-30 23:52:53 +0000 | [diff] [blame] | 495 | if (const auto *LA = dyn_cast<Argument>(LV)) { |
| 496 | const auto *RA = cast<Argument>(RV); |
Sanjoy Das | 9cd877a | 2016-10-18 17:45:13 +0000 | [diff] [blame] | 497 | unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); |
| 498 | return (int)LArgNo - (int)RArgNo; |
| 499 | } |
| 500 | |
Sanjoy Das | 299e672 | 2016-10-30 23:52:56 +0000 | [diff] [blame] | 501 | if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { |
| 502 | const auto *RGV = cast<GlobalValue>(RV); |
| 503 | |
| 504 | const auto IsGVNameSemantic = [&](const GlobalValue *GV) { |
| 505 | auto LT = GV->getLinkage(); |
| 506 | return !(GlobalValue::isPrivateLinkage(LT) || |
| 507 | GlobalValue::isInternalLinkage(LT)); |
| 508 | }; |
| 509 | |
| 510 | // Use the names to distinguish the two values, but only if the |
| 511 | // names are semantically important. |
| 512 | if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) |
| 513 | return LGV->getName().compare(RGV->getName()); |
| 514 | } |
| 515 | |
Sanjoy Das | 9cd877a | 2016-10-18 17:45:13 +0000 | [diff] [blame] | 516 | // For instructions, compare their loop depth, and their operand count. This |
| 517 | // is pretty loose. |
Sanjoy Das | b4830a8 | 2016-10-30 23:52:53 +0000 | [diff] [blame] | 518 | if (const auto *LInst = dyn_cast<Instruction>(LV)) { |
| 519 | const auto *RInst = cast<Instruction>(RV); |
Sanjoy Das | 9cd877a | 2016-10-18 17:45:13 +0000 | [diff] [blame] | 520 | |
| 521 | // Compare loop depths. |
| 522 | const BasicBlock *LParent = LInst->getParent(), |
| 523 | *RParent = RInst->getParent(); |
| 524 | if (LParent != RParent) { |
| 525 | unsigned LDepth = LI->getLoopDepth(LParent), |
| 526 | RDepth = LI->getLoopDepth(RParent); |
| 527 | if (LDepth != RDepth) |
| 528 | return (int)LDepth - (int)RDepth; |
| 529 | } |
| 530 | |
| 531 | // Compare the number of operands. |
| 532 | unsigned LNumOps = LInst->getNumOperands(), |
| 533 | RNumOps = RInst->getNumOperands(); |
Sanjoy Das | 1707869 | 2016-10-31 03:32:43 +0000 | [diff] [blame] | 534 | if (LNumOps != RNumOps) |
Sanjoy Das | 507dd40 | 2016-10-18 17:45:16 +0000 | [diff] [blame] | 535 | return (int)LNumOps - (int)RNumOps; |
| 536 | |
Sanjoy Das | 1707869 | 2016-10-31 03:32:43 +0000 | [diff] [blame] | 537 | for (unsigned Idx : seq(0u, LNumOps)) { |
| 538 | int Result = |
| 539 | CompareValueComplexity(EqCache, LI, LInst->getOperand(Idx), |
| 540 | RInst->getOperand(Idx), DepthLeft - 1); |
| 541 | if (Result != 0) |
| 542 | return Result; |
| 543 | EqCache.insert({LV, RV}); |
| 544 | } |
Sanjoy Das | 9cd877a | 2016-10-18 17:45:13 +0000 | [diff] [blame] | 545 | } |
| 546 | |
| 547 | return 0; |
| 548 | } |
| 549 | |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 550 | // Return negative, zero, or positive, if LHS is less than, equal to, or greater |
| 551 | // than RHS, respectively. A three-way result allows recursive comparisons to be |
| 552 | // more efficient. |
| 553 | static int CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS, |
| 554 | const SCEV *RHS) { |
| 555 | // Fast-path: SCEVs are uniqued so we can do a quick equality check. |
| 556 | if (LHS == RHS) |
| 557 | return 0; |
Dan Gohman | 9ba542c | 2009-05-07 14:39:04 +0000 | [diff] [blame] | 558 | |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 559 | // Primarily, sort the SCEVs by their getSCEVType(). |
| 560 | unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); |
| 561 | if (LType != RType) |
| 562 | return (int)LType - (int)RType; |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 563 | |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 564 | // Aside from the getSCEVType() ordering, the particular ordering |
| 565 | // isn't very important except that it's beneficial to be consistent, |
| 566 | // so that (a + b) and (b + a) don't end up as different expressions. |
| 567 | switch (static_cast<SCEVTypes>(LType)) { |
| 568 | case scUnknown: { |
| 569 | const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); |
| 570 | const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 571 | |
Sanjoy Das | 1707869 | 2016-10-31 03:32:43 +0000 | [diff] [blame] | 572 | SmallSet<std::pair<Value *, Value *>, 8> EqCache; |
| 573 | return CompareValueComplexity(EqCache, LI, LU->getValue(), RU->getValue()); |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 574 | } |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 575 | |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 576 | case scConstant: { |
| 577 | const SCEVConstant *LC = cast<SCEVConstant>(LHS); |
| 578 | const SCEVConstant *RC = cast<SCEVConstant>(RHS); |
| 579 | |
| 580 | // Compare constant values. |
| 581 | const APInt &LA = LC->getAPInt(); |
| 582 | const APInt &RA = RC->getAPInt(); |
| 583 | unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); |
| 584 | if (LBitWidth != RBitWidth) |
| 585 | return (int)LBitWidth - (int)RBitWidth; |
| 586 | return LA.ult(RA) ? -1 : 1; |
| 587 | } |
| 588 | |
| 589 | case scAddRecExpr: { |
| 590 | const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); |
| 591 | const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); |
| 592 | |
| 593 | // Compare addrec loop depths. |
| 594 | const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); |
| 595 | if (LLoop != RLoop) { |
| 596 | unsigned LDepth = LLoop->getLoopDepth(), RDepth = RLoop->getLoopDepth(); |
| 597 | if (LDepth != RDepth) |
| 598 | return (int)LDepth - (int)RDepth; |
| 599 | } |
| 600 | |
| 601 | // Addrec complexity grows with operand count. |
| 602 | unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); |
| 603 | if (LNumOps != RNumOps) |
| 604 | return (int)LNumOps - (int)RNumOps; |
| 605 | |
| 606 | // Lexicographically compare. |
| 607 | for (unsigned i = 0; i != LNumOps; ++i) { |
| 608 | long X = CompareSCEVComplexity(LI, LA->getOperand(i), RA->getOperand(i)); |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 609 | if (X != 0) |
| 610 | return X; |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 611 | } |
| 612 | |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 613 | return 0; |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 614 | } |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 615 | |
| 616 | case scAddExpr: |
| 617 | case scMulExpr: |
| 618 | case scSMaxExpr: |
| 619 | case scUMaxExpr: { |
| 620 | const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); |
| 621 | const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); |
| 622 | |
| 623 | // Lexicographically compare n-ary expressions. |
| 624 | unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); |
| 625 | if (LNumOps != RNumOps) |
| 626 | return (int)LNumOps - (int)RNumOps; |
| 627 | |
| 628 | for (unsigned i = 0; i != LNumOps; ++i) { |
| 629 | if (i >= RNumOps) |
| 630 | return 1; |
| 631 | long X = CompareSCEVComplexity(LI, LC->getOperand(i), RC->getOperand(i)); |
| 632 | if (X != 0) |
| 633 | return X; |
| 634 | } |
| 635 | return (int)LNumOps - (int)RNumOps; |
| 636 | } |
| 637 | |
| 638 | case scUDivExpr: { |
| 639 | const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); |
| 640 | const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); |
| 641 | |
| 642 | // Lexicographically compare udiv expressions. |
| 643 | long X = CompareSCEVComplexity(LI, LC->getLHS(), RC->getLHS()); |
| 644 | if (X != 0) |
| 645 | return X; |
| 646 | return CompareSCEVComplexity(LI, LC->getRHS(), RC->getRHS()); |
| 647 | } |
| 648 | |
| 649 | case scTruncate: |
| 650 | case scZeroExtend: |
| 651 | case scSignExtend: { |
| 652 | const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); |
| 653 | const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); |
| 654 | |
| 655 | // Compare cast expressions by operand. |
| 656 | return CompareSCEVComplexity(LI, LC->getOperand(), RC->getOperand()); |
| 657 | } |
| 658 | |
| 659 | case scCouldNotCompute: |
| 660 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
| 661 | } |
| 662 | llvm_unreachable("Unknown SCEV kind!"); |
| 663 | } |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 664 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 665 | /// Given a list of SCEV objects, order them by their complexity, and group |
| 666 | /// objects of the same complexity together by value. When this routine is |
| 667 | /// finished, we know that any duplicates in the vector are consecutive and that |
| 668 | /// complexity is monotonically increasing. |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 669 | /// |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 670 | /// 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] | 671 | /// results from this routine. In other words, we don't want the results of |
| 672 | /// this to depend on where the addresses of various SCEV objects happened to |
| 673 | /// land in memory. |
| 674 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 675 | static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, |
Dan Gohman | 9ba542c | 2009-05-07 14:39:04 +0000 | [diff] [blame] | 676 | LoopInfo *LI) { |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 677 | if (Ops.size() < 2) return; // Noop |
| 678 | if (Ops.size() == 2) { |
| 679 | // This is the common case, which also happens to be trivially simple. |
| 680 | // Special case it. |
Dan Gohman | 7712d29 | 2010-08-29 15:07:13 +0000 | [diff] [blame] | 681 | const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 682 | if (CompareSCEVComplexity(LI, RHS, LHS) < 0) |
Dan Gohman | 7712d29 | 2010-08-29 15:07:13 +0000 | [diff] [blame] | 683 | std::swap(LHS, RHS); |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 684 | return; |
| 685 | } |
| 686 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 687 | // Do the rough sort by complexity. |
Sanjoy Das | 237c845 | 2016-09-27 18:01:48 +0000 | [diff] [blame] | 688 | std::stable_sort(Ops.begin(), Ops.end(), |
| 689 | [LI](const SCEV *LHS, const SCEV *RHS) { |
| 690 | return CompareSCEVComplexity(LI, LHS, RHS) < 0; |
| 691 | }); |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 692 | |
| 693 | // Now that we are sorted by complexity, group elements of the same |
| 694 | // complexity. Note that this is, at worst, N^2, but the vector is likely to |
| 695 | // be extremely short in practice. Note that we take this approach because we |
| 696 | // do not want to depend on the addresses of the objects we are grouping. |
| 697 | for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { |
| 698 | const SCEV *S = Ops[i]; |
| 699 | unsigned Complexity = S->getSCEVType(); |
| 700 | |
| 701 | // If there are any objects of the same complexity and same value as this |
| 702 | // one, group them. |
| 703 | for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { |
| 704 | if (Ops[j] == S) { // Found a duplicate. |
| 705 | // Move it to immediately after i'th element. |
| 706 | std::swap(Ops[i+1], Ops[j]); |
| 707 | ++i; // no need to rescan it. |
| 708 | if (i == e-2) return; // Done! |
| 709 | } |
| 710 | } |
| 711 | } |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 712 | } |
| 713 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 714 | // Returns the size of the SCEV S. |
| 715 | static inline int sizeOfSCEV(const SCEV *S) { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 716 | struct FindSCEVSize { |
| 717 | int Size; |
| 718 | FindSCEVSize() : Size(0) {} |
| 719 | |
| 720 | bool follow(const SCEV *S) { |
| 721 | ++Size; |
| 722 | // Keep looking at all operands of S. |
| 723 | return true; |
| 724 | } |
| 725 | bool isDone() const { |
| 726 | return false; |
| 727 | } |
| 728 | }; |
| 729 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 730 | FindSCEVSize F; |
| 731 | SCEVTraversal<FindSCEVSize> ST(F); |
| 732 | ST.visitAll(S); |
| 733 | return F.Size; |
| 734 | } |
| 735 | |
| 736 | namespace { |
| 737 | |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 738 | struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 739 | public: |
| 740 | // Computes the Quotient and Remainder of the division of Numerator by |
| 741 | // Denominator. |
| 742 | static void divide(ScalarEvolution &SE, const SCEV *Numerator, |
| 743 | const SCEV *Denominator, const SCEV **Quotient, |
| 744 | const SCEV **Remainder) { |
| 745 | assert(Numerator && Denominator && "Uninitialized SCEV"); |
| 746 | |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 747 | SCEVDivision D(SE, Numerator, Denominator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 748 | |
| 749 | // Check for the trivial case here to avoid having to check for it in the |
| 750 | // rest of the code. |
| 751 | if (Numerator == Denominator) { |
| 752 | *Quotient = D.One; |
| 753 | *Remainder = D.Zero; |
| 754 | return; |
| 755 | } |
| 756 | |
| 757 | if (Numerator->isZero()) { |
| 758 | *Quotient = D.Zero; |
| 759 | *Remainder = D.Zero; |
| 760 | return; |
| 761 | } |
| 762 | |
Brendon Cahoon | a57cc8b | 2015-04-20 16:03:28 +0000 | [diff] [blame] | 763 | // A simple case when N/1. The quotient is N. |
| 764 | if (Denominator->isOne()) { |
| 765 | *Quotient = Numerator; |
| 766 | *Remainder = D.Zero; |
| 767 | return; |
| 768 | } |
| 769 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 770 | // Split the Denominator when it is a product. |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 771 | if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 772 | const SCEV *Q, *R; |
| 773 | *Quotient = Numerator; |
| 774 | for (const SCEV *Op : T->operands()) { |
| 775 | divide(SE, *Quotient, Op, &Q, &R); |
| 776 | *Quotient = Q; |
| 777 | |
| 778 | // Bail out when the Numerator is not divisible by one of the terms of |
| 779 | // the Denominator. |
| 780 | if (!R->isZero()) { |
| 781 | *Quotient = D.Zero; |
| 782 | *Remainder = Numerator; |
| 783 | return; |
| 784 | } |
| 785 | } |
| 786 | *Remainder = D.Zero; |
| 787 | return; |
| 788 | } |
| 789 | |
| 790 | D.visit(Numerator); |
| 791 | *Quotient = D.Quotient; |
| 792 | *Remainder = D.Remainder; |
| 793 | } |
| 794 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 795 | // Except in the trivial case described above, we do not know how to divide |
| 796 | // Expr by Denominator for the following functions with empty implementation. |
| 797 | void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} |
| 798 | void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} |
| 799 | void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} |
| 800 | void visitUDivExpr(const SCEVUDivExpr *Numerator) {} |
| 801 | void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} |
| 802 | void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} |
| 803 | void visitUnknown(const SCEVUnknown *Numerator) {} |
| 804 | void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} |
| 805 | |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 806 | void visitConstant(const SCEVConstant *Numerator) { |
| 807 | if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 808 | APInt NumeratorVal = Numerator->getAPInt(); |
| 809 | APInt DenominatorVal = D->getAPInt(); |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 810 | uint32_t NumeratorBW = NumeratorVal.getBitWidth(); |
| 811 | uint32_t DenominatorBW = DenominatorVal.getBitWidth(); |
| 812 | |
| 813 | if (NumeratorBW > DenominatorBW) |
| 814 | DenominatorVal = DenominatorVal.sext(NumeratorBW); |
| 815 | else if (NumeratorBW < DenominatorBW) |
| 816 | NumeratorVal = NumeratorVal.sext(DenominatorBW); |
| 817 | |
| 818 | APInt QuotientVal(NumeratorVal.getBitWidth(), 0); |
| 819 | APInt RemainderVal(NumeratorVal.getBitWidth(), 0); |
| 820 | APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); |
| 821 | Quotient = SE.getConstant(QuotientVal); |
| 822 | Remainder = SE.getConstant(RemainderVal); |
| 823 | return; |
| 824 | } |
| 825 | } |
| 826 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 827 | void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { |
| 828 | const SCEV *StartQ, *StartR, *StepQ, *StepR; |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 829 | if (!Numerator->isAffine()) |
| 830 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 831 | divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); |
| 832 | divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); |
Brendon Cahoon | f9751ad | 2015-04-22 15:06:40 +0000 | [diff] [blame] | 833 | // Bail out if the types do not match. |
| 834 | Type *Ty = Denominator->getType(); |
| 835 | if (Ty != StartQ->getType() || Ty != StartR->getType() || |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 836 | Ty != StepQ->getType() || Ty != StepR->getType()) |
| 837 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 838 | Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), |
| 839 | Numerator->getNoWrapFlags()); |
| 840 | Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), |
| 841 | Numerator->getNoWrapFlags()); |
| 842 | } |
| 843 | |
| 844 | void visitAddExpr(const SCEVAddExpr *Numerator) { |
| 845 | SmallVector<const SCEV *, 2> Qs, Rs; |
| 846 | Type *Ty = Denominator->getType(); |
| 847 | |
| 848 | for (const SCEV *Op : Numerator->operands()) { |
| 849 | const SCEV *Q, *R; |
| 850 | divide(SE, Op, Denominator, &Q, &R); |
| 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() || Ty != R->getType()) |
| 854 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 855 | |
| 856 | Qs.push_back(Q); |
| 857 | Rs.push_back(R); |
| 858 | } |
| 859 | |
| 860 | if (Qs.size() == 1) { |
| 861 | Quotient = Qs[0]; |
| 862 | Remainder = Rs[0]; |
| 863 | return; |
| 864 | } |
| 865 | |
| 866 | Quotient = SE.getAddExpr(Qs); |
| 867 | Remainder = SE.getAddExpr(Rs); |
| 868 | } |
| 869 | |
| 870 | void visitMulExpr(const SCEVMulExpr *Numerator) { |
| 871 | SmallVector<const SCEV *, 2> Qs; |
| 872 | Type *Ty = Denominator->getType(); |
| 873 | |
| 874 | bool FoundDenominatorTerm = false; |
| 875 | for (const SCEV *Op : Numerator->operands()) { |
| 876 | // Bail out if types do not match. |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 877 | if (Ty != Op->getType()) |
| 878 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 879 | |
| 880 | if (FoundDenominatorTerm) { |
| 881 | Qs.push_back(Op); |
| 882 | continue; |
| 883 | } |
| 884 | |
| 885 | // Check whether Denominator divides one of the product operands. |
| 886 | const SCEV *Q, *R; |
| 887 | divide(SE, Op, Denominator, &Q, &R); |
| 888 | if (!R->isZero()) { |
| 889 | Qs.push_back(Op); |
| 890 | continue; |
| 891 | } |
| 892 | |
| 893 | // Bail out if types do not match. |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 894 | if (Ty != Q->getType()) |
| 895 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 896 | |
| 897 | FoundDenominatorTerm = true; |
| 898 | Qs.push_back(Q); |
| 899 | } |
| 900 | |
| 901 | if (FoundDenominatorTerm) { |
| 902 | Remainder = Zero; |
| 903 | if (Qs.size() == 1) |
| 904 | Quotient = Qs[0]; |
| 905 | else |
| 906 | Quotient = SE.getMulExpr(Qs); |
| 907 | return; |
| 908 | } |
| 909 | |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 910 | if (!isa<SCEVUnknown>(Denominator)) |
| 911 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 912 | |
| 913 | // The Remainder is obtained by replacing Denominator by 0 in Numerator. |
| 914 | ValueToValueMap RewriteMap; |
| 915 | RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = |
| 916 | cast<SCEVConstant>(Zero)->getValue(); |
| 917 | Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); |
| 918 | |
| 919 | if (Remainder->isZero()) { |
| 920 | // The Quotient is obtained by replacing Denominator by 1 in Numerator. |
| 921 | RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = |
| 922 | cast<SCEVConstant>(One)->getValue(); |
| 923 | Quotient = |
| 924 | SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); |
| 925 | return; |
| 926 | } |
| 927 | |
| 928 | // Quotient is (Numerator - Remainder) divided by Denominator. |
| 929 | const SCEV *Q, *R; |
| 930 | const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 931 | // This SCEV does not seem to simplify: fail the division here. |
| 932 | if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) |
| 933 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 934 | divide(SE, Diff, Denominator, &Q, &R); |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 935 | if (R != Zero) |
| 936 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 937 | Quotient = Q; |
| 938 | } |
| 939 | |
| 940 | private: |
David Majnemer | 5d2670c | 2014-11-17 11:27:45 +0000 | [diff] [blame] | 941 | SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, |
| 942 | const SCEV *Denominator) |
| 943 | : SE(S), Denominator(Denominator) { |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 944 | Zero = SE.getZero(Denominator->getType()); |
| 945 | One = SE.getOne(Denominator->getType()); |
David Majnemer | 5d2670c | 2014-11-17 11:27:45 +0000 | [diff] [blame] | 946 | |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 947 | // We generally do not know how to divide Expr by Denominator. We |
| 948 | // initialize the division to a "cannot divide" state to simplify the rest |
| 949 | // of the code. |
| 950 | cannotDivide(Numerator); |
| 951 | } |
| 952 | |
| 953 | // Convenience function for giving up on the division. We set the quotient to |
| 954 | // be equal to zero and the remainder to be equal to the numerator. |
| 955 | void cannotDivide(const SCEV *Numerator) { |
David Majnemer | 5d2670c | 2014-11-17 11:27:45 +0000 | [diff] [blame] | 956 | Quotient = Zero; |
| 957 | Remainder = Numerator; |
| 958 | } |
| 959 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 960 | ScalarEvolution &SE; |
| 961 | const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; |
David Majnemer | 32b8ccf | 2014-11-16 20:35:19 +0000 | [diff] [blame] | 962 | }; |
| 963 | |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 964 | } |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 965 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 966 | //===----------------------------------------------------------------------===// |
| 967 | // Simple SCEV method implementations |
| 968 | //===----------------------------------------------------------------------===// |
| 969 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 970 | /// Compute BC(It, K). The result has width W. Assume, K > 0. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 971 | static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, |
Dan Gohman | 32291b1 | 2009-07-21 00:38:55 +0000 | [diff] [blame] | 972 | ScalarEvolution &SE, |
Nick Lewycky | 702cf1e | 2011-09-06 06:39:54 +0000 | [diff] [blame] | 973 | Type *ResultTy) { |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 974 | // Handle the simplest case efficiently. |
| 975 | if (K == 1) |
| 976 | return SE.getTruncateOrZeroExtend(It, ResultTy); |
| 977 | |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 978 | // We are using the following formula for BC(It, K): |
| 979 | // |
| 980 | // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! |
| 981 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 982 | // Suppose, W is the bitwidth of the return value. We must be prepared for |
| 983 | // overflow. Hence, we must assure that the result of our computation is |
| 984 | // equal to the accurate one modulo 2^W. Unfortunately, division isn't |
| 985 | // safe in modular arithmetic. |
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 | // 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] | 988 | // 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] | 989 | // K! (i.e. trailing zeros in the binary representation of K!), and ^ is |
| 990 | // exponentiation: |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 991 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 992 | // 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] | 993 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 994 | // This formula is trivially equivalent to the previous formula. However, |
| 995 | // this formula can be implemented much more efficiently. The trick is that |
| 996 | // K! / 2^T is odd, and exact division by an odd number *is* safe in modular |
| 997 | // arithmetic. To do exact division in modular arithmetic, all we have |
| 998 | // to do is multiply by the inverse. Therefore, this step can be done at |
| 999 | // width W. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 1000 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1001 | // The next issue is how to safely do the division by 2^T. The way this |
| 1002 | // is done is by doing the multiplication step at a width of at least W + T |
| 1003 | // bits. This way, the bottom W+T bits of the product are accurate. Then, |
| 1004 | // when we perform the division by 2^T (which is equivalent to a right shift |
| 1005 | // by T), the bottom W bits are accurate. Extra bits are okay; they'll get |
| 1006 | // truncated out after the division by 2^T. |
| 1007 | // |
| 1008 | // In comparison to just directly using the first formula, this technique |
| 1009 | // is much more efficient; using the first formula requires W * K bits, |
| 1010 | // but this formula less than W + K bits. Also, the first formula requires |
| 1011 | // a division step, whereas this formula only requires multiplies and shifts. |
| 1012 | // |
| 1013 | // It doesn't matter whether the subtraction step is done in the calculation |
| 1014 | // width or the input iteration count's width; if the subtraction overflows, |
| 1015 | // the result must be zero anyway. We prefer here to do it in the width of |
| 1016 | // the induction variable because it helps a lot for certain cases; CodeGen |
| 1017 | // isn't smart enough to ignore the overflow, which leads to much less |
| 1018 | // efficient code if the width of the subtraction is wider than the native |
| 1019 | // register width. |
| 1020 | // |
| 1021 | // (It's possible to not widen at all by pulling out factors of 2 before |
| 1022 | // the multiplication; for example, K=2 can be calculated as |
| 1023 | // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires |
| 1024 | // extra arithmetic, so it's not an obvious win, and it gets |
| 1025 | // much more complicated for K > 3.) |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1026 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1027 | // Protection from insane SCEVs; this bound is conservative, |
| 1028 | // but it probably doesn't matter. |
| 1029 | if (K > 1000) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 1030 | return SE.getCouldNotCompute(); |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1031 | |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1032 | unsigned W = SE.getTypeSizeInBits(ResultTy); |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1033 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1034 | // Calculate K! / 2^T and T; we divide out the factors of two before |
| 1035 | // multiplying for calculating K! / 2^T to avoid overflow. |
| 1036 | // Other overflow doesn't matter because we only care about the bottom |
| 1037 | // W bits of the result. |
| 1038 | APInt OddFactorial(W, 1); |
| 1039 | unsigned T = 1; |
| 1040 | for (unsigned i = 3; i <= K; ++i) { |
| 1041 | APInt Mult(W, i); |
| 1042 | unsigned TwoFactors = Mult.countTrailingZeros(); |
| 1043 | T += TwoFactors; |
| 1044 | Mult = Mult.lshr(TwoFactors); |
| 1045 | OddFactorial *= Mult; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1046 | } |
Nick Lewycky | ed169d5 | 2008-06-13 04:38:55 +0000 | [diff] [blame] | 1047 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1048 | // We need at least W + T bits for the multiplication step |
Nick Lewycky | 21add8f | 2009-01-25 08:16:27 +0000 | [diff] [blame] | 1049 | unsigned CalculationBits = W + T; |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1050 | |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 1051 | // Calculate 2^T, at width T+W. |
Benjamin Kramer | fc3ea6f | 2013-07-11 16:05:50 +0000 | [diff] [blame] | 1052 | APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1053 | |
| 1054 | // Calculate the multiplicative inverse of K! / 2^T; |
| 1055 | // this multiplication factor will perform the exact division by |
| 1056 | // K! / 2^T. |
| 1057 | APInt Mod = APInt::getSignedMinValue(W+1); |
| 1058 | APInt MultiplyFactor = OddFactorial.zext(W+1); |
| 1059 | MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); |
| 1060 | MultiplyFactor = MultiplyFactor.trunc(W); |
| 1061 | |
| 1062 | // Calculate the product, at width T+W |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1063 | IntegerType *CalculationTy = IntegerType::get(SE.getContext(), |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1064 | CalculationBits); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1065 | const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1066 | for (unsigned i = 1; i != K; ++i) { |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 1067 | const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1068 | Dividend = SE.getMulExpr(Dividend, |
| 1069 | SE.getTruncateOrZeroExtend(S, CalculationTy)); |
| 1070 | } |
| 1071 | |
| 1072 | // Divide by 2^T |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1073 | const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1074 | |
| 1075 | // Truncate the result, and divide by K! / 2^T. |
| 1076 | |
| 1077 | return SE.getMulExpr(SE.getConstant(MultiplyFactor), |
| 1078 | SE.getTruncateOrZeroExtend(DivResult, ResultTy)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1079 | } |
| 1080 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 1081 | /// Return the value of this chain of recurrences at the specified iteration |
| 1082 | /// number. We can evaluate this recurrence by multiplying each element in the |
| 1083 | /// chain by the binomial coefficient corresponding to it. In other words, we |
| 1084 | /// can evaluate {A,+,B,+,C,+,D} as: |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1085 | /// |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1086 | /// 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] | 1087 | /// |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1088 | /// where BC(It, k) stands for binomial coefficient. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1089 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1090 | const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, |
Dan Gohman | 32291b1 | 2009-07-21 00:38:55 +0000 | [diff] [blame] | 1091 | ScalarEvolution &SE) const { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1092 | const SCEV *Result = getStart(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1093 | for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1094 | // The computation is correct in the face of overflow provided that the |
| 1095 | // multiplication is performed _after_ the evaluation of the binomial |
| 1096 | // coefficient. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1097 | const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); |
Nick Lewycky | 707663e | 2008-10-13 03:58:02 +0000 | [diff] [blame] | 1098 | if (isa<SCEVCouldNotCompute>(Coeff)) |
| 1099 | return Coeff; |
| 1100 | |
| 1101 | Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1102 | } |
| 1103 | return Result; |
| 1104 | } |
| 1105 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1106 | //===----------------------------------------------------------------------===// |
| 1107 | // SCEV Expression folder implementations |
| 1108 | //===----------------------------------------------------------------------===// |
| 1109 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1110 | const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1111 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1112 | assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1113 | "This is not a truncating conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1114 | assert(isSCEVable(Ty) && |
| 1115 | "This is not a conversion to a SCEVable type!"); |
| 1116 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1117 | |
Dan Gohman | 3a302cb | 2009-07-13 20:50:19 +0000 | [diff] [blame] | 1118 | FoldingSetNodeID ID; |
| 1119 | ID.AddInteger(scTruncate); |
| 1120 | ID.AddPointer(Op); |
| 1121 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1122 | void *IP = nullptr; |
Dan Gohman | 3a302cb | 2009-07-13 20:50:19 +0000 | [diff] [blame] | 1123 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1124 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1125 | // Fold if the operand is constant. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1126 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
Dan Gohman | 8d7576e | 2009-06-24 00:38:39 +0000 | [diff] [blame] | 1127 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1128 | cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1129 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1130 | // trunc(trunc(x)) --> trunc(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1131 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1132 | return getTruncateExpr(ST->getOperand(), Ty); |
| 1133 | |
Nick Lewycky | b4d9f7a | 2009-04-23 05:15:08 +0000 | [diff] [blame] | 1134 | // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1135 | if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) |
Nick Lewycky | b4d9f7a | 2009-04-23 05:15:08 +0000 | [diff] [blame] | 1136 | return getTruncateOrSignExtend(SS->getOperand(), Ty); |
| 1137 | |
| 1138 | // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1139 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
Nick Lewycky | b4d9f7a | 2009-04-23 05:15:08 +0000 | [diff] [blame] | 1140 | return getTruncateOrZeroExtend(SZ->getOperand(), Ty); |
| 1141 | |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1142 | // 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] | 1143 | // eliminate all the truncates, or we replace other casts with truncates. |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1144 | if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { |
| 1145 | SmallVector<const SCEV *, 4> Operands; |
| 1146 | bool hasTrunc = false; |
| 1147 | for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { |
| 1148 | const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); |
Nick Lewycky | be8af48 | 2015-03-20 02:25:00 +0000 | [diff] [blame] | 1149 | if (!isa<SCEVCastExpr>(SA->getOperand(i))) |
| 1150 | hasTrunc = isa<SCEVTruncateExpr>(S); |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1151 | Operands.push_back(S); |
| 1152 | } |
| 1153 | if (!hasTrunc) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1154 | return getAddExpr(Operands); |
Nick Lewycky | d9e6b4a | 2011-01-26 08:40:22 +0000 | [diff] [blame] | 1155 | UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1156 | } |
| 1157 | |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1158 | // 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] | 1159 | // eliminate all the truncates, or we replace other casts with truncates. |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1160 | if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { |
| 1161 | SmallVector<const SCEV *, 4> Operands; |
| 1162 | bool hasTrunc = false; |
| 1163 | for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { |
| 1164 | const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); |
Nick Lewycky | be8af48 | 2015-03-20 02:25:00 +0000 | [diff] [blame] | 1165 | if (!isa<SCEVCastExpr>(SM->getOperand(i))) |
| 1166 | hasTrunc = isa<SCEVTruncateExpr>(S); |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1167 | Operands.push_back(S); |
| 1168 | } |
| 1169 | if (!hasTrunc) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1170 | return getMulExpr(Operands); |
Nick Lewycky | d9e6b4a | 2011-01-26 08:40:22 +0000 | [diff] [blame] | 1171 | UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1172 | } |
| 1173 | |
Dan Gohman | 5a728c9 | 2009-06-18 16:24:47 +0000 | [diff] [blame] | 1174 | // 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] | 1175 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1176 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 1177 | for (const SCEV *Op : AddRec->operands()) |
| 1178 | Operands.push_back(getTruncateExpr(Op, Ty)); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1179 | return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1180 | } |
| 1181 | |
Dan Gohman | 89dd42a | 2010-06-25 18:47:08 +0000 | [diff] [blame] | 1182 | // The cast wasn't folded; create an explicit cast node. We can reuse |
| 1183 | // the existing insert position since if we get here, we won't have |
| 1184 | // made any changes which would invalidate it. |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1185 | SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), |
| 1186 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1187 | UniqueSCEVs.InsertNode(S, IP); |
| 1188 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1189 | } |
| 1190 | |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1191 | // Get the limit of a recurrence such that incrementing by Step cannot cause |
| 1192 | // signed overflow as long as the value of the recurrence within the |
| 1193 | // loop does not exceed this limit before incrementing. |
| 1194 | static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, |
| 1195 | ICmpInst::Predicate *Pred, |
| 1196 | ScalarEvolution *SE) { |
| 1197 | unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); |
| 1198 | if (SE->isKnownPositive(Step)) { |
| 1199 | *Pred = ICmpInst::ICMP_SLT; |
| 1200 | return SE->getConstant(APInt::getSignedMinValue(BitWidth) - |
| 1201 | SE->getSignedRange(Step).getSignedMax()); |
| 1202 | } |
| 1203 | if (SE->isKnownNegative(Step)) { |
| 1204 | *Pred = ICmpInst::ICMP_SGT; |
| 1205 | return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - |
| 1206 | SE->getSignedRange(Step).getSignedMin()); |
| 1207 | } |
| 1208 | return nullptr; |
| 1209 | } |
| 1210 | |
| 1211 | // Get the limit of a recurrence such that incrementing by Step cannot cause |
| 1212 | // unsigned overflow as long as the value of the recurrence within the loop does |
| 1213 | // not exceed this limit before incrementing. |
| 1214 | static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, |
| 1215 | ICmpInst::Predicate *Pred, |
| 1216 | ScalarEvolution *SE) { |
| 1217 | unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); |
| 1218 | *Pred = ICmpInst::ICMP_ULT; |
| 1219 | |
| 1220 | return SE->getConstant(APInt::getMinValue(BitWidth) - |
| 1221 | SE->getUnsignedRange(Step).getUnsignedMax()); |
| 1222 | } |
| 1223 | |
| 1224 | namespace { |
| 1225 | |
| 1226 | struct ExtendOpTraitsBase { |
| 1227 | typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *); |
| 1228 | }; |
| 1229 | |
| 1230 | // Used to make code generic over signed and unsigned overflow. |
| 1231 | template <typename ExtendOp> struct ExtendOpTraits { |
| 1232 | // Members present: |
| 1233 | // |
| 1234 | // static const SCEV::NoWrapFlags WrapType; |
| 1235 | // |
| 1236 | // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; |
| 1237 | // |
| 1238 | // static const SCEV *getOverflowLimitForStep(const SCEV *Step, |
| 1239 | // ICmpInst::Predicate *Pred, |
| 1240 | // ScalarEvolution *SE); |
| 1241 | }; |
| 1242 | |
| 1243 | template <> |
| 1244 | struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { |
| 1245 | static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; |
| 1246 | |
| 1247 | static const GetExtendExprTy GetExtendExpr; |
| 1248 | |
| 1249 | static const SCEV *getOverflowLimitForStep(const SCEV *Step, |
| 1250 | ICmpInst::Predicate *Pred, |
| 1251 | ScalarEvolution *SE) { |
| 1252 | return getSignedOverflowLimitForStep(Step, Pred, SE); |
| 1253 | } |
| 1254 | }; |
| 1255 | |
Sanjoy Das | c1065b9 | 2015-02-18 08:03:22 +0000 | [diff] [blame] | 1256 | const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1257 | SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; |
| 1258 | |
| 1259 | template <> |
| 1260 | struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { |
| 1261 | static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; |
| 1262 | |
| 1263 | static const GetExtendExprTy GetExtendExpr; |
| 1264 | |
| 1265 | static const SCEV *getOverflowLimitForStep(const SCEV *Step, |
| 1266 | ICmpInst::Predicate *Pred, |
| 1267 | ScalarEvolution *SE) { |
| 1268 | return getUnsignedOverflowLimitForStep(Step, Pred, SE); |
| 1269 | } |
| 1270 | }; |
| 1271 | |
Sanjoy Das | c1065b9 | 2015-02-18 08:03:22 +0000 | [diff] [blame] | 1272 | const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1273 | SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 1274 | } |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1275 | |
| 1276 | // The recurrence AR has been shown to have no signed/unsigned wrap or something |
| 1277 | // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as |
| 1278 | // easily prove NSW/NUW for its preincrement or postincrement sibling. This |
| 1279 | // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + |
| 1280 | // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the |
| 1281 | // expression "Step + sext/zext(PreIncAR)" is congruent with |
| 1282 | // "sext/zext(PostIncAR)" |
| 1283 | template <typename ExtendOpTy> |
| 1284 | static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, |
| 1285 | ScalarEvolution *SE) { |
| 1286 | auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; |
| 1287 | auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; |
| 1288 | |
| 1289 | const Loop *L = AR->getLoop(); |
| 1290 | const SCEV *Start = AR->getStart(); |
| 1291 | const SCEV *Step = AR->getStepRecurrence(*SE); |
| 1292 | |
| 1293 | // Check for a simple looking step prior to loop entry. |
| 1294 | const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); |
| 1295 | if (!SA) |
| 1296 | return nullptr; |
| 1297 | |
| 1298 | // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV |
| 1299 | // subtraction is expensive. For this purpose, perform a quick and dirty |
| 1300 | // difference, by checking for Step in the operand list. |
| 1301 | SmallVector<const SCEV *, 4> DiffOps; |
| 1302 | for (const SCEV *Op : SA->operands()) |
| 1303 | if (Op != Step) |
| 1304 | DiffOps.push_back(Op); |
| 1305 | |
| 1306 | if (DiffOps.size() == SA->getNumOperands()) |
| 1307 | return nullptr; |
| 1308 | |
| 1309 | // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + |
| 1310 | // `Step`: |
| 1311 | |
| 1312 | // 1. NSW/NUW flags on the step increment. |
Sanjoy Das | 0714e3e | 2015-10-23 06:33:47 +0000 | [diff] [blame] | 1313 | auto PreStartFlags = |
| 1314 | ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); |
| 1315 | const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1316 | const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( |
| 1317 | SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); |
| 1318 | |
Sanjoy Das | b14010d | 2015-02-24 01:02:42 +0000 | [diff] [blame] | 1319 | // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies |
| 1320 | // "S+X does not sign/unsign-overflow". |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1321 | // |
| 1322 | |
Sanjoy Das | b14010d | 2015-02-24 01:02:42 +0000 | [diff] [blame] | 1323 | const SCEV *BECount = SE->getBackedgeTakenCount(L); |
| 1324 | if (PreAR && PreAR->getNoWrapFlags(WrapType) && |
| 1325 | !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1326 | return PreStart; |
| 1327 | |
| 1328 | // 2. Direct overflow check on the step operation's expression. |
| 1329 | unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); |
| 1330 | Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); |
| 1331 | const SCEV *OperandExtendedStart = |
| 1332 | SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy), |
| 1333 | (SE->*GetExtendExpr)(Step, WideTy)); |
| 1334 | if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) { |
| 1335 | if (PreAR && AR->getNoWrapFlags(WrapType)) { |
| 1336 | // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW |
| 1337 | // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then |
| 1338 | // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. |
| 1339 | const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); |
| 1340 | } |
| 1341 | return PreStart; |
| 1342 | } |
| 1343 | |
| 1344 | // 3. Loop precondition. |
| 1345 | ICmpInst::Predicate Pred; |
| 1346 | const SCEV *OverflowLimit = |
| 1347 | ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); |
| 1348 | |
| 1349 | if (OverflowLimit && |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 1350 | SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1351 | return PreStart; |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 1352 | |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1353 | return nullptr; |
| 1354 | } |
| 1355 | |
| 1356 | // Get the normalized zero or sign extended expression for this AddRec's Start. |
| 1357 | template <typename ExtendOpTy> |
| 1358 | static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, |
| 1359 | ScalarEvolution *SE) { |
| 1360 | auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; |
| 1361 | |
| 1362 | const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE); |
| 1363 | if (!PreStart) |
| 1364 | return (SE->*GetExtendExpr)(AR->getStart(), Ty); |
| 1365 | |
| 1366 | return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty), |
| 1367 | (SE->*GetExtendExpr)(PreStart, Ty)); |
| 1368 | } |
| 1369 | |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1370 | // Try to prove away overflow by looking at "nearby" add recurrences. A |
| 1371 | // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it |
| 1372 | // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. |
| 1373 | // |
| 1374 | // Formally: |
| 1375 | // |
| 1376 | // {S,+,X} == {S-T,+,X} + T |
| 1377 | // => Ext({S,+,X}) == Ext({S-T,+,X} + T) |
| 1378 | // |
| 1379 | // If ({S-T,+,X} + T) does not overflow ... (1) |
| 1380 | // |
| 1381 | // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) |
| 1382 | // |
| 1383 | // If {S-T,+,X} does not overflow ... (2) |
| 1384 | // |
| 1385 | // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) |
| 1386 | // == {Ext(S-T)+Ext(T),+,Ext(X)} |
| 1387 | // |
| 1388 | // If (S-T)+T does not overflow ... (3) |
| 1389 | // |
| 1390 | // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} |
| 1391 | // == {Ext(S),+,Ext(X)} == LHS |
| 1392 | // |
| 1393 | // Thus, if (1), (2) and (3) are true for some T, then |
| 1394 | // Ext({S,+,X}) == {Ext(S),+,Ext(X)} |
| 1395 | // |
| 1396 | // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) |
| 1397 | // does not overflow" restricted to the 0th iteration. Therefore we only need |
| 1398 | // to check for (1) and (2). |
| 1399 | // |
| 1400 | // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T |
| 1401 | // is `Delta` (defined below). |
| 1402 | // |
| 1403 | template <typename ExtendOpTy> |
| 1404 | bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, |
| 1405 | const SCEV *Step, |
| 1406 | const Loop *L) { |
| 1407 | auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; |
| 1408 | |
| 1409 | // We restrict `Start` to a constant to prevent SCEV from spending too much |
| 1410 | // time here. It is correct (but more expensive) to continue with a |
| 1411 | // non-constant `Start` and do a general SCEV subtraction to compute |
| 1412 | // `PreStart` below. |
| 1413 | // |
| 1414 | const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); |
| 1415 | if (!StartC) |
| 1416 | return false; |
| 1417 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1418 | APInt StartAI = StartC->getAPInt(); |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1419 | |
| 1420 | for (unsigned Delta : {-2, -1, 1, 2}) { |
| 1421 | const SCEV *PreStart = getConstant(StartAI - Delta); |
| 1422 | |
Sanjoy Das | 4280110 | 2015-10-23 06:57:21 +0000 | [diff] [blame] | 1423 | FoldingSetNodeID ID; |
| 1424 | ID.AddInteger(scAddRecExpr); |
| 1425 | ID.AddPointer(PreStart); |
| 1426 | ID.AddPointer(Step); |
| 1427 | ID.AddPointer(L); |
| 1428 | void *IP = nullptr; |
| 1429 | const auto *PreAR = |
| 1430 | static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 1431 | |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1432 | // Give up if we don't already have the add recurrence we need because |
| 1433 | // actually constructing an add recurrence is relatively expensive. |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1434 | if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) |
| 1435 | const SCEV *DeltaS = getConstant(StartC->getType(), Delta); |
| 1436 | ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; |
| 1437 | const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( |
| 1438 | DeltaS, &Pred, this); |
| 1439 | if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) |
| 1440 | return true; |
| 1441 | } |
| 1442 | } |
| 1443 | |
| 1444 | return false; |
| 1445 | } |
| 1446 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1447 | const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1448 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1449 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
Dan Gohman | c1c2ba7 | 2009-04-16 19:25:55 +0000 | [diff] [blame] | 1450 | "This is not an extending conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1451 | assert(isSCEVable(Ty) && |
| 1452 | "This is not a conversion to a SCEVable type!"); |
| 1453 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | c1c2ba7 | 2009-04-16 19:25:55 +0000 | [diff] [blame] | 1454 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1455 | // Fold if the operand is constant. |
Dan Gohman | 5235cc2 | 2010-06-24 16:47:03 +0000 | [diff] [blame] | 1456 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
| 1457 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1458 | cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1459 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1460 | // zext(zext(x)) --> zext(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1461 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1462 | return getZeroExtendExpr(SZ->getOperand(), Ty); |
| 1463 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1464 | // Before doing any expensive analysis, check to see if we've already |
| 1465 | // computed a SCEV for this Op and Ty. |
| 1466 | FoldingSetNodeID ID; |
| 1467 | ID.AddInteger(scZeroExtend); |
| 1468 | ID.AddPointer(Op); |
| 1469 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1470 | void *IP = nullptr; |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1471 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1472 | |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1473 | // zext(trunc(x)) --> zext(x) or x or trunc(x) |
| 1474 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { |
| 1475 | // It's possible the bits taken off by the truncate were all zero bits. If |
| 1476 | // so, we should be able to simplify this further. |
| 1477 | const SCEV *X = ST->getOperand(); |
| 1478 | ConstantRange CR = getUnsignedRange(X); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1479 | unsigned TruncBits = getTypeSizeInBits(ST->getType()); |
| 1480 | unsigned NewBits = getTypeSizeInBits(Ty); |
| 1481 | if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( |
Nick Lewycky | d4192f7 | 2011-01-23 20:06:05 +0000 | [diff] [blame] | 1482 | CR.zextOrTrunc(NewBits))) |
| 1483 | return getTruncateOrZeroExtend(X, Ty); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1484 | } |
| 1485 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1486 | // 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] | 1487 | // 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] | 1488 | // operands (often constants). This allows analysis of something like |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1489 | // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1490 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1491 | if (AR->isAffine()) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1492 | const SCEV *Start = AR->getStart(); |
| 1493 | const SCEV *Step = AR->getStepRecurrence(*this); |
| 1494 | unsigned BitWidth = getTypeSizeInBits(AR->getType()); |
| 1495 | const Loop *L = AR->getLoop(); |
| 1496 | |
Sanjoy Das | 724f5cf | 2016-03-03 18:31:29 +0000 | [diff] [blame] | 1497 | if (!AR->hasNoUnsignedWrap()) { |
| 1498 | auto NewFlags = proveNoWrapViaConstantRanges(AR); |
| 1499 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); |
| 1500 | } |
| 1501 | |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1502 | // If we have special knowledge that this addrec won't overflow, |
| 1503 | // we don't need to do any further analysis. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1504 | if (AR->hasNoUnsignedWrap()) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1505 | return getAddRecExpr( |
| 1506 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1507 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1508 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1509 | // Check whether the backedge-taken count is SCEVCouldNotCompute. |
| 1510 | // Note that this serves two purposes: It filters out loops that are |
| 1511 | // simply not analyzable, and it covers the case where this code is |
| 1512 | // being called from within backedge-taken count analysis, such that |
| 1513 | // attempting to ask for the backedge-taken count would likely result |
| 1514 | // in infinite recursion. In the later case, the analysis code will |
| 1515 | // cope with a conservative value, and it will take care to purge |
| 1516 | // that value once it has finished. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1517 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1518 | if (!isa<SCEVCouldNotCompute>(MaxBECount)) { |
Dan Gohman | 95c5b0e | 2009-04-29 01:54:20 +0000 | [diff] [blame] | 1519 | // Manually compute the final value for AR, checking for |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1520 | // overflow. |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1521 | |
| 1522 | // Check whether the backedge-taken count can be losslessly casted to |
| 1523 | // the addrec's type. The count is always unsigned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1524 | const SCEV *CastedMaxBECount = |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1525 | getTruncateOrZeroExtend(MaxBECount, Start->getType()); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1526 | const SCEV *RecastedMaxBECount = |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1527 | getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); |
| 1528 | if (MaxBECount == RecastedMaxBECount) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1529 | Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1530 | // Check whether Start+Step*MaxBECount has no unsigned overflow. |
Dan Gohman | 007f504 | 2010-02-24 19:31:06 +0000 | [diff] [blame] | 1531 | const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1532 | const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy); |
| 1533 | const SCEV *WideStart = getZeroExtendExpr(Start, WideTy); |
| 1534 | const SCEV *WideMaxBECount = |
| 1535 | getZeroExtendExpr(CastedMaxBECount, WideTy); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1536 | const SCEV *OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1537 | getAddExpr(WideStart, |
| 1538 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1539 | getZeroExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1540 | if (ZAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1541 | // Cache knowledge of AR NUW, which is propagated to this AddRec. |
| 1542 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1543 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1544 | return getAddRecExpr( |
| 1545 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1546 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1547 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1548 | // Similar to above, only this time treat the step value as signed. |
| 1549 | // This covers loops that count down. |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1550 | OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1551 | getAddExpr(WideStart, |
| 1552 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1553 | getSignExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1554 | if (ZAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1555 | // Cache knowledge of AR NW, which is propagated to this AddRec. |
| 1556 | // Negative step causes unsigned wrap, but it still can't self-wrap. |
| 1557 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1558 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1559 | return getAddRecExpr( |
| 1560 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1561 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1562 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1563 | } |
Sanjoy Das | f5d40d5 | 2016-05-17 17:51:14 +0000 | [diff] [blame] | 1564 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1565 | |
Sanjoy Das | f5d40d5 | 2016-05-17 17:51:14 +0000 | [diff] [blame] | 1566 | // Normally, in the cases we can prove no-overflow via a |
| 1567 | // backedge guarding condition, we can also compute a backedge |
| 1568 | // taken count for the loop. The exceptions are assumptions and |
| 1569 | // guards present in the loop -- SCEV is not great at exploiting |
| 1570 | // these to compute max backedge taken counts, but can still use |
| 1571 | // these to prove lack of overflow. Use this fact to avoid |
| 1572 | // doing extra work that may not pay off. |
| 1573 | if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || |
| 1574 | !AC.assumptions().empty()) { |
| 1575 | // If the backedge is guarded by a comparison with the pre-inc |
| 1576 | // value the addrec is safe. Also, if the entry is guarded by |
| 1577 | // a comparison with the start value and the backedge is |
| 1578 | // guarded by a comparison with the post-inc value, the addrec |
| 1579 | // is safe. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1580 | if (isKnownPositive(Step)) { |
| 1581 | const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - |
| 1582 | getUnsignedRange(Step).getUnsignedMax()); |
| 1583 | if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || |
Dan Gohman | b50349a | 2010-04-11 19:27:13 +0000 | [diff] [blame] | 1584 | (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1585 | isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1586 | AR->getPostIncExpr(*this), N))) { |
Sanjoy Das | f5d40d5 | 2016-05-17 17:51:14 +0000 | [diff] [blame] | 1587 | // Cache knowledge of AR NUW, which is propagated to this |
| 1588 | // AddRec. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1589 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1590 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1591 | return getAddRecExpr( |
| 1592 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1593 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1594 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1595 | } else if (isKnownNegative(Step)) { |
| 1596 | const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - |
| 1597 | getSignedRange(Step).getSignedMin()); |
Dan Gohman | 5f18c54 | 2010-05-04 01:11:15 +0000 | [diff] [blame] | 1598 | if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || |
| 1599 | (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1600 | isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1601 | AR->getPostIncExpr(*this), N))) { |
Sanjoy Das | f5d40d5 | 2016-05-17 17:51:14 +0000 | [diff] [blame] | 1602 | // Cache knowledge of AR NW, which is propagated to this |
| 1603 | // AddRec. Negative step causes unsigned wrap, but it |
| 1604 | // still can't self-wrap. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1605 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
| 1606 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1607 | return getAddRecExpr( |
| 1608 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1609 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1610 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1611 | } |
| 1612 | } |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1613 | |
| 1614 | if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { |
| 1615 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
| 1616 | return getAddRecExpr( |
| 1617 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1618 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
| 1619 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1620 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1621 | |
Sanjoy Das | eeca9f6 | 2015-10-22 19:57:38 +0000 | [diff] [blame] | 1622 | if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { |
| 1623 | // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1624 | if (SA->hasNoUnsignedWrap()) { |
Sanjoy Das | eeca9f6 | 2015-10-22 19:57:38 +0000 | [diff] [blame] | 1625 | // If the addition does not unsign overflow then we can, by definition, |
| 1626 | // commute the zero extension with the addition operation. |
| 1627 | SmallVector<const SCEV *, 4> Ops; |
| 1628 | for (const auto *Op : SA->operands()) |
| 1629 | Ops.push_back(getZeroExtendExpr(Op, Ty)); |
| 1630 | return getAddExpr(Ops, SCEV::FlagNUW); |
| 1631 | } |
| 1632 | } |
| 1633 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1634 | // The cast wasn't folded; create an explicit cast node. |
| 1635 | // Recompute the insert position, as it may have been invalidated. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1636 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1637 | SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), |
| 1638 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1639 | UniqueSCEVs.InsertNode(S, IP); |
| 1640 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1641 | } |
| 1642 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1643 | const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1644 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1645 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1646 | "This is not an extending conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1647 | assert(isSCEVable(Ty) && |
| 1648 | "This is not a conversion to a SCEVable type!"); |
| 1649 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1650 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1651 | // Fold if the operand is constant. |
Dan Gohman | 5235cc2 | 2010-06-24 16:47:03 +0000 | [diff] [blame] | 1652 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
| 1653 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1654 | cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1655 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1656 | // sext(sext(x)) --> sext(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1657 | if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1658 | return getSignExtendExpr(SS->getOperand(), Ty); |
| 1659 | |
Nick Lewycky | e9ea75e | 2011-01-19 15:56:12 +0000 | [diff] [blame] | 1660 | // sext(zext(x)) --> zext(x) |
| 1661 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
| 1662 | return getZeroExtendExpr(SZ->getOperand(), Ty); |
| 1663 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1664 | // Before doing any expensive analysis, check to see if we've already |
| 1665 | // computed a SCEV for this Op and Ty. |
| 1666 | FoldingSetNodeID ID; |
| 1667 | ID.AddInteger(scSignExtend); |
| 1668 | ID.AddPointer(Op); |
| 1669 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1670 | void *IP = nullptr; |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1671 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1672 | |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1673 | // sext(trunc(x)) --> sext(x) or x or trunc(x) |
| 1674 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { |
| 1675 | // It's possible the bits taken off by the truncate were all sign bits. If |
| 1676 | // so, we should be able to simplify this further. |
| 1677 | const SCEV *X = ST->getOperand(); |
| 1678 | ConstantRange CR = getSignedRange(X); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1679 | unsigned TruncBits = getTypeSizeInBits(ST->getType()); |
| 1680 | unsigned NewBits = getTypeSizeInBits(Ty); |
| 1681 | if (CR.truncate(TruncBits).signExtend(NewBits).contains( |
Nick Lewycky | d4192f7 | 2011-01-23 20:06:05 +0000 | [diff] [blame] | 1682 | CR.sextOrTrunc(NewBits))) |
| 1683 | return getTruncateOrSignExtend(X, Ty); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1684 | } |
| 1685 | |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1686 | // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1687 | if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1688 | if (SA->getNumOperands() == 2) { |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1689 | auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); |
| 1690 | auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1691 | if (SMul && SC1) { |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1692 | if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1693 | const APInt &C1 = SC1->getAPInt(); |
| 1694 | const APInt &C2 = SC2->getAPInt(); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1695 | if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && |
Michael Zolotukhin | 265dfa4 | 2014-05-26 14:49:46 +0000 | [diff] [blame] | 1696 | C2.ugt(C1) && C2.isPowerOf2()) |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1697 | return getAddExpr(getSignExtendExpr(SC1, Ty), |
| 1698 | getSignExtendExpr(SMul, Ty)); |
| 1699 | } |
| 1700 | } |
| 1701 | } |
Sanjoy Das | a060e60 | 2015-10-22 19:57:25 +0000 | [diff] [blame] | 1702 | |
| 1703 | // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1704 | if (SA->hasNoSignedWrap()) { |
Sanjoy Das | a060e60 | 2015-10-22 19:57:25 +0000 | [diff] [blame] | 1705 | // If the addition does not sign overflow then we can, by definition, |
| 1706 | // commute the sign extension with the addition operation. |
| 1707 | SmallVector<const SCEV *, 4> Ops; |
| 1708 | for (const auto *Op : SA->operands()) |
| 1709 | Ops.push_back(getSignExtendExpr(Op, Ty)); |
| 1710 | return getAddExpr(Ops, SCEV::FlagNSW); |
| 1711 | } |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1712 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1713 | // 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] | 1714 | // 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] | 1715 | // operands (often constants). This allows analysis of something like |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1716 | // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1717 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1718 | if (AR->isAffine()) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1719 | const SCEV *Start = AR->getStart(); |
| 1720 | const SCEV *Step = AR->getStepRecurrence(*this); |
| 1721 | unsigned BitWidth = getTypeSizeInBits(AR->getType()); |
| 1722 | const Loop *L = AR->getLoop(); |
| 1723 | |
Sanjoy Das | 724f5cf | 2016-03-03 18:31:29 +0000 | [diff] [blame] | 1724 | if (!AR->hasNoSignedWrap()) { |
| 1725 | auto NewFlags = proveNoWrapViaConstantRanges(AR); |
| 1726 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); |
| 1727 | } |
| 1728 | |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1729 | // If we have special knowledge that this addrec won't overflow, |
| 1730 | // we don't need to do any further analysis. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1731 | if (AR->hasNoSignedWrap()) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1732 | return getAddRecExpr( |
| 1733 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1734 | getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW); |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1735 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1736 | // Check whether the backedge-taken count is SCEVCouldNotCompute. |
| 1737 | // Note that this serves two purposes: It filters out loops that are |
| 1738 | // simply not analyzable, and it covers the case where this code is |
| 1739 | // being called from within backedge-taken count analysis, such that |
| 1740 | // attempting to ask for the backedge-taken count would likely result |
| 1741 | // in infinite recursion. In the later case, the analysis code will |
| 1742 | // cope with a conservative value, and it will take care to purge |
| 1743 | // that value once it has finished. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1744 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1745 | if (!isa<SCEVCouldNotCompute>(MaxBECount)) { |
Dan Gohman | 95c5b0e | 2009-04-29 01:54:20 +0000 | [diff] [blame] | 1746 | // Manually compute the final value for AR, checking for |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1747 | // overflow. |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1748 | |
| 1749 | // Check whether the backedge-taken count can be losslessly casted to |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1750 | // the addrec's type. The count is always unsigned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1751 | const SCEV *CastedMaxBECount = |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1752 | getTruncateOrZeroExtend(MaxBECount, Start->getType()); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1753 | const SCEV *RecastedMaxBECount = |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1754 | getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); |
| 1755 | if (MaxBECount == RecastedMaxBECount) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1756 | Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1757 | // Check whether Start+Step*MaxBECount has no signed overflow. |
Dan Gohman | 007f504 | 2010-02-24 19:31:06 +0000 | [diff] [blame] | 1758 | const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1759 | const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy); |
| 1760 | const SCEV *WideStart = getSignExtendExpr(Start, WideTy); |
| 1761 | const SCEV *WideMaxBECount = |
| 1762 | getZeroExtendExpr(CastedMaxBECount, WideTy); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1763 | const SCEV *OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1764 | getAddExpr(WideStart, |
| 1765 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1766 | getSignExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1767 | if (SAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1768 | // Cache knowledge of AR NSW, which is propagated to this AddRec. |
| 1769 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1770 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1771 | return getAddRecExpr( |
| 1772 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1773 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1774 | } |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1775 | // Similar to above, only this time treat the step value as unsigned. |
| 1776 | // This covers loops that count up with an unsigned step. |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1777 | OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1778 | getAddExpr(WideStart, |
| 1779 | getMulExpr(WideMaxBECount, |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1780 | getZeroExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1781 | if (SAdd == OperandExtendedAdd) { |
Sanjoy Das | bf5d870 | 2015-02-09 18:34:55 +0000 | [diff] [blame] | 1782 | // If AR wraps around then |
| 1783 | // |
| 1784 | // abs(Step) * MaxBECount > unsigned-max(AR->getType()) |
| 1785 | // => SAdd != OperandExtendedAdd |
| 1786 | // |
| 1787 | // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> |
| 1788 | // (SAdd == OperandExtendedAdd => AR is NW) |
| 1789 | |
| 1790 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
| 1791 | |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1792 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1793 | return getAddRecExpr( |
| 1794 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1795 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1796 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1797 | } |
Sanjoy Das | 787c246 | 2016-05-11 17:41:26 +0000 | [diff] [blame] | 1798 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1799 | |
Sanjoy Das | 787c246 | 2016-05-11 17:41:26 +0000 | [diff] [blame] | 1800 | // Normally, in the cases we can prove no-overflow via a |
| 1801 | // backedge guarding condition, we can also compute a backedge |
| 1802 | // taken count for the loop. The exceptions are assumptions and |
| 1803 | // guards present in the loop -- SCEV is not great at exploiting |
| 1804 | // these to compute max backedge taken counts, but can still use |
| 1805 | // these to prove lack of overflow. Use this fact to avoid |
| 1806 | // doing extra work that may not pay off. |
| 1807 | |
| 1808 | if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || |
| 1809 | !AC.assumptions().empty()) { |
| 1810 | // If the backedge is guarded by a comparison with the pre-inc |
| 1811 | // value the addrec is safe. Also, if the entry is guarded by |
| 1812 | // a comparison with the start value and the backedge is |
| 1813 | // guarded by a comparison with the post-inc value, the addrec |
| 1814 | // is safe. |
Andrew Trick | 812276e | 2011-05-31 21:17:47 +0000 | [diff] [blame] | 1815 | ICmpInst::Predicate Pred; |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1816 | const SCEV *OverflowLimit = |
| 1817 | getSignedOverflowLimitForStep(Step, &Pred, this); |
Andrew Trick | 812276e | 2011-05-31 21:17:47 +0000 | [diff] [blame] | 1818 | if (OverflowLimit && |
| 1819 | (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || |
| 1820 | (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && |
| 1821 | isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), |
| 1822 | OverflowLimit)))) { |
| 1823 | // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. |
| 1824 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1825 | return getAddRecExpr( |
| 1826 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1827 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1828 | } |
| 1829 | } |
Sanjoy Das | 787c246 | 2016-05-11 17:41:26 +0000 | [diff] [blame] | 1830 | |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1831 | // If Start and Step are constants, check if we can apply this |
| 1832 | // transformation: |
| 1833 | // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1834 | auto *SC1 = dyn_cast<SCEVConstant>(Start); |
| 1835 | auto *SC2 = dyn_cast<SCEVConstant>(Step); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1836 | if (SC1 && SC2) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1837 | const APInt &C1 = SC1->getAPInt(); |
| 1838 | const APInt &C2 = SC2->getAPInt(); |
Michael Zolotukhin | 265dfa4 | 2014-05-26 14:49:46 +0000 | [diff] [blame] | 1839 | if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && |
| 1840 | C2.isPowerOf2()) { |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1841 | Start = getSignExtendExpr(Start, Ty); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 1842 | const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, |
| 1843 | AR->getNoWrapFlags()); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1844 | return getAddExpr(Start, getSignExtendExpr(NewAR, Ty)); |
| 1845 | } |
| 1846 | } |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1847 | |
| 1848 | if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { |
| 1849 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
| 1850 | return getAddRecExpr( |
| 1851 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1852 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
| 1853 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1854 | } |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1855 | |
Sanjoy Das | 11ef606 | 2016-03-03 18:31:23 +0000 | [diff] [blame] | 1856 | // If the input value is provably positive and we could not simplify |
| 1857 | // away the sext build a zext instead. |
| 1858 | if (isKnownNonNegative(Op)) |
| 1859 | return getZeroExtendExpr(Op, Ty); |
| 1860 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1861 | // The cast wasn't folded; create an explicit cast node. |
| 1862 | // Recompute the insert position, as it may have been invalidated. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1863 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1864 | SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), |
| 1865 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1866 | UniqueSCEVs.InsertNode(S, IP); |
| 1867 | return S; |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1868 | } |
| 1869 | |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1870 | /// getAnyExtendExpr - Return a SCEV for the given operand extended with |
| 1871 | /// unspecified bits out to the given type. |
| 1872 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1873 | const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1874 | Type *Ty) { |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1875 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
| 1876 | "This is not an extending conversion!"); |
| 1877 | assert(isSCEVable(Ty) && |
| 1878 | "This is not a conversion to a SCEVable type!"); |
| 1879 | Ty = getEffectiveSCEVType(Ty); |
| 1880 | |
| 1881 | // Sign-extend negative constants. |
| 1882 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1883 | if (SC->getAPInt().isNegative()) |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1884 | return getSignExtendExpr(Op, Ty); |
| 1885 | |
| 1886 | // Peel off a truncate cast. |
| 1887 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1888 | const SCEV *NewOp = T->getOperand(); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1889 | if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) |
| 1890 | return getAnyExtendExpr(NewOp, Ty); |
| 1891 | return getTruncateOrNoop(NewOp, Ty); |
| 1892 | } |
| 1893 | |
| 1894 | // Next try a zext cast. If the cast is folded, use it. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1895 | const SCEV *ZExt = getZeroExtendExpr(Op, Ty); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1896 | if (!isa<SCEVZeroExtendExpr>(ZExt)) |
| 1897 | return ZExt; |
| 1898 | |
| 1899 | // Next try a sext cast. If the cast is folded, use it. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1900 | const SCEV *SExt = getSignExtendExpr(Op, Ty); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1901 | if (!isa<SCEVSignExtendExpr>(SExt)) |
| 1902 | return SExt; |
| 1903 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1904 | // Force the cast to be folded into the operands of an addrec. |
| 1905 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { |
| 1906 | SmallVector<const SCEV *, 4> Ops; |
Tobias Grosser | 924221c | 2014-05-07 06:07:47 +0000 | [diff] [blame] | 1907 | for (const SCEV *Op : AR->operands()) |
| 1908 | Ops.push_back(getAnyExtendExpr(Op, Ty)); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1909 | return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1910 | } |
| 1911 | |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1912 | // If the expression is obviously signed, use the sext cast value. |
| 1913 | if (isa<SCEVSMaxExpr>(Op)) |
| 1914 | return SExt; |
| 1915 | |
| 1916 | // Absent any other information, use the zext cast value. |
| 1917 | return ZExt; |
| 1918 | } |
| 1919 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 1920 | /// Process the given Ops list, which is a list of operands to be added under |
| 1921 | /// the given scale, update the given map. This is a helper function for |
| 1922 | /// getAddRecExpr. As an example of what it does, given a sequence of operands |
| 1923 | /// that would form an add expression like this: |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1924 | /// |
Tobias Grosser | ba49e42 | 2014-03-05 10:37:17 +0000 | [diff] [blame] | 1925 | /// 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] | 1926 | /// |
| 1927 | /// where A and B are constants, update the map with these values: |
| 1928 | /// |
| 1929 | /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) |
| 1930 | /// |
| 1931 | /// and add 13 + A*B*29 to AccumulatedConstant. |
| 1932 | /// This will allow getAddRecExpr to produce this: |
| 1933 | /// |
| 1934 | /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) |
| 1935 | /// |
| 1936 | /// This form often exposes folding opportunities that are hidden in |
| 1937 | /// the original operand list. |
| 1938 | /// |
Sylvestre Ledru | 91ce36c | 2012-09-27 10:14:43 +0000 | [diff] [blame] | 1939 | /// Return true iff it appears that any interesting folding opportunities |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1940 | /// may be exposed. This helps getAddRecExpr short-circuit extra work in |
| 1941 | /// the common case where no interesting opportunities are present, and |
| 1942 | /// is also used as a check to avoid infinite recursion. |
| 1943 | /// |
| 1944 | static bool |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1945 | CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, |
Craig Topper | 2cd5ff8 | 2013-07-11 16:22:38 +0000 | [diff] [blame] | 1946 | SmallVectorImpl<const SCEV *> &NewOps, |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1947 | APInt &AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1948 | const SCEV *const *Ops, size_t NumOperands, |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1949 | const APInt &Scale, |
| 1950 | ScalarEvolution &SE) { |
| 1951 | bool Interesting = false; |
| 1952 | |
Dan Gohman | 4507304 | 2010-06-18 19:12:32 +0000 | [diff] [blame] | 1953 | // Iterate over the add operands. They are sorted, with constants first. |
| 1954 | unsigned i = 0; |
| 1955 | while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { |
| 1956 | ++i; |
| 1957 | // Pull a buried constant out to the outside. |
| 1958 | if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) |
| 1959 | Interesting = true; |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1960 | AccumulatedConstant += Scale * C->getAPInt(); |
Dan Gohman | 4507304 | 2010-06-18 19:12:32 +0000 | [diff] [blame] | 1961 | } |
| 1962 | |
| 1963 | // Next comes everything else. We're especially interested in multiplies |
| 1964 | // here, but they're in the middle, so just visit the rest with one loop. |
| 1965 | for (; i != NumOperands; ++i) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1966 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); |
| 1967 | if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { |
| 1968 | APInt NewScale = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1969 | Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1970 | if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { |
| 1971 | // A multiplication of a constant with another add; recurse. |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1972 | const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1973 | Interesting |= |
| 1974 | CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1975 | Add->op_begin(), Add->getNumOperands(), |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1976 | NewScale, SE); |
| 1977 | } else { |
| 1978 | // A multiplication of a constant with some other value. Update |
| 1979 | // the map. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1980 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); |
| 1981 | const SCEV *Key = SE.getMulExpr(MulOps); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 1982 | auto Pair = M.insert({Key, NewScale}); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1983 | if (Pair.second) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1984 | NewOps.push_back(Pair.first->first); |
| 1985 | } else { |
| 1986 | Pair.first->second += NewScale; |
| 1987 | // The map already had an entry for this value, which may indicate |
| 1988 | // a folding opportunity. |
| 1989 | Interesting = true; |
| 1990 | } |
| 1991 | } |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1992 | } else { |
| 1993 | // An ordinary operand. Update the map. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1994 | std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 1995 | M.insert({Ops[i], Scale}); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1996 | if (Pair.second) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1997 | NewOps.push_back(Pair.first->first); |
| 1998 | } else { |
| 1999 | Pair.first->second += Scale; |
| 2000 | // The map already had an entry for this value, which may indicate |
| 2001 | // a folding opportunity. |
| 2002 | Interesting = true; |
| 2003 | } |
| 2004 | } |
| 2005 | } |
| 2006 | |
| 2007 | return Interesting; |
| 2008 | } |
| 2009 | |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2010 | // We're trying to construct a SCEV of type `Type' with `Ops' as operands and |
| 2011 | // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of |
| 2012 | // can't-overflow flags for the operation if possible. |
| 2013 | static SCEV::NoWrapFlags |
| 2014 | StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, |
| 2015 | const SmallVectorImpl<const SCEV *> &Ops, |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2016 | SCEV::NoWrapFlags Flags) { |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2017 | using namespace std::placeholders; |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2018 | typedef OverflowingBinaryOperator OBO; |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2019 | |
| 2020 | bool CanAnalyze = |
| 2021 | Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; |
| 2022 | (void)CanAnalyze; |
| 2023 | assert(CanAnalyze && "don't call from other places!"); |
| 2024 | |
| 2025 | int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; |
| 2026 | SCEV::NoWrapFlags SignOrUnsignWrap = |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2027 | ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2028 | |
| 2029 | // 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] | 2030 | auto IsKnownNonNegative = [&](const SCEV *S) { |
| 2031 | return SE->isKnownNonNegative(S); |
| 2032 | }; |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2033 | |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 2034 | if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2035 | Flags = |
| 2036 | ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2037 | |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2038 | SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); |
| 2039 | |
| 2040 | if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && |
| 2041 | Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { |
| 2042 | |
| 2043 | // (A + C) --> (A + C)<nsw> if the addition does not sign overflow |
| 2044 | // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow |
| 2045 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2046 | const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2047 | if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { |
Sanjoy Das | 5079f62 | 2016-02-22 16:13:02 +0000 | [diff] [blame] | 2048 | auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 2049 | Instruction::Add, C, OBO::NoSignedWrap); |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2050 | if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) |
| 2051 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); |
| 2052 | } |
| 2053 | if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { |
Sanjoy Das | 5079f62 | 2016-02-22 16:13:02 +0000 | [diff] [blame] | 2054 | auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 2055 | Instruction::Add, C, OBO::NoUnsignedWrap); |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2056 | if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) |
| 2057 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); |
| 2058 | } |
| 2059 | } |
| 2060 | |
| 2061 | return Flags; |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2062 | } |
| 2063 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 2064 | /// Get a canonical add expression, or something simpler if possible. |
Dan Gohman | 816fe0a | 2009-10-09 00:10:36 +0000 | [diff] [blame] | 2065 | const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2066 | SCEV::NoWrapFlags Flags) { |
| 2067 | assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && |
| 2068 | "only nuw or nsw allowed"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2069 | assert(!Ops.empty() && "Cannot get empty add!"); |
Chris Lattner | 74498e1 | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 2070 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2071 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2072 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2073 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | 9136d9f | 2010-06-18 19:09:27 +0000 | [diff] [blame] | 2074 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2075 | "SCEVAddExpr operand types don't match!"); |
| 2076 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2077 | |
| 2078 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2079 | GroupByComplexity(Ops, &LI); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2080 | |
Sanjoy Das | 6489561 | 2015-10-09 02:44:45 +0000 | [diff] [blame] | 2081 | Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); |
| 2082 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2083 | // If there are any constants, fold them together. |
| 2084 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2085 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2086 | ++Idx; |
Chris Lattner | 74498e1 | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 2087 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2088 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2089 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2090 | Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); |
Dan Gohman | 011cf68 | 2009-06-14 22:53:57 +0000 | [diff] [blame] | 2091 | if (Ops.size() == 2) return Ops[0]; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2092 | Ops.erase(Ops.begin()+1); // Erase the folded element |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2093 | LHSC = cast<SCEVConstant>(Ops[0]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2094 | } |
| 2095 | |
| 2096 | // 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] | 2097 | if (LHSC->getValue()->isZero()) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2098 | Ops.erase(Ops.begin()); |
| 2099 | --Idx; |
| 2100 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2101 | |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 2102 | if (Ops.size() == 1) return Ops[0]; |
| 2103 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2104 | |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2105 | // Okay, check to see if the same value occurs in the operand list more than |
| 2106 | // once. If so, merge them together into an multiply expression. Since we |
| 2107 | // sorted the list, these values are required to be adjacent. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2108 | Type *Ty = Ops[0]->getType(); |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2109 | bool FoundMatch = false; |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2110 | for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2111 | if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2112 | // Scan ahead to count how many equal operands there are. |
| 2113 | unsigned Count = 2; |
| 2114 | while (i+Count != e && Ops[i+Count] == Ops[i]) |
| 2115 | ++Count; |
| 2116 | // Merge the values into a multiply. |
| 2117 | const SCEV *Scale = getConstant(Ty, Count); |
| 2118 | const SCEV *Mul = getMulExpr(Scale, Ops[i]); |
| 2119 | if (Ops.size() == Count) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2120 | return Mul; |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2121 | Ops[i] = Mul; |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2122 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); |
Dan Gohman | fe22f1d | 2010-08-28 00:39:27 +0000 | [diff] [blame] | 2123 | --i; e -= Count - 1; |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2124 | FoundMatch = true; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2125 | } |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2126 | if (FoundMatch) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2127 | return getAddExpr(Ops, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2128 | |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2129 | // Check for truncates. If all the operands are truncated from the same |
| 2130 | // type, see if factoring out the truncate would permit the result to be |
| 2131 | // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) |
| 2132 | // if the contents of the resulting outer trunc fold to something simple. |
| 2133 | for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { |
| 2134 | const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2135 | Type *DstType = Trunc->getType(); |
| 2136 | Type *SrcType = Trunc->getOperand()->getType(); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2137 | SmallVector<const SCEV *, 8> LargeOps; |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2138 | bool Ok = true; |
| 2139 | // Check all the operands to see if they can be represented in the |
| 2140 | // source type of the truncate. |
| 2141 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) { |
| 2142 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { |
| 2143 | if (T->getOperand()->getType() != SrcType) { |
| 2144 | Ok = false; |
| 2145 | break; |
| 2146 | } |
| 2147 | LargeOps.push_back(T->getOperand()); |
| 2148 | } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { |
Dan Gohman | ff3174e | 2010-04-23 01:51:29 +0000 | [diff] [blame] | 2149 | LargeOps.push_back(getAnyExtendExpr(C, SrcType)); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2150 | } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2151 | SmallVector<const SCEV *, 8> LargeMulOps; |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2152 | for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { |
| 2153 | if (const SCEVTruncateExpr *T = |
| 2154 | dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { |
| 2155 | if (T->getOperand()->getType() != SrcType) { |
| 2156 | Ok = false; |
| 2157 | break; |
| 2158 | } |
| 2159 | LargeMulOps.push_back(T->getOperand()); |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 2160 | } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { |
Dan Gohman | ff3174e | 2010-04-23 01:51:29 +0000 | [diff] [blame] | 2161 | LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2162 | } else { |
| 2163 | Ok = false; |
| 2164 | break; |
| 2165 | } |
| 2166 | } |
| 2167 | if (Ok) |
| 2168 | LargeOps.push_back(getMulExpr(LargeMulOps)); |
| 2169 | } else { |
| 2170 | Ok = false; |
| 2171 | break; |
| 2172 | } |
| 2173 | } |
| 2174 | if (Ok) { |
| 2175 | // Evaluate the expression in the larger type. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2176 | const SCEV *Fold = getAddExpr(LargeOps, Flags); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2177 | // If it folds to something simple, use it. Otherwise, don't. |
| 2178 | if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) |
| 2179 | return getTruncateExpr(Fold, DstType); |
| 2180 | } |
| 2181 | } |
| 2182 | |
| 2183 | // Skip past any other cast SCEVs. |
Dan Gohman | eed125f | 2007-06-18 19:30:09 +0000 | [diff] [blame] | 2184 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) |
| 2185 | ++Idx; |
| 2186 | |
| 2187 | // If there are add operands they would be next. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2188 | if (Idx < Ops.size()) { |
| 2189 | bool DeletedAdd = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2190 | while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2191 | // If we have an add, expand the add operands onto the end of the operands |
| 2192 | // list. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2193 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2194 | Ops.append(Add->op_begin(), Add->op_end()); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2195 | DeletedAdd = true; |
| 2196 | } |
| 2197 | |
| 2198 | // If we deleted at least one add, we added operands to the end of the list, |
| 2199 | // and they are not necessarily sorted. Recurse to resort and resimplify |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 2200 | // any operands we just acquired. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2201 | if (DeletedAdd) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2202 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2203 | } |
| 2204 | |
| 2205 | // Skip over the add expression until we get to a multiply. |
| 2206 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) |
| 2207 | ++Idx; |
| 2208 | |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2209 | // Check to see if there are any folding opportunities present with |
| 2210 | // operands multiplied by constant values. |
| 2211 | if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { |
| 2212 | uint64_t BitWidth = getTypeSizeInBits(Ty); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2213 | DenseMap<const SCEV *, APInt> M; |
| 2214 | SmallVector<const SCEV *, 8> NewOps; |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2215 | APInt AccumulatedConstant(BitWidth, 0); |
| 2216 | if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2217 | Ops.data(), Ops.size(), |
| 2218 | APInt(BitWidth, 1), *this)) { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 2219 | struct APIntCompare { |
| 2220 | bool operator()(const APInt &LHS, const APInt &RHS) const { |
| 2221 | return LHS.ult(RHS); |
| 2222 | } |
| 2223 | }; |
| 2224 | |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2225 | // Some interesting folding opportunity is present, so its worthwhile to |
| 2226 | // re-generate the operands list. Group the operands by constant scale, |
| 2227 | // to avoid multiplying by the same constant scale multiple times. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2228 | std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; |
Sanjoy Das | f25d25a | 2015-10-31 23:21:32 +0000 | [diff] [blame] | 2229 | for (const SCEV *NewOp : NewOps) |
| 2230 | MulOpLists[M.find(NewOp)->second].push_back(NewOp); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2231 | // Re-generate the operands list. |
| 2232 | Ops.clear(); |
| 2233 | if (AccumulatedConstant != 0) |
| 2234 | Ops.push_back(getConstant(AccumulatedConstant)); |
Sanjoy Das | f25d25a | 2015-10-31 23:21:32 +0000 | [diff] [blame] | 2235 | for (auto &MulOp : MulOpLists) |
| 2236 | if (MulOp.first != 0) |
| 2237 | Ops.push_back(getMulExpr(getConstant(MulOp.first), |
| 2238 | getAddExpr(MulOp.second))); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2239 | if (Ops.empty()) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2240 | return getZero(Ty); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2241 | if (Ops.size() == 1) |
| 2242 | return Ops[0]; |
| 2243 | return getAddExpr(Ops); |
| 2244 | } |
| 2245 | } |
| 2246 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2247 | // If we are adding something to a multiply expression, make sure the |
| 2248 | // something is not already an operand of the multiply. If so, merge it into |
| 2249 | // the multiply. |
| 2250 | for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2251 | const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2252 | for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2253 | const SCEV *MulOpSCEV = Mul->getOperand(MulOp); |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2254 | if (isa<SCEVConstant>(MulOpSCEV)) |
| 2255 | continue; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2256 | for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2257 | if (MulOpSCEV == Ops[AddOp]) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2258 | // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2259 | const SCEV *InnerMul = Mul->getOperand(MulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2260 | if (Mul->getNumOperands() != 2) { |
| 2261 | // If the multiply has more than two operands, we must get the |
| 2262 | // Y*Z term. |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2263 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), |
| 2264 | Mul->op_begin()+MulOp); |
| 2265 | MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2266 | InnerMul = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2267 | } |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2268 | const SCEV *One = getOne(Ty); |
Dan Gohman | cf32f2b | 2010-08-13 20:17:14 +0000 | [diff] [blame] | 2269 | const SCEV *AddOne = getAddExpr(One, InnerMul); |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2270 | const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2271 | if (Ops.size() == 2) return OuterMul; |
| 2272 | if (AddOp < Idx) { |
| 2273 | Ops.erase(Ops.begin()+AddOp); |
| 2274 | Ops.erase(Ops.begin()+Idx-1); |
| 2275 | } else { |
| 2276 | Ops.erase(Ops.begin()+Idx); |
| 2277 | Ops.erase(Ops.begin()+AddOp-1); |
| 2278 | } |
| 2279 | Ops.push_back(OuterMul); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2280 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2281 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2282 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2283 | // Check this multiply against other multiplies being added together. |
| 2284 | for (unsigned OtherMulIdx = Idx+1; |
| 2285 | OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); |
| 2286 | ++OtherMulIdx) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2287 | const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2288 | // If MulOp occurs in OtherMul, we can fold the two multiplies |
| 2289 | // together. |
| 2290 | for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); |
| 2291 | OMulOp != e; ++OMulOp) |
| 2292 | if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { |
| 2293 | // 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] | 2294 | const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2295 | if (Mul->getNumOperands() != 2) { |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2296 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2297 | Mul->op_begin()+MulOp); |
| 2298 | MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2299 | InnerMul1 = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2300 | } |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2301 | const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2302 | if (OtherMul->getNumOperands() != 2) { |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2303 | SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2304 | OtherMul->op_begin()+OMulOp); |
| 2305 | MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2306 | InnerMul2 = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2307 | } |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2308 | const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2); |
| 2309 | const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2310 | if (Ops.size() == 2) return OuterMul; |
Dan Gohman | aabfc52 | 2010-08-31 22:50:31 +0000 | [diff] [blame] | 2311 | Ops.erase(Ops.begin()+Idx); |
| 2312 | Ops.erase(Ops.begin()+OtherMulIdx-1); |
| 2313 | Ops.push_back(OuterMul); |
| 2314 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2315 | } |
| 2316 | } |
| 2317 | } |
| 2318 | } |
| 2319 | |
| 2320 | // If there are any add recurrences in the operands list, see if any other |
| 2321 | // added values are loop invariant. If so, we can fold them into the |
| 2322 | // recurrence. |
| 2323 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) |
| 2324 | ++Idx; |
| 2325 | |
| 2326 | // Scan over all recurrences, trying to fold loop invariants into them. |
| 2327 | for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { |
| 2328 | // Scan all of the other operands to this add and add them to the vector if |
| 2329 | // they are loop invariant w.r.t. the recurrence. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2330 | SmallVector<const SCEV *, 8> LIOps; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2331 | const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 2332 | const Loop *AddRecLoop = AddRec->getLoop(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2333 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2334 | if (isLoopInvariant(Ops[i], AddRecLoop)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2335 | LIOps.push_back(Ops[i]); |
| 2336 | Ops.erase(Ops.begin()+i); |
| 2337 | --i; --e; |
| 2338 | } |
| 2339 | |
| 2340 | // If we found some loop invariants, fold them into the recurrence. |
| 2341 | if (!LIOps.empty()) { |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 2342 | // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2343 | LIOps.push_back(AddRec->getStart()); |
| 2344 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2345 | SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), |
Dan Gohman | 7a2dab8 | 2009-12-18 03:57:04 +0000 | [diff] [blame] | 2346 | AddRec->op_end()); |
Oleg Ranevskyy | eb4ecca | 2016-05-25 13:01:33 +0000 | [diff] [blame] | 2347 | // This follows from the fact that the no-wrap flags on the outer add |
| 2348 | // expression are applicable on the 0th iteration, when the add recurrence |
| 2349 | // will be equal to its start value. |
| 2350 | AddRecOps[0] = getAddExpr(LIOps, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2351 | |
Dan Gohman | 1620613 | 2010-06-30 07:16:37 +0000 | [diff] [blame] | 2352 | // 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] | 2353 | // outer add and the inner addrec are guaranteed to have no overflow. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2354 | // Always propagate NW. |
| 2355 | Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2356 | const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); |
Dan Gohman | 51f1305 | 2009-12-18 18:45:31 +0000 | [diff] [blame] | 2357 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2358 | // If all of the other operands were loop invariant, we are done. |
| 2359 | if (Ops.size() == 1) return NewRec; |
| 2360 | |
Nick Lewycky | db66b82 | 2011-09-06 05:08:09 +0000 | [diff] [blame] | 2361 | // Otherwise, add the folded AddRec by the non-invariant parts. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2362 | for (unsigned i = 0;; ++i) |
| 2363 | if (Ops[i] == AddRec) { |
| 2364 | Ops[i] = NewRec; |
| 2365 | break; |
| 2366 | } |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2367 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2368 | } |
| 2369 | |
| 2370 | // Okay, if there weren't any loop invariants to be folded, check to see if |
| 2371 | // there are multiple AddRec's with the same loop induction variable being |
| 2372 | // added together. If so, we can fold them. |
| 2373 | for (unsigned OtherIdx = Idx+1; |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2374 | OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2375 | ++OtherIdx) |
| 2376 | if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { |
| 2377 | // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> |
| 2378 | SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), |
| 2379 | AddRec->op_end()); |
| 2380 | for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2381 | ++OtherIdx) |
Sanjoy Das | f25d25a | 2015-10-31 23:21:32 +0000 | [diff] [blame] | 2382 | if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2383 | if (OtherAddRec->getLoop() == AddRecLoop) { |
| 2384 | for (unsigned i = 0, e = OtherAddRec->getNumOperands(); |
| 2385 | i != e; ++i) { |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2386 | if (i >= AddRecOps.size()) { |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2387 | AddRecOps.append(OtherAddRec->op_begin()+i, |
| 2388 | OtherAddRec->op_end()); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2389 | break; |
| 2390 | } |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2391 | AddRecOps[i] = getAddExpr(AddRecOps[i], |
| 2392 | OtherAddRec->getOperand(i)); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2393 | } |
| 2394 | Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2395 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2396 | // Step size has changed, so we cannot guarantee no self-wraparound. |
| 2397 | Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2398 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2399 | } |
| 2400 | |
| 2401 | // Otherwise couldn't fold anything into this recurrence. Move onto the |
| 2402 | // next one. |
| 2403 | } |
| 2404 | |
| 2405 | // Okay, it looks like we really DO need an add expr. Check to see if we |
| 2406 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2407 | FoldingSetNodeID ID; |
| 2408 | ID.AddInteger(scAddExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2409 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 2410 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2411 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2412 | SCEVAddExpr *S = |
| 2413 | static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2414 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2415 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 2416 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2417 | S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator), |
| 2418 | O, Ops.size()); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2419 | UniqueSCEVs.InsertNode(S, IP); |
| 2420 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2421 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2422 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2423 | } |
| 2424 | |
Nick Lewycky | 287682e | 2011-10-04 06:51:26 +0000 | [diff] [blame] | 2425 | static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { |
| 2426 | uint64_t k = i*j; |
| 2427 | if (j > 1 && k / j != i) Overflow = true; |
| 2428 | return k; |
| 2429 | } |
| 2430 | |
| 2431 | /// Compute the result of "n choose k", the binomial coefficient. If an |
| 2432 | /// intermediate computation overflows, Overflow will be set and the return will |
Benjamin Kramer | bde9176 | 2012-06-02 10:20:22 +0000 | [diff] [blame] | 2433 | /// be garbage. Overflow is not cleared on absence of overflow. |
Nick Lewycky | 287682e | 2011-10-04 06:51:26 +0000 | [diff] [blame] | 2434 | static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { |
| 2435 | // We use the multiplicative formula: |
| 2436 | // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . |
| 2437 | // At each iteration, we take the n-th term of the numeral and divide by the |
| 2438 | // (k-n)th term of the denominator. This division will always produce an |
| 2439 | // integral result, and helps reduce the chance of overflow in the |
| 2440 | // intermediate computations. However, we can still overflow even when the |
| 2441 | // final result would fit. |
| 2442 | |
| 2443 | if (n == 0 || n == k) return 1; |
| 2444 | if (k > n) return 0; |
| 2445 | |
| 2446 | if (k > n/2) |
| 2447 | k = n-k; |
| 2448 | |
| 2449 | uint64_t r = 1; |
| 2450 | for (uint64_t i = 1; i <= k; ++i) { |
| 2451 | r = umul_ov(r, n-(i-1), Overflow); |
| 2452 | r /= i; |
| 2453 | } |
| 2454 | return r; |
| 2455 | } |
| 2456 | |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2457 | /// Determine if any of the operands in this SCEV are a constant or if |
| 2458 | /// any of the add or multiply expressions in this SCEV contain a constant. |
| 2459 | static bool containsConstantSomewhere(const SCEV *StartExpr) { |
| 2460 | SmallVector<const SCEV *, 4> Ops; |
| 2461 | Ops.push_back(StartExpr); |
| 2462 | while (!Ops.empty()) { |
| 2463 | const SCEV *CurrentExpr = Ops.pop_back_val(); |
| 2464 | if (isa<SCEVConstant>(*CurrentExpr)) |
| 2465 | return true; |
| 2466 | |
| 2467 | if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { |
| 2468 | const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); |
Benjamin Kramer | 6cd780f | 2015-02-17 15:29:18 +0000 | [diff] [blame] | 2469 | Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2470 | } |
| 2471 | } |
| 2472 | return false; |
| 2473 | } |
| 2474 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 2475 | /// Get a canonical multiply expression, or something simpler if possible. |
Dan Gohman | 816fe0a | 2009-10-09 00:10:36 +0000 | [diff] [blame] | 2476 | const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2477 | SCEV::NoWrapFlags Flags) { |
| 2478 | assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && |
| 2479 | "only nuw or nsw allowed"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2480 | assert(!Ops.empty() && "Cannot get empty mul!"); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2481 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2482 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2483 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2484 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 2485 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2486 | "SCEVMulExpr operand types don't match!"); |
| 2487 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2488 | |
| 2489 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2490 | GroupByComplexity(Ops, &LI); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2491 | |
Sanjoy Das | 6489561 | 2015-10-09 02:44:45 +0000 | [diff] [blame] | 2492 | Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); |
| 2493 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2494 | // If there are any constants, fold them together. |
| 2495 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2496 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2497 | |
| 2498 | // C1*(C2+V) -> C1*C2 + C1*V |
| 2499 | if (Ops.size() == 2) |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2500 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) |
| 2501 | // If any of Add's ops are Adds or Muls with a constant, |
| 2502 | // apply this transformation as well. |
| 2503 | if (Add->getNumOperands() == 2) |
| 2504 | if (containsConstantSomewhere(Add)) |
| 2505 | return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), |
| 2506 | getMulExpr(LHSC, Add->getOperand(1))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2507 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2508 | ++Idx; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2509 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2510 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2511 | ConstantInt *Fold = |
| 2512 | ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2513 | Ops[0] = getConstant(Fold); |
| 2514 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 2515 | if (Ops.size() == 1) return Ops[0]; |
| 2516 | LHSC = cast<SCEVConstant>(Ops[0]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2517 | } |
| 2518 | |
| 2519 | // If we are left with a constant one being multiplied, strip it off. |
| 2520 | if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { |
| 2521 | Ops.erase(Ops.begin()); |
| 2522 | --Idx; |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 2523 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2524 | // If we have a multiply of zero, it will always be zero. |
| 2525 | return Ops[0]; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2526 | } else if (Ops[0]->isAllOnesValue()) { |
| 2527 | // If we have a mul by -1 of an add, try distributing the -1 among the |
| 2528 | // add operands. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2529 | if (Ops.size() == 2) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2530 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { |
| 2531 | SmallVector<const SCEV *, 4> NewOps; |
| 2532 | bool AnyFolded = false; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 2533 | for (const SCEV *AddOp : Add->operands()) { |
| 2534 | const SCEV *Mul = getMulExpr(Ops[0], AddOp); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2535 | if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; |
| 2536 | NewOps.push_back(Mul); |
| 2537 | } |
| 2538 | if (AnyFolded) |
| 2539 | return getAddExpr(NewOps); |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 2540 | } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { |
Andrew Trick | e92dcce | 2011-03-14 17:38:54 +0000 | [diff] [blame] | 2541 | // Negation preserves a recurrence's no self-wrap property. |
| 2542 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 2543 | for (const SCEV *AddRecOp : AddRec->operands()) |
| 2544 | Operands.push_back(getMulExpr(Ops[0], AddRecOp)); |
| 2545 | |
Andrew Trick | e92dcce | 2011-03-14 17:38:54 +0000 | [diff] [blame] | 2546 | return getAddRecExpr(Operands, AddRec->getLoop(), |
| 2547 | AddRec->getNoWrapFlags(SCEV::FlagNW)); |
| 2548 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2549 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2550 | } |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 2551 | |
| 2552 | if (Ops.size() == 1) |
| 2553 | return Ops[0]; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2554 | } |
| 2555 | |
| 2556 | // Skip over the add expression until we get to a multiply. |
| 2557 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) |
| 2558 | ++Idx; |
| 2559 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2560 | // If there are mul operands inline them all into this expression. |
| 2561 | if (Idx < Ops.size()) { |
| 2562 | bool DeletedMul = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2563 | while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { |
Li Huang | fcfe8cd | 2016-10-20 21:38:39 +0000 | [diff] [blame] | 2564 | if (Ops.size() > MulOpsInlineThreshold) |
| 2565 | break; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2566 | // If we have an mul, expand the mul operands onto the end of the operands |
| 2567 | // list. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2568 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2569 | Ops.append(Mul->op_begin(), Mul->op_end()); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2570 | DeletedMul = true; |
| 2571 | } |
| 2572 | |
| 2573 | // If we deleted at least one mul, we added operands to the end of the list, |
| 2574 | // and they are not necessarily sorted. Recurse to resort and resimplify |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 2575 | // any operands we just acquired. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2576 | if (DeletedMul) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2577 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2578 | } |
| 2579 | |
| 2580 | // If there are any add recurrences in the operands list, see if any other |
| 2581 | // added values are loop invariant. If so, we can fold them into the |
| 2582 | // recurrence. |
| 2583 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) |
| 2584 | ++Idx; |
| 2585 | |
| 2586 | // Scan over all recurrences, trying to fold loop invariants into them. |
| 2587 | for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { |
| 2588 | // Scan all of the other operands to this mul and add them to the vector if |
| 2589 | // they are loop invariant w.r.t. the recurrence. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2590 | SmallVector<const SCEV *, 8> LIOps; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2591 | const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); |
Dan Gohman | 0f2de01 | 2010-08-29 14:55:19 +0000 | [diff] [blame] | 2592 | const Loop *AddRecLoop = AddRec->getLoop(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2593 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2594 | if (isLoopInvariant(Ops[i], AddRecLoop)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2595 | LIOps.push_back(Ops[i]); |
| 2596 | Ops.erase(Ops.begin()+i); |
| 2597 | --i; --e; |
| 2598 | } |
| 2599 | |
| 2600 | // If we found some loop invariants, fold them into the recurrence. |
| 2601 | if (!LIOps.empty()) { |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 2602 | // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2603 | SmallVector<const SCEV *, 4> NewOps; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2604 | NewOps.reserve(AddRec->getNumOperands()); |
Dan Gohman | 8f5954f | 2010-06-17 23:34:09 +0000 | [diff] [blame] | 2605 | const SCEV *Scale = getMulExpr(LIOps); |
| 2606 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) |
| 2607 | NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2608 | |
Dan Gohman | 1620613 | 2010-06-30 07:16:37 +0000 | [diff] [blame] | 2609 | // Build the new addrec. Propagate the NUW and NSW flags if both the |
| 2610 | // outer mul and the inner addrec are guaranteed to have no overflow. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2611 | // |
| 2612 | // No self-wrap cannot be guaranteed after changing the step size, but |
Chris Lattner | 0ab5e2c | 2011-04-15 05:18:47 +0000 | [diff] [blame] | 2613 | // will be inferred if either NUW or NSW is true. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2614 | Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); |
| 2615 | const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2616 | |
| 2617 | // If all of the other operands were loop invariant, we are done. |
| 2618 | if (Ops.size() == 1) return NewRec; |
| 2619 | |
Nick Lewycky | db66b82 | 2011-09-06 05:08:09 +0000 | [diff] [blame] | 2620 | // Otherwise, multiply the folded AddRec by the non-invariant parts. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2621 | for (unsigned i = 0;; ++i) |
| 2622 | if (Ops[i] == AddRec) { |
| 2623 | Ops[i] = NewRec; |
| 2624 | break; |
| 2625 | } |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2626 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2627 | } |
| 2628 | |
| 2629 | // Okay, if there weren't any loop invariants to be folded, check to see if |
| 2630 | // there are multiple AddRec's with the same loop induction variable being |
| 2631 | // multiplied together. If so, we can fold them. |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2632 | |
| 2633 | // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> |
| 2634 | // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ |
| 2635 | // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z |
| 2636 | // ]]],+,...up to x=2n}. |
| 2637 | // Note that the arguments to choose() are always integers with values |
| 2638 | // known at compile time, never SCEV objects. |
| 2639 | // |
| 2640 | // The implementation avoids pointless extra computations when the two |
| 2641 | // addrec's are of different length (mathematically, it's equivalent to |
| 2642 | // an infinite stream of zeros on the right). |
| 2643 | bool OpsModified = false; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2644 | for (unsigned OtherIdx = Idx+1; |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2645 | OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
Nick Lewycky | e0aa54b | 2011-09-06 21:42:18 +0000 | [diff] [blame] | 2646 | ++OtherIdx) { |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2647 | const SCEVAddRecExpr *OtherAddRec = |
| 2648 | dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2649 | if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2650 | continue; |
| 2651 | |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2652 | bool Overflow = false; |
| 2653 | Type *Ty = AddRec->getType(); |
| 2654 | bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; |
| 2655 | SmallVector<const SCEV*, 7> AddRecOps; |
| 2656 | for (int x = 0, xe = AddRec->getNumOperands() + |
| 2657 | OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2658 | const SCEV *Term = getZero(Ty); |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2659 | for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { |
| 2660 | uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); |
| 2661 | for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), |
| 2662 | ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); |
| 2663 | z < ze && !Overflow; ++z) { |
| 2664 | uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); |
| 2665 | uint64_t Coeff; |
| 2666 | if (LargerThan64Bits) |
| 2667 | Coeff = umul_ov(Coeff1, Coeff2, Overflow); |
| 2668 | else |
| 2669 | Coeff = Coeff1*Coeff2; |
| 2670 | const SCEV *CoeffTerm = getConstant(Ty, Coeff); |
| 2671 | const SCEV *Term1 = AddRec->getOperand(y-z); |
| 2672 | const SCEV *Term2 = OtherAddRec->getOperand(z); |
| 2673 | Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2674 | } |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2675 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2676 | AddRecOps.push_back(Term); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2677 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2678 | if (!Overflow) { |
| 2679 | const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), |
| 2680 | SCEV::FlagAnyWrap); |
| 2681 | if (Ops.size() == 2) return NewAddRec; |
| 2682 | Ops[Idx] = NewAddRec; |
| 2683 | Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; |
| 2684 | OpsModified = true; |
| 2685 | AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); |
| 2686 | if (!AddRec) |
| 2687 | break; |
| 2688 | } |
Nick Lewycky | e0aa54b | 2011-09-06 21:42:18 +0000 | [diff] [blame] | 2689 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2690 | if (OpsModified) |
| 2691 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2692 | |
| 2693 | // Otherwise couldn't fold anything into this recurrence. Move onto the |
| 2694 | // next one. |
| 2695 | } |
| 2696 | |
| 2697 | // Okay, it looks like we really DO need an mul expr. Check to see if we |
| 2698 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2699 | FoldingSetNodeID ID; |
| 2700 | ID.AddInteger(scMulExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2701 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 2702 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2703 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2704 | SCEVMulExpr *S = |
| 2705 | static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2706 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2707 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 2708 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2709 | S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), |
| 2710 | O, Ops.size()); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2711 | UniqueSCEVs.InsertNode(S, IP); |
| 2712 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2713 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2714 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2715 | } |
| 2716 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 2717 | /// Get a canonical unsigned division expression, or something simpler if |
| 2718 | /// possible. |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 2719 | const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, |
| 2720 | const SCEV *RHS) { |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2721 | assert(getEffectiveSCEVType(LHS->getType()) == |
| 2722 | getEffectiveSCEVType(RHS->getType()) && |
| 2723 | "SCEVUDivExpr operand types don't match!"); |
| 2724 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2725 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2726 | if (RHSC->getValue()->equalsInt(1)) |
Dan Gohman | 8a8ad7d | 2009-08-20 16:42:55 +0000 | [diff] [blame] | 2727 | return LHS; // X udiv 1 --> x |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2728 | // If the denominator is zero, the result of the udiv is undefined. Don't |
| 2729 | // try to analyze it, because the resolution chosen here may differ from |
| 2730 | // the resolution chosen in other parts of the compiler. |
| 2731 | if (!RHSC->getValue()->isZero()) { |
| 2732 | // Determine if the division can be folded into the operands of |
| 2733 | // its operands. |
| 2734 | // TODO: Generalize this to non-constants by using known-bits information. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2735 | Type *Ty = LHS->getType(); |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2736 | unsigned LZ = RHSC->getAPInt().countLeadingZeros(); |
Dan Gohman | db764c6 | 2010-08-04 19:52:50 +0000 | [diff] [blame] | 2737 | unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2738 | // For non-power-of-two values, effectively round the value up to the |
| 2739 | // nearest power of two. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2740 | if (!RHSC->getAPInt().isPowerOf2()) |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2741 | ++MaxShiftAmt; |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2742 | IntegerType *ExtTy = |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2743 | IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2744 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) |
| 2745 | if (const SCEVConstant *Step = |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2746 | dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { |
| 2747 | // {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] | 2748 | const APInt &StepInt = Step->getAPInt(); |
| 2749 | const APInt &DivInt = RHSC->getAPInt(); |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2750 | if (!StepInt.urem(DivInt) && |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2751 | getZeroExtendExpr(AR, ExtTy) == |
| 2752 | getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), |
| 2753 | getZeroExtendExpr(Step, ExtTy), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2754 | AR->getLoop(), SCEV::FlagAnyWrap)) { |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2755 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 2756 | for (const SCEV *Op : AR->operands()) |
| 2757 | Operands.push_back(getUDivExpr(Op, RHS)); |
| 2758 | return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2759 | } |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2760 | /// Get a canonical UDivExpr for a recurrence. |
| 2761 | /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. |
| 2762 | // We can currently only fold X%N if X is constant. |
| 2763 | const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); |
| 2764 | if (StartC && !DivInt.urem(StepInt) && |
| 2765 | getZeroExtendExpr(AR, ExtTy) == |
| 2766 | getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), |
| 2767 | getZeroExtendExpr(Step, ExtTy), |
| 2768 | AR->getLoop(), SCEV::FlagAnyWrap)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2769 | const APInt &StartInt = StartC->getAPInt(); |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2770 | const APInt &StartRem = StartInt.urem(StepInt); |
| 2771 | if (StartRem != 0) |
| 2772 | LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, |
| 2773 | AR->getLoop(), SCEV::FlagNW); |
| 2774 | } |
| 2775 | } |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2776 | // (A*B)/C --> A*(B/C) if safe and B/C can be folded. |
| 2777 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { |
| 2778 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 2779 | for (const SCEV *Op : M->operands()) |
| 2780 | Operands.push_back(getZeroExtendExpr(Op, ExtTy)); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2781 | if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) |
| 2782 | // Find an operand that's safely divisible. |
| 2783 | for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { |
| 2784 | const SCEV *Op = M->getOperand(i); |
| 2785 | const SCEV *Div = getUDivExpr(Op, RHSC); |
| 2786 | if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { |
| 2787 | Operands = SmallVector<const SCEV *, 4>(M->op_begin(), |
| 2788 | M->op_end()); |
| 2789 | Operands[i] = Div; |
| 2790 | return getMulExpr(Operands); |
| 2791 | } |
| 2792 | } |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2793 | } |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2794 | // (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] | 2795 | if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2796 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 2797 | for (const SCEV *Op : A->operands()) |
| 2798 | Operands.push_back(getZeroExtendExpr(Op, ExtTy)); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2799 | if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { |
| 2800 | Operands.clear(); |
| 2801 | for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { |
| 2802 | const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); |
| 2803 | if (isa<SCEVUDivExpr>(Op) || |
| 2804 | getMulExpr(Op, RHS) != A->getOperand(i)) |
| 2805 | break; |
| 2806 | Operands.push_back(Op); |
| 2807 | } |
| 2808 | if (Operands.size() == A->getNumOperands()) |
| 2809 | return getAddExpr(Operands); |
| 2810 | } |
| 2811 | } |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2812 | |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2813 | // Fold if both operands are constant. |
| 2814 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { |
| 2815 | Constant *LHSCV = LHSC->getValue(); |
| 2816 | Constant *RHSCV = RHSC->getValue(); |
| 2817 | return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, |
| 2818 | RHSCV))); |
| 2819 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2820 | } |
| 2821 | } |
| 2822 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2823 | FoldingSetNodeID ID; |
| 2824 | ID.AddInteger(scUDivExpr); |
| 2825 | ID.AddPointer(LHS); |
| 2826 | ID.AddPointer(RHS); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2827 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2828 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2829 | SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), |
| 2830 | LHS, RHS); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2831 | UniqueSCEVs.InsertNode(S, IP); |
| 2832 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2833 | } |
| 2834 | |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2835 | static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2836 | APInt A = C1->getAPInt().abs(); |
| 2837 | APInt B = C2->getAPInt().abs(); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2838 | uint32_t ABW = A.getBitWidth(); |
| 2839 | uint32_t BBW = B.getBitWidth(); |
| 2840 | |
| 2841 | if (ABW > BBW) |
| 2842 | B = B.zext(ABW); |
| 2843 | else if (ABW < BBW) |
| 2844 | A = A.zext(BBW); |
| 2845 | |
| 2846 | return APIntOps::GreatestCommonDivisor(A, B); |
| 2847 | } |
| 2848 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 2849 | /// Get a canonical unsigned division expression, or something simpler if |
| 2850 | /// possible. There is no representation for an exact udiv in SCEV IR, but we |
| 2851 | /// can attempt to remove factors from the LHS and RHS. We can't do this when |
| 2852 | /// it's not exact because the udiv may be clearing bits. |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2853 | const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, |
| 2854 | const SCEV *RHS) { |
| 2855 | // TODO: we could try to find factors in all sorts of things, but for now we |
| 2856 | // just deal with u/exact (multiply, constant). See SCEVDivision towards the |
| 2857 | // end of this file for inspiration. |
| 2858 | |
| 2859 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); |
| 2860 | if (!Mul) |
| 2861 | return getUDivExpr(LHS, RHS); |
| 2862 | |
| 2863 | if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { |
| 2864 | // If the mulexpr multiplies by a constant, then that constant must be the |
| 2865 | // first element of the mulexpr. |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 2866 | if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2867 | if (LHSCst == RHSCst) { |
| 2868 | SmallVector<const SCEV *, 2> Operands; |
| 2869 | Operands.append(Mul->op_begin() + 1, Mul->op_end()); |
| 2870 | return getMulExpr(Operands); |
| 2871 | } |
| 2872 | |
| 2873 | // We can't just assume that LHSCst divides RHSCst cleanly, it could be |
| 2874 | // that there's a factor provided by one of the other terms. We need to |
| 2875 | // check. |
| 2876 | APInt Factor = gcd(LHSCst, RHSCst); |
| 2877 | if (!Factor.isIntN(1)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2878 | LHSCst = |
| 2879 | cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); |
| 2880 | RHSCst = |
| 2881 | cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2882 | SmallVector<const SCEV *, 2> Operands; |
| 2883 | Operands.push_back(LHSCst); |
| 2884 | Operands.append(Mul->op_begin() + 1, Mul->op_end()); |
| 2885 | LHS = getMulExpr(Operands); |
| 2886 | RHS = RHSCst; |
Nick Lewycky | 629199c | 2014-01-27 10:47:44 +0000 | [diff] [blame] | 2887 | Mul = dyn_cast<SCEVMulExpr>(LHS); |
| 2888 | if (!Mul) |
| 2889 | return getUDivExactExpr(LHS, RHS); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2890 | } |
| 2891 | } |
| 2892 | } |
| 2893 | |
| 2894 | for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { |
| 2895 | if (Mul->getOperand(i) == RHS) { |
| 2896 | SmallVector<const SCEV *, 2> Operands; |
| 2897 | Operands.append(Mul->op_begin(), Mul->op_begin() + i); |
| 2898 | Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); |
| 2899 | return getMulExpr(Operands); |
| 2900 | } |
| 2901 | } |
| 2902 | |
| 2903 | return getUDivExpr(LHS, RHS); |
| 2904 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2905 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 2906 | /// Get an add recurrence expression for the specified loop. Simplify the |
| 2907 | /// expression as much as possible. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2908 | const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, |
| 2909 | const Loop *L, |
| 2910 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2911 | SmallVector<const SCEV *, 4> Operands; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2912 | Operands.push_back(Start); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2913 | if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2914 | if (StepChrec->getLoop() == L) { |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2915 | Operands.append(StepChrec->op_begin(), StepChrec->op_end()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2916 | return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2917 | } |
| 2918 | |
| 2919 | Operands.push_back(Step); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2920 | return getAddRecExpr(Operands, L, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2921 | } |
| 2922 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 2923 | /// Get an add recurrence expression for the specified loop. Simplify the |
| 2924 | /// expression as much as possible. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2925 | const SCEV * |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2926 | ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2927 | const Loop *L, SCEV::NoWrapFlags Flags) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2928 | if (Operands.size() == 1) return Operands[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2929 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2930 | Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2931 | for (unsigned i = 1, e = Operands.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 2932 | assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2933 | "SCEVAddRecExpr operand types don't match!"); |
Dan Gohman | d3a32ae | 2010-11-17 20:48:38 +0000 | [diff] [blame] | 2934 | for (unsigned i = 0, e = Operands.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2935 | assert(isLoopInvariant(Operands[i], L) && |
Dan Gohman | d3a32ae | 2010-11-17 20:48:38 +0000 | [diff] [blame] | 2936 | "SCEVAddRecExpr operand is not loop-invariant!"); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2937 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2938 | |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 2939 | if (Operands.back()->isZero()) { |
| 2940 | Operands.pop_back(); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2941 | return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 2942 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2943 | |
Dan Gohman | cf9c64e | 2010-02-19 18:49:22 +0000 | [diff] [blame] | 2944 | // It's tempting to want to call getMaxBackedgeTakenCount count here and |
| 2945 | // use that information to infer NUW and NSW flags. However, computing a |
| 2946 | // BE count requires calling getAddRecExpr, so we may not yet have a |
| 2947 | // meaningful BE count at this point (and if we don't, we'd be stuck |
| 2948 | // with a SCEVCouldNotCompute as the cached BE count). |
| 2949 | |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2950 | Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2951 | |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2952 | // Canonicalize nested AddRecs in by nesting them in order of loop depth. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2953 | if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 2954 | const Loop *NestedLoop = NestedAR->getLoop(); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2955 | if (L->contains(NestedLoop) |
| 2956 | ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) |
| 2957 | : (!NestedLoop->contains(L) && |
| 2958 | DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2959 | SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 2960 | NestedAR->op_end()); |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2961 | Operands[0] = NestedAR->getStart(); |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2962 | // AddRecs require their operands be loop-invariant with respect to their |
| 2963 | // loops. Don't perform this transformation if it would break this |
| 2964 | // requirement. |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 2965 | bool AllInvariant = all_of( |
| 2966 | Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); |
Sanjoy Das | f07d2a7 | 2015-10-18 00:29:23 +0000 | [diff] [blame] | 2967 | |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2968 | if (AllInvariant) { |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2969 | // Create a recurrence for the outer loop with the same step size. |
| 2970 | // |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2971 | // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the |
| 2972 | // inner recurrence has the same property. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2973 | SCEV::NoWrapFlags OuterFlags = |
| 2974 | maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2975 | |
| 2976 | NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 2977 | AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { |
| 2978 | return isLoopInvariant(Op, NestedLoop); |
| 2979 | }); |
Sanjoy Das | f07d2a7 | 2015-10-18 00:29:23 +0000 | [diff] [blame] | 2980 | |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2981 | if (AllInvariant) { |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2982 | // Ok, both add recurrences are valid after the transformation. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2983 | // |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2984 | // The inner recurrence keeps its NW flag but only keeps NUW/NSW if |
| 2985 | // the outer recurrence has the same property. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2986 | SCEV::NoWrapFlags InnerFlags = |
| 2987 | maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2988 | return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); |
| 2989 | } |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2990 | } |
| 2991 | // Reset Operands to its original state. |
| 2992 | Operands[0] = NestedAR; |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2993 | } |
| 2994 | } |
| 2995 | |
Dan Gohman | 8d67d2f | 2010-01-19 22:27:22 +0000 | [diff] [blame] | 2996 | // Okay, it looks like we really DO need an addrec expr. Check to see if we |
| 2997 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2998 | FoldingSetNodeID ID; |
| 2999 | ID.AddInteger(scAddRecExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3000 | for (unsigned i = 0, e = Operands.size(); i != e; ++i) |
| 3001 | ID.AddPointer(Operands[i]); |
| 3002 | ID.AddPointer(L); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3003 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 3004 | SCEVAddRecExpr *S = |
| 3005 | static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 3006 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 3007 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); |
| 3008 | std::uninitialized_copy(Operands.begin(), Operands.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 3009 | S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), |
| 3010 | O, Operands.size(), L); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 3011 | UniqueSCEVs.InsertNode(S, IP); |
| 3012 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3013 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3014 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3015 | } |
| 3016 | |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 3017 | const SCEV * |
Peter Collingbourne | 8dff039 | 2016-11-13 06:59:50 +0000 | [diff] [blame^] | 3018 | ScalarEvolution::getGEPExpr(GEPOperator *GEP, |
| 3019 | const SmallVectorImpl<const SCEV *> &IndexExprs) { |
| 3020 | const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 3021 | // getSCEV(Base)->getType() has the same address space as Base->getType() |
| 3022 | // because SCEV::getType() preserves the address space. |
| 3023 | Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); |
| 3024 | // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP |
| 3025 | // instruction to its SCEV, because the Instruction may be guarded by control |
| 3026 | // 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] | 3027 | // context. This can be fixed similarly to how these flags are handled for |
| 3028 | // adds. |
Peter Collingbourne | 8dff039 | 2016-11-13 06:59:50 +0000 | [diff] [blame^] | 3029 | SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW |
| 3030 | : SCEV::FlagAnyWrap; |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 3031 | |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 3032 | const SCEV *TotalOffset = getZero(IntPtrTy); |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 3033 | // The address space is unimportant. The first thing we do on CurTy is getting |
| 3034 | // its element type. |
Peter Collingbourne | 8dff039 | 2016-11-13 06:59:50 +0000 | [diff] [blame^] | 3035 | Type *CurTy = PointerType::getUnqual(GEP->getSourceElementType()); |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 3036 | for (const SCEV *IndexExpr : IndexExprs) { |
| 3037 | // Compute the (potentially symbolic) offset in bytes for this index. |
| 3038 | if (StructType *STy = dyn_cast<StructType>(CurTy)) { |
| 3039 | // For a struct, add the member offset. |
| 3040 | ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); |
| 3041 | unsigned FieldNo = Index->getZExtValue(); |
| 3042 | const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); |
| 3043 | |
| 3044 | // Add the field offset to the running total offset. |
| 3045 | TotalOffset = getAddExpr(TotalOffset, FieldOffset); |
| 3046 | |
| 3047 | // Update CurTy to the type of the field at Index. |
| 3048 | CurTy = STy->getTypeAtIndex(Index); |
| 3049 | } else { |
| 3050 | // Update CurTy to its element type. |
| 3051 | CurTy = cast<SequentialType>(CurTy)->getElementType(); |
| 3052 | // For an array, add the element offset, explicitly scaled. |
| 3053 | const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); |
| 3054 | // Getelementptr indices are signed. |
| 3055 | IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); |
| 3056 | |
| 3057 | // Multiply the index by the element size to compute the element offset. |
| 3058 | const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); |
| 3059 | |
| 3060 | // Add the element offset to the running total offset. |
| 3061 | TotalOffset = getAddExpr(TotalOffset, LocalOffset); |
| 3062 | } |
| 3063 | } |
| 3064 | |
| 3065 | // Add the total offset from all the GEP indices to the base. |
| 3066 | return getAddExpr(BaseExpr, TotalOffset, Wrap); |
| 3067 | } |
| 3068 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3069 | const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, |
| 3070 | const SCEV *RHS) { |
Benjamin Kramer | 3bc1edf | 2016-07-02 11:41:39 +0000 | [diff] [blame] | 3071 | SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3072 | return getSMaxExpr(Ops); |
| 3073 | } |
| 3074 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3075 | const SCEV * |
| 3076 | ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3077 | assert(!Ops.empty() && "Cannot get empty smax!"); |
| 3078 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3079 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3080 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3081 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 3082 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3083 | "SCEVSMaxExpr operand types don't match!"); |
| 3084 | #endif |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3085 | |
| 3086 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3087 | GroupByComplexity(Ops, &LI); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3088 | |
| 3089 | // If there are any constants, fold them together. |
| 3090 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3091 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3092 | ++Idx; |
| 3093 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3094 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3095 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 3096 | ConstantInt *Fold = ConstantInt::get( |
| 3097 | getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3098 | Ops[0] = getConstant(Fold); |
| 3099 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 3100 | if (Ops.size() == 1) return Ops[0]; |
| 3101 | LHSC = cast<SCEVConstant>(Ops[0]); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3102 | } |
| 3103 | |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3104 | // If we are left with a constant minimum-int, strip it off. |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3105 | if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { |
| 3106 | Ops.erase(Ops.begin()); |
| 3107 | --Idx; |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3108 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { |
| 3109 | // If we have an smax with a constant maximum-int, it will always be |
| 3110 | // maximum-int. |
| 3111 | return Ops[0]; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3112 | } |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3113 | |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 3114 | if (Ops.size() == 1) return Ops[0]; |
| 3115 | } |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3116 | |
| 3117 | // Find the first SMax |
| 3118 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) |
| 3119 | ++Idx; |
| 3120 | |
| 3121 | // Check to see if one of the operands is an SMax. If so, expand its operands |
| 3122 | // onto our operand list, and recurse to simplify. |
| 3123 | if (Idx < Ops.size()) { |
| 3124 | bool DeletedSMax = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3125 | while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3126 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 3127 | Ops.append(SMax->op_begin(), SMax->op_end()); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3128 | DeletedSMax = true; |
| 3129 | } |
| 3130 | |
| 3131 | if (DeletedSMax) |
| 3132 | return getSMaxExpr(Ops); |
| 3133 | } |
| 3134 | |
| 3135 | // Okay, check to see if the same value occurs in the operand list twice. If |
| 3136 | // so, delete one. Since we sorted the list, these values are required to |
| 3137 | // be adjacent. |
| 3138 | for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) |
Dan Gohman | 7ef0dc2 | 2010-04-13 16:51:03 +0000 | [diff] [blame] | 3139 | // X smax Y smax Y --> X smax Y |
| 3140 | // X smax Y --> X, if X is always greater than Y |
| 3141 | if (Ops[i] == Ops[i+1] || |
| 3142 | isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { |
| 3143 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); |
| 3144 | --i; --e; |
| 3145 | } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3146 | Ops.erase(Ops.begin()+i, Ops.begin()+i+1); |
| 3147 | --i; --e; |
| 3148 | } |
| 3149 | |
| 3150 | if (Ops.size() == 1) return Ops[0]; |
| 3151 | |
| 3152 | assert(!Ops.empty() && "Reduced smax down to nothing!"); |
| 3153 | |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3154 | // 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] | 3155 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3156 | FoldingSetNodeID ID; |
| 3157 | ID.AddInteger(scSMaxExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3158 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 3159 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3160 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3161 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 3162 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 3163 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 3164 | SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), |
| 3165 | O, Ops.size()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3166 | UniqueSCEVs.InsertNode(S, IP); |
| 3167 | return S; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3168 | } |
| 3169 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3170 | const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, |
| 3171 | const SCEV *RHS) { |
Benjamin Kramer | 3bc1edf | 2016-07-02 11:41:39 +0000 | [diff] [blame] | 3172 | SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3173 | return getUMaxExpr(Ops); |
| 3174 | } |
| 3175 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3176 | const SCEV * |
| 3177 | ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3178 | assert(!Ops.empty() && "Cannot get empty umax!"); |
| 3179 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3180 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3181 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3182 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 3183 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3184 | "SCEVUMaxExpr operand types don't match!"); |
| 3185 | #endif |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3186 | |
| 3187 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3188 | GroupByComplexity(Ops, &LI); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3189 | |
| 3190 | // If there are any constants, fold them together. |
| 3191 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3192 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3193 | ++Idx; |
| 3194 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3195 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3196 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 3197 | ConstantInt *Fold = ConstantInt::get( |
| 3198 | getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3199 | Ops[0] = getConstant(Fold); |
| 3200 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 3201 | if (Ops.size() == 1) return Ops[0]; |
| 3202 | LHSC = cast<SCEVConstant>(Ops[0]); |
| 3203 | } |
| 3204 | |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3205 | // If we are left with a constant minimum-int, strip it off. |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3206 | if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { |
| 3207 | Ops.erase(Ops.begin()); |
| 3208 | --Idx; |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3209 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { |
| 3210 | // If we have an umax with a constant maximum-int, it will always be |
| 3211 | // maximum-int. |
| 3212 | return Ops[0]; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3213 | } |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3214 | |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 3215 | if (Ops.size() == 1) return Ops[0]; |
| 3216 | } |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3217 | |
| 3218 | // Find the first UMax |
| 3219 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) |
| 3220 | ++Idx; |
| 3221 | |
| 3222 | // Check to see if one of the operands is a UMax. If so, expand its operands |
| 3223 | // onto our operand list, and recurse to simplify. |
| 3224 | if (Idx < Ops.size()) { |
| 3225 | bool DeletedUMax = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3226 | while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3227 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 3228 | Ops.append(UMax->op_begin(), UMax->op_end()); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3229 | DeletedUMax = true; |
| 3230 | } |
| 3231 | |
| 3232 | if (DeletedUMax) |
| 3233 | return getUMaxExpr(Ops); |
| 3234 | } |
| 3235 | |
| 3236 | // Okay, check to see if the same value occurs in the operand list twice. If |
| 3237 | // so, delete one. Since we sorted the list, these values are required to |
| 3238 | // be adjacent. |
| 3239 | for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) |
Dan Gohman | 7ef0dc2 | 2010-04-13 16:51:03 +0000 | [diff] [blame] | 3240 | // X umax Y umax Y --> X umax Y |
| 3241 | // X umax Y --> X, if X is always greater than Y |
| 3242 | if (Ops[i] == Ops[i+1] || |
| 3243 | isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { |
| 3244 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); |
| 3245 | --i; --e; |
| 3246 | } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3247 | Ops.erase(Ops.begin()+i, Ops.begin()+i+1); |
| 3248 | --i; --e; |
| 3249 | } |
| 3250 | |
| 3251 | if (Ops.size() == 1) return Ops[0]; |
| 3252 | |
| 3253 | assert(!Ops.empty() && "Reduced umax down to nothing!"); |
| 3254 | |
| 3255 | // Okay, it looks like we really DO need a umax expr. Check to see if we |
| 3256 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3257 | FoldingSetNodeID ID; |
| 3258 | ID.AddInteger(scUMaxExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3259 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 3260 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3261 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3262 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 3263 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 3264 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 3265 | SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), |
| 3266 | O, Ops.size()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3267 | UniqueSCEVs.InsertNode(S, IP); |
| 3268 | return S; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3269 | } |
| 3270 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3271 | const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, |
| 3272 | const SCEV *RHS) { |
Dan Gohman | 692b468 | 2009-06-22 03:18:45 +0000 | [diff] [blame] | 3273 | // ~smax(~x, ~y) == smin(x, y). |
| 3274 | return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); |
| 3275 | } |
| 3276 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3277 | const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, |
| 3278 | const SCEV *RHS) { |
Dan Gohman | 692b468 | 2009-06-22 03:18:45 +0000 | [diff] [blame] | 3279 | // ~umax(~x, ~y) == umin(x, y) |
| 3280 | return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); |
| 3281 | } |
| 3282 | |
Matt Arsenault | a90a18e | 2013-09-10 19:55:24 +0000 | [diff] [blame] | 3283 | const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3284 | // We can bypass creating a target-independent |
Dan Gohman | 11862a6 | 2010-04-12 23:03:26 +0000 | [diff] [blame] | 3285 | // constant expression and then folding it back into a ConstantInt. |
| 3286 | // This is just a compile-time optimization. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3287 | return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 3288 | } |
| 3289 | |
Matt Arsenault | a90a18e | 2013-09-10 19:55:24 +0000 | [diff] [blame] | 3290 | const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, |
| 3291 | StructType *STy, |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 3292 | unsigned FieldNo) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3293 | // We can bypass creating a target-independent |
Dan Gohman | 11862a6 | 2010-04-12 23:03:26 +0000 | [diff] [blame] | 3294 | // constant expression and then folding it back into a ConstantInt. |
| 3295 | // This is just a compile-time optimization. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3296 | return getConstant( |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3297 | IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3298 | } |
| 3299 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3300 | const SCEV *ScalarEvolution::getUnknown(Value *V) { |
Dan Gohman | f436bac | 2009-06-24 00:54:57 +0000 | [diff] [blame] | 3301 | // Don't attempt to do anything other than create a SCEVUnknown object |
| 3302 | // here. createSCEV only calls getUnknown after checking for all other |
| 3303 | // interesting possibilities, and any other code that calls getUnknown |
| 3304 | // is doing so in order to hide a value from SCEV canonicalization. |
| 3305 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3306 | FoldingSetNodeID ID; |
| 3307 | ID.AddInteger(scUnknown); |
| 3308 | ID.AddPointer(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3309 | void *IP = nullptr; |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 3310 | if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { |
| 3311 | assert(cast<SCEVUnknown>(S)->getValue() == V && |
| 3312 | "Stale SCEVUnknown in uniquing map!"); |
| 3313 | return S; |
| 3314 | } |
| 3315 | SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, |
| 3316 | FirstUnknown); |
| 3317 | FirstUnknown = cast<SCEVUnknown>(S); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3318 | UniqueSCEVs.InsertNode(S, IP); |
| 3319 | return S; |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 3320 | } |
| 3321 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3322 | //===----------------------------------------------------------------------===// |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3323 | // Basic SCEV Analysis and PHI Idiom Recognition Code |
| 3324 | // |
| 3325 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3326 | /// Test if values of the given type are analyzable within the SCEV |
| 3327 | /// framework. This primarily includes integer types, and it can optionally |
| 3328 | /// include pointer types if the ScalarEvolution class has access to |
| 3329 | /// target-specific information. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3330 | bool ScalarEvolution::isSCEVable(Type *Ty) const { |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3331 | // Integers and pointers are always SCEVable. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3332 | return Ty->isIntegerTy() || Ty->isPointerTy(); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3333 | } |
| 3334 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3335 | /// Return the size in bits of the specified type, for which isSCEVable must |
| 3336 | /// return true. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3337 | uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3338 | assert(isSCEVable(Ty) && "Type is not SCEVable!"); |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3339 | return getDataLayout().getTypeSizeInBits(Ty); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3340 | } |
| 3341 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3342 | /// Return a type with the same bitwidth as the given type and which represents |
| 3343 | /// how SCEV will treat the given type, for which isSCEVable must return |
| 3344 | /// true. For pointer types, this is the pointer-sized integer type. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3345 | Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3346 | assert(isSCEVable(Ty) && "Type is not SCEVable!"); |
| 3347 | |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 3348 | if (Ty->isIntegerTy()) |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3349 | return Ty; |
| 3350 | |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3351 | // The only other support type is pointer. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3352 | assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3353 | return getDataLayout().getIntPtrType(Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3354 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3355 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3356 | const SCEV *ScalarEvolution::getCouldNotCompute() { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3357 | return CouldNotCompute.get(); |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 3358 | } |
| 3359 | |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 3360 | bool ScalarEvolution::checkValidity(const SCEV *S) const { |
Sanjoy Das | 6b46a0d | 2016-11-09 18:22:43 +0000 | [diff] [blame] | 3361 | bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { |
| 3362 | auto *SU = dyn_cast<SCEVUnknown>(S); |
| 3363 | return SU && SU->getValue() == nullptr; |
| 3364 | }); |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3365 | |
Sanjoy Das | 6b46a0d | 2016-11-09 18:22:43 +0000 | [diff] [blame] | 3366 | return !ContainsNulls; |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3367 | } |
| 3368 | |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3369 | bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { |
Sanjoy Das | a260214 | 2016-09-27 18:01:46 +0000 | [diff] [blame] | 3370 | HasRecMapType::iterator I = HasRecMap.find(S); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3371 | if (I != HasRecMap.end()) |
| 3372 | return I->second; |
| 3373 | |
Sanjoy Das | 0ae390a | 2016-11-10 06:33:54 +0000 | [diff] [blame] | 3374 | bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); |
Sanjoy Das | 6b46a0d | 2016-11-09 18:22:43 +0000 | [diff] [blame] | 3375 | HasRecMap.insert({S, FoundAddRec}); |
| 3376 | return FoundAddRec; |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3377 | } |
| 3378 | |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3379 | /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. |
| 3380 | /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an |
| 3381 | /// offset I, then return {S', I}, else return {\p S, nullptr}. |
| 3382 | static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { |
| 3383 | const auto *Add = dyn_cast<SCEVAddExpr>(S); |
| 3384 | if (!Add) |
| 3385 | return {S, nullptr}; |
| 3386 | |
| 3387 | if (Add->getNumOperands() != 2) |
| 3388 | return {S, nullptr}; |
| 3389 | |
| 3390 | auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); |
| 3391 | if (!ConstOp) |
| 3392 | return {S, nullptr}; |
| 3393 | |
| 3394 | return {Add->getOperand(1), ConstOp->getValue()}; |
| 3395 | } |
| 3396 | |
| 3397 | /// Return the ValueOffsetPair set for \p S. \p S can be represented |
| 3398 | /// by the value and offset from any ValueOffsetPair in the set. |
| 3399 | SetVector<ScalarEvolution::ValueOffsetPair> * |
| 3400 | ScalarEvolution::getSCEVValues(const SCEV *S) { |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3401 | ExprValueMapType::iterator SI = ExprValueMap.find_as(S); |
| 3402 | if (SI == ExprValueMap.end()) |
| 3403 | return nullptr; |
| 3404 | #ifndef NDEBUG |
| 3405 | if (VerifySCEVMap) { |
| 3406 | // Check there is no dangling Value in the set returned. |
| 3407 | for (const auto &VE : SI->second) |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3408 | assert(ValueExprMap.count(VE.first)); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3409 | } |
| 3410 | #endif |
| 3411 | return &SI->second; |
| 3412 | } |
| 3413 | |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3414 | /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) |
| 3415 | /// cannot be used separately. eraseValueFromMap should be used to remove |
| 3416 | /// V from ValueExprMap and ExprValueMap at the same time. |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3417 | void ScalarEvolution::eraseValueFromMap(Value *V) { |
| 3418 | ValueExprMapType::iterator I = ValueExprMap.find_as(V); |
| 3419 | if (I != ValueExprMap.end()) { |
| 3420 | const SCEV *S = I->second; |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3421 | // Remove {V, 0} from the set of ExprValueMap[S] |
| 3422 | if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) |
| 3423 | SV->remove({V, nullptr}); |
| 3424 | |
| 3425 | // Remove {V, Offset} from the set of ExprValueMap[Stripped] |
| 3426 | const SCEV *Stripped; |
| 3427 | ConstantInt *Offset; |
| 3428 | std::tie(Stripped, Offset) = splitAddExpr(S); |
| 3429 | if (Offset != nullptr) { |
| 3430 | if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) |
| 3431 | SV->remove({V, Offset}); |
| 3432 | } |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3433 | ValueExprMap.erase(V); |
| 3434 | } |
| 3435 | } |
| 3436 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3437 | /// Return an existing SCEV if it exists, otherwise analyze the expression and |
| 3438 | /// create a new one. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3439 | const SCEV *ScalarEvolution::getSCEV(Value *V) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3440 | assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3441 | |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3442 | const SCEV *S = getExistingSCEV(V); |
| 3443 | if (S == nullptr) { |
| 3444 | S = createSCEV(V); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3445 | // During PHI resolution, it is possible to create two SCEVs for the same |
| 3446 | // V, so it is needed to double check whether V->S is inserted into |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3447 | // ValueExprMap before insert S->{V, 0} into ExprValueMap. |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3448 | std::pair<ValueExprMapType::iterator, bool> Pair = |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 3449 | ValueExprMap.insert({SCEVCallbackVH(V, this), S}); |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3450 | if (Pair.second) { |
| 3451 | ExprValueMap[S].insert({V, nullptr}); |
| 3452 | |
| 3453 | // If S == Stripped + Offset, add Stripped -> {V, Offset} into |
| 3454 | // ExprValueMap. |
| 3455 | const SCEV *Stripped = S; |
| 3456 | ConstantInt *Offset = nullptr; |
| 3457 | std::tie(Stripped, Offset) = splitAddExpr(S); |
| 3458 | // If stripped is SCEVUnknown, don't bother to save |
| 3459 | // Stripped -> {V, offset}. It doesn't simplify and sometimes even |
| 3460 | // increase the complexity of the expansion code. |
| 3461 | // If V is GetElementPtrInst, don't save Stripped -> {V, offset} |
| 3462 | // because it may generate add/sub instead of GEP in SCEV expansion. |
| 3463 | if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && |
| 3464 | !isa<GetElementPtrInst>(V)) |
| 3465 | ExprValueMap[Stripped].insert({V, Offset}); |
| 3466 | } |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3467 | } |
| 3468 | return S; |
| 3469 | } |
| 3470 | |
| 3471 | const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { |
| 3472 | assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); |
| 3473 | |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3474 | ValueExprMapType::iterator I = ValueExprMap.find_as(V); |
| 3475 | if (I != ValueExprMap.end()) { |
| 3476 | const SCEV *S = I->second; |
Shuxin Yang | 23773b3 | 2013-07-12 07:25:38 +0000 | [diff] [blame] | 3477 | if (checkValidity(S)) |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3478 | return S; |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3479 | eraseValueFromMap(V); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3480 | forgetMemoizedResults(S); |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3481 | } |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3482 | return nullptr; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3483 | } |
| 3484 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3485 | /// Return a SCEV corresponding to -V = -1*V |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3486 | /// |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3487 | const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, |
| 3488 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3489 | if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) |
Owen Anderson | 53a5221 | 2009-07-13 04:09:18 +0000 | [diff] [blame] | 3490 | return getConstant( |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 3491 | cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3492 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3493 | Type *Ty = V->getType(); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3494 | Ty = getEffectiveSCEVType(Ty); |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3495 | return getMulExpr( |
| 3496 | V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3497 | } |
| 3498 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3499 | /// Return a SCEV corresponding to ~V = -1-V |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3500 | const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3501 | if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) |
Owen Anderson | 542619e | 2009-07-13 20:58:05 +0000 | [diff] [blame] | 3502 | return getConstant( |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 3503 | cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3504 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3505 | Type *Ty = V->getType(); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3506 | Ty = getEffectiveSCEVType(Ty); |
Owen Anderson | 542619e | 2009-07-13 20:58:05 +0000 | [diff] [blame] | 3507 | const SCEV *AllOnes = |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 3508 | getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3509 | return getMinusSCEV(AllOnes, V); |
| 3510 | } |
| 3511 | |
Chris Lattner | fc87752 | 2011-01-09 22:26:35 +0000 | [diff] [blame] | 3512 | const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3513 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | 46f00a2 | 2010-07-20 16:53:00 +0000 | [diff] [blame] | 3514 | // Fast path: X - X --> 0. |
| 3515 | if (LHS == RHS) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 3516 | return getZero(LHS->getType()); |
Dan Gohman | 46f00a2 | 2010-07-20 16:53:00 +0000 | [diff] [blame] | 3517 | |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3518 | // We represent LHS - RHS as LHS + (-1)*RHS. This transformation |
| 3519 | // makes it so that we cannot make much use of NUW. |
| 3520 | auto AddFlags = SCEV::FlagAnyWrap; |
| 3521 | const bool RHSIsNotMinSigned = |
| 3522 | !getSignedRange(RHS).getSignedMin().isMinSignedValue(); |
| 3523 | if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { |
| 3524 | // Let M be the minimum representable signed value. Then (-1)*RHS |
| 3525 | // signed-wraps if and only if RHS is M. That can happen even for |
| 3526 | // a NSW subtraction because e.g. (-1)*M signed-wraps even though |
| 3527 | // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + |
| 3528 | // (-1)*RHS, we need to prove that RHS != M. |
| 3529 | // |
| 3530 | // If LHS is non-negative and we know that LHS - RHS does not |
| 3531 | // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap |
| 3532 | // either by proving that RHS > M or that LHS >= 0. |
| 3533 | if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { |
| 3534 | AddFlags = SCEV::FlagNSW; |
| 3535 | } |
| 3536 | } |
| 3537 | |
| 3538 | // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - |
| 3539 | // RHS is NSW and LHS >= 0. |
| 3540 | // |
| 3541 | // The difficulty here is that the NSW flag may have been proven |
| 3542 | // relative to a loop that is to be found in a recurrence in LHS and |
| 3543 | // not in RHS. Applying NSW to (-1)*M may then let the NSW have a |
| 3544 | // larger scope than intended. |
| 3545 | auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; |
| 3546 | |
| 3547 | return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3548 | } |
| 3549 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3550 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3551 | ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { |
| 3552 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3553 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3554 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3555 | "Cannot truncate or zero extend with non-integer arguments!"); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3556 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3557 | return V; // No conversion |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3558 | if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3559 | return getTruncateExpr(V, Ty); |
| 3560 | return getZeroExtendExpr(V, Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3561 | } |
| 3562 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3563 | const SCEV * |
| 3564 | ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3565 | Type *Ty) { |
| 3566 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3567 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3568 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3569 | "Cannot truncate or zero extend with non-integer arguments!"); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3570 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3571 | return V; // No conversion |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3572 | if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3573 | return getTruncateExpr(V, Ty); |
| 3574 | return getSignExtendExpr(V, Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3575 | } |
| 3576 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3577 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3578 | ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { |
| 3579 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3580 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3581 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3582 | "Cannot noop or zero extend with non-integer arguments!"); |
| 3583 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3584 | "getNoopOrZeroExtend cannot truncate!"); |
| 3585 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3586 | return V; // No conversion |
| 3587 | return getZeroExtendExpr(V, Ty); |
| 3588 | } |
| 3589 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3590 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3591 | ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { |
| 3592 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3593 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3594 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3595 | "Cannot noop or sign extend with non-integer arguments!"); |
| 3596 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3597 | "getNoopOrSignExtend cannot truncate!"); |
| 3598 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3599 | return V; // No conversion |
| 3600 | return getSignExtendExpr(V, Ty); |
| 3601 | } |
| 3602 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3603 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3604 | ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { |
| 3605 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3606 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3607 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 3608 | "Cannot noop or any extend with non-integer arguments!"); |
| 3609 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3610 | "getNoopOrAnyExtend cannot truncate!"); |
| 3611 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3612 | return V; // No conversion |
| 3613 | return getAnyExtendExpr(V, Ty); |
| 3614 | } |
| 3615 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3616 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3617 | ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { |
| 3618 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3619 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3620 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3621 | "Cannot truncate or noop with non-integer arguments!"); |
| 3622 | assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && |
| 3623 | "getTruncateOrNoop cannot extend!"); |
| 3624 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3625 | return V; // No conversion |
| 3626 | return getTruncateExpr(V, Ty); |
| 3627 | } |
| 3628 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3629 | const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, |
| 3630 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3631 | const SCEV *PromotedLHS = LHS; |
| 3632 | const SCEV *PromotedRHS = RHS; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 3633 | |
| 3634 | if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) |
| 3635 | PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); |
| 3636 | else |
| 3637 | PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); |
| 3638 | |
| 3639 | return getUMaxExpr(PromotedLHS, PromotedRHS); |
| 3640 | } |
| 3641 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3642 | const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, |
| 3643 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3644 | const SCEV *PromotedLHS = LHS; |
| 3645 | const SCEV *PromotedRHS = RHS; |
Dan Gohman | 2bc2230 | 2009-06-22 15:03:27 +0000 | [diff] [blame] | 3646 | |
| 3647 | if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) |
| 3648 | PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); |
| 3649 | else |
| 3650 | PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); |
| 3651 | |
| 3652 | return getUMinExpr(PromotedLHS, PromotedRHS); |
| 3653 | } |
| 3654 | |
Andrew Trick | 87716c9 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 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 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3679 | /// Push users of the given Instruction onto the given Worklist. |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3680 | static void |
| 3681 | PushDefUseChildren(Instruction *I, |
| 3682 | SmallVectorImpl<Instruction *> &Worklist) { |
| 3683 | // Push the def-use children onto the Worklist stack. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3684 | for (User *U : I->users()) |
| 3685 | Worklist.push_back(cast<Instruction>(U)); |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3686 | } |
| 3687 | |
Sanjoy Das | f1e9cae0 | 2016-03-01 19:28:01 +0000 | [diff] [blame] | 3688 | void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3689 | SmallVector<Instruction *, 16> Worklist; |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3690 | PushDefUseChildren(PN, Worklist); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3691 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3692 | SmallPtrSet<Instruction *, 8> Visited; |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3693 | Visited.insert(PN); |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3694 | while (!Worklist.empty()) { |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3695 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3696 | if (!Visited.insert(I).second) |
| 3697 | continue; |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3698 | |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 3699 | auto It = ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3700 | if (It != ValueExprMap.end()) { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 3701 | const SCEV *Old = It->second; |
| 3702 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3703 | // Short-circuit the def-use traversal if the symbolic name |
| 3704 | // ceases to appear in expressions. |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 3705 | if (Old != SymName && !hasOperand(Old, SymName)) |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3706 | continue; |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3707 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3708 | // SCEVUnknown for a PHI either means that it has an unrecognized |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3709 | // structure, it's a PHI that's in the progress of being computed |
| 3710 | // by createNodeForPHI, or it's a single-value PHI. In the first case, |
| 3711 | // additional loop trip count information isn't going to change anything. |
| 3712 | // In the second case, createNodeForPHI will perform the necessary |
| 3713 | // updates on its own when it gets to that point. In the third, we do |
| 3714 | // want to forget the SCEVUnknown. |
| 3715 | if (!isa<PHINode>(I) || |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 3716 | !isa<SCEVUnknown>(Old) || |
| 3717 | (I != PN && Old == SymName)) { |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3718 | eraseValueFromMap(It->first); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 3719 | forgetMemoizedResults(Old); |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 3720 | } |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3721 | } |
| 3722 | |
| 3723 | PushDefUseChildren(I, Worklist); |
| 3724 | } |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3725 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3726 | |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 3727 | namespace { |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3728 | class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { |
| 3729 | public: |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3730 | static const SCEV *rewrite(const SCEV *S, const Loop *L, |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3731 | ScalarEvolution &SE) { |
| 3732 | SCEVInitRewriter Rewriter(L, SE); |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3733 | const SCEV *Result = Rewriter.visit(S); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3734 | return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); |
| 3735 | } |
| 3736 | |
| 3737 | SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) |
| 3738 | : SCEVRewriteVisitor(SE), L(L), Valid(true) {} |
| 3739 | |
| 3740 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { |
| 3741 | if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) |
| 3742 | Valid = false; |
| 3743 | return Expr; |
| 3744 | } |
| 3745 | |
| 3746 | const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { |
| 3747 | // Only allow AddRecExprs for this loop. |
| 3748 | if (Expr->getLoop() == L) |
| 3749 | return Expr->getStart(); |
| 3750 | Valid = false; |
| 3751 | return Expr; |
| 3752 | } |
| 3753 | |
| 3754 | bool isValid() { return Valid; } |
| 3755 | |
| 3756 | private: |
| 3757 | const Loop *L; |
| 3758 | bool Valid; |
| 3759 | }; |
| 3760 | |
| 3761 | class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { |
| 3762 | public: |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3763 | static const SCEV *rewrite(const SCEV *S, const Loop *L, |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3764 | ScalarEvolution &SE) { |
| 3765 | SCEVShiftRewriter Rewriter(L, SE); |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3766 | const SCEV *Result = Rewriter.visit(S); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3767 | return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); |
| 3768 | } |
| 3769 | |
| 3770 | SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) |
| 3771 | : SCEVRewriteVisitor(SE), L(L), Valid(true) {} |
| 3772 | |
| 3773 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { |
| 3774 | // Only allow AddRecExprs for this loop. |
| 3775 | if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) |
| 3776 | Valid = false; |
| 3777 | return Expr; |
| 3778 | } |
| 3779 | |
| 3780 | const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { |
| 3781 | if (Expr->getLoop() == L && Expr->isAffine()) |
| 3782 | return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); |
| 3783 | Valid = false; |
| 3784 | return Expr; |
| 3785 | } |
| 3786 | bool isValid() { return Valid; } |
| 3787 | |
| 3788 | private: |
| 3789 | const Loop *L; |
| 3790 | bool Valid; |
| 3791 | }; |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 3792 | } // end anonymous namespace |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3793 | |
Sanjoy Das | 724f5cf | 2016-03-03 18:31:29 +0000 | [diff] [blame] | 3794 | SCEV::NoWrapFlags |
| 3795 | ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { |
| 3796 | if (!AR->isAffine()) |
| 3797 | return SCEV::FlagAnyWrap; |
| 3798 | |
| 3799 | typedef OverflowingBinaryOperator OBO; |
| 3800 | SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; |
| 3801 | |
| 3802 | if (!AR->hasNoSignedWrap()) { |
| 3803 | ConstantRange AddRecRange = getSignedRange(AR); |
| 3804 | ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); |
| 3805 | |
| 3806 | auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 3807 | Instruction::Add, IncRange, OBO::NoSignedWrap); |
| 3808 | if (NSWRegion.contains(AddRecRange)) |
| 3809 | Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); |
| 3810 | } |
| 3811 | |
| 3812 | if (!AR->hasNoUnsignedWrap()) { |
| 3813 | ConstantRange AddRecRange = getUnsignedRange(AR); |
| 3814 | ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); |
| 3815 | |
| 3816 | auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 3817 | Instruction::Add, IncRange, OBO::NoUnsignedWrap); |
| 3818 | if (NUWRegion.contains(AddRecRange)) |
| 3819 | Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); |
| 3820 | } |
| 3821 | |
| 3822 | return Result; |
| 3823 | } |
| 3824 | |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3825 | namespace { |
| 3826 | /// Represents an abstract binary operation. This may exist as a |
| 3827 | /// normal instruction or constant expression, or may have been |
| 3828 | /// derived from an expression tree. |
| 3829 | struct BinaryOp { |
| 3830 | unsigned Opcode; |
| 3831 | Value *LHS; |
| 3832 | Value *RHS; |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 3833 | bool IsNSW; |
| 3834 | bool IsNUW; |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3835 | |
| 3836 | /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or |
| 3837 | /// constant expression. |
| 3838 | Operator *Op; |
| 3839 | |
| 3840 | explicit BinaryOp(Operator *Op) |
| 3841 | : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 3842 | IsNSW(false), IsNUW(false), Op(Op) { |
| 3843 | if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { |
| 3844 | IsNSW = OBO->hasNoSignedWrap(); |
| 3845 | IsNUW = OBO->hasNoUnsignedWrap(); |
| 3846 | } |
| 3847 | } |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3848 | |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 3849 | explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, |
| 3850 | bool IsNUW = false) |
| 3851 | : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), |
| 3852 | Op(nullptr) {} |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3853 | }; |
| 3854 | } |
| 3855 | |
| 3856 | |
| 3857 | /// Try to map \p V into a BinaryOp, and return \c None on failure. |
Sanjoy Das | f49ca52 | 2016-05-29 00:34:42 +0000 | [diff] [blame] | 3858 | static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3859 | auto *Op = dyn_cast<Operator>(V); |
| 3860 | if (!Op) |
| 3861 | return None; |
| 3862 | |
| 3863 | // Implementation detail: all the cleverness here should happen without |
| 3864 | // creating new SCEV expressions -- our caller knowns tricks to avoid creating |
| 3865 | // SCEV expressions when possible, and we should not break that. |
| 3866 | |
| 3867 | switch (Op->getOpcode()) { |
| 3868 | case Instruction::Add: |
| 3869 | case Instruction::Sub: |
| 3870 | case Instruction::Mul: |
| 3871 | case Instruction::UDiv: |
| 3872 | case Instruction::And: |
| 3873 | case Instruction::Or: |
| 3874 | case Instruction::AShr: |
| 3875 | case Instruction::Shl: |
| 3876 | return BinaryOp(Op); |
| 3877 | |
| 3878 | case Instruction::Xor: |
| 3879 | if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) |
| 3880 | // If the RHS of the xor is a signbit, then this is just an add. |
| 3881 | // Instcombine turns add of signbit into xor as a strength reduction step. |
| 3882 | if (RHSC->getValue().isSignBit()) |
| 3883 | return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); |
| 3884 | return BinaryOp(Op); |
| 3885 | |
| 3886 | case Instruction::LShr: |
| 3887 | // Turn logical shift right of a constant into a unsigned divide. |
| 3888 | if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { |
| 3889 | uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); |
| 3890 | |
| 3891 | // If the shift count is not less than the bitwidth, the result of |
| 3892 | // the shift is undefined. Don't try to analyze it, because the |
| 3893 | // resolution chosen here may differ from the resolution chosen in |
| 3894 | // other parts of the compiler. |
| 3895 | if (SA->getValue().ult(BitWidth)) { |
| 3896 | Constant *X = |
| 3897 | ConstantInt::get(SA->getContext(), |
| 3898 | APInt::getOneBitSet(BitWidth, SA->getZExtValue())); |
| 3899 | return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); |
| 3900 | } |
| 3901 | } |
| 3902 | return BinaryOp(Op); |
| 3903 | |
Sanjoy Das | f49ca52 | 2016-05-29 00:34:42 +0000 | [diff] [blame] | 3904 | case Instruction::ExtractValue: { |
| 3905 | auto *EVI = cast<ExtractValueInst>(Op); |
| 3906 | if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) |
| 3907 | break; |
| 3908 | |
| 3909 | auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); |
| 3910 | if (!CI) |
| 3911 | break; |
| 3912 | |
| 3913 | if (auto *F = CI->getCalledFunction()) |
| 3914 | switch (F->getIntrinsicID()) { |
| 3915 | case Intrinsic::sadd_with_overflow: |
| 3916 | case Intrinsic::uadd_with_overflow: { |
| 3917 | if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) |
| 3918 | return BinaryOp(Instruction::Add, CI->getArgOperand(0), |
| 3919 | CI->getArgOperand(1)); |
| 3920 | |
| 3921 | // Now that we know that all uses of the arithmetic-result component of |
| 3922 | // CI are guarded by the overflow check, we can go ahead and pretend |
| 3923 | // that the arithmetic is non-overflowing. |
| 3924 | if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) |
| 3925 | return BinaryOp(Instruction::Add, CI->getArgOperand(0), |
| 3926 | CI->getArgOperand(1), /* IsNSW = */ true, |
| 3927 | /* IsNUW = */ false); |
| 3928 | else |
| 3929 | return BinaryOp(Instruction::Add, CI->getArgOperand(0), |
| 3930 | CI->getArgOperand(1), /* IsNSW = */ false, |
| 3931 | /* IsNUW*/ true); |
| 3932 | } |
| 3933 | |
| 3934 | case Intrinsic::ssub_with_overflow: |
| 3935 | case Intrinsic::usub_with_overflow: |
| 3936 | return BinaryOp(Instruction::Sub, CI->getArgOperand(0), |
| 3937 | CI->getArgOperand(1)); |
| 3938 | |
| 3939 | case Intrinsic::smul_with_overflow: |
| 3940 | case Intrinsic::umul_with_overflow: |
| 3941 | return BinaryOp(Instruction::Mul, CI->getArgOperand(0), |
| 3942 | CI->getArgOperand(1)); |
| 3943 | default: |
| 3944 | break; |
| 3945 | } |
| 3946 | } |
| 3947 | |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3948 | default: |
| 3949 | break; |
| 3950 | } |
| 3951 | |
| 3952 | return None; |
| 3953 | } |
| 3954 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3955 | const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { |
| 3956 | const Loop *L = LI.getLoopFor(PN->getParent()); |
| 3957 | if (!L || L->getHeader() != PN->getParent()) |
| 3958 | return nullptr; |
| 3959 | |
| 3960 | // The loop may have multiple entrances or multiple exits; we can analyze |
| 3961 | // this phi as an addrec if it has a unique entry value and a unique |
| 3962 | // backedge value. |
| 3963 | Value *BEValueV = nullptr, *StartValueV = nullptr; |
| 3964 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 3965 | Value *V = PN->getIncomingValue(i); |
| 3966 | if (L->contains(PN->getIncomingBlock(i))) { |
| 3967 | if (!BEValueV) { |
| 3968 | BEValueV = V; |
| 3969 | } else if (BEValueV != V) { |
| 3970 | BEValueV = nullptr; |
| 3971 | break; |
| 3972 | } |
| 3973 | } else if (!StartValueV) { |
| 3974 | StartValueV = V; |
| 3975 | } else if (StartValueV != V) { |
| 3976 | StartValueV = nullptr; |
| 3977 | break; |
| 3978 | } |
| 3979 | } |
| 3980 | if (BEValueV && StartValueV) { |
| 3981 | // While we are analyzing this PHI node, handle its value symbolically. |
| 3982 | const SCEV *SymbolicName = getUnknown(PN); |
| 3983 | assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && |
| 3984 | "PHI node already processed?"); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 3985 | ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3986 | |
| 3987 | // Using this symbolic name for the PHI, analyze the value coming around |
| 3988 | // the back-edge. |
| 3989 | const SCEV *BEValue = getSCEV(BEValueV); |
| 3990 | |
| 3991 | // NOTE: If BEValue is loop invariant, we know that the PHI node just |
| 3992 | // has a special value for the first iteration of the loop. |
| 3993 | |
| 3994 | // If the value coming around the backedge is an add with the symbolic |
| 3995 | // value we just inserted, then we found a simple induction variable! |
| 3996 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { |
| 3997 | // If there is a single occurrence of the symbolic value, replace it |
| 3998 | // with a recurrence. |
| 3999 | unsigned FoundIndex = Add->getNumOperands(); |
| 4000 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) |
| 4001 | if (Add->getOperand(i) == SymbolicName) |
| 4002 | if (FoundIndex == e) { |
| 4003 | FoundIndex = i; |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 4004 | break; |
| 4005 | } |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4006 | |
| 4007 | if (FoundIndex != Add->getNumOperands()) { |
| 4008 | // Create an add with everything but the specified operand. |
| 4009 | SmallVector<const SCEV *, 8> Ops; |
| 4010 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) |
| 4011 | if (i != FoundIndex) |
| 4012 | Ops.push_back(Add->getOperand(i)); |
| 4013 | const SCEV *Accum = getAddExpr(Ops); |
| 4014 | |
| 4015 | // This is not a valid addrec if the step amount is varying each |
| 4016 | // loop iteration, but is not itself an addrec in this loop. |
| 4017 | if (isLoopInvariant(Accum, L) || |
| 4018 | (isa<SCEVAddRecExpr>(Accum) && |
| 4019 | cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { |
| 4020 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
| 4021 | |
Sanjoy Das | f49ca52 | 2016-05-29 00:34:42 +0000 | [diff] [blame] | 4022 | if (auto BO = MatchBinaryOp(BEValueV, DT)) { |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 4023 | if (BO->Opcode == Instruction::Add && BO->LHS == PN) { |
| 4024 | if (BO->IsNUW) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4025 | Flags = setFlags(Flags, SCEV::FlagNUW); |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 4026 | if (BO->IsNSW) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4027 | Flags = setFlags(Flags, SCEV::FlagNSW); |
| 4028 | } |
| 4029 | } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { |
| 4030 | // If the increment is an inbounds GEP, then we know the address |
| 4031 | // space cannot be wrapped around. We cannot make any guarantee |
| 4032 | // about signed or unsigned overflow because pointers are |
| 4033 | // unsigned but we may have a negative index from the base |
| 4034 | // pointer. We can guarantee that no unsigned wrap occurs if the |
| 4035 | // indices form a positive value. |
| 4036 | if (GEP->isInBounds() && GEP->getOperand(0) == PN) { |
| 4037 | Flags = setFlags(Flags, SCEV::FlagNW); |
| 4038 | |
| 4039 | const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); |
| 4040 | if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) |
| 4041 | Flags = setFlags(Flags, SCEV::FlagNUW); |
| 4042 | } |
| 4043 | |
| 4044 | // We cannot transfer nuw and nsw flags from subtraction |
| 4045 | // operations -- sub nuw X, Y is not the same as add nuw X, -Y |
| 4046 | // for instance. |
| 4047 | } |
| 4048 | |
| 4049 | const SCEV *StartVal = getSCEV(StartValueV); |
| 4050 | const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); |
| 4051 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4052 | // Okay, for the entire analysis of this edge we assumed the PHI |
| 4053 | // to be symbolic. We now need to go back and purge all of the |
| 4054 | // entries for the scalars that use the symbolic expression. |
Sanjoy Das | f1e9cae0 | 2016-03-01 19:28:01 +0000 | [diff] [blame] | 4055 | forgetSymbolicName(PN, SymbolicName); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4056 | ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4057 | |
| 4058 | // We can add Flags to the post-inc expression only if we |
| 4059 | // know that it us *undefined behavior* for BEValueV to |
| 4060 | // overflow. |
| 4061 | if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) |
| 4062 | if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) |
| 4063 | (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); |
| 4064 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4065 | return PHISCEV; |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 4066 | } |
| 4067 | } |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 4068 | } else { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4069 | // Otherwise, this could be a loop like this: |
| 4070 | // i = 0; for (j = 1; ..; ++j) { .... i = j; } |
| 4071 | // In this case, j = {1,+,1} and BEValue is j. |
| 4072 | // Because the other in-value of i (0) fits the evolution of BEValue |
| 4073 | // i really is an addrec evolution. |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 4074 | // |
| 4075 | // We can generalize this saying that i is the shifted value of BEValue |
| 4076 | // by one iteration: |
| 4077 | // PHI(f(0), f({1,+,1})) --> f({0,+,1}) |
| 4078 | const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); |
| 4079 | const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); |
| 4080 | if (Shifted != getCouldNotCompute() && |
| 4081 | Start != getCouldNotCompute()) { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4082 | const SCEV *StartVal = getSCEV(StartValueV); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 4083 | if (Start == StartVal) { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4084 | // Okay, for the entire analysis of this edge we assumed the PHI |
| 4085 | // to be symbolic. We now need to go back and purge all of the |
| 4086 | // entries for the scalars that use the symbolic expression. |
Sanjoy Das | f1e9cae0 | 2016-03-01 19:28:01 +0000 | [diff] [blame] | 4087 | forgetSymbolicName(PN, SymbolicName); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 4088 | ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; |
| 4089 | return Shifted; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4090 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4091 | } |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 4092 | } |
Tobias Grosser | 934fcf4 | 2016-02-21 18:50:09 +0000 | [diff] [blame] | 4093 | |
| 4094 | // Remove the temporary PHI node SCEV that has been inserted while intending |
| 4095 | // to create an AddRecExpr for this PHI node. We can not keep this temporary |
| 4096 | // as it will prevent later (possibly simpler) SCEV expressions to be added |
| 4097 | // to the ValueExprMap. |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 4098 | eraseValueFromMap(PN); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4099 | } |
| 4100 | |
| 4101 | return nullptr; |
| 4102 | } |
| 4103 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4104 | // Checks if the SCEV S is available at BB. S is considered available at BB |
| 4105 | // if S can be materialized at BB without introducing a fault. |
| 4106 | static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, |
| 4107 | BasicBlock *BB) { |
| 4108 | struct CheckAvailable { |
| 4109 | bool TraversalDone = false; |
| 4110 | bool Available = true; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4111 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4112 | const Loop *L = nullptr; // The loop BB is in (can be nullptr) |
| 4113 | BasicBlock *BB = nullptr; |
| 4114 | DominatorTree &DT; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4115 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4116 | CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) |
| 4117 | : L(L), BB(BB), DT(DT) {} |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4118 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4119 | bool setUnavailable() { |
| 4120 | TraversalDone = true; |
| 4121 | Available = false; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4122 | return false; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4123 | } |
| 4124 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4125 | bool follow(const SCEV *S) { |
| 4126 | switch (S->getSCEVType()) { |
| 4127 | case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: |
| 4128 | case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: |
Sanjoy Das | bb5ffc5 | 2015-10-24 05:37:28 +0000 | [diff] [blame] | 4129 | // These expressions are available if their operand(s) is/are. |
| 4130 | return true; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4131 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4132 | case scAddRecExpr: { |
| 4133 | // We allow add recurrences that are on the loop BB is in, or some |
| 4134 | // outer loop. This guarantees availability because the value of the |
| 4135 | // add recurrence at BB is simply the "current" value of the induction |
| 4136 | // variable. We can relax this in the future; for instance an add |
| 4137 | // recurrence on a sibling dominating loop is also available at BB. |
| 4138 | const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); |
| 4139 | if (L && (ARLoop == L || ARLoop->contains(L))) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4140 | return true; |
| 4141 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4142 | return setUnavailable(); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4143 | } |
| 4144 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4145 | case scUnknown: { |
| 4146 | // For SCEVUnknown, we check for simple dominance. |
| 4147 | const auto *SU = cast<SCEVUnknown>(S); |
| 4148 | Value *V = SU->getValue(); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4149 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4150 | if (isa<Argument>(V)) |
| 4151 | return false; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4152 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4153 | if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) |
| 4154 | return false; |
| 4155 | |
| 4156 | return setUnavailable(); |
| 4157 | } |
| 4158 | |
| 4159 | case scUDivExpr: |
| 4160 | case scCouldNotCompute: |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 4161 | // We do not try to smart about these at all. |
| 4162 | return setUnavailable(); |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4163 | } |
| 4164 | llvm_unreachable("switch should be fully covered!"); |
| 4165 | } |
| 4166 | |
| 4167 | bool isDone() { return TraversalDone; } |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4168 | }; |
| 4169 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4170 | CheckAvailable CA(L, BB, DT); |
| 4171 | SCEVTraversal<CheckAvailable> ST(CA); |
| 4172 | |
| 4173 | ST.visitAll(S); |
| 4174 | return CA.Available; |
| 4175 | } |
| 4176 | |
| 4177 | // Try to match a control flow sequence that branches out at BI and merges back |
| 4178 | // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful |
| 4179 | // match. |
| 4180 | static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, |
| 4181 | Value *&C, Value *&LHS, Value *&RHS) { |
| 4182 | C = BI->getCondition(); |
| 4183 | |
| 4184 | BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); |
| 4185 | BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); |
| 4186 | |
| 4187 | if (!LeftEdge.isSingleEdge()) |
| 4188 | return false; |
| 4189 | |
| 4190 | assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); |
| 4191 | |
| 4192 | Use &LeftUse = Merge->getOperandUse(0); |
| 4193 | Use &RightUse = Merge->getOperandUse(1); |
| 4194 | |
| 4195 | if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { |
| 4196 | LHS = LeftUse; |
| 4197 | RHS = RightUse; |
| 4198 | return true; |
| 4199 | } |
| 4200 | |
| 4201 | if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { |
| 4202 | LHS = RightUse; |
| 4203 | RHS = LeftUse; |
| 4204 | return true; |
| 4205 | } |
| 4206 | |
| 4207 | return false; |
| 4208 | } |
| 4209 | |
| 4210 | const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { |
Sanjoy Das | b0b4e86 | 2016-08-05 18:34:14 +0000 | [diff] [blame] | 4211 | auto IsReachable = |
| 4212 | [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; |
| 4213 | if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4214 | const Loop *L = LI.getLoopFor(PN->getParent()); |
| 4215 | |
Sanjoy Das | 337d478 | 2015-10-31 23:21:40 +0000 | [diff] [blame] | 4216 | // We don't want to break LCSSA, even in a SCEV expression tree. |
| 4217 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
| 4218 | if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) |
| 4219 | return nullptr; |
| 4220 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4221 | // Try to match |
| 4222 | // |
| 4223 | // br %cond, label %left, label %right |
| 4224 | // left: |
| 4225 | // br label %merge |
| 4226 | // right: |
| 4227 | // br label %merge |
| 4228 | // merge: |
| 4229 | // V = phi [ %x, %left ], [ %y, %right ] |
| 4230 | // |
| 4231 | // as "select %cond, %x, %y" |
| 4232 | |
| 4233 | BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); |
| 4234 | assert(IDom && "At least the entry block should dominate PN"); |
| 4235 | |
| 4236 | auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); |
| 4237 | Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; |
| 4238 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4239 | if (BI && BI->isConditional() && |
| 4240 | BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && |
| 4241 | IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && |
| 4242 | IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4243 | return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); |
| 4244 | } |
| 4245 | |
| 4246 | return nullptr; |
| 4247 | } |
| 4248 | |
| 4249 | const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { |
| 4250 | if (const SCEV *S = createAddRecFromPHI(PN)) |
| 4251 | return S; |
| 4252 | |
| 4253 | if (const SCEV *S = createNodeFromSelectLikePHI(PN)) |
| 4254 | return S; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 4255 | |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 4256 | // If the PHI has a single incoming value, follow that value, unless the |
| 4257 | // PHI's incoming blocks are in a different loop, in which case doing so |
| 4258 | // risks breaking LCSSA form. Instcombine would normally zap these, but |
| 4259 | // it doesn't have DominatorTree information, so it may miss cases. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 4260 | if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC)) |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4261 | if (LI.replacementPreservesLCSSAForm(PN, V)) |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 4262 | return getSCEV(V); |
Duncan Sands | 39d77131 | 2010-11-17 20:49:12 +0000 | [diff] [blame] | 4263 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4264 | // 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] | 4265 | return getUnknown(PN); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4266 | } |
| 4267 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4268 | const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, |
| 4269 | Value *Cond, |
| 4270 | Value *TrueVal, |
| 4271 | Value *FalseVal) { |
Mehdi Amini | 044cb34 | 2015-10-07 18:14:25 +0000 | [diff] [blame] | 4272 | // Handle "constant" branch or select. This can occur for instance when a |
| 4273 | // loop pass transforms an inner loop and moves on to process the outer loop. |
| 4274 | if (auto *CI = dyn_cast<ConstantInt>(Cond)) |
| 4275 | return getSCEV(CI->isOne() ? TrueVal : FalseVal); |
| 4276 | |
Sanjoy Das | d067134 | 2015-10-02 19:39:59 +0000 | [diff] [blame] | 4277 | // Try to match some simple smax or umax patterns. |
| 4278 | auto *ICI = dyn_cast<ICmpInst>(Cond); |
| 4279 | if (!ICI) |
| 4280 | return getUnknown(I); |
| 4281 | |
| 4282 | Value *LHS = ICI->getOperand(0); |
| 4283 | Value *RHS = ICI->getOperand(1); |
| 4284 | |
| 4285 | switch (ICI->getPredicate()) { |
| 4286 | case ICmpInst::ICMP_SLT: |
| 4287 | case ICmpInst::ICMP_SLE: |
| 4288 | std::swap(LHS, RHS); |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 4289 | LLVM_FALLTHROUGH; |
Sanjoy Das | d067134 | 2015-10-02 19:39:59 +0000 | [diff] [blame] | 4290 | case ICmpInst::ICMP_SGT: |
| 4291 | case ICmpInst::ICMP_SGE: |
| 4292 | // a >s b ? a+x : b+x -> smax(a, b)+x |
| 4293 | // a >s b ? b+x : a+x -> smin(a, b)+x |
| 4294 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { |
| 4295 | const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); |
| 4296 | const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); |
| 4297 | const SCEV *LA = getSCEV(TrueVal); |
| 4298 | const SCEV *RA = getSCEV(FalseVal); |
| 4299 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4300 | const SCEV *RDiff = getMinusSCEV(RA, RS); |
| 4301 | if (LDiff == RDiff) |
| 4302 | return getAddExpr(getSMaxExpr(LS, RS), LDiff); |
| 4303 | LDiff = getMinusSCEV(LA, RS); |
| 4304 | RDiff = getMinusSCEV(RA, LS); |
| 4305 | if (LDiff == RDiff) |
| 4306 | return getAddExpr(getSMinExpr(LS, RS), LDiff); |
| 4307 | } |
| 4308 | break; |
| 4309 | case ICmpInst::ICMP_ULT: |
| 4310 | case ICmpInst::ICMP_ULE: |
| 4311 | std::swap(LHS, RHS); |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 4312 | LLVM_FALLTHROUGH; |
Sanjoy Das | d067134 | 2015-10-02 19:39:59 +0000 | [diff] [blame] | 4313 | case ICmpInst::ICMP_UGT: |
| 4314 | case ICmpInst::ICMP_UGE: |
| 4315 | // a >u b ? a+x : b+x -> umax(a, b)+x |
| 4316 | // a >u b ? b+x : a+x -> umin(a, b)+x |
| 4317 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { |
| 4318 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); |
| 4319 | const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); |
| 4320 | const SCEV *LA = getSCEV(TrueVal); |
| 4321 | const SCEV *RA = getSCEV(FalseVal); |
| 4322 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4323 | const SCEV *RDiff = getMinusSCEV(RA, RS); |
| 4324 | if (LDiff == RDiff) |
| 4325 | return getAddExpr(getUMaxExpr(LS, RS), LDiff); |
| 4326 | LDiff = getMinusSCEV(LA, RS); |
| 4327 | RDiff = getMinusSCEV(RA, LS); |
| 4328 | if (LDiff == RDiff) |
| 4329 | return getAddExpr(getUMinExpr(LS, RS), LDiff); |
| 4330 | } |
| 4331 | break; |
| 4332 | case ICmpInst::ICMP_NE: |
| 4333 | // n != 0 ? n+x : 1+x -> umax(n, 1)+x |
| 4334 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && |
| 4335 | isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { |
| 4336 | const SCEV *One = getOne(I->getType()); |
| 4337 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); |
| 4338 | const SCEV *LA = getSCEV(TrueVal); |
| 4339 | const SCEV *RA = getSCEV(FalseVal); |
| 4340 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4341 | const SCEV *RDiff = getMinusSCEV(RA, One); |
| 4342 | if (LDiff == RDiff) |
| 4343 | return getAddExpr(getUMaxExpr(One, LS), LDiff); |
| 4344 | } |
| 4345 | break; |
| 4346 | case ICmpInst::ICMP_EQ: |
| 4347 | // n == 0 ? 1+x : n+x -> umax(n, 1)+x |
| 4348 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && |
| 4349 | isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { |
| 4350 | const SCEV *One = getOne(I->getType()); |
| 4351 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); |
| 4352 | const SCEV *LA = getSCEV(TrueVal); |
| 4353 | const SCEV *RA = getSCEV(FalseVal); |
| 4354 | const SCEV *LDiff = getMinusSCEV(LA, One); |
| 4355 | const SCEV *RDiff = getMinusSCEV(RA, LS); |
| 4356 | if (LDiff == RDiff) |
| 4357 | return getAddExpr(getUMaxExpr(One, LS), LDiff); |
| 4358 | } |
| 4359 | break; |
| 4360 | default: |
| 4361 | break; |
| 4362 | } |
| 4363 | |
| 4364 | return getUnknown(I); |
| 4365 | } |
| 4366 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 4367 | /// Expand GEP instructions into add and multiply operations. This allows them |
| 4368 | /// to be analyzed by regular SCEV code. |
Dan Gohman | b256ccf | 2009-12-18 02:09:29 +0000 | [diff] [blame] | 4369 | const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { |
Dan Gohman | 30f24fe | 2009-05-09 00:14:52 +0000 | [diff] [blame] | 4370 | // Don't attempt to analyze GEPs over unsized objects. |
Eduard Burtescu | 19eb031 | 2016-01-19 17:28:00 +0000 | [diff] [blame] | 4371 | if (!GEP->getSourceElementType()->isSized()) |
Dan Gohman | 30f24fe | 2009-05-09 00:14:52 +0000 | [diff] [blame] | 4372 | return getUnknown(GEP); |
Matt Arsenault | 4c26590 | 2013-09-27 22:38:23 +0000 | [diff] [blame] | 4373 | |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 4374 | SmallVector<const SCEV *, 4> IndexExprs; |
| 4375 | for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) |
| 4376 | IndexExprs.push_back(getSCEV(*Index)); |
Peter Collingbourne | 8dff039 | 2016-11-13 06:59:50 +0000 | [diff] [blame^] | 4377 | return getGEPExpr(GEP, IndexExprs); |
Dan Gohman | ee750d1 | 2009-05-08 20:26:55 +0000 | [diff] [blame] | 4378 | } |
| 4379 | |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4380 | uint32_t |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4381 | ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4382 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 4383 | return C->getAPInt().countTrailingZeros(); |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4384 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4385 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4386 | return std::min(GetMinTrailingZeros(T->getOperand()), |
| 4387 | (uint32_t)getTypeSizeInBits(T->getType())); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4388 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4389 | if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4390 | uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); |
| 4391 | return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? |
| 4392 | getTypeSizeInBits(E->getType()) : OpRes; |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4393 | } |
| 4394 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4395 | if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4396 | uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); |
| 4397 | return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? |
| 4398 | getTypeSizeInBits(E->getType()) : OpRes; |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4399 | } |
| 4400 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4401 | if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +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(A->getOperand(0)); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4404 | for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4405 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4406 | return MinOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4407 | } |
| 4408 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4409 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4410 | // The result is the sum of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4411 | uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); |
| 4412 | uint32_t BitWidth = getTypeSizeInBits(M->getType()); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4413 | for (unsigned i = 1, e = M->getNumOperands(); |
| 4414 | SumOpRes != BitWidth && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4415 | SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4416 | BitWidth); |
| 4417 | return SumOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4418 | } |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4419 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4420 | if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4421 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4422 | uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4423 | for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4424 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4425 | return MinOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4426 | } |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4427 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4428 | if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 4429 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4430 | uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 4431 | for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4432 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 4433 | return MinOpRes; |
| 4434 | } |
| 4435 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4436 | if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 4437 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4438 | uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 4439 | for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4440 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 4441 | return MinOpRes; |
| 4442 | } |
| 4443 | |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4444 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { |
| 4445 | // For a SCEVUnknown, ask ValueTracking. |
| 4446 | unsigned BitWidth = getTypeSizeInBits(U->getType()); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4447 | APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 4448 | computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC, |
| 4449 | nullptr, &DT); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4450 | return Zeros.countTrailingOnes(); |
| 4451 | } |
| 4452 | |
| 4453 | // SCEVUDivExpr |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4454 | return 0; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4455 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4456 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 4457 | /// Helper method to assign a range to V from metadata present in the IR. |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 4458 | static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { |
Sanjoy Das | a7e1378 | 2015-10-24 05:37:35 +0000 | [diff] [blame] | 4459 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 4460 | if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) |
| 4461 | return getConstantRangeFromMetadata(*MD); |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 4462 | |
| 4463 | return None; |
| 4464 | } |
| 4465 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 4466 | /// Determine the range for a particular SCEV. If SignHint is |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4467 | /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges |
| 4468 | /// with a "cleaner" unsigned (resp. signed) representation. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4469 | ConstantRange |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4470 | ScalarEvolution::getRange(const SCEV *S, |
| 4471 | ScalarEvolution::RangeSignHint SignHint) { |
| 4472 | DenseMap<const SCEV *, ConstantRange> &Cache = |
| 4473 | SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges |
| 4474 | : SignedRanges; |
| 4475 | |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 4476 | // See if we've computed this range already. |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4477 | DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); |
| 4478 | if (I != Cache.end()) |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 4479 | return I->second; |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4480 | |
| 4481 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 4482 | return setRange(C, SignHint, ConstantRange(C->getAPInt())); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4483 | |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4484 | unsigned BitWidth = getTypeSizeInBits(S->getType()); |
| 4485 | ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); |
| 4486 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4487 | // If the value has known zeros, the maximum value will have those known zeros |
| 4488 | // as well. |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4489 | uint32_t TZ = GetMinTrailingZeros(S); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4490 | if (TZ != 0) { |
| 4491 | if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) |
| 4492 | ConservativeResult = |
| 4493 | ConstantRange(APInt::getMinValue(BitWidth), |
| 4494 | APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); |
| 4495 | else |
| 4496 | ConservativeResult = ConstantRange( |
| 4497 | APInt::getSignedMinValue(BitWidth), |
| 4498 | APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); |
| 4499 | } |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4500 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4501 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4502 | ConstantRange X = getRange(Add->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4503 | for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4504 | X = X.add(getRange(Add->getOperand(i), SignHint)); |
| 4505 | return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4506 | } |
| 4507 | |
| 4508 | if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4509 | ConstantRange X = getRange(Mul->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4510 | for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4511 | X = X.multiply(getRange(Mul->getOperand(i), SignHint)); |
| 4512 | return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4513 | } |
| 4514 | |
| 4515 | if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4516 | ConstantRange X = getRange(SMax->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4517 | for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4518 | X = X.smax(getRange(SMax->getOperand(i), SignHint)); |
| 4519 | return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4520 | } |
| 4521 | |
| 4522 | if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4523 | ConstantRange X = getRange(UMax->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4524 | for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4525 | X = X.umax(getRange(UMax->getOperand(i), SignHint)); |
| 4526 | return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4527 | } |
| 4528 | |
| 4529 | if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4530 | ConstantRange X = getRange(UDiv->getLHS(), SignHint); |
| 4531 | ConstantRange Y = getRange(UDiv->getRHS(), SignHint); |
| 4532 | return setRange(UDiv, SignHint, |
| 4533 | ConservativeResult.intersectWith(X.udiv(Y))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4534 | } |
| 4535 | |
| 4536 | if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4537 | ConstantRange X = getRange(ZExt->getOperand(), SignHint); |
| 4538 | return setRange(ZExt, SignHint, |
| 4539 | ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4540 | } |
| 4541 | |
| 4542 | if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4543 | ConstantRange X = getRange(SExt->getOperand(), SignHint); |
| 4544 | return setRange(SExt, SignHint, |
| 4545 | ConservativeResult.intersectWith(X.signExtend(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4546 | } |
| 4547 | |
| 4548 | if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4549 | ConstantRange X = getRange(Trunc->getOperand(), SignHint); |
| 4550 | return setRange(Trunc, SignHint, |
| 4551 | ConservativeResult.intersectWith(X.truncate(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4552 | } |
| 4553 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4554 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4555 | // If there's no unsigned wrap, the value will never be less than its |
| 4556 | // initial value. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 4557 | if (AddRec->hasNoUnsignedWrap()) |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4558 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 4559 | if (!C->getValue()->isZero()) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 4560 | ConservativeResult = ConservativeResult.intersectWith( |
| 4561 | ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4562 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4563 | // If there's no signed wrap, and all the operands have the same sign or |
| 4564 | // zero, the value won't ever change sign. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 4565 | if (AddRec->hasNoSignedWrap()) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4566 | bool AllNonNeg = true; |
| 4567 | bool AllNonPos = true; |
| 4568 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { |
| 4569 | if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; |
| 4570 | if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; |
| 4571 | } |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4572 | if (AllNonNeg) |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 4573 | ConservativeResult = ConservativeResult.intersectWith( |
| 4574 | ConstantRange(APInt(BitWidth, 0), |
| 4575 | APInt::getSignedMinValue(BitWidth))); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4576 | else if (AllNonPos) |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 4577 | ConservativeResult = ConservativeResult.intersectWith( |
| 4578 | ConstantRange(APInt::getSignedMinValue(BitWidth), |
| 4579 | APInt(BitWidth, 1))); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4580 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4581 | |
| 4582 | // TODO: non-affine addrec |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4583 | if (AddRec->isAffine()) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4584 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4585 | if (!isa<SCEVCouldNotCompute>(MaxBECount) && |
| 4586 | getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { |
Sanjoy Das | b765b63 | 2016-03-02 00:57:39 +0000 | [diff] [blame] | 4587 | auto RangeFromAffine = getRangeForAffineAR( |
| 4588 | AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, |
| 4589 | BitWidth); |
| 4590 | if (!RangeFromAffine.isFullSet()) |
| 4591 | ConservativeResult = |
| 4592 | ConservativeResult.intersectWith(RangeFromAffine); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4593 | |
| 4594 | auto RangeFromFactoring = getRangeViaFactoring( |
| 4595 | AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, |
| 4596 | BitWidth); |
| 4597 | if (!RangeFromFactoring.isFullSet()) |
| 4598 | ConservativeResult = |
| 4599 | ConservativeResult.intersectWith(RangeFromFactoring); |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4600 | } |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4601 | } |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4602 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4603 | return setRange(AddRec, SignHint, ConservativeResult); |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4604 | } |
| 4605 | |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4606 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 4607 | // Check if the IR explicitly contains !range metadata. |
| 4608 | Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); |
| 4609 | if (MDRange.hasValue()) |
| 4610 | ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); |
| 4611 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4612 | // Split here to avoid paying the compile-time cost of calling both |
| 4613 | // computeKnownBits and ComputeNumSignBits. This restriction can be lifted |
| 4614 | // if needed. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 4615 | const DataLayout &DL = getDataLayout(); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4616 | if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { |
| 4617 | // For a SCEVUnknown, ask ValueTracking. |
| 4618 | APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4619 | computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4620 | if (Ones != ~Zeros + 1) |
| 4621 | ConservativeResult = |
| 4622 | ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)); |
| 4623 | } else { |
| 4624 | assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && |
| 4625 | "generalize as needed!"); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4626 | unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4627 | if (NS > 1) |
| 4628 | ConservativeResult = ConservativeResult.intersectWith( |
| 4629 | ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), |
| 4630 | APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4631 | } |
| 4632 | |
| 4633 | return setRange(U, SignHint, ConservativeResult); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4634 | } |
| 4635 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4636 | return setRange(S, SignHint, ConservativeResult); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4637 | } |
| 4638 | |
Sanjoy Das | b765b63 | 2016-03-02 00:57:39 +0000 | [diff] [blame] | 4639 | ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, |
| 4640 | const SCEV *Step, |
| 4641 | const SCEV *MaxBECount, |
| 4642 | unsigned BitWidth) { |
| 4643 | assert(!isa<SCEVCouldNotCompute>(MaxBECount) && |
| 4644 | getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && |
| 4645 | "Precondition!"); |
| 4646 | |
| 4647 | ConstantRange Result(BitWidth, /* isFullSet = */ true); |
| 4648 | |
| 4649 | // Check for overflow. This must be done with ConstantRange arithmetic |
| 4650 | // because we could be called from within the ScalarEvolution overflow |
| 4651 | // checking code. |
| 4652 | |
| 4653 | MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); |
| 4654 | ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); |
| 4655 | ConstantRange ZExtMaxBECountRange = |
| 4656 | MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1); |
| 4657 | |
| 4658 | ConstantRange StepSRange = getSignedRange(Step); |
| 4659 | ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1); |
| 4660 | |
| 4661 | ConstantRange StartURange = getUnsignedRange(Start); |
| 4662 | ConstantRange EndURange = |
| 4663 | StartURange.add(MaxBECountRange.multiply(StepSRange)); |
| 4664 | |
| 4665 | // Check for unsigned overflow. |
| 4666 | ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1); |
| 4667 | ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1); |
| 4668 | if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == |
| 4669 | ZExtEndURange) { |
| 4670 | APInt Min = APIntOps::umin(StartURange.getUnsignedMin(), |
| 4671 | EndURange.getUnsignedMin()); |
| 4672 | APInt Max = APIntOps::umax(StartURange.getUnsignedMax(), |
| 4673 | EndURange.getUnsignedMax()); |
| 4674 | bool IsFullRange = Min.isMinValue() && Max.isMaxValue(); |
| 4675 | if (!IsFullRange) |
| 4676 | Result = |
| 4677 | Result.intersectWith(ConstantRange(Min, Max + 1)); |
| 4678 | } |
| 4679 | |
| 4680 | ConstantRange StartSRange = getSignedRange(Start); |
| 4681 | ConstantRange EndSRange = |
| 4682 | StartSRange.add(MaxBECountRange.multiply(StepSRange)); |
| 4683 | |
| 4684 | // Check for signed overflow. This must be done with ConstantRange |
| 4685 | // arithmetic because we could be called from within the ScalarEvolution |
| 4686 | // overflow checking code. |
| 4687 | ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1); |
| 4688 | ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1); |
| 4689 | if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == |
| 4690 | SExtEndSRange) { |
| 4691 | APInt Min = |
| 4692 | APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin()); |
| 4693 | APInt Max = |
| 4694 | APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax()); |
| 4695 | bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue(); |
| 4696 | if (!IsFullRange) |
| 4697 | Result = |
| 4698 | Result.intersectWith(ConstantRange(Min, Max + 1)); |
| 4699 | } |
| 4700 | |
| 4701 | return Result; |
| 4702 | } |
| 4703 | |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4704 | ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, |
| 4705 | const SCEV *Step, |
| 4706 | const SCEV *MaxBECount, |
| 4707 | unsigned BitWidth) { |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4708 | // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) |
| 4709 | // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) |
| 4710 | |
| 4711 | struct SelectPattern { |
| 4712 | Value *Condition = nullptr; |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4713 | APInt TrueValue; |
| 4714 | APInt FalseValue; |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4715 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4716 | explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, |
| 4717 | const SCEV *S) { |
| 4718 | Optional<unsigned> CastOp; |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4719 | APInt Offset(BitWidth, 0); |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4720 | |
| 4721 | assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && |
| 4722 | "Should be!"); |
| 4723 | |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4724 | // Peel off a constant offset: |
| 4725 | if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { |
| 4726 | // In the future we could consider being smarter here and handle |
| 4727 | // {Start+Step,+,Step} too. |
| 4728 | if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) |
| 4729 | return; |
| 4730 | |
| 4731 | Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); |
| 4732 | S = SA->getOperand(1); |
| 4733 | } |
| 4734 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4735 | // Peel off a cast operation |
| 4736 | if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { |
| 4737 | CastOp = SCast->getSCEVType(); |
| 4738 | S = SCast->getOperand(); |
| 4739 | } |
| 4740 | |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4741 | using namespace llvm::PatternMatch; |
| 4742 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4743 | auto *SU = dyn_cast<SCEVUnknown>(S); |
| 4744 | const APInt *TrueVal, *FalseVal; |
| 4745 | if (!SU || |
| 4746 | !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), |
| 4747 | m_APInt(FalseVal)))) { |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4748 | Condition = nullptr; |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4749 | return; |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4750 | } |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4751 | |
| 4752 | TrueValue = *TrueVal; |
| 4753 | FalseValue = *FalseVal; |
| 4754 | |
| 4755 | // Re-apply the cast we peeled off earlier |
| 4756 | if (CastOp.hasValue()) |
| 4757 | switch (*CastOp) { |
| 4758 | default: |
| 4759 | llvm_unreachable("Unknown SCEV cast type!"); |
| 4760 | |
| 4761 | case scTruncate: |
| 4762 | TrueValue = TrueValue.trunc(BitWidth); |
| 4763 | FalseValue = FalseValue.trunc(BitWidth); |
| 4764 | break; |
| 4765 | case scZeroExtend: |
| 4766 | TrueValue = TrueValue.zext(BitWidth); |
| 4767 | FalseValue = FalseValue.zext(BitWidth); |
| 4768 | break; |
| 4769 | case scSignExtend: |
| 4770 | TrueValue = TrueValue.sext(BitWidth); |
| 4771 | FalseValue = FalseValue.sext(BitWidth); |
| 4772 | break; |
| 4773 | } |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4774 | |
| 4775 | // Re-apply the constant offset we peeled off earlier |
| 4776 | TrueValue += Offset; |
| 4777 | FalseValue += Offset; |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4778 | } |
| 4779 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4780 | bool isRecognized() { return Condition != nullptr; } |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4781 | }; |
| 4782 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4783 | SelectPattern StartPattern(*this, BitWidth, Start); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4784 | if (!StartPattern.isRecognized()) |
| 4785 | return ConstantRange(BitWidth, /* isFullSet = */ true); |
| 4786 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4787 | SelectPattern StepPattern(*this, BitWidth, Step); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4788 | if (!StepPattern.isRecognized()) |
| 4789 | return ConstantRange(BitWidth, /* isFullSet = */ true); |
| 4790 | |
| 4791 | if (StartPattern.Condition != StepPattern.Condition) { |
| 4792 | // We don't handle this case today; but we could, by considering four |
| 4793 | // possibilities below instead of two. I'm not sure if there are cases where |
| 4794 | // that will help over what getRange already does, though. |
| 4795 | return ConstantRange(BitWidth, /* isFullSet = */ true); |
| 4796 | } |
| 4797 | |
| 4798 | // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to |
| 4799 | // construct arbitrary general SCEV expressions here. This function is called |
| 4800 | // from deep in the call stack, and calling getSCEV (on a sext instruction, |
| 4801 | // say) can end up caching a suboptimal value. |
| 4802 | |
Sanjoy Das | 6b017a1 | 2016-03-02 02:56:29 +0000 | [diff] [blame] | 4803 | // FIXME: without the explicit `this` receiver below, MSVC errors out with |
| 4804 | // C2352 and C2512 (otherwise it isn't needed). |
| 4805 | |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4806 | const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4807 | const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4808 | const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4809 | const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); |
Sanjoy Das | 62a1c33 | 2016-03-02 02:15:42 +0000 | [diff] [blame] | 4810 | |
Sanjoy Das | 1168f93 | 2016-03-02 02:34:20 +0000 | [diff] [blame] | 4811 | ConstantRange TrueRange = |
Sanjoy Das | eca1b53 | 2016-03-02 02:44:08 +0000 | [diff] [blame] | 4812 | this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); |
Sanjoy Das | 1168f93 | 2016-03-02 02:34:20 +0000 | [diff] [blame] | 4813 | ConstantRange FalseRange = |
Sanjoy Das | eca1b53 | 2016-03-02 02:44:08 +0000 | [diff] [blame] | 4814 | this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4815 | |
| 4816 | return TrueRange.unionWith(FalseRange); |
| 4817 | } |
| 4818 | |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4819 | SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4820 | if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4821 | const BinaryOperator *BinOp = cast<BinaryOperator>(V); |
| 4822 | |
| 4823 | // Return early if there are no flags to propagate to the SCEV. |
| 4824 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
| 4825 | if (BinOp->hasNoUnsignedWrap()) |
| 4826 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); |
| 4827 | if (BinOp->hasNoSignedWrap()) |
| 4828 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); |
Sanjoy Das | dcd3a88 | 2016-03-02 04:52:22 +0000 | [diff] [blame] | 4829 | if (Flags == SCEV::FlagAnyWrap) |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4830 | return SCEV::FlagAnyWrap; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4831 | |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4832 | return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; |
| 4833 | } |
| 4834 | |
| 4835 | bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { |
| 4836 | // Here we check that I is in the header of the innermost loop containing I, |
| 4837 | // since we only deal with instructions in the loop header. The actual loop we |
| 4838 | // need to check later will come from an add recurrence, but getting that |
| 4839 | // requires computing the SCEV of the operands, which can be expensive. This |
| 4840 | // check we can do cheaply to rule out some cases early. |
| 4841 | Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); |
Sanjoy Das | dcd3a88 | 2016-03-02 04:52:22 +0000 | [diff] [blame] | 4842 | if (InnermostContainingLoop == nullptr || |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4843 | InnermostContainingLoop->getHeader() != I->getParent()) |
| 4844 | return false; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4845 | |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4846 | // Only proceed if we can prove that I does not yield poison. |
| 4847 | if (!isKnownNotFullPoison(I)) return false; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4848 | |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4849 | // At this point we know that if I is executed, then it does not wrap |
| 4850 | // according to at least one of NSW or NUW. If I is not executed, then we do |
| 4851 | // not know if the calculation that I represents would wrap. Multiple |
| 4852 | // 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] | 4853 | // the SCEV, we must guarantee no wrapping for that SCEV also when it is |
| 4854 | // 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] | 4855 | // that guarantee for cases where I is not executed. So we need to find the |
| 4856 | // loop that I is considered in relation to and prove that I is executed for |
| 4857 | // every iteration of that loop. That implies that the value that I |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4858 | // calculates does not wrap anywhere in the loop, so then we can apply the |
| 4859 | // flags to the SCEV. |
| 4860 | // |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4861 | // We check isLoopInvariant to disambiguate in case we are adding recurrences |
| 4862 | // from different loops, so that we know which loop to prove that I is |
| 4863 | // executed in. |
| 4864 | for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { |
Hans Wennborg | 3879035 | 2016-08-17 22:50:18 +0000 | [diff] [blame] | 4865 | // I could be an extractvalue from a call to an overflow intrinsic. |
| 4866 | // TODO: We can do better here in some cases. |
| 4867 | if (!isSCEVable(I->getOperand(OpIndex)->getType())) |
| 4868 | return false; |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4869 | const SCEV *Op = getSCEV(I->getOperand(OpIndex)); |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4870 | if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4871 | bool AllOtherOpsLoopInvariant = true; |
| 4872 | for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); |
| 4873 | ++OtherOpIndex) { |
| 4874 | if (OtherOpIndex != OpIndex) { |
| 4875 | const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); |
| 4876 | if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { |
| 4877 | AllOtherOpsLoopInvariant = false; |
| 4878 | break; |
| 4879 | } |
| 4880 | } |
| 4881 | } |
| 4882 | if (AllOtherOpsLoopInvariant && |
| 4883 | isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) |
| 4884 | return true; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4885 | } |
| 4886 | } |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4887 | return false; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4888 | } |
| 4889 | |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4890 | bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { |
| 4891 | // If we know that \c I can never be poison period, then that's enough. |
| 4892 | if (isSCEVExprNeverPoison(I)) |
| 4893 | return true; |
| 4894 | |
| 4895 | // For an add recurrence specifically, we assume that infinite loops without |
| 4896 | // side effects are undefined behavior, and then reason as follows: |
| 4897 | // |
| 4898 | // If the add recurrence is poison in any iteration, it is poison on all |
| 4899 | // future iterations (since incrementing poison yields poison). If the result |
| 4900 | // of the add recurrence is fed into the loop latch condition and the loop |
| 4901 | // does not contain any throws or exiting blocks other than the latch, we now |
| 4902 | // have the ability to "choose" whether the backedge is taken or not (by |
| 4903 | // choosing a sufficiently evil value for the poison feeding into the branch) |
| 4904 | // for every iteration including and after the one in which \p I first became |
| 4905 | // poison. There are two possibilities (let's call the iteration in which \p |
| 4906 | // I first became poison as K): |
| 4907 | // |
| 4908 | // 1. In the set of iterations including and after K, the loop body executes |
| 4909 | // no side effects. In this case executing the backege an infinte number |
| 4910 | // of times will yield undefined behavior. |
| 4911 | // |
| 4912 | // 2. In the set of iterations including and after K, the loop body executes |
| 4913 | // at least one side effect. In this case, that specific instance of side |
| 4914 | // effect is control dependent on poison, which also yields undefined |
| 4915 | // behavior. |
| 4916 | |
| 4917 | auto *ExitingBB = L->getExitingBlock(); |
| 4918 | auto *LatchBB = L->getLoopLatch(); |
| 4919 | if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) |
| 4920 | return false; |
| 4921 | |
| 4922 | SmallPtrSet<const Instruction *, 16> Pushed; |
Sanjoy Das | a19edc4 | 2016-06-08 17:48:31 +0000 | [diff] [blame] | 4923 | SmallVector<const Instruction *, 8> PoisonStack; |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4924 | |
Sanjoy Das | a19edc4 | 2016-06-08 17:48:31 +0000 | [diff] [blame] | 4925 | // We start by assuming \c I, the post-inc add recurrence, is poison. Only |
| 4926 | // things that are known to be fully poison under that assumption go on the |
| 4927 | // PoisonStack. |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4928 | Pushed.insert(I); |
Sanjoy Das | a19edc4 | 2016-06-08 17:48:31 +0000 | [diff] [blame] | 4929 | PoisonStack.push_back(I); |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4930 | |
| 4931 | bool LatchControlDependentOnPoison = false; |
Sanjoy Das | 2401c98 | 2016-06-08 17:48:46 +0000 | [diff] [blame] | 4932 | while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { |
Sanjoy Das | a19edc4 | 2016-06-08 17:48:31 +0000 | [diff] [blame] | 4933 | const Instruction *Poison = PoisonStack.pop_back_val(); |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4934 | |
Sanjoy Das | a19edc4 | 2016-06-08 17:48:31 +0000 | [diff] [blame] | 4935 | for (auto *PoisonUser : Poison->users()) { |
| 4936 | if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { |
| 4937 | if (Pushed.insert(cast<Instruction>(PoisonUser)).second) |
| 4938 | PoisonStack.push_back(cast<Instruction>(PoisonUser)); |
| 4939 | } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4940 | assert(BI->isConditional() && "Only possibility!"); |
| 4941 | if (BI->getParent() == LatchBB) { |
| 4942 | LatchControlDependentOnPoison = true; |
| 4943 | break; |
| 4944 | } |
| 4945 | } |
| 4946 | } |
| 4947 | } |
| 4948 | |
Sanjoy Das | 97cd7d5 | 2016-06-09 01:13:54 +0000 | [diff] [blame] | 4949 | return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); |
| 4950 | } |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4951 | |
Sanjoy Das | 5603fc0 | 2016-09-26 02:44:07 +0000 | [diff] [blame] | 4952 | ScalarEvolution::LoopProperties |
| 4953 | ScalarEvolution::getLoopProperties(const Loop *L) { |
| 4954 | typedef ScalarEvolution::LoopProperties LoopProperties; |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 4955 | |
Sanjoy Das | 5603fc0 | 2016-09-26 02:44:07 +0000 | [diff] [blame] | 4956 | auto Itr = LoopPropertiesCache.find(L); |
| 4957 | if (Itr == LoopPropertiesCache.end()) { |
| 4958 | auto HasSideEffects = [](Instruction *I) { |
| 4959 | if (auto *SI = dyn_cast<StoreInst>(I)) |
| 4960 | return !SI->isSimple(); |
| 4961 | |
| 4962 | return I->mayHaveSideEffects(); |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 4963 | }; |
| 4964 | |
Sanjoy Das | 5603fc0 | 2016-09-26 02:44:07 +0000 | [diff] [blame] | 4965 | LoopProperties LP = {/* HasNoAbnormalExits */ true, |
| 4966 | /*HasNoSideEffects*/ true}; |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 4967 | |
Sanjoy Das | 5603fc0 | 2016-09-26 02:44:07 +0000 | [diff] [blame] | 4968 | for (auto *BB : L->getBlocks()) |
| 4969 | for (auto &I : *BB) { |
| 4970 | if (!isGuaranteedToTransferExecutionToSuccessor(&I)) |
| 4971 | LP.HasNoAbnormalExits = false; |
| 4972 | if (HasSideEffects(&I)) |
| 4973 | LP.HasNoSideEffects = false; |
| 4974 | if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) |
| 4975 | break; // We're already as pessimistic as we can get. |
| 4976 | } |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 4977 | |
Sanjoy Das | 5603fc0 | 2016-09-26 02:44:07 +0000 | [diff] [blame] | 4978 | auto InsertPair = LoopPropertiesCache.insert({L, LP}); |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4979 | assert(InsertPair.second && "We just checked!"); |
| 4980 | Itr = InsertPair.first; |
| 4981 | } |
| 4982 | |
Sanjoy Das | 97cd7d5 | 2016-06-09 01:13:54 +0000 | [diff] [blame] | 4983 | return Itr->second; |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4984 | } |
| 4985 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4986 | const SCEV *ScalarEvolution::createSCEV(Value *V) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 4987 | if (!isSCEVable(V->getType())) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4988 | return getUnknown(V); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 4989 | |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 4990 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 4991 | // Don't attempt to analyze instructions in blocks that aren't |
| 4992 | // reachable. Such instructions don't matter, and they aren't required |
| 4993 | // to obey basic rules for definitions dominating uses which this |
| 4994 | // analysis depends on. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4995 | if (!DT.isReachableFromEntry(I->getParent())) |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 4996 | return getUnknown(V); |
Sanjoy Das | 260ad4d | 2016-03-29 16:40:39 +0000 | [diff] [blame] | 4997 | } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) |
Dan Gohman | f436bac | 2009-06-24 00:54:57 +0000 | [diff] [blame] | 4998 | return getConstant(CI); |
| 4999 | else if (isa<ConstantPointerNull>(V)) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 5000 | return getZero(V->getType()); |
Dan Gohman | f161e06e | 2009-08-25 17:49:57 +0000 | [diff] [blame] | 5001 | else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) |
Sanjoy Das | 5ce3272 | 2016-04-08 00:48:30 +0000 | [diff] [blame] | 5002 | return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); |
Sanjoy Das | 260ad4d | 2016-03-29 16:40:39 +0000 | [diff] [blame] | 5003 | else if (!isa<ConstantExpr>(V)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5004 | return getUnknown(V); |
Chris Lattner | a3e0bb4 | 2007-04-02 05:41:38 +0000 | [diff] [blame] | 5005 | |
Dan Gohman | 80ca01c | 2009-07-17 20:47:02 +0000 | [diff] [blame] | 5006 | Operator *U = cast<Operator>(V); |
Sanjoy Das | f49ca52 | 2016-05-29 00:34:42 +0000 | [diff] [blame] | 5007 | if (auto BO = MatchBinaryOp(U, DT)) { |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5008 | switch (BO->Opcode) { |
| 5009 | case Instruction::Add: { |
| 5010 | // The simple thing to do would be to just call getSCEV on both operands |
| 5011 | // and call getAddExpr with the result. However if we're looking at a |
| 5012 | // bunch of things all added together, this can be quite inefficient, |
| 5013 | // because it leads to N-1 getAddExpr calls for N ultimate operands. |
| 5014 | // Instead, gather up all the operands and make a single getAddExpr call. |
| 5015 | // LLVM IR canonical form means we need only traverse the left operands. |
| 5016 | SmallVector<const SCEV *, 4> AddOps; |
| 5017 | do { |
| 5018 | if (BO->Op) { |
| 5019 | if (auto *OpSCEV = getExistingSCEV(BO->Op)) { |
| 5020 | AddOps.push_back(OpSCEV); |
| 5021 | break; |
| 5022 | } |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 5023 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5024 | // If a NUW or NSW flag can be applied to the SCEV for this |
| 5025 | // addition, then compute the SCEV for this addition by itself |
| 5026 | // with a separate call to getAddExpr. We need to do that |
| 5027 | // instead of pushing the operands of the addition onto AddOps, |
| 5028 | // since the flags are only known to apply to this particular |
| 5029 | // addition - they may not apply to other additions that can be |
| 5030 | // formed with operands from AddOps. |
| 5031 | const SCEV *RHS = getSCEV(BO->RHS); |
| 5032 | SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); |
| 5033 | if (Flags != SCEV::FlagAnyWrap) { |
| 5034 | const SCEV *LHS = getSCEV(BO->LHS); |
| 5035 | if (BO->Opcode == Instruction::Sub) |
| 5036 | AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); |
| 5037 | else |
| 5038 | AddOps.push_back(getAddExpr(LHS, RHS, Flags)); |
| 5039 | break; |
| 5040 | } |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 5041 | } |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5042 | |
| 5043 | if (BO->Opcode == Instruction::Sub) |
| 5044 | AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); |
| 5045 | else |
| 5046 | AddOps.push_back(getSCEV(BO->RHS)); |
| 5047 | |
Sanjoy Das | f49ca52 | 2016-05-29 00:34:42 +0000 | [diff] [blame] | 5048 | auto NewBO = MatchBinaryOp(BO->LHS, DT); |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5049 | if (!NewBO || (NewBO->Opcode != Instruction::Add && |
| 5050 | NewBO->Opcode != Instruction::Sub)) { |
| 5051 | AddOps.push_back(getSCEV(BO->LHS)); |
| 5052 | break; |
| 5053 | } |
| 5054 | BO = NewBO; |
| 5055 | } while (true); |
| 5056 | |
| 5057 | return getAddExpr(AddOps); |
| 5058 | } |
| 5059 | |
| 5060 | case Instruction::Mul: { |
| 5061 | SmallVector<const SCEV *, 4> MulOps; |
| 5062 | do { |
| 5063 | if (BO->Op) { |
| 5064 | if (auto *OpSCEV = getExistingSCEV(BO->Op)) { |
| 5065 | MulOps.push_back(OpSCEV); |
| 5066 | break; |
| 5067 | } |
| 5068 | |
| 5069 | SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); |
| 5070 | if (Flags != SCEV::FlagAnyWrap) { |
| 5071 | MulOps.push_back( |
| 5072 | getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); |
| 5073 | break; |
| 5074 | } |
| 5075 | } |
| 5076 | |
| 5077 | MulOps.push_back(getSCEV(BO->RHS)); |
Sanjoy Das | f49ca52 | 2016-05-29 00:34:42 +0000 | [diff] [blame] | 5078 | auto NewBO = MatchBinaryOp(BO->LHS, DT); |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5079 | if (!NewBO || NewBO->Opcode != Instruction::Mul) { |
| 5080 | MulOps.push_back(getSCEV(BO->LHS)); |
| 5081 | break; |
| 5082 | } |
NAKAMURA Takumi | 940cd93 | 2016-07-04 01:26:21 +0000 | [diff] [blame] | 5083 | BO = NewBO; |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5084 | } while (true); |
| 5085 | |
| 5086 | return getMulExpr(MulOps); |
| 5087 | } |
| 5088 | case Instruction::UDiv: |
| 5089 | return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); |
| 5090 | case Instruction::Sub: { |
| 5091 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
| 5092 | if (BO->Op) |
| 5093 | Flags = getNoWrapFlagsFromUB(BO->Op); |
| 5094 | return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); |
| 5095 | } |
| 5096 | case Instruction::And: |
| 5097 | // For an expression like x&255 that merely masks off the high bits, |
| 5098 | // use zext(trunc(x)) as the SCEV expression. |
| 5099 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { |
| 5100 | if (CI->isNullValue()) |
| 5101 | return getSCEV(BO->RHS); |
| 5102 | if (CI->isAllOnesValue()) |
| 5103 | return getSCEV(BO->LHS); |
| 5104 | const APInt &A = CI->getValue(); |
| 5105 | |
| 5106 | // Instcombine's ShrinkDemandedConstant may strip bits out of |
| 5107 | // constants, obscuring what would otherwise be a low-bits mask. |
| 5108 | // Use computeKnownBits to compute what ShrinkDemandedConstant |
| 5109 | // knew about to reconstruct a low-bits mask value. |
| 5110 | unsigned LZ = A.countLeadingZeros(); |
| 5111 | unsigned TZ = A.countTrailingZeros(); |
| 5112 | unsigned BitWidth = A.getBitWidth(); |
| 5113 | APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); |
| 5114 | computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(), |
| 5115 | 0, &AC, nullptr, &DT); |
| 5116 | |
| 5117 | APInt EffectiveMask = |
| 5118 | APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); |
| 5119 | if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) { |
| 5120 | const SCEV *MulCount = getConstant(ConstantInt::get( |
| 5121 | getContext(), APInt::getOneBitSet(BitWidth, TZ))); |
| 5122 | return getMulExpr( |
| 5123 | getZeroExtendExpr( |
| 5124 | getTruncateExpr( |
| 5125 | getUDivExactExpr(getSCEV(BO->LHS), MulCount), |
| 5126 | IntegerType::get(getContext(), BitWidth - LZ - TZ)), |
| 5127 | BO->LHS->getType()), |
| 5128 | MulCount); |
| 5129 | } |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 5130 | } |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5131 | break; |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 5132 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5133 | case Instruction::Or: |
| 5134 | // If the RHS of the Or is a constant, we may have something like: |
| 5135 | // X*4+1 which got turned into X*4|1. Handle this as an Add so loop |
| 5136 | // optimizations will transparently handle this case. |
| 5137 | // |
| 5138 | // In order for this transformation to be safe, the LHS must be of the |
| 5139 | // form X*(2^n) and the Or constant must be less than 2^n. |
| 5140 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { |
| 5141 | const SCEV *LHS = getSCEV(BO->LHS); |
| 5142 | const APInt &CIVal = CI->getValue(); |
| 5143 | if (GetMinTrailingZeros(LHS) >= |
| 5144 | (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { |
| 5145 | // Build a plain add SCEV. |
| 5146 | const SCEV *S = getAddExpr(LHS, getSCEV(CI)); |
| 5147 | // If the LHS of the add was an addrec and it has no-wrap flags, |
| 5148 | // transfer the no-wrap flags, since an or won't introduce a wrap. |
| 5149 | if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { |
| 5150 | const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); |
| 5151 | const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( |
| 5152 | OldAR->getNoWrapFlags()); |
| 5153 | } |
| 5154 | return S; |
| 5155 | } |
| 5156 | } |
| 5157 | break; |
Dan Gohman | 6350296e | 2009-05-18 16:29:04 +0000 | [diff] [blame] | 5158 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5159 | case Instruction::Xor: |
| 5160 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { |
| 5161 | // If the RHS of xor is -1, then this is a not operation. |
| 5162 | if (CI->isAllOnesValue()) |
| 5163 | return getNotSCEV(getSCEV(BO->LHS)); |
Dan Gohman | eddf771 | 2009-06-18 00:00:20 +0000 | [diff] [blame] | 5164 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5165 | // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. |
| 5166 | // This is a variant of the check for xor with -1, and it handles |
| 5167 | // the case where instcombine has trimmed non-demanded bits out |
| 5168 | // of an xor with -1. |
| 5169 | if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) |
| 5170 | if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) |
| 5171 | if (LBO->getOpcode() == Instruction::And && |
| 5172 | LCI->getValue() == CI->getValue()) |
| 5173 | if (const SCEVZeroExtendExpr *Z = |
| 5174 | dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { |
| 5175 | Type *UTy = BO->LHS->getType(); |
| 5176 | const SCEV *Z0 = Z->getOperand(); |
| 5177 | Type *Z0Ty = Z0->getType(); |
| 5178 | unsigned Z0TySize = getTypeSizeInBits(Z0Ty); |
Dan Gohman | eddf771 | 2009-06-18 00:00:20 +0000 | [diff] [blame] | 5179 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5180 | // If C is a low-bits mask, the zero extend is serving to |
| 5181 | // mask off the high bits. Complement the operand and |
| 5182 | // re-apply the zext. |
| 5183 | if (APIntOps::isMask(Z0TySize, CI->getValue())) |
| 5184 | return getZeroExtendExpr(getNotSCEV(Z0), UTy); |
| 5185 | |
| 5186 | // If C is a single bit, it may be in the sign-bit position |
| 5187 | // before the zero-extend. In this case, represent the xor |
| 5188 | // using an add, which is equivalent, and re-apply the zext. |
| 5189 | APInt Trunc = CI->getValue().trunc(Z0TySize); |
| 5190 | if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && |
| 5191 | Trunc.isSignBit()) |
| 5192 | return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), |
| 5193 | UTy); |
| 5194 | } |
| 5195 | } |
| 5196 | break; |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5197 | |
| 5198 | case Instruction::Shl: |
| 5199 | // Turn shift left of a constant amount into a multiply. |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5200 | if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { |
| 5201 | uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 5202 | |
| 5203 | // If the shift count is not less than the bitwidth, the result of |
| 5204 | // the shift is undefined. Don't try to analyze it, because the |
| 5205 | // resolution chosen here may differ from the resolution chosen in |
| 5206 | // other parts of the compiler. |
| 5207 | if (SA->getValue().uge(BitWidth)) |
| 5208 | break; |
| 5209 | |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 5210 | // It is currently not resolved how to interpret NSW for left |
| 5211 | // shift by BitWidth - 1, so we avoid applying flags in that |
| 5212 | // case. Remove this check (or this comment) once the situation |
| 5213 | // is resolved. See |
| 5214 | // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html |
| 5215 | // and http://reviews.llvm.org/D8890 . |
| 5216 | auto Flags = SCEV::FlagAnyWrap; |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5217 | if (BO->Op && SA->getValue().ult(BitWidth - 1)) |
| 5218 | Flags = getNoWrapFlagsFromUB(BO->Op); |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 5219 | |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 5220 | Constant *X = ConstantInt::get(getContext(), |
Benjamin Kramer | fc3ea6f | 2013-07-11 16:05:50 +0000 | [diff] [blame] | 5221 | APInt::getOneBitSet(BitWidth, SA->getZExtValue())); |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5222 | return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5223 | } |
| 5224 | break; |
| 5225 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5226 | case Instruction::AShr: |
| 5227 | // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. |
| 5228 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) |
| 5229 | if (Operator *L = dyn_cast<Operator>(BO->LHS)) |
| 5230 | if (L->getOpcode() == Instruction::Shl && |
| 5231 | L->getOperand(1) == BO->RHS) { |
| 5232 | uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType()); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 5233 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5234 | // If the shift count is not less than the bitwidth, the result of |
| 5235 | // the shift is undefined. Don't try to analyze it, because the |
| 5236 | // resolution chosen here may differ from the resolution chosen in |
| 5237 | // other parts of the compiler. |
| 5238 | if (CI->getValue().uge(BitWidth)) |
| 5239 | break; |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 5240 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5241 | uint64_t Amt = BitWidth - CI->getZExtValue(); |
| 5242 | if (Amt == BitWidth) |
| 5243 | return getSCEV(L->getOperand(0)); // shift by zero --> noop |
| 5244 | return getSignExtendExpr( |
| 5245 | getTruncateExpr(getSCEV(L->getOperand(0)), |
| 5246 | IntegerType::get(getContext(), Amt)), |
| 5247 | BO->LHS->getType()); |
| 5248 | } |
| 5249 | break; |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 5250 | } |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5251 | } |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 5252 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5253 | switch (U->getOpcode()) { |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5254 | case Instruction::Trunc: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5255 | return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5256 | |
| 5257 | case Instruction::ZExt: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5258 | return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5259 | |
| 5260 | case Instruction::SExt: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5261 | return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5262 | |
| 5263 | case Instruction::BitCast: |
| 5264 | // BitCasts are no-op casts so we just eliminate the cast. |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 5265 | if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5266 | return getSCEV(U->getOperand(0)); |
| 5267 | break; |
| 5268 | |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 5269 | // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can |
| 5270 | // lead to pointer expressions which cannot safely be expanded to GEPs, |
| 5271 | // because ScalarEvolution doesn't respect the GEP aliasing rules when |
| 5272 | // simplifying integer expressions. |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 5273 | |
Dan Gohman | ee750d1 | 2009-05-08 20:26:55 +0000 | [diff] [blame] | 5274 | case Instruction::GetElementPtr: |
Dan Gohman | b256ccf | 2009-12-18 02:09:29 +0000 | [diff] [blame] | 5275 | return createNodeForGEP(cast<GEPOperator>(U)); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 5276 | |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5277 | case Instruction::PHI: |
| 5278 | return createNodeForPHI(cast<PHINode>(U)); |
| 5279 | |
| 5280 | case Instruction::Select: |
Sanjoy Das | d067134 | 2015-10-02 19:39:59 +0000 | [diff] [blame] | 5281 | // U can also be a select constant expr, which let fall through. Since |
| 5282 | // createNodeForSelect only works for a condition that is an `ICmpInst`, and |
| 5283 | // constant expressions cannot have instructions as operands, we'd have |
| 5284 | // returned getUnknown for a select constant expressions anyway. |
| 5285 | if (isa<Instruction>(U)) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 5286 | return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), |
| 5287 | U->getOperand(1), U->getOperand(2)); |
Hal Finkel | e186deb | 2016-07-11 02:48:23 +0000 | [diff] [blame] | 5288 | break; |
| 5289 | |
| 5290 | case Instruction::Call: |
| 5291 | case Instruction::Invoke: |
| 5292 | if (Value *RV = CallSite(U).getReturnedArgOperand()) |
| 5293 | return getSCEV(RV); |
| 5294 | break; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5295 | } |
| 5296 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5297 | return getUnknown(V); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5298 | } |
| 5299 | |
| 5300 | |
| 5301 | |
| 5302 | //===----------------------------------------------------------------------===// |
| 5303 | // Iteration Count Computation Code |
| 5304 | // |
| 5305 | |
Haicheng Wu | 1ef17e9 | 2016-10-12 21:29:38 +0000 | [diff] [blame] | 5306 | static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { |
| 5307 | if (!ExitCount) |
| 5308 | return 0; |
| 5309 | |
| 5310 | ConstantInt *ExitConst = ExitCount->getValue(); |
| 5311 | |
| 5312 | // Guard against huge trip counts. |
| 5313 | if (ExitConst->getValue().getActiveBits() > 32) |
| 5314 | return 0; |
| 5315 | |
| 5316 | // In case of integer overflow, this returns 0, which is correct. |
| 5317 | return ((unsigned)ExitConst->getZExtValue()) + 1; |
| 5318 | } |
| 5319 | |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5320 | unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) { |
| 5321 | if (BasicBlock *ExitingBB = L->getExitingBlock()) |
| 5322 | return getSmallConstantTripCount(L, ExitingBB); |
| 5323 | |
| 5324 | // No trip count information for multiple exits. |
| 5325 | return 0; |
| 5326 | } |
| 5327 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5328 | unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L, |
| 5329 | BasicBlock *ExitingBlock) { |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5330 | assert(ExitingBlock && "Must pass a non-null exiting block!"); |
| 5331 | assert(L->isLoopExiting(ExitingBlock) && |
| 5332 | "Exiting block must actually branch out of the loop!"); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5333 | const SCEVConstant *ExitCount = |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5334 | dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); |
Haicheng Wu | 1ef17e9 | 2016-10-12 21:29:38 +0000 | [diff] [blame] | 5335 | return getConstantTripCount(ExitCount); |
| 5336 | } |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5337 | |
Haicheng Wu | 1ef17e9 | 2016-10-12 21:29:38 +0000 | [diff] [blame] | 5338 | unsigned ScalarEvolution::getSmallConstantMaxTripCount(Loop *L) { |
| 5339 | const auto *MaxExitCount = |
| 5340 | dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L)); |
| 5341 | return getConstantTripCount(MaxExitCount); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5342 | } |
| 5343 | |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5344 | unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) { |
| 5345 | if (BasicBlock *ExitingBB = L->getExitingBlock()) |
| 5346 | return getSmallConstantTripMultiple(L, ExitingBB); |
| 5347 | |
| 5348 | // No trip multiple information for multiple exits. |
| 5349 | return 0; |
| 5350 | } |
| 5351 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5352 | /// Returns the largest constant divisor of the trip count of this loop as a |
| 5353 | /// normal unsigned value, if possible. This means that the actual trip count is |
| 5354 | /// always a multiple of the returned value (don't forget the trip count could |
| 5355 | /// very well be zero as well!). |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5356 | /// |
| 5357 | /// Returns 1 if the trip count is unknown or not guaranteed to be the |
| 5358 | /// multiple of a constant (which is also the case if the trip count is simply |
| 5359 | /// constant, use getSmallConstantTripCount for that case), Will also return 1 |
| 5360 | /// if the trip count is very large (>= 2^32). |
Andrew Trick | e81211f | 2012-01-11 06:52:55 +0000 | [diff] [blame] | 5361 | /// |
| 5362 | /// As explained in the comments for getSmallConstantTripCount, this assumes |
| 5363 | /// that control exits the loop via ExitingBlock. |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5364 | unsigned |
| 5365 | ScalarEvolution::getSmallConstantTripMultiple(Loop *L, |
| 5366 | BasicBlock *ExitingBlock) { |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5367 | assert(ExitingBlock && "Must pass a non-null exiting block!"); |
| 5368 | assert(L->isLoopExiting(ExitingBlock) && |
| 5369 | "Exiting block must actually branch out of the loop!"); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5370 | const SCEV *ExitCount = getExitCount(L, ExitingBlock); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5371 | if (ExitCount == getCouldNotCompute()) |
| 5372 | return 1; |
| 5373 | |
| 5374 | // Get the trip count from the BE count by adding 1. |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 5375 | const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType())); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5376 | // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt |
| 5377 | // to factor simple cases. |
| 5378 | if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul)) |
| 5379 | TCMul = Mul->getOperand(0); |
| 5380 | |
| 5381 | const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul); |
| 5382 | if (!MulC) |
| 5383 | return 1; |
| 5384 | |
| 5385 | ConstantInt *Result = MulC->getValue(); |
| 5386 | |
Hal Finkel | 30bd934 | 2012-10-24 19:46:44 +0000 | [diff] [blame] | 5387 | // Guard against huge trip counts (this requires checking |
| 5388 | // for zero to handle the case where the trip count == -1 and the |
| 5389 | // addition wraps). |
| 5390 | if (!Result || Result->getValue().getActiveBits() > 32 || |
| 5391 | Result->getValue().getActiveBits() == 0) |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5392 | return 1; |
| 5393 | |
| 5394 | return (unsigned)Result->getZExtValue(); |
| 5395 | } |
| 5396 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5397 | /// Get the expression for the number of loop iterations for which this loop is |
| 5398 | /// guaranteed not to exit via ExitingBlock. Otherwise return |
| 5399 | /// SCEVCouldNotCompute. |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5400 | const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) { |
| 5401 | return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5402 | } |
| 5403 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5404 | const SCEV * |
| 5405 | ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, |
| 5406 | SCEVUnionPredicate &Preds) { |
| 5407 | return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); |
| 5408 | } |
| 5409 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5410 | const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5411 | return getBackedgeTakenInfo(L).getExact(this); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5412 | } |
| 5413 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5414 | /// Similar to getBackedgeTakenCount, except return the least SCEV value that is |
| 5415 | /// known never to be less than the actual backedge taken count. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5416 | const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5417 | return getBackedgeTakenInfo(L).getMax(this); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5418 | } |
| 5419 | |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5420 | bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { |
| 5421 | return getBackedgeTakenInfo(L).isMaxOrZero(this); |
| 5422 | } |
| 5423 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5424 | /// Push PHI nodes in the header of the given loop onto the given Worklist. |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5425 | static void |
| 5426 | PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { |
| 5427 | BasicBlock *Header = L->getHeader(); |
| 5428 | |
| 5429 | // Push all Loop-header PHIs onto the Worklist stack. |
| 5430 | for (BasicBlock::iterator I = Header->begin(); |
| 5431 | PHINode *PN = dyn_cast<PHINode>(I); ++I) |
| 5432 | Worklist.push_back(PN); |
| 5433 | } |
| 5434 | |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5435 | const ScalarEvolution::BackedgeTakenInfo & |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5436 | ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { |
| 5437 | auto &BTI = getBackedgeTakenInfo(L); |
| 5438 | if (BTI.hasFullInfo()) |
| 5439 | return BTI; |
| 5440 | |
| 5441 | auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); |
| 5442 | |
| 5443 | if (!Pair.second) |
| 5444 | return Pair.first->second; |
| 5445 | |
| 5446 | BackedgeTakenInfo Result = |
| 5447 | computeBackedgeTakenCount(L, /*AllowPredicates=*/true); |
| 5448 | |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5449 | return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5450 | } |
| 5451 | |
| 5452 | const ScalarEvolution::BackedgeTakenInfo & |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5453 | ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5454 | // Initially insert an invalid entry for this loop. If the insertion |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 5455 | // succeeds, proceed to actually compute a backedge-taken count and |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 5456 | // update the value. The temporary CouldNotCompute value tells SCEV |
| 5457 | // code elsewhere that it shouldn't attempt to request a new |
| 5458 | // backedge-taken count, which could result in infinite recursion. |
Dan Gohman | 0daf687 | 2011-05-09 18:44:09 +0000 | [diff] [blame] | 5459 | std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 5460 | BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5461 | if (!Pair.second) |
| 5462 | return Pair.first->second; |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 5463 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5464 | // computeBackedgeTakenCount may allocate memory for its result. Inserting it |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5465 | // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result |
| 5466 | // must be cleared in this scope. |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5467 | BackedgeTakenInfo Result = computeBackedgeTakenCount(L); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5468 | |
| 5469 | if (Result.getExact(this) != getCouldNotCompute()) { |
| 5470 | assert(isLoopInvariant(Result.getExact(this), L) && |
| 5471 | isLoopInvariant(Result.getMax(this), L) && |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5472 | "Computed backedge-taken count isn't loop invariant for loop!"); |
| 5473 | ++NumTripCountsComputed; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5474 | } |
| 5475 | else if (Result.getMax(this) == getCouldNotCompute() && |
| 5476 | isa<PHINode>(L->getHeader()->begin())) { |
| 5477 | // Only count loops that have phi nodes as not being computable. |
| 5478 | ++NumTripCountsNotComputed; |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5479 | } |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5480 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5481 | // Now that we know more about the trip count for this loop, forget any |
| 5482 | // existing SCEV values for PHI nodes in this loop since they are only |
| 5483 | // conservative estimates made without the benefit of trip count |
| 5484 | // information. This is similar to the code in forgetLoop, except that |
| 5485 | // it handles SCEVUnknown PHI nodes specially. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5486 | if (Result.hasAnyInfo()) { |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5487 | SmallVector<Instruction *, 16> Worklist; |
| 5488 | PushLoopPHIs(L, Worklist); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5489 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5490 | SmallPtrSet<Instruction *, 8> Visited; |
| 5491 | while (!Worklist.empty()) { |
| 5492 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5493 | if (!Visited.insert(I).second) |
| 5494 | continue; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5495 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5496 | ValueExprMapType::iterator It = |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 5497 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5498 | if (It != ValueExprMap.end()) { |
| 5499 | const SCEV *Old = It->second; |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 5500 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5501 | // SCEVUnknown for a PHI either means that it has an unrecognized |
| 5502 | // structure, or it's a PHI that's in the progress of being computed |
| 5503 | // by createNodeForPHI. In the former case, additional loop trip |
| 5504 | // count information isn't going to change anything. In the later |
| 5505 | // case, createNodeForPHI will perform the necessary updates on its |
| 5506 | // own when it gets to that point. |
| 5507 | if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 5508 | eraseValueFromMap(It->first); |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5509 | forgetMemoizedResults(Old); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5510 | } |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5511 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5512 | ConstantEvolutionLoopExitValue.erase(PN); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5513 | } |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5514 | |
| 5515 | PushDefUseChildren(I, Worklist); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5516 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5517 | } |
Dan Gohman | 6acd95b | 2011-04-25 22:48:29 +0000 | [diff] [blame] | 5518 | |
| 5519 | // Re-lookup the insert position, since the call to |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5520 | // computeBackedgeTakenCount above could result in a |
Dan Gohman | 6acd95b | 2011-04-25 22:48:29 +0000 | [diff] [blame] | 5521 | // recusive call to getBackedgeTakenInfo (on a different |
| 5522 | // loop), which would invalidate the iterator computed |
| 5523 | // earlier. |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5524 | return BackedgeTakenCounts.find(L)->second = std::move(Result); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5525 | } |
| 5526 | |
Dan Gohman | 880c92a | 2009-10-31 15:04:55 +0000 | [diff] [blame] | 5527 | void ScalarEvolution::forgetLoop(const Loop *L) { |
| 5528 | // Drop any stored trip count value. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5529 | auto RemoveLoopFromBackedgeMap = |
| 5530 | [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { |
| 5531 | auto BTCPos = Map.find(L); |
| 5532 | if (BTCPos != Map.end()) { |
| 5533 | BTCPos->second.clear(); |
| 5534 | Map.erase(BTCPos); |
| 5535 | } |
| 5536 | }; |
| 5537 | |
| 5538 | RemoveLoopFromBackedgeMap(BackedgeTakenCounts); |
| 5539 | RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts); |
Dan Gohman | f150572 | 2009-05-02 17:43:35 +0000 | [diff] [blame] | 5540 | |
Dan Gohman | 880c92a | 2009-10-31 15:04:55 +0000 | [diff] [blame] | 5541 | // Drop information about expressions based on loop-header PHIs. |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5542 | SmallVector<Instruction *, 16> Worklist; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5543 | PushLoopPHIs(L, Worklist); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5544 | |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5545 | SmallPtrSet<Instruction *, 8> Visited; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5546 | while (!Worklist.empty()) { |
| 5547 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5548 | if (!Visited.insert(I).second) |
| 5549 | continue; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5550 | |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 5551 | ValueExprMapType::iterator It = |
| 5552 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 5553 | if (It != ValueExprMap.end()) { |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 5554 | eraseValueFromMap(It->first); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 5555 | forgetMemoizedResults(It->second); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5556 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5557 | ConstantEvolutionLoopExitValue.erase(PN); |
| 5558 | } |
| 5559 | |
| 5560 | PushDefUseChildren(I, Worklist); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5561 | } |
Dan Gohman | dcb354b | 2010-10-29 20:16:10 +0000 | [diff] [blame] | 5562 | |
| 5563 | // Forget all contained loops too, to avoid dangling entries in the |
| 5564 | // ValuesAtScopes map. |
Benjamin Kramer | aa20915 | 2016-06-26 17:27:42 +0000 | [diff] [blame] | 5565 | for (Loop *I : *L) |
| 5566 | forgetLoop(I); |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 5567 | |
Sanjoy Das | 5603fc0 | 2016-09-26 02:44:07 +0000 | [diff] [blame] | 5568 | LoopPropertiesCache.erase(L); |
Dan Gohman | 4330034 | 2009-02-17 20:49:49 +0000 | [diff] [blame] | 5569 | } |
| 5570 | |
Eric Christopher | ef6d593 | 2010-07-29 01:25:38 +0000 | [diff] [blame] | 5571 | void ScalarEvolution::forgetValue(Value *V) { |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 5572 | Instruction *I = dyn_cast<Instruction>(V); |
| 5573 | if (!I) return; |
| 5574 | |
| 5575 | // Drop information about expressions based on loop-header PHIs. |
| 5576 | SmallVector<Instruction *, 16> Worklist; |
| 5577 | Worklist.push_back(I); |
| 5578 | |
| 5579 | SmallPtrSet<Instruction *, 8> Visited; |
| 5580 | while (!Worklist.empty()) { |
| 5581 | I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5582 | if (!Visited.insert(I).second) |
| 5583 | continue; |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 5584 | |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 5585 | ValueExprMapType::iterator It = |
| 5586 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 5587 | if (It != ValueExprMap.end()) { |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 5588 | eraseValueFromMap(It->first); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 5589 | forgetMemoizedResults(It->second); |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 5590 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5591 | ConstantEvolutionLoopExitValue.erase(PN); |
| 5592 | } |
| 5593 | |
| 5594 | PushDefUseChildren(I, Worklist); |
| 5595 | } |
| 5596 | } |
| 5597 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5598 | /// Get the exact loop backedge taken count considering all loop exits. A |
| 5599 | /// computable result can only be returned for loops with a single exit. |
| 5600 | /// Returning the minimum taken count among all exits is incorrect because one |
| 5601 | /// of the loop's exit limit's may have been skipped. howFarToZero assumes that |
| 5602 | /// the limit of each loop test is never skipped. This is a valid assumption as |
| 5603 | /// long as the loop exits via that test. For precise results, it is the |
| 5604 | /// caller's responsibility to specify the relevant loop exit using |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5605 | /// getExact(ExitingBlock, SE). |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5606 | const SCEV * |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5607 | ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, |
| 5608 | SCEVUnionPredicate *Preds) const { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5609 | // If any exits were not computable, the loop is not computable. |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5610 | if (!isComplete() || ExitNotTaken.empty()) |
| 5611 | return SE->getCouldNotCompute(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5612 | |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5613 | const SCEV *BECount = nullptr; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5614 | for (auto &ENT : ExitNotTaken) { |
| 5615 | assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5616 | |
| 5617 | if (!BECount) |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5618 | BECount = ENT.ExactNotTaken; |
| 5619 | else if (BECount != ENT.ExactNotTaken) |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5620 | return SE->getCouldNotCompute(); |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5621 | if (Preds && !ENT.hasAlwaysTruePredicate()) |
| 5622 | Preds->add(ENT.Predicate.get()); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5623 | |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5624 | assert((Preds || ENT.hasAlwaysTruePredicate()) && |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5625 | "Predicate should be always true!"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5626 | } |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5627 | |
Andrew Trick | bbb226a | 2011-09-02 21:20:46 +0000 | [diff] [blame] | 5628 | assert(BECount && "Invalid not taken count for loop exit"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5629 | return BECount; |
| 5630 | } |
| 5631 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5632 | /// Get the exact not taken count for this loop exit. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5633 | const SCEV * |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5634 | ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5635 | ScalarEvolution *SE) const { |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5636 | for (auto &ENT : ExitNotTaken) |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5637 | if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5638 | return ENT.ExactNotTaken; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5639 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5640 | return SE->getCouldNotCompute(); |
| 5641 | } |
| 5642 | |
| 5643 | /// getMax - Get the max backedge taken count for the loop. |
| 5644 | const SCEV * |
| 5645 | ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { |
Sanjoy Das | 7326861 | 2016-09-26 01:10:22 +0000 | [diff] [blame] | 5646 | auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { |
| 5647 | return !ENT.hasAlwaysTruePredicate(); |
| 5648 | }; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5649 | |
Sanjoy Das | 7326861 | 2016-09-26 01:10:22 +0000 | [diff] [blame] | 5650 | if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) |
| 5651 | return SE->getCouldNotCompute(); |
| 5652 | |
| 5653 | return getMax(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5654 | } |
| 5655 | |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5656 | bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { |
| 5657 | auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { |
| 5658 | return !ENT.hasAlwaysTruePredicate(); |
| 5659 | }; |
| 5660 | return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); |
| 5661 | } |
| 5662 | |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 5663 | bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, |
| 5664 | ScalarEvolution *SE) const { |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5665 | if (getMax() && getMax() != SE->getCouldNotCompute() && |
| 5666 | SE->hasOperand(getMax(), S)) |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 5667 | return true; |
| 5668 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5669 | for (auto &ENT : ExitNotTaken) |
| 5670 | if (ENT.ExactNotTaken != SE->getCouldNotCompute() && |
| 5671 | SE->hasOperand(ENT.ExactNotTaken, S)) |
Silviu Baranga | a393baf | 2016-04-06 14:06:32 +0000 | [diff] [blame] | 5672 | return true; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5673 | |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 5674 | return false; |
| 5675 | } |
| 5676 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5677 | /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each |
| 5678 | /// computable exit into a persistent ExitNotTakenInfo array. |
| 5679 | ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( |
Sanjoy Das | 5c4869b | 2016-09-26 01:10:27 +0000 | [diff] [blame] | 5680 | SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> |
| 5681 | &&ExitCounts, |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5682 | bool Complete, const SCEV *MaxCount, bool MaxOrZero) |
| 5683 | : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { |
Sanjoy Das | 6b76cdf | 2016-09-26 01:10:25 +0000 | [diff] [blame] | 5684 | typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; |
Sanjoy Das | e935c77 | 2016-09-25 23:12:08 +0000 | [diff] [blame] | 5685 | ExitNotTaken.reserve(ExitCounts.size()); |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5686 | std::transform( |
| 5687 | ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), |
Sanjoy Das | 6b76cdf | 2016-09-26 01:10:25 +0000 | [diff] [blame] | 5688 | [&](const EdgeExitInfo &EEI) { |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5689 | BasicBlock *ExitBB = EEI.first; |
| 5690 | const ExitLimit &EL = EEI.second; |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 5691 | if (EL.Predicates.empty()) |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5692 | return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 5693 | |
| 5694 | std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); |
| 5695 | for (auto *Pred : EL.Predicates) |
| 5696 | Predicate->add(Pred); |
| 5697 | |
| 5698 | return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate)); |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5699 | }); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5700 | } |
| 5701 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5702 | /// Invalidate this result and free the ExitNotTakenInfo array. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5703 | void ScalarEvolution::BackedgeTakenInfo::clear() { |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5704 | ExitNotTaken.clear(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5705 | } |
| 5706 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5707 | /// Compute the number of times the backedge of the specified loop will execute. |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5708 | ScalarEvolution::BackedgeTakenInfo |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5709 | ScalarEvolution::computeBackedgeTakenCount(const Loop *L, |
| 5710 | bool AllowPredicates) { |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 5711 | SmallVector<BasicBlock *, 8> ExitingBlocks; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5712 | L->getExitingBlocks(ExitingBlocks); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5713 | |
Sanjoy Das | 6b76cdf | 2016-09-26 01:10:25 +0000 | [diff] [blame] | 5714 | typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; |
| 5715 | |
| 5716 | SmallVector<EdgeExitInfo, 4> ExitCounts; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5717 | bool CouldComputeBECount = true; |
Andrew Trick | ee5aa7f | 2014-01-15 06:42:11 +0000 | [diff] [blame] | 5718 | BasicBlock *Latch = L->getLoopLatch(); // may be NULL. |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5719 | const SCEV *MustExitMaxBECount = nullptr; |
| 5720 | const SCEV *MayExitMaxBECount = nullptr; |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5721 | bool MustExitMaxOrZero = false; |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5722 | |
| 5723 | // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts |
| 5724 | // and compute maxBECount. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5725 | // Do a union of all the predicates here. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5726 | for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5727 | BasicBlock *ExitBB = ExitingBlocks[i]; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5728 | ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); |
| 5729 | |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 5730 | assert((AllowPredicates || EL.Predicates.empty()) && |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5731 | "Predicated exit limit when predicates are not allowed!"); |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5732 | |
| 5733 | // 1. For each exit that can be computed, add an entry to ExitCounts. |
| 5734 | // CouldComputeBECount is true only if all exits can be computed. |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5735 | if (EL.ExactNotTaken == getCouldNotCompute()) |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5736 | // We couldn't compute an exact value for this exit, so |
Dan Gohman | 8885b37 | 2009-06-22 21:10:22 +0000 | [diff] [blame] | 5737 | // 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] | 5738 | CouldComputeBECount = false; |
| 5739 | else |
Sanjoy Das | bdd9710 | 2016-09-25 23:11:55 +0000 | [diff] [blame] | 5740 | ExitCounts.emplace_back(ExitBB, EL); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5741 | |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5742 | // 2. Derive the loop's MaxBECount from each exit's max number of |
| 5743 | // non-exiting iterations. Partition the loop exits into two kinds: |
| 5744 | // LoopMustExits and LoopMayExits. |
| 5745 | // |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5746 | // If the exit dominates the loop latch, it is a LoopMustExit otherwise it |
| 5747 | // is a LoopMayExit. If any computable LoopMustExit is found, then |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5748 | // MaxBECount is the minimum EL.MaxNotTaken of computable |
| 5749 | // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum |
| 5750 | // EL.MaxNotTaken, where CouldNotCompute is considered greater than any |
| 5751 | // computable EL.MaxNotTaken. |
| 5752 | if (EL.MaxNotTaken != getCouldNotCompute() && Latch && |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 5753 | DT.dominates(ExitBB, Latch)) { |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5754 | if (!MustExitMaxBECount) { |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5755 | MustExitMaxBECount = EL.MaxNotTaken; |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5756 | MustExitMaxOrZero = EL.MaxOrZero; |
| 5757 | } else { |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5758 | MustExitMaxBECount = |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5759 | getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); |
Andrew Trick | e255359 | 2014-05-22 00:37:03 +0000 | [diff] [blame] | 5760 | } |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5761 | } else if (MayExitMaxBECount != getCouldNotCompute()) { |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5762 | if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) |
| 5763 | MayExitMaxBECount = EL.MaxNotTaken; |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5764 | else { |
| 5765 | MayExitMaxBECount = |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5766 | getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5767 | } |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5768 | } |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5769 | } |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5770 | const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : |
| 5771 | (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5772 | // The loop backedge will be taken the maximum or zero times if there's |
| 5773 | // a single exit that must be taken the maximum or zero times. |
| 5774 | bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); |
Sanjoy Das | 5c4869b | 2016-09-26 01:10:27 +0000 | [diff] [blame] | 5775 | return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5776 | MaxBECount, MaxOrZero); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5777 | } |
| 5778 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5779 | ScalarEvolution::ExitLimit |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5780 | ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, |
| 5781 | bool AllowPredicates) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5782 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5783 | // Okay, we've chosen an exiting block. See what condition causes us to exit |
| 5784 | // 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] | 5785 | // lead to the loop header. |
| 5786 | bool MustExecuteLoopHeader = true; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5787 | BasicBlock *Exit = nullptr; |
Sanjoy Das | 0ff0787 | 2016-01-19 20:53:46 +0000 | [diff] [blame] | 5788 | for (auto *SBB : successors(ExitingBlock)) |
| 5789 | if (!L->contains(SBB)) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5790 | if (Exit) // Multiple exit successors. |
| 5791 | return getCouldNotCompute(); |
Sanjoy Das | 0ff0787 | 2016-01-19 20:53:46 +0000 | [diff] [blame] | 5792 | Exit = SBB; |
| 5793 | } else if (SBB != L->getHeader()) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5794 | MustExecuteLoopHeader = false; |
| 5795 | } |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 5796 | |
Chris Lattner | 1895485 | 2007-01-07 02:24:26 +0000 | [diff] [blame] | 5797 | // At this point, we know we have a conditional branch that determines whether |
| 5798 | // the loop is exited. However, we don't know if the branch is executed each |
| 5799 | // time through the loop. If not, then the execution count of the branch will |
| 5800 | // not be equal to the trip count of the loop. |
| 5801 | // |
| 5802 | // Currently we check for this by checking to see if the Exit branch goes to |
| 5803 | // 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] | 5804 | // 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] | 5805 | // loop header. This is common for un-rotated loops. |
| 5806 | // |
| 5807 | // If both of those tests fail, walk up the unique predecessor chain to the |
| 5808 | // header, stopping if there is an edge that doesn't exit the loop. If the |
| 5809 | // header is reached, the execution count of the branch will be equal to the |
| 5810 | // trip count of the loop. |
| 5811 | // |
| 5812 | // More extensive analysis could be done to handle more cases here. |
| 5813 | // |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5814 | if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5815 | // The simple checks failed, try climbing the unique predecessor chain |
| 5816 | // up to the header. |
| 5817 | bool Ok = false; |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5818 | for (BasicBlock *BB = ExitingBlock; BB; ) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5819 | BasicBlock *Pred = BB->getUniquePredecessor(); |
| 5820 | if (!Pred) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5821 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5822 | TerminatorInst *PredTerm = Pred->getTerminator(); |
Pete Cooper | ebcd748 | 2015-08-06 20:22:46 +0000 | [diff] [blame] | 5823 | for (const BasicBlock *PredSucc : PredTerm->successors()) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5824 | if (PredSucc == BB) |
| 5825 | continue; |
| 5826 | // If the predecessor has a successor that isn't BB and isn't |
| 5827 | // outside the loop, assume the worst. |
| 5828 | if (L->contains(PredSucc)) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5829 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5830 | } |
| 5831 | if (Pred == L->getHeader()) { |
| 5832 | Ok = true; |
| 5833 | break; |
| 5834 | } |
| 5835 | BB = Pred; |
| 5836 | } |
| 5837 | if (!Ok) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5838 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5839 | } |
| 5840 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5841 | bool IsOnlyExit = (L->getExitingBlock() != nullptr); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5842 | TerminatorInst *Term = ExitingBlock->getTerminator(); |
| 5843 | if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { |
| 5844 | assert(BI->isConditional() && "If unconditional, it can't be in loop!"); |
| 5845 | // Proceed to the next level to examine the exit condition expression. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5846 | return computeExitLimitFromCond( |
| 5847 | L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), |
| 5848 | /*ControlsExit=*/IsOnlyExit, AllowPredicates); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5849 | } |
| 5850 | |
| 5851 | if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5852 | return computeExitLimitFromSingleExitSwitch(L, SI, Exit, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5853 | /*ControlsExit=*/IsOnlyExit); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5854 | |
| 5855 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5856 | } |
| 5857 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5858 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5859 | ScalarEvolution::computeExitLimitFromCond(const Loop *L, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5860 | Value *ExitCond, |
| 5861 | BasicBlock *TBB, |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5862 | BasicBlock *FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5863 | bool ControlsExit, |
| 5864 | bool AllowPredicates) { |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 5865 | // 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] | 5866 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { |
| 5867 | if (BO->getOpcode() == Instruction::And) { |
| 5868 | // Recurse on the operands of the and. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5869 | bool EitherMayExit = L->contains(TBB); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5870 | ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5871 | ControlsExit && !EitherMayExit, |
| 5872 | AllowPredicates); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5873 | ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5874 | ControlsExit && !EitherMayExit, |
| 5875 | AllowPredicates); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5876 | const SCEV *BECount = getCouldNotCompute(); |
| 5877 | const SCEV *MaxBECount = getCouldNotCompute(); |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5878 | if (EitherMayExit) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5879 | // Both conditions must be true for the loop to continue executing. |
| 5880 | // Choose the less conservative count. |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5881 | if (EL0.ExactNotTaken == getCouldNotCompute() || |
| 5882 | EL1.ExactNotTaken == getCouldNotCompute()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5883 | BECount = getCouldNotCompute(); |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5884 | else |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5885 | BECount = |
| 5886 | getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); |
| 5887 | if (EL0.MaxNotTaken == getCouldNotCompute()) |
| 5888 | MaxBECount = EL1.MaxNotTaken; |
| 5889 | else if (EL1.MaxNotTaken == getCouldNotCompute()) |
| 5890 | MaxBECount = EL0.MaxNotTaken; |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5891 | else |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5892 | MaxBECount = |
| 5893 | getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5894 | } else { |
Dan Gohman | f7495f2 | 2010-08-11 00:12:36 +0000 | [diff] [blame] | 5895 | // Both conditions must be true at the same time for the loop to exit. |
| 5896 | // For now, be conservative. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5897 | assert(L->contains(FBB) && "Loop block has no successor in loop!"); |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5898 | if (EL0.MaxNotTaken == EL1.MaxNotTaken) |
| 5899 | MaxBECount = EL0.MaxNotTaken; |
| 5900 | if (EL0.ExactNotTaken == EL1.ExactNotTaken) |
| 5901 | BECount = EL0.ExactNotTaken; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5902 | } |
| 5903 | |
Sanjoy Das | 29a4b5d | 2016-01-19 20:53:51 +0000 | [diff] [blame] | 5904 | // There are cases (e.g. PR26207) where computeExitLimitFromCond is able |
| 5905 | // to be more aggressive when computing BECount than when computing |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5906 | // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and |
| 5907 | // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken |
| 5908 | // to not. |
Sanjoy Das | 29a4b5d | 2016-01-19 20:53:51 +0000 | [diff] [blame] | 5909 | if (isa<SCEVCouldNotCompute>(MaxBECount) && |
| 5910 | !isa<SCEVCouldNotCompute>(BECount)) |
| 5911 | MaxBECount = BECount; |
| 5912 | |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5913 | return ExitLimit(BECount, MaxBECount, false, |
| 5914 | {&EL0.Predicates, &EL1.Predicates}); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5915 | } |
| 5916 | if (BO->getOpcode() == Instruction::Or) { |
| 5917 | // Recurse on the operands of the or. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5918 | bool EitherMayExit = L->contains(FBB); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5919 | ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5920 | ControlsExit && !EitherMayExit, |
| 5921 | AllowPredicates); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5922 | ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5923 | ControlsExit && !EitherMayExit, |
| 5924 | AllowPredicates); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5925 | const SCEV *BECount = getCouldNotCompute(); |
| 5926 | const SCEV *MaxBECount = getCouldNotCompute(); |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5927 | if (EitherMayExit) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5928 | // Both conditions must be false for the loop to continue executing. |
| 5929 | // Choose the less conservative count. |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5930 | if (EL0.ExactNotTaken == getCouldNotCompute() || |
| 5931 | EL1.ExactNotTaken == getCouldNotCompute()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5932 | BECount = getCouldNotCompute(); |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5933 | else |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5934 | BECount = |
| 5935 | getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); |
| 5936 | if (EL0.MaxNotTaken == getCouldNotCompute()) |
| 5937 | MaxBECount = EL1.MaxNotTaken; |
| 5938 | else if (EL1.MaxNotTaken == getCouldNotCompute()) |
| 5939 | MaxBECount = EL0.MaxNotTaken; |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5940 | else |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5941 | MaxBECount = |
| 5942 | getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5943 | } else { |
Dan Gohman | f7495f2 | 2010-08-11 00:12:36 +0000 | [diff] [blame] | 5944 | // Both conditions must be false at the same time for the loop to exit. |
| 5945 | // For now, be conservative. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5946 | assert(L->contains(TBB) && "Loop block has no successor in loop!"); |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5947 | if (EL0.MaxNotTaken == EL1.MaxNotTaken) |
| 5948 | MaxBECount = EL0.MaxNotTaken; |
| 5949 | if (EL0.ExactNotTaken == EL1.ExactNotTaken) |
| 5950 | BECount = EL0.ExactNotTaken; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5951 | } |
| 5952 | |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 5953 | return ExitLimit(BECount, MaxBECount, false, |
| 5954 | {&EL0.Predicates, &EL1.Predicates}); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5955 | } |
| 5956 | } |
| 5957 | |
| 5958 | // 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] | 5959 | // Proceed to the next level to examine the icmp. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5960 | if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { |
| 5961 | ExitLimit EL = |
| 5962 | computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); |
| 5963 | if (EL.hasFullInfo() || !AllowPredicates) |
| 5964 | return EL; |
| 5965 | |
| 5966 | // Try again, but use SCEV predicates this time. |
| 5967 | return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, |
| 5968 | /*AllowPredicates=*/true); |
| 5969 | } |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5970 | |
Dan Gohman | 6b1e2a8 | 2010-02-19 18:12:07 +0000 | [diff] [blame] | 5971 | // Check for a constant condition. These are normally stripped out by |
| 5972 | // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to |
| 5973 | // preserve the CFG and is temporarily leaving constant conditions |
| 5974 | // in place. |
| 5975 | if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { |
| 5976 | if (L->contains(FBB) == !CI->getZExtValue()) |
| 5977 | // The backedge is always taken. |
| 5978 | return getCouldNotCompute(); |
| 5979 | else |
| 5980 | // The backedge is never taken. |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 5981 | return getZero(CI->getType()); |
Dan Gohman | 6b1e2a8 | 2010-02-19 18:12:07 +0000 | [diff] [blame] | 5982 | } |
| 5983 | |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 5984 | // 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] | 5985 | return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5986 | } |
| 5987 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5988 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5989 | ScalarEvolution::computeExitLimitFromICmp(const Loop *L, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5990 | ICmpInst *ExitCond, |
| 5991 | BasicBlock *TBB, |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5992 | BasicBlock *FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5993 | bool ControlsExit, |
| 5994 | bool AllowPredicates) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5995 | |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5996 | // If the condition was exit on true, convert the condition to exit on false |
| 5997 | ICmpInst::Predicate Cond; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5998 | if (!L->contains(FBB)) |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5999 | Cond = ExitCond->getPredicate(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6000 | else |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6001 | Cond = ExitCond->getInversePredicate(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6002 | |
| 6003 | // Handle common loops like: for (X = "string"; *X; ++X) |
| 6004 | if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) |
| 6005 | if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6006 | ExitLimit ItCnt = |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 6007 | computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); |
Dan Gohman | ba82034 | 2010-02-24 17:31:30 +0000 | [diff] [blame] | 6008 | if (ItCnt.hasAnyInfo()) |
| 6009 | return ItCnt; |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6010 | } |
| 6011 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6012 | const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); |
| 6013 | const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6014 | |
| 6015 | // Try to evaluate any dependencies out of the loop. |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 6016 | LHS = getSCEVAtScope(LHS, L); |
| 6017 | RHS = getSCEVAtScope(RHS, L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6018 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6019 | // 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] | 6020 | // loop the predicate will return true for these inputs. |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 6021 | if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { |
Dan Gohman | dc5f5cb | 2008-09-16 18:52:57 +0000 | [diff] [blame] | 6022 | // If there is a loop-invariant, force it into the RHS. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6023 | std::swap(LHS, RHS); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6024 | Cond = ICmpInst::getSwappedPredicate(Cond); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6025 | } |
| 6026 | |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 6027 | // Simplify the operands before analyzing them. |
| 6028 | (void)SimplifyICmpOperands(Cond, LHS, RHS); |
| 6029 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6030 | // If we have a comparison of a chrec against a constant, try to use value |
| 6031 | // ranges to answer this query. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6032 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) |
| 6033 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6034 | if (AddRec->getLoop() == L) { |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 6035 | // Form the constant range. |
Sanjoy Das | 1f7b813 | 2016-10-02 00:09:57 +0000 | [diff] [blame] | 6036 | ConstantRange CompRange = |
| 6037 | ConstantRange::makeExactICmpRegion(Cond, RHSC->getAPInt()); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6038 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6039 | const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 6040 | if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6041 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6042 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6043 | switch (Cond) { |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6044 | case ICmpInst::ICMP_NE: { // while (X != Y) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6045 | // Convert to: while (X-Y != 0) |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 6046 | ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 6047 | AllowPredicates); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6048 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6049 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6050 | } |
Dan Gohman | 8a8ad7d | 2009-08-20 16:42:55 +0000 | [diff] [blame] | 6051 | case ICmpInst::ICMP_EQ: { // while (X == Y) |
| 6052 | // Convert to: while (X-Y == 0) |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 6053 | ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6054 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6055 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6056 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 6057 | case ICmpInst::ICMP_SLT: |
| 6058 | case ICmpInst::ICMP_ULT: { // while (X < Y) |
| 6059 | bool IsSigned = Cond == ICmpInst::ICMP_SLT; |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 6060 | ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 6061 | AllowPredicates); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6062 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 6063 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6064 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 6065 | case ICmpInst::ICMP_SGT: |
| 6066 | case ICmpInst::ICMP_UGT: { // while (X > Y) |
| 6067 | bool IsSigned = Cond == ICmpInst::ICMP_SGT; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 6068 | ExitLimit EL = |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 6069 | howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 6070 | AllowPredicates); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6071 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 6072 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6073 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6074 | default: |
Chris Lattner | 0defaa1 | 2004-04-03 00:43:03 +0000 | [diff] [blame] | 6075 | break; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6076 | } |
Sanjoy Das | 0da2d14 | 2016-06-30 02:47:28 +0000 | [diff] [blame] | 6077 | |
| 6078 | auto *ExhaustiveCount = |
| 6079 | computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); |
| 6080 | |
| 6081 | if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) |
| 6082 | return ExhaustiveCount; |
| 6083 | |
| 6084 | return computeShiftCompareExitLimit(ExitCond->getOperand(0), |
| 6085 | ExitCond->getOperand(1), L, Cond); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6086 | } |
| 6087 | |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 6088 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 6089 | ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 6090 | SwitchInst *Switch, |
| 6091 | BasicBlock *ExitingBlock, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 6092 | bool ControlsExit) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 6093 | assert(!L->contains(ExitingBlock) && "Not an exiting block!"); |
| 6094 | |
| 6095 | // Give up if the exit is the default dest of a switch. |
| 6096 | if (Switch->getDefaultDest() == ExitingBlock) |
| 6097 | return getCouldNotCompute(); |
| 6098 | |
| 6099 | assert(L->contains(Switch->getDefaultDest()) && |
| 6100 | "Default case must not exit the loop!"); |
| 6101 | const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); |
| 6102 | const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); |
| 6103 | |
| 6104 | // while (X != Y) --> while (X-Y != 0) |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 6105 | ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 6106 | if (EL.hasAnyInfo()) |
| 6107 | return EL; |
| 6108 | |
| 6109 | return getCouldNotCompute(); |
| 6110 | } |
| 6111 | |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6112 | static ConstantInt * |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 6113 | EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, |
| 6114 | ScalarEvolution &SE) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6115 | const SCEV *InVal = SE.getConstant(C); |
| 6116 | const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6117 | assert(isa<SCEVConstant>(Val) && |
| 6118 | "Evaluation of SCEV at constant didn't fold correctly?"); |
| 6119 | return cast<SCEVConstant>(Val)->getValue(); |
| 6120 | } |
| 6121 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 6122 | /// Given an exit condition of 'icmp op load X, cst', try to see if we can |
| 6123 | /// compute the backedge execution count. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6124 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 6125 | ScalarEvolution::computeLoadConstantCompareExitLimit( |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6126 | LoadInst *LI, |
| 6127 | Constant *RHS, |
| 6128 | const Loop *L, |
| 6129 | ICmpInst::Predicate predicate) { |
| 6130 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6131 | if (LI->isVolatile()) return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6132 | |
| 6133 | // 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] | 6134 | // TODO: Use SCEV instead of manually grubbing with GEPs. |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6135 | GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6136 | if (!GEP) return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6137 | |
| 6138 | // Make sure that it is really a constant global we are gepping, with an |
| 6139 | // initializer, and make sure the first IDX is really 0. |
| 6140 | GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); |
Dan Gohman | 5d5bc6d | 2009-08-19 18:20:44 +0000 | [diff] [blame] | 6141 | if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6142 | GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || |
| 6143 | !cast<Constant>(GEP->getOperand(1))->isNullValue()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6144 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6145 | |
| 6146 | // Okay, we allow one non-constant index into the GEP instruction. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6147 | Value *VarIdx = nullptr; |
Chris Lattner | e166a85 | 2012-01-24 05:49:24 +0000 | [diff] [blame] | 6148 | std::vector<Constant*> Indexes; |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6149 | unsigned VarIdxNum = 0; |
| 6150 | for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) |
| 6151 | if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { |
| 6152 | Indexes.push_back(CI); |
| 6153 | } else if (!isa<ConstantInt>(GEP->getOperand(i))) { |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6154 | if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6155 | VarIdx = GEP->getOperand(i); |
| 6156 | VarIdxNum = i-2; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6157 | Indexes.push_back(nullptr); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6158 | } |
| 6159 | |
Andrew Trick | 7004e4b | 2012-03-26 22:33:59 +0000 | [diff] [blame] | 6160 | // Loop-invariant loads may be a byproduct of loop optimization. Skip them. |
| 6161 | if (!VarIdx) |
| 6162 | return getCouldNotCompute(); |
| 6163 | |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6164 | // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. |
| 6165 | // Check to see if X is a loop variant variable value now. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6166 | const SCEV *Idx = getSCEV(VarIdx); |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 6167 | Idx = getSCEVAtScope(Idx, L); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6168 | |
| 6169 | // We can only recognize very limited forms of loop index expressions, in |
| 6170 | // particular, only affine AddRec's like {C1,+,C2}. |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6171 | const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 6172 | if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6173 | !isa<SCEVConstant>(IdxExpr->getOperand(0)) || |
| 6174 | !isa<SCEVConstant>(IdxExpr->getOperand(1))) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6175 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6176 | |
| 6177 | unsigned MaxSteps = MaxBruteForceIterations; |
| 6178 | for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 6179 | ConstantInt *ItCst = ConstantInt::get( |
Owen Anderson | b6b2530 | 2009-07-14 23:09:55 +0000 | [diff] [blame] | 6180 | cast<IntegerType>(IdxExpr->getType()), IterationNum); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6181 | ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6182 | |
| 6183 | // Form the GEP offset. |
| 6184 | Indexes[VarIdxNum] = Val; |
| 6185 | |
Chris Lattner | e166a85 | 2012-01-24 05:49:24 +0000 | [diff] [blame] | 6186 | Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), |
| 6187 | Indexes); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6188 | if (!Result) break; // Cannot compute! |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6189 | |
| 6190 | // Evaluate the condition for this iteration. |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6191 | Result = ConstantExpr::getICmp(predicate, Result, RHS); |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6192 | if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6193 | if (cast<ConstantInt>(Result)->getValue().isMinValue()) { |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6194 | ++NumArrayLenItCounts; |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6195 | return getConstant(ItCst); // Found terminating iteration! |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6196 | } |
| 6197 | } |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6198 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6199 | } |
| 6200 | |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 6201 | ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( |
| 6202 | Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { |
| 6203 | ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); |
| 6204 | if (!RHS) |
| 6205 | return getCouldNotCompute(); |
| 6206 | |
| 6207 | const BasicBlock *Latch = L->getLoopLatch(); |
| 6208 | if (!Latch) |
| 6209 | return getCouldNotCompute(); |
| 6210 | |
| 6211 | const BasicBlock *Predecessor = L->getLoopPredecessor(); |
| 6212 | if (!Predecessor) |
| 6213 | return getCouldNotCompute(); |
| 6214 | |
| 6215 | // Return true if V is of the form "LHS `shift_op` <positive constant>". |
| 6216 | // Return LHS in OutLHS and shift_opt in OutOpCode. |
| 6217 | auto MatchPositiveShift = |
| 6218 | [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { |
| 6219 | |
| 6220 | using namespace PatternMatch; |
| 6221 | |
| 6222 | ConstantInt *ShiftAmt; |
| 6223 | if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) |
| 6224 | OutOpCode = Instruction::LShr; |
| 6225 | else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) |
| 6226 | OutOpCode = Instruction::AShr; |
| 6227 | else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) |
| 6228 | OutOpCode = Instruction::Shl; |
| 6229 | else |
| 6230 | return false; |
| 6231 | |
| 6232 | return ShiftAmt->getValue().isStrictlyPositive(); |
| 6233 | }; |
| 6234 | |
| 6235 | // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in |
| 6236 | // |
| 6237 | // loop: |
| 6238 | // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] |
| 6239 | // %iv.shifted = lshr i32 %iv, <positive constant> |
| 6240 | // |
| 6241 | // Return true on a succesful match. Return the corresponding PHI node (%iv |
| 6242 | // above) in PNOut and the opcode of the shift operation in OpCodeOut. |
| 6243 | auto MatchShiftRecurrence = |
| 6244 | [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { |
| 6245 | Optional<Instruction::BinaryOps> PostShiftOpCode; |
| 6246 | |
| 6247 | { |
| 6248 | Instruction::BinaryOps OpC; |
| 6249 | Value *V; |
| 6250 | |
| 6251 | // If we encounter a shift instruction, "peel off" the shift operation, |
| 6252 | // and remember that we did so. Later when we inspect %iv's backedge |
| 6253 | // value, we will make sure that the backedge value uses the same |
| 6254 | // operation. |
| 6255 | // |
| 6256 | // Note: the peeled shift operation does not have to be the same |
| 6257 | // instruction as the one feeding into the PHI's backedge value. We only |
| 6258 | // really care about it being the same *kind* of shift instruction -- |
| 6259 | // that's all that is required for our later inferences to hold. |
| 6260 | if (MatchPositiveShift(LHS, V, OpC)) { |
| 6261 | PostShiftOpCode = OpC; |
| 6262 | LHS = V; |
| 6263 | } |
| 6264 | } |
| 6265 | |
| 6266 | PNOut = dyn_cast<PHINode>(LHS); |
| 6267 | if (!PNOut || PNOut->getParent() != L->getHeader()) |
| 6268 | return false; |
| 6269 | |
| 6270 | Value *BEValue = PNOut->getIncomingValueForBlock(Latch); |
| 6271 | Value *OpLHS; |
| 6272 | |
| 6273 | return |
| 6274 | // The backedge value for the PHI node must be a shift by a positive |
| 6275 | // amount |
| 6276 | MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && |
| 6277 | |
| 6278 | // of the PHI node itself |
| 6279 | OpLHS == PNOut && |
| 6280 | |
| 6281 | // and the kind of shift should be match the kind of shift we peeled |
| 6282 | // off, if any. |
| 6283 | (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); |
| 6284 | }; |
| 6285 | |
| 6286 | PHINode *PN; |
| 6287 | Instruction::BinaryOps OpCode; |
| 6288 | if (!MatchShiftRecurrence(LHS, PN, OpCode)) |
| 6289 | return getCouldNotCompute(); |
| 6290 | |
| 6291 | const DataLayout &DL = getDataLayout(); |
| 6292 | |
| 6293 | // The key rationale for this optimization is that for some kinds of shift |
| 6294 | // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 |
| 6295 | // within a finite number of iterations. If the condition guarding the |
| 6296 | // backedge (in the sense that the backedge is taken if the condition is true) |
| 6297 | // is false for the value the shift recurrence stabilizes to, then we know |
| 6298 | // that the backedge is taken only a finite number of times. |
| 6299 | |
| 6300 | ConstantInt *StableValue = nullptr; |
| 6301 | switch (OpCode) { |
| 6302 | default: |
| 6303 | llvm_unreachable("Impossible case!"); |
| 6304 | |
| 6305 | case Instruction::AShr: { |
| 6306 | // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most |
| 6307 | // bitwidth(K) iterations. |
| 6308 | Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); |
| 6309 | bool KnownZero, KnownOne; |
| 6310 | ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr, |
| 6311 | Predecessor->getTerminator(), &DT); |
| 6312 | auto *Ty = cast<IntegerType>(RHS->getType()); |
| 6313 | if (KnownZero) |
| 6314 | StableValue = ConstantInt::get(Ty, 0); |
| 6315 | else if (KnownOne) |
| 6316 | StableValue = ConstantInt::get(Ty, -1, true); |
| 6317 | else |
| 6318 | return getCouldNotCompute(); |
| 6319 | |
| 6320 | break; |
| 6321 | } |
| 6322 | case Instruction::LShr: |
| 6323 | case Instruction::Shl: |
| 6324 | // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} |
| 6325 | // stabilize to 0 in at most bitwidth(K) iterations. |
| 6326 | StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); |
| 6327 | break; |
| 6328 | } |
| 6329 | |
| 6330 | auto *Result = |
| 6331 | ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); |
| 6332 | assert(Result->getType()->isIntegerTy(1) && |
| 6333 | "Otherwise cannot be an operand to a branch instruction"); |
| 6334 | |
| 6335 | if (Result->isZeroValue()) { |
| 6336 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
| 6337 | const SCEV *UpperBound = |
| 6338 | getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 6339 | return ExitLimit(getCouldNotCompute(), UpperBound, false); |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 6340 | } |
| 6341 | |
| 6342 | return getCouldNotCompute(); |
| 6343 | } |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6344 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 6345 | /// Return true if we can constant fold an instruction of the specified type, |
| 6346 | /// assuming that all operands were constants. |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6347 | static bool CanConstantFold(const Instruction *I) { |
Reid Spencer | 2341c22 | 2007-02-02 02:16:23 +0000 | [diff] [blame] | 6348 | if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6349 | isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || |
| 6350 | isa<LoadInst>(I)) |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6351 | return true; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6352 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6353 | if (const CallInst *CI = dyn_cast<CallInst>(I)) |
| 6354 | if (const Function *F = CI->getCalledFunction()) |
Dan Gohman | a65951f | 2008-01-31 01:05:10 +0000 | [diff] [blame] | 6355 | return canConstantFoldCallTo(F); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6356 | return false; |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6357 | } |
| 6358 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6359 | /// Determine whether this instruction can constant evolve within this loop |
| 6360 | /// assuming its operands can all constant evolve. |
| 6361 | static bool canConstantEvolve(Instruction *I, const Loop *L) { |
| 6362 | // An instruction outside of the loop can't be derived from a loop PHI. |
| 6363 | if (!L->contains(I)) return false; |
| 6364 | |
| 6365 | if (isa<PHINode>(I)) { |
David Blaikie | 19ef0d3 | 2015-03-24 16:33:19 +0000 | [diff] [blame] | 6366 | // We don't currently keep track of the control flow needed to evaluate |
| 6367 | // PHIs, so we cannot handle PHIs inside of loops. |
| 6368 | return L->getHeader() == I->getParent(); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6369 | } |
| 6370 | |
| 6371 | // If we won't be able to constant fold this expression even if the operands |
| 6372 | // are constants, bail early. |
| 6373 | return CanConstantFold(I); |
| 6374 | } |
| 6375 | |
| 6376 | /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by |
| 6377 | /// recursing through each instruction operand until reaching a loop header phi. |
| 6378 | static PHINode * |
| 6379 | getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6380 | DenseMap<Instruction *, PHINode *> &PHIMap) { |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6381 | |
| 6382 | // Otherwise, we can evaluate this instruction if all of its operands are |
| 6383 | // constant or derived from a PHI node themselves. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6384 | PHINode *PHI = nullptr; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 6385 | for (Value *Op : UseInst->operands()) { |
| 6386 | if (isa<Constant>(Op)) continue; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6387 | |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 6388 | Instruction *OpInst = dyn_cast<Instruction>(Op); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6389 | if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6390 | |
| 6391 | PHINode *P = dyn_cast<PHINode>(OpInst); |
Andrew Trick | 3e8a576 | 2011-10-05 22:06:53 +0000 | [diff] [blame] | 6392 | if (!P) |
| 6393 | // If this operand is already visited, reuse the prior result. |
| 6394 | // We may have P != PHI if this is the deepest point at which the |
| 6395 | // inconsistent paths meet. |
| 6396 | P = PHIMap.lookup(OpInst); |
| 6397 | if (!P) { |
| 6398 | // Recurse and memoize the results, whether a phi is found or not. |
| 6399 | // This recursive call invalidates pointers into PHIMap. |
| 6400 | P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap); |
| 6401 | PHIMap[OpInst] = P; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6402 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6403 | if (!P) |
| 6404 | return nullptr; // Not evolving from PHI |
| 6405 | if (PHI && PHI != P) |
| 6406 | return nullptr; // Evolving from multiple different PHIs. |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6407 | PHI = P; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6408 | } |
| 6409 | // This is a expression evolving from a constant PHI! |
| 6410 | return PHI; |
| 6411 | } |
| 6412 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6413 | /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node |
| 6414 | /// in the loop that V is derived from. We allow arbitrary operations along the |
| 6415 | /// way, but the operands of an operation must either be constants or a value |
| 6416 | /// derived from a constant PHI. If this expression does not fit with these |
| 6417 | /// constraints, return null. |
| 6418 | static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6419 | Instruction *I = dyn_cast<Instruction>(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6420 | if (!I || !canConstantEvolve(I, L)) return nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6421 | |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 6422 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6423 | return PN; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6424 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6425 | // Record non-constant instructions contained by the loop. |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6426 | DenseMap<Instruction *, PHINode *> PHIMap; |
| 6427 | return getConstantEvolvingPHIOperands(I, L, PHIMap); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6428 | } |
| 6429 | |
| 6430 | /// EvaluateExpression - Given an expression that passes the |
| 6431 | /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node |
| 6432 | /// in the loop has the value PHIVal. If we can't fold this expression for some |
| 6433 | /// reason, return null. |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6434 | static Constant *EvaluateExpression(Value *V, const Loop *L, |
| 6435 | DenseMap<Instruction *, Constant *> &Vals, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 6436 | const DataLayout &DL, |
Chad Rosier | e6de63d | 2011-12-01 21:29:16 +0000 | [diff] [blame] | 6437 | const TargetLibraryInfo *TLI) { |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6438 | // Convenient constant check, but redundant for recursive calls. |
Reid Spencer | 30d69a5 | 2004-07-18 00:18:30 +0000 | [diff] [blame] | 6439 | if (Constant *C = dyn_cast<Constant>(V)) return C; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6440 | Instruction *I = dyn_cast<Instruction>(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6441 | if (!I) return nullptr; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6442 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6443 | if (Constant *C = Vals.lookup(I)) return C; |
| 6444 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6445 | // An instruction inside the loop depends on a value outside the loop that we |
| 6446 | // 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] | 6447 | if (!canConstantEvolve(I, L)) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6448 | |
| 6449 | // An unmapped PHI can be due to a branch or another loop inside this loop, |
| 6450 | // or due to this not being the initial iteration through a loop where we |
| 6451 | // couldn't compute the evolution of this particular PHI last time. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6452 | if (isa<PHINode>(I)) return nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6453 | |
Dan Gohman | f820bd3 | 2010-06-22 13:15:46 +0000 | [diff] [blame] | 6454 | std::vector<Constant*> Operands(I->getNumOperands()); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6455 | |
| 6456 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6457 | Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); |
| 6458 | if (!Operand) { |
Nick Lewycky | a447e0f3 | 2011-10-14 09:38:46 +0000 | [diff] [blame] | 6459 | Operands[i] = dyn_cast<Constant>(I->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6460 | if (!Operands[i]) return nullptr; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6461 | continue; |
| 6462 | } |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 6463 | Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6464 | Vals[Operand] = C; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6465 | if (!C) return nullptr; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6466 | Operands[i] = C; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6467 | } |
| 6468 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6469 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Chris Lattner | cdfb80d | 2009-11-09 23:06:58 +0000 | [diff] [blame] | 6470 | return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 6471 | Operands[1], DL, TLI); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6472 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
| 6473 | if (!LI->isVolatile()) |
Eduard Burtescu | 1423921 | 2016-01-22 01:17:26 +0000 | [diff] [blame] | 6474 | return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6475 | } |
Manuel Jacob | e902459 | 2016-01-21 06:33:22 +0000 | [diff] [blame] | 6476 | return ConstantFoldInstOperands(I, Operands, DL, TLI); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6477 | } |
| 6478 | |
Sanjoy Das | 52bfa0f | 2015-11-02 02:06:01 +0000 | [diff] [blame] | 6479 | |
| 6480 | // If every incoming value to PN except the one for BB is a specific Constant, |
| 6481 | // return that, else return nullptr. |
| 6482 | static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { |
| 6483 | Constant *IncomingVal = nullptr; |
| 6484 | |
| 6485 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 6486 | if (PN->getIncomingBlock(i) == BB) |
| 6487 | continue; |
| 6488 | |
| 6489 | auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); |
| 6490 | if (!CurrentVal) |
| 6491 | return nullptr; |
| 6492 | |
| 6493 | if (IncomingVal != CurrentVal) { |
| 6494 | if (IncomingVal) |
| 6495 | return nullptr; |
| 6496 | IncomingVal = CurrentVal; |
| 6497 | } |
| 6498 | } |
| 6499 | |
| 6500 | return IncomingVal; |
| 6501 | } |
| 6502 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6503 | /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is |
| 6504 | /// in the header of its containing loop, we know the loop executes a |
| 6505 | /// constant number of times, and the PHI node is just a recurrence |
| 6506 | /// involving constants, fold it. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6507 | Constant * |
| 6508 | ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 6509 | const APInt &BEs, |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6510 | const Loop *L) { |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6511 | auto I = ConstantEvolutionLoopExitValue.find(PN); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6512 | if (I != ConstantEvolutionLoopExitValue.end()) |
| 6513 | return I->second; |
| 6514 | |
Dan Gohman | 4ce1fb1 | 2010-04-08 23:03:40 +0000 | [diff] [blame] | 6515 | if (BEs.ugt(MaxBruteForceIterations)) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6516 | return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6517 | |
| 6518 | Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; |
| 6519 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6520 | DenseMap<Instruction *, Constant *> CurrentIterVals; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6521 | BasicBlock *Header = L->getHeader(); |
| 6522 | assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6523 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6524 | BasicBlock *Latch = L->getLoopLatch(); |
| 6525 | if (!Latch) |
| 6526 | return nullptr; |
| 6527 | |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6528 | for (auto &I : *Header) { |
| 6529 | PHINode *PHI = dyn_cast<PHINode>(&I); |
| 6530 | if (!PHI) break; |
Sanjoy Das | 52bfa0f | 2015-11-02 02:06:01 +0000 | [diff] [blame] | 6531 | auto *StartCST = getOtherIncomingValue(PHI, Latch); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6532 | if (!StartCST) continue; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6533 | CurrentIterVals[PHI] = StartCST; |
| 6534 | } |
| 6535 | if (!CurrentIterVals.count(PN)) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6536 | return RetVal = nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6537 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6538 | Value *BEValue = PN->getIncomingValueForBlock(Latch); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6539 | |
| 6540 | // Execute the loop symbolically to determine the exit value. |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6541 | if (BEs.getActiveBits() >= 32) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6542 | return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6543 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6544 | unsigned NumIterations = BEs.getZExtValue(); // must be in range |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6545 | unsigned IterationNum = 0; |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 6546 | const DataLayout &DL = getDataLayout(); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6547 | for (; ; ++IterationNum) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6548 | if (IterationNum == NumIterations) |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6549 | return RetVal = CurrentIterVals[PN]; // Got exit value! |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6550 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6551 | // Compute the value of the PHIs for the next iteration. |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6552 | // EvaluateExpression adds non-phi values to the CurrentIterVals map. |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6553 | DenseMap<Instruction *, Constant *> NextIterVals; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 6554 | Constant *NextPHI = |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6555 | EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6556 | if (!NextPHI) |
| 6557 | return nullptr; // Couldn't evaluate! |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6558 | NextIterVals[PN] = NextPHI; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6559 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6560 | bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; |
| 6561 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6562 | // Also evaluate the other PHI nodes. However, we don't get to stop if we |
| 6563 | // cease to be able to evaluate one of them or if they stop evolving, |
| 6564 | // because that doesn't necessarily prevent us from computing PN. |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6565 | SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6566 | for (const auto &I : CurrentIterVals) { |
| 6567 | PHINode *PHI = dyn_cast<PHINode>(I.first); |
Nick Lewycky | 8e904de | 2011-10-24 05:51:01 +0000 | [diff] [blame] | 6568 | if (!PHI || PHI == PN || PHI->getParent() != Header) continue; |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6569 | PHIsToCompute.emplace_back(PHI, I.second); |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6570 | } |
| 6571 | // We use two distinct loops because EvaluateExpression may invalidate any |
| 6572 | // iterators into CurrentIterVals. |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6573 | for (const auto &I : PHIsToCompute) { |
| 6574 | PHINode *PHI = I.first; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6575 | Constant *&NextPHI = NextIterVals[PHI]; |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6576 | if (!NextPHI) { // Not already computed. |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6577 | Value *BEValue = PHI->getIncomingValueForBlock(Latch); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6578 | NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6579 | } |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6580 | if (NextPHI != I.second) |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6581 | StoppedEvolving = false; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6582 | } |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6583 | |
| 6584 | // If all entries in CurrentIterVals == NextIterVals then we can stop |
| 6585 | // iterating, the loop can't continue to change. |
| 6586 | if (StoppedEvolving) |
| 6587 | return RetVal = CurrentIterVals[PN]; |
| 6588 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6589 | CurrentIterVals.swap(NextIterVals); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6590 | } |
| 6591 | } |
| 6592 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 6593 | const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6594 | Value *Cond, |
| 6595 | bool ExitWhen) { |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6596 | PHINode *PN = getConstantEvolvingPHI(Cond, L); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6597 | if (!PN) return getCouldNotCompute(); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6598 | |
Dan Gohman | 866971e | 2010-06-19 14:17:24 +0000 | [diff] [blame] | 6599 | // If the loop is canonicalized, the PHI will have exactly two entries. |
| 6600 | // That's the only form we support here. |
| 6601 | if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); |
| 6602 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6603 | DenseMap<Instruction *, Constant *> CurrentIterVals; |
| 6604 | BasicBlock *Header = L->getHeader(); |
| 6605 | assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); |
| 6606 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6607 | BasicBlock *Latch = L->getLoopLatch(); |
| 6608 | assert(Latch && "Should follow from NumIncomingValues == 2!"); |
| 6609 | |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6610 | for (auto &I : *Header) { |
| 6611 | PHINode *PHI = dyn_cast<PHINode>(&I); |
| 6612 | if (!PHI) |
| 6613 | break; |
Sanjoy Das | 52bfa0f | 2015-11-02 02:06:01 +0000 | [diff] [blame] | 6614 | auto *StartCST = getOtherIncomingValue(PHI, Latch); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6615 | if (!StartCST) continue; |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6616 | CurrentIterVals[PHI] = StartCST; |
| 6617 | } |
| 6618 | if (!CurrentIterVals.count(PN)) |
| 6619 | return getCouldNotCompute(); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6620 | |
| 6621 | // Okay, we find a PHI node that defines the trip count of this loop. Execute |
| 6622 | // the loop symbolically to determine when the condition gets a value of |
| 6623 | // "ExitWhen". |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 6624 | unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 6625 | const DataLayout &DL = getDataLayout(); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6626 | for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6627 | auto *CondVal = dyn_cast_or_null<ConstantInt>( |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6628 | EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6629 | |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6630 | // Couldn't symbolically evaluate. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6631 | if (!CondVal) return getCouldNotCompute(); |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6632 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6633 | if (CondVal->getValue() == uint64_t(ExitWhen)) { |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6634 | ++NumBruteForceTripCountsComputed; |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 6635 | return getConstant(Type::getInt32Ty(getContext()), IterationNum); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6636 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6637 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6638 | // Update all the PHI nodes for the next iteration. |
| 6639 | DenseMap<Instruction *, Constant *> NextIterVals; |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6640 | |
| 6641 | // Create a list of which PHIs we need to compute. We want to do this before |
| 6642 | // calling EvaluateExpression on them because that may invalidate iterators |
| 6643 | // into CurrentIterVals. |
| 6644 | SmallVector<PHINode *, 8> PHIsToCompute; |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6645 | for (const auto &I : CurrentIterVals) { |
| 6646 | PHINode *PHI = dyn_cast<PHINode>(I.first); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6647 | if (!PHI || PHI->getParent() != Header) continue; |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6648 | PHIsToCompute.push_back(PHI); |
| 6649 | } |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6650 | for (PHINode *PHI : PHIsToCompute) { |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6651 | Constant *&NextPHI = NextIterVals[PHI]; |
| 6652 | if (NextPHI) continue; // Already computed! |
| 6653 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6654 | Value *BEValue = PHI->getIncomingValueForBlock(Latch); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6655 | NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6656 | } |
| 6657 | CurrentIterVals.swap(NextIterVals); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6658 | } |
| 6659 | |
| 6660 | // Too many iterations were needed to evaluate. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6661 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6662 | } |
| 6663 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6664 | const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 6665 | SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = |
| 6666 | ValuesAtScopes[V]; |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6667 | // 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] | 6668 | for (auto &LS : Values) |
| 6669 | if (LS.first == L) |
| 6670 | return LS.second ? LS.second : V; |
| 6671 | |
| 6672 | Values.emplace_back(L, nullptr); |
| 6673 | |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6674 | // Otherwise compute it. |
| 6675 | const SCEV *C = computeSCEVAtScope(V, L); |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 6676 | for (auto &LS : reverse(ValuesAtScopes[V])) |
| 6677 | if (LS.first == L) { |
| 6678 | LS.second = C; |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 6679 | break; |
| 6680 | } |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6681 | return C; |
| 6682 | } |
| 6683 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6684 | /// This builds up a Constant using the ConstantExpr interface. That way, we |
| 6685 | /// will return Constants for objects which aren't represented by a |
| 6686 | /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. |
| 6687 | /// Returns NULL if the SCEV isn't representable as a Constant. |
| 6688 | static Constant *BuildConstantFromSCEV(const SCEV *V) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 6689 | switch (static_cast<SCEVTypes>(V->getSCEVType())) { |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6690 | case scCouldNotCompute: |
| 6691 | case scAddRecExpr: |
| 6692 | break; |
| 6693 | case scConstant: |
| 6694 | return cast<SCEVConstant>(V)->getValue(); |
| 6695 | case scUnknown: |
| 6696 | return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); |
| 6697 | case scSignExtend: { |
| 6698 | const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); |
| 6699 | if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) |
| 6700 | return ConstantExpr::getSExt(CastOp, SS->getType()); |
| 6701 | break; |
| 6702 | } |
| 6703 | case scZeroExtend: { |
| 6704 | const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); |
| 6705 | if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) |
| 6706 | return ConstantExpr::getZExt(CastOp, SZ->getType()); |
| 6707 | break; |
| 6708 | } |
| 6709 | case scTruncate: { |
| 6710 | const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); |
| 6711 | if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) |
| 6712 | return ConstantExpr::getTrunc(CastOp, ST->getType()); |
| 6713 | break; |
| 6714 | } |
| 6715 | case scAddExpr: { |
| 6716 | const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); |
| 6717 | if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6718 | if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { |
| 6719 | unsigned AS = PTy->getAddressSpace(); |
| 6720 | Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); |
| 6721 | C = ConstantExpr::getBitCast(C, DestPtrTy); |
| 6722 | } |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6723 | for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { |
| 6724 | Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6725 | if (!C2) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6726 | |
| 6727 | // First pointer! |
| 6728 | if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6729 | unsigned AS = C2->getType()->getPointerAddressSpace(); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6730 | std::swap(C, C2); |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6731 | Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6732 | // The offsets have been converted to bytes. We can add bytes to an |
| 6733 | // i8* by GEP with the byte count in the first index. |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6734 | C = ConstantExpr::getBitCast(C, DestPtrTy); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6735 | } |
| 6736 | |
| 6737 | // Don't bother trying to sum two pointers. We probably can't |
| 6738 | // statically compute a load that results from it anyway. |
| 6739 | if (C2->getType()->isPointerTy()) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6740 | return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6741 | |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6742 | if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { |
| 6743 | if (PTy->getElementType()->isStructTy()) |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6744 | C2 = ConstantExpr::getIntegerCast( |
| 6745 | C2, Type::getInt32Ty(C->getContext()), true); |
David Blaikie | 4a2e73b | 2015-04-02 18:55:32 +0000 | [diff] [blame] | 6746 | C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6747 | } else |
| 6748 | C = ConstantExpr::getAdd(C, C2); |
| 6749 | } |
| 6750 | return C; |
| 6751 | } |
| 6752 | break; |
| 6753 | } |
| 6754 | case scMulExpr: { |
| 6755 | const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); |
| 6756 | if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { |
| 6757 | // Don't bother with pointers at all. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6758 | if (C->getType()->isPointerTy()) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6759 | for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { |
| 6760 | Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6761 | if (!C2 || C2->getType()->isPointerTy()) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6762 | C = ConstantExpr::getMul(C, C2); |
| 6763 | } |
| 6764 | return C; |
| 6765 | } |
| 6766 | break; |
| 6767 | } |
| 6768 | case scUDivExpr: { |
| 6769 | const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); |
| 6770 | if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) |
| 6771 | if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) |
| 6772 | if (LHS->getType() == RHS->getType()) |
| 6773 | return ConstantExpr::getUDiv(LHS, RHS); |
| 6774 | break; |
| 6775 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 6776 | case scSMaxExpr: |
| 6777 | case scUMaxExpr: |
| 6778 | break; // TODO: smax, umax. |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6779 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6780 | return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6781 | } |
| 6782 | |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6783 | const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6784 | if (isa<SCEVConstant>(V)) return V; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6785 | |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 6786 | // If this instruction is evolved from a constant-evolving PHI, compute the |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6787 | // exit value from the loop without using SCEVs. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6788 | if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6789 | if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6790 | const Loop *LI = this->LI[I->getParent()]; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6791 | if (LI && LI->getParentLoop() == L) // Looking for loop exit value. |
| 6792 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 6793 | if (PN->getParent() == LI->getHeader()) { |
| 6794 | // Okay, there is no closed form solution for the PHI node. Check |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6795 | // to see if the loop that contains it has a known backedge-taken |
| 6796 | // count. If so, we may be able to force computation of the exit |
| 6797 | // value. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6798 | const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6799 | if (const SCEVConstant *BTCC = |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6800 | dyn_cast<SCEVConstant>(BackedgeTakenCount)) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6801 | // Okay, we know how many times the containing loop executes. If |
| 6802 | // this is a constant evolving PHI node, get the final value at |
| 6803 | // the specified iteration number. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 6804 | Constant *RV = |
| 6805 | getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); |
Dan Gohman | 9d203c6 | 2009-06-29 21:31:18 +0000 | [diff] [blame] | 6806 | if (RV) return getSCEV(RV); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6807 | } |
| 6808 | } |
| 6809 | |
Reid Spencer | e6328ca | 2006-12-04 21:33:23 +0000 | [diff] [blame] | 6810 | // Okay, this is an expression that we cannot symbolically evaluate |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6811 | // 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] | 6812 | // the arguments into constants, and if so, try to constant propagate the |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6813 | // result. This is particularly useful for computing loop exit values. |
| 6814 | if (CanConstantFold(I)) { |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6815 | SmallVector<Constant *, 4> Operands; |
| 6816 | bool MadeImprovement = false; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 6817 | for (Value *Op : I->operands()) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6818 | if (Constant *C = dyn_cast<Constant>(Op)) { |
| 6819 | Operands.push_back(C); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6820 | continue; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6821 | } |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6822 | |
| 6823 | // If any of the operands is non-constant and if they are |
| 6824 | // non-integer and non-pointer, don't even try to analyze them |
| 6825 | // with scev techniques. |
| 6826 | if (!isSCEVable(Op->getType())) |
| 6827 | return V; |
| 6828 | |
| 6829 | const SCEV *OrigV = getSCEV(Op); |
| 6830 | const SCEV *OpV = getSCEVAtScope(OrigV, L); |
| 6831 | MadeImprovement |= OrigV != OpV; |
| 6832 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6833 | Constant *C = BuildConstantFromSCEV(OpV); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6834 | if (!C) return V; |
| 6835 | if (C->getType() != Op->getType()) |
| 6836 | C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, |
| 6837 | Op->getType(), |
| 6838 | false), |
| 6839 | C, Op->getType()); |
| 6840 | Operands.push_back(C); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6841 | } |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6842 | |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6843 | // Check to see if getSCEVAtScope actually made an improvement. |
| 6844 | if (MadeImprovement) { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6845 | Constant *C = nullptr; |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 6846 | const DataLayout &DL = getDataLayout(); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6847 | if (const CmpInst *CI = dyn_cast<CmpInst>(I)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 6848 | C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6849 | Operands[1], DL, &TLI); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6850 | else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { |
| 6851 | if (!LI->isVolatile()) |
Eduard Burtescu | 1423921 | 2016-01-22 01:17:26 +0000 | [diff] [blame] | 6852 | C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6853 | } else |
Manuel Jacob | e902459 | 2016-01-21 06:33:22 +0000 | [diff] [blame] | 6854 | C = ConstantFoldInstOperands(I, Operands, DL, &TLI); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6855 | if (!C) return V; |
Dan Gohman | 4aad750 | 2010-02-24 19:31:47 +0000 | [diff] [blame] | 6856 | return getSCEV(C); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6857 | } |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6858 | } |
| 6859 | } |
| 6860 | |
| 6861 | // This is some other type of SCEVUnknown, just return it. |
| 6862 | return V; |
| 6863 | } |
| 6864 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6865 | if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6866 | // Avoid performing the look-up in the common case where the specified |
| 6867 | // expression has no loop-variant portions. |
| 6868 | for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6869 | const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6870 | if (OpAtScope != Comm->getOperand(i)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6871 | // Okay, at least one of these operands is loop variant but might be |
| 6872 | // foldable. Build a new instance of the folded commutative expression. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6873 | SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), |
| 6874 | Comm->op_begin()+i); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6875 | NewOps.push_back(OpAtScope); |
| 6876 | |
| 6877 | for (++i; i != e; ++i) { |
| 6878 | OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6879 | NewOps.push_back(OpAtScope); |
| 6880 | } |
| 6881 | if (isa<SCEVAddExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6882 | return getAddExpr(NewOps); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 6883 | if (isa<SCEVMulExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6884 | return getMulExpr(NewOps); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 6885 | if (isa<SCEVSMaxExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6886 | return getSMaxExpr(NewOps); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 6887 | if (isa<SCEVUMaxExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6888 | return getUMaxExpr(NewOps); |
Torok Edwin | fbcc663 | 2009-07-14 16:55:14 +0000 | [diff] [blame] | 6889 | llvm_unreachable("Unknown commutative SCEV type!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6890 | } |
| 6891 | } |
| 6892 | // If we got here, all operands are loop invariant. |
| 6893 | return Comm; |
| 6894 | } |
| 6895 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6896 | if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6897 | const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); |
| 6898 | const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); |
Nick Lewycky | 5234830 | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 6899 | if (LHS == Div->getLHS() && RHS == Div->getRHS()) |
| 6900 | return Div; // must be loop invariant |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6901 | return getUDivExpr(LHS, RHS); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6902 | } |
| 6903 | |
| 6904 | // If this is a loop recurrence for a loop that does not contain L, then we |
| 6905 | // are dealing with the final value computed by the loop. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6906 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6907 | // First, attempt to evaluate each operand. |
| 6908 | // Avoid performing the look-up in the common case where the specified |
| 6909 | // expression has no loop-variant portions. |
| 6910 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { |
| 6911 | const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); |
| 6912 | if (OpAtScope == AddRec->getOperand(i)) |
| 6913 | continue; |
| 6914 | |
| 6915 | // Okay, at least one of these operands is loop variant but might be |
| 6916 | // foldable. Build a new instance of the folded commutative expression. |
| 6917 | SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), |
| 6918 | AddRec->op_begin()+i); |
| 6919 | NewOps.push_back(OpAtScope); |
| 6920 | for (++i; i != e; ++i) |
| 6921 | NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); |
| 6922 | |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6923 | const SCEV *FoldedRec = |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6924 | getAddRecExpr(NewOps, AddRec->getLoop(), |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6925 | AddRec->getNoWrapFlags(SCEV::FlagNW)); |
| 6926 | AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); |
Andrew Trick | 01eff82 | 2011-04-27 05:42:17 +0000 | [diff] [blame] | 6927 | // The addrec may be folded to a nonrecurrence, for example, if the |
| 6928 | // induction variable is multiplied by zero after constant folding. Go |
| 6929 | // ahead and return the folded value. |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6930 | if (!AddRec) |
| 6931 | return FoldedRec; |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6932 | break; |
| 6933 | } |
| 6934 | |
| 6935 | // If the scope is outside the addrec's loop, evaluate it by using the |
| 6936 | // loop exit value of the addrec. |
| 6937 | if (!AddRec->getLoop()->contains(L)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6938 | // To evaluate this recurrence, we need to know how many times the AddRec |
| 6939 | // loop iterates. Compute this now. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6940 | const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6941 | if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6942 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 6943 | // Then, evaluate the AddRec. |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6944 | return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6945 | } |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6946 | |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 6947 | return AddRec; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6948 | } |
| 6949 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6950 | if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6951 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 6952 | if (Op == Cast->getOperand()) |
| 6953 | return Cast; // must be loop invariant |
| 6954 | return getZeroExtendExpr(Op, Cast->getType()); |
| 6955 | } |
| 6956 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6957 | if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6958 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 6959 | if (Op == Cast->getOperand()) |
| 6960 | return Cast; // must be loop invariant |
| 6961 | return getSignExtendExpr(Op, Cast->getType()); |
| 6962 | } |
| 6963 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6964 | if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6965 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 6966 | if (Op == Cast->getOperand()) |
| 6967 | return Cast; // must be loop invariant |
| 6968 | return getTruncateExpr(Op, Cast->getType()); |
| 6969 | } |
| 6970 | |
Torok Edwin | fbcc663 | 2009-07-14 16:55:14 +0000 | [diff] [blame] | 6971 | llvm_unreachable("Unknown SCEV type!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6972 | } |
| 6973 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6974 | const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6975 | return getSCEVAtScope(getSCEV(V), L); |
| 6976 | } |
| 6977 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 6978 | /// Finds the minimum unsigned root of the following equation: |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6979 | /// |
| 6980 | /// A * X = B (mod N) |
| 6981 | /// |
| 6982 | /// where N = 2^BW and BW is the common bit width of A and B. The signedness of |
| 6983 | /// A and B isn't important. |
| 6984 | /// |
| 6985 | /// If the equation does not have a solution, SCEVCouldNotCompute is returned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6986 | static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B, |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6987 | ScalarEvolution &SE) { |
| 6988 | uint32_t BW = A.getBitWidth(); |
| 6989 | assert(BW == B.getBitWidth() && "Bit widths must be the same."); |
| 6990 | assert(A != 0 && "A must be non-zero."); |
| 6991 | |
| 6992 | // 1. D = gcd(A, N) |
| 6993 | // |
| 6994 | // The gcd of A and N may have only one prime factor: 2. The number of |
| 6995 | // trailing zeros in A is its multiplicity |
| 6996 | uint32_t Mult2 = A.countTrailingZeros(); |
| 6997 | // D = 2^Mult2 |
| 6998 | |
| 6999 | // 2. Check if B is divisible by D. |
| 7000 | // |
| 7001 | // B is divisible by D if and only if the multiplicity of prime factor 2 for B |
| 7002 | // is not less than multiplicity of this prime factor for D. |
| 7003 | if (B.countTrailingZeros() < Mult2) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 7004 | return SE.getCouldNotCompute(); |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 7005 | |
| 7006 | // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic |
| 7007 | // modulo (N / D). |
| 7008 | // |
| 7009 | // (N / D) may need BW+1 bits in its representation. Hence, we'll use this |
| 7010 | // bit width during computations. |
| 7011 | APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D |
| 7012 | APInt Mod(BW + 1, 0); |
Jay Foad | 25a5e4c | 2010-12-01 08:53:58 +0000 | [diff] [blame] | 7013 | Mod.setBit(BW - Mult2); // Mod = N / D |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 7014 | APInt I = AD.multiplicativeInverse(Mod); |
| 7015 | |
| 7016 | // 4. Compute the minimum unsigned root of the equation: |
| 7017 | // I * (B / D) mod (N / D) |
| 7018 | APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); |
| 7019 | |
| 7020 | // The result is guaranteed to be less than 2^BW so we may truncate it to BW |
| 7021 | // bits. |
| 7022 | return SE.getConstant(Result.trunc(BW)); |
| 7023 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7024 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 7025 | /// Find the roots of the quadratic equation for the given quadratic chrec |
| 7026 | /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or |
| 7027 | /// two SCEVCouldNotCompute objects. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7028 | /// |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 7029 | static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 7030 | SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7031 | assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 7032 | const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); |
| 7033 | const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); |
| 7034 | const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7035 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7036 | // We currently can only solve this if the coefficients are constants. |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 7037 | if (!LC || !MC || !NC) |
| 7038 | return None; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7039 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7040 | uint32_t BitWidth = LC->getAPInt().getBitWidth(); |
| 7041 | const APInt &L = LC->getAPInt(); |
| 7042 | const APInt &M = MC->getAPInt(); |
| 7043 | const APInt &N = NC->getAPInt(); |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7044 | APInt Two(BitWidth, 2); |
| 7045 | APInt Four(BitWidth, 4); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7046 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 7047 | { |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7048 | using namespace APIntOps; |
Zhou Sheng | 2852d99 | 2007-04-07 17:48:27 +0000 | [diff] [blame] | 7049 | const APInt& C = L; |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7050 | // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C |
| 7051 | // The B coefficient is M-N/2 |
| 7052 | APInt B(M); |
| 7053 | B -= sdiv(N,Two); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7054 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7055 | // The A coefficient is N/2 |
Zhou Sheng | 2852d99 | 2007-04-07 17:48:27 +0000 | [diff] [blame] | 7056 | APInt A(N.sdiv(Two)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7057 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7058 | // Compute the B^2-4ac term. |
| 7059 | APInt SqrtTerm(B); |
| 7060 | SqrtTerm *= B; |
| 7061 | SqrtTerm -= Four * (A * C); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7062 | |
Nick Lewycky | fb78083 | 2012-08-01 09:14:36 +0000 | [diff] [blame] | 7063 | if (SqrtTerm.isNegative()) { |
| 7064 | // The loop is provably infinite. |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 7065 | return None; |
Nick Lewycky | fb78083 | 2012-08-01 09:14:36 +0000 | [diff] [blame] | 7066 | } |
| 7067 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7068 | // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest |
| 7069 | // integer value or else APInt::sqrt() will assert. |
| 7070 | APInt SqrtVal(SqrtTerm.sqrt()); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7071 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 7072 | // Compute the two solutions for the quadratic formula. |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7073 | // The divisions must be performed as signed divisions. |
| 7074 | APInt NegB(-B); |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 7075 | APInt TwoA(A << 1); |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 7076 | if (TwoA.isMinValue()) |
| 7077 | return None; |
Nick Lewycky | 7b14e20 | 2008-11-03 02:43:49 +0000 | [diff] [blame] | 7078 | |
Owen Anderson | 47db941 | 2009-07-22 00:24:57 +0000 | [diff] [blame] | 7079 | LLVMContext &Context = SE.getContext(); |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 7080 | |
| 7081 | ConstantInt *Solution1 = |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 7082 | ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 7083 | ConstantInt *Solution2 = |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 7084 | ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7085 | |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 7086 | return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), |
| 7087 | cast<SCEVConstant>(SE.getConstant(Solution2))); |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 7088 | } // end APIntOps namespace |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7089 | } |
| 7090 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 7091 | ScalarEvolution::ExitLimit |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 7092 | ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7093 | bool AllowPredicates) { |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 7094 | |
| 7095 | // This is only used for loops with a "x != y" exit test. The exit condition |
| 7096 | // is now expressed as a single expression, V = x-y. So the exit test is |
| 7097 | // effectively V != 0. We know and take advantage of the fact that this |
| 7098 | // expression only being used in a comparison by zero context. |
| 7099 | |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 7100 | SmallPtrSet<const SCEVPredicate *, 4> Predicates; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7101 | // If the value is a constant |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 7102 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7103 | // If the value is already zero, the branch will execute zero times. |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 7104 | if (C->getValue()->isZero()) return C; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7105 | return getCouldNotCompute(); // Otherwise it will loop infinitely. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7106 | } |
| 7107 | |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 7108 | const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7109 | if (!AddRec && AllowPredicates) |
| 7110 | // Try to make this an AddRec using runtime tests, in the first X |
| 7111 | // iterations of this loop, where X is the SCEV expression found by the |
| 7112 | // algorithm below. |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 7113 | AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7114 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7115 | if (!AddRec || AddRec->getLoop() != L) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7116 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7117 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7118 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of |
| 7119 | // the quadratic equation to solve it. |
| 7120 | if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 7121 | if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { |
| 7122 | const SCEVConstant *R1 = Roots->first; |
| 7123 | const SCEVConstant *R2 = Roots->second; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7124 | // Pick the smallest positive root value. |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 7125 | if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( |
| 7126 | CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 7127 | if (!CB->getZExtValue()) |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 7128 | std::swap(R1, R2); // R1 is the minimum root now. |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 7129 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7130 | // We can only use this value if the chrec ends up with an exact zero |
| 7131 | // value at this index. When solving for "X*X != 5", for example, we |
| 7132 | // should not accept a root of 2. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 7133 | const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 7134 | if (Val->isZero()) |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 7135 | // We found a quadratic root! |
| 7136 | return ExitLimit(R1, R1, false, Predicates); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7137 | } |
| 7138 | } |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7139 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7140 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7141 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7142 | // Otherwise we can only handle this if it is affine. |
| 7143 | if (!AddRec->isAffine()) |
| 7144 | return getCouldNotCompute(); |
| 7145 | |
| 7146 | // If this is an affine expression, the execution count of this branch is |
| 7147 | // the minimum unsigned root of the following equation: |
| 7148 | // |
| 7149 | // Start + Step*N = 0 (mod 2^BW) |
| 7150 | // |
| 7151 | // equivalent to: |
| 7152 | // |
| 7153 | // Step*N = -Start (mod 2^BW) |
| 7154 | // |
| 7155 | // where BW is the common bit width of Start and Step. |
| 7156 | |
| 7157 | // Get the initial value for the loop. |
| 7158 | const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); |
| 7159 | const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); |
| 7160 | |
| 7161 | // For now we handle only constant steps. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7162 | // |
| 7163 | // TODO: Handle a nonconstant Step given AddRec<NUW>. If the |
| 7164 | // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap |
| 7165 | // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. |
| 7166 | // We have not yet seen any such cases. |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7167 | const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 7168 | if (!StepC || StepC->getValue()->equalsInt(0)) |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7169 | return getCouldNotCompute(); |
| 7170 | |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7171 | // For positive steps (counting up until unsigned overflow): |
| 7172 | // N = -Start/Step (as unsigned) |
| 7173 | // For negative steps (counting down to zero): |
| 7174 | // N = Start/-Step |
| 7175 | // First compute the unsigned distance from zero in the direction of Step. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7176 | bool CountDown = StepC->getAPInt().isNegative(); |
Andrew Trick | f1781db | 2011-03-14 17:28:02 +0000 | [diff] [blame] | 7177 | const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7178 | |
| 7179 | // Handle unitary steps, which cannot wraparound. |
Andrew Trick | f1781db | 2011-03-14 17:28:02 +0000 | [diff] [blame] | 7180 | // 1*N = -Start; -1*N = Start (mod 2^BW), so: |
| 7181 | // N = Distance (as unsigned) |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 7182 | if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { |
| 7183 | ConstantRange CR = getUnsignedRange(Start); |
| 7184 | const SCEV *MaxBECount; |
| 7185 | if (!CountDown && CR.getUnsignedMin().isMinValue()) |
| 7186 | // When counting up, the worst starting value is 1, not 0. |
| 7187 | MaxBECount = CR.getUnsignedMax().isMinValue() |
| 7188 | ? getConstant(APInt::getMinValue(CR.getBitWidth())) |
| 7189 | : getConstant(APInt::getMaxValue(CR.getBitWidth())); |
| 7190 | else |
| 7191 | MaxBECount = getConstant(CountDown ? CR.getUnsignedMax() |
| 7192 | : -CR.getUnsignedMin()); |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 7193 | return ExitLimit(Distance, MaxBECount, false, Predicates); |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 7194 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 7195 | |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 7196 | // As a special case, handle the instance where Step is a positive power of |
| 7197 | // two. In this case, determining whether Step divides Distance evenly can be |
| 7198 | // done by counting and comparing the number of trailing zeros of Step and |
| 7199 | // Distance. |
| 7200 | if (!CountDown) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7201 | const APInt &StepV = StepC->getAPInt(); |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 7202 | // StepV.isPowerOf2() returns true if StepV is an positive power of two. It |
| 7203 | // also returns true if StepV is maximally negative (eg, INT_MIN), but that |
| 7204 | // case is not handled as this code is guarded by !CountDown. |
| 7205 | if (StepV.isPowerOf2() && |
Sanjoy Das | f3132d3 | 2015-09-10 05:27:38 +0000 | [diff] [blame] | 7206 | GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) { |
| 7207 | // Here we've constrained the equation to be of the form |
| 7208 | // |
| 7209 | // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0) |
| 7210 | // |
| 7211 | // where we're operating on a W bit wide integer domain and k is |
| 7212 | // non-negative. The smallest unsigned solution for X is the trip count. |
| 7213 | // |
| 7214 | // (0) is equivalent to: |
| 7215 | // |
| 7216 | // 2^(N + k) * Distance' - 2^N * X = L * 2^W |
| 7217 | // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N |
| 7218 | // <=> 2^k * Distance' - X = L * 2^(W - N) |
| 7219 | // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1) |
| 7220 | // |
| 7221 | // The smallest X satisfying (1) is unsigned remainder of dividing the LHS |
| 7222 | // by 2^(W - N). |
| 7223 | // |
| 7224 | // <=> X = 2^k * Distance' URem 2^(W - N) ... (2) |
| 7225 | // |
| 7226 | // E.g. say we're solving |
| 7227 | // |
| 7228 | // 2 * Val = 2 * X (in i8) ... (3) |
| 7229 | // |
| 7230 | // then from (2), we get X = Val URem i8 128 (k = 0 in this case). |
| 7231 | // |
| 7232 | // Note: It is tempting to solve (3) by setting X = Val, but Val is not |
| 7233 | // necessarily the smallest unsigned value of X that satisfies (3). |
| 7234 | // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3) |
| 7235 | // is i8 1, not i8 -127 |
| 7236 | |
| 7237 | const auto *ModuloResult = getUDivExactExpr(Distance, Step); |
| 7238 | |
| 7239 | // Since SCEV does not have a URem node, we construct one using a truncate |
| 7240 | // and a zero extend. |
| 7241 | |
| 7242 | unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros(); |
| 7243 | auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth); |
| 7244 | auto *WideTy = Distance->getType(); |
| 7245 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7246 | const SCEV *Limit = |
| 7247 | getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy); |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 7248 | return ExitLimit(Limit, Limit, false, Predicates); |
Sanjoy Das | f3132d3 | 2015-09-10 05:27:38 +0000 | [diff] [blame] | 7249 | } |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 7250 | } |
Benjamin Kramer | e75eaca | 2014-03-25 16:25:12 +0000 | [diff] [blame] | 7251 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7252 | // If the condition controls loop exit (the loop exits only if the expression |
| 7253 | // is true) and the addition is no-wrap we can use unsigned divide to |
| 7254 | // compute the backedge count. In this case, the step may not divide the |
| 7255 | // distance, but we don't care because if the condition is "missed" the loop |
| 7256 | // will have undefined behavior due to wrapping. |
Sanjoy Das | c7f69b9 | 2016-06-09 01:13:59 +0000 | [diff] [blame] | 7257 | if (ControlsExit && AddRec->hasNoSelfWrap() && |
| 7258 | loopHasNoAbnormalExits(AddRec->getLoop())) { |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7259 | const SCEV *Exact = |
| 7260 | getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 7261 | return ExitLimit(Exact, Exact, false, Predicates); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7262 | } |
Benjamin Kramer | e75eaca | 2014-03-25 16:25:12 +0000 | [diff] [blame] | 7263 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7264 | // Then, try to solve the above equation provided that Start is constant. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7265 | if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) { |
| 7266 | const SCEV *E = SolveLinEquationWithOverflow( |
| 7267 | StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this); |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 7268 | return ExitLimit(E, E, false, Predicates); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7269 | } |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7270 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7271 | } |
| 7272 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 7273 | ScalarEvolution::ExitLimit |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 7274 | ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7275 | // Loops that look like: while (X == 0) are very strange indeed. We don't |
| 7276 | // handle them yet except for the trivial case. This could be expanded in the |
| 7277 | // future as needed. |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7278 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7279 | // If the value is a constant, check to see if it is known to be non-zero |
| 7280 | // already. If so, the backedge will execute zero times. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 7281 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { |
Nick Lewycky | 5a3db14 | 2008-02-21 09:14:53 +0000 | [diff] [blame] | 7282 | if (!C->getValue()->isNullValue()) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 7283 | return getZero(C->getType()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7284 | return getCouldNotCompute(); // Otherwise it will loop infinitely. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7285 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7286 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7287 | // We could implement others, but I really doubt anyone writes loops like |
| 7288 | // this, and if they did, they would already be constant folded. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7289 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7290 | } |
| 7291 | |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7292 | std::pair<BasicBlock *, BasicBlock *> |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 7293 | ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { |
Dan Gohman | fa066ef | 2009-04-30 20:48:53 +0000 | [diff] [blame] | 7294 | // If the block has a unique predecessor, then there is no path from the |
| 7295 | // predecessor to the block that does not go through the direct edge |
| 7296 | // from the predecessor to the block. |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7297 | if (BasicBlock *Pred = BB->getSinglePredecessor()) |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 7298 | return {Pred, BB}; |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7299 | |
| 7300 | // 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] | 7301 | // If the header has a unique predecessor outside the loop, it must be |
| 7302 | // a block that has exactly one successor that can reach the loop. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7303 | if (Loop *L = LI.getLoopFor(BB)) |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 7304 | return {L->getLoopPredecessor(), L->getHeader()}; |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7305 | |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 7306 | return {nullptr, nullptr}; |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7307 | } |
| 7308 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 7309 | /// SCEV structural equivalence is usually sufficient for testing whether two |
| 7310 | /// expressions are equal, however for the purposes of looking for a condition |
| 7311 | /// guarding a loop, it can be useful to be a little more general, since a |
| 7312 | /// front-end may have replicated the controlling expression. |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7313 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 7314 | static bool HasSameValue(const SCEV *A, const SCEV *B) { |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7315 | // Quick check to see if they are the same SCEV. |
| 7316 | if (A == B) return true; |
| 7317 | |
Sanjoy Das | f1090b6 | 2015-09-27 21:09:48 +0000 | [diff] [blame] | 7318 | auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { |
| 7319 | // Not all instructions that are "identical" compute the same value. For |
| 7320 | // instance, two distinct alloca instructions allocating the same type are |
| 7321 | // identical and do not read memory; but compute distinct values. |
| 7322 | return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); |
| 7323 | }; |
| 7324 | |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7325 | // Otherwise, if they're both SCEVUnknown, it's possible that they hold |
| 7326 | // two different instructions with the same value. Check for this case. |
| 7327 | if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) |
| 7328 | if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) |
| 7329 | if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) |
| 7330 | if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) |
Sanjoy Das | f1090b6 | 2015-09-27 21:09:48 +0000 | [diff] [blame] | 7331 | if (ComputesEqualValues(AI, BI)) |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7332 | return true; |
| 7333 | |
| 7334 | // Otherwise assume they may have a different value. |
| 7335 | return false; |
| 7336 | } |
| 7337 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7338 | bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7339 | const SCEV *&LHS, const SCEV *&RHS, |
| 7340 | unsigned Depth) { |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7341 | bool Changed = false; |
| 7342 | |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7343 | // If we hit the max recursion limit bail out. |
| 7344 | if (Depth >= 3) |
| 7345 | return false; |
| 7346 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7347 | // Canonicalize a constant to the right side. |
| 7348 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { |
| 7349 | // Check for both operands constant. |
| 7350 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { |
| 7351 | if (ConstantExpr::getICmp(Pred, |
| 7352 | LHSC->getValue(), |
| 7353 | RHSC->getValue())->isNullValue()) |
| 7354 | goto trivially_false; |
| 7355 | else |
| 7356 | goto trivially_true; |
| 7357 | } |
| 7358 | // Otherwise swap the operands to put the constant on the right. |
| 7359 | std::swap(LHS, RHS); |
| 7360 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7361 | Changed = true; |
| 7362 | } |
| 7363 | |
| 7364 | // 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] | 7365 | // addrec's loop, put the addrec on the left. Also make a dominance check, |
| 7366 | // as both operands could be addrecs loop-invariant in each other's loop. |
| 7367 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { |
| 7368 | const Loop *L = AR->getLoop(); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 7369 | if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7370 | std::swap(LHS, RHS); |
| 7371 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7372 | Changed = true; |
| 7373 | } |
Dan Gohman | df564ca | 2010-05-03 17:00:11 +0000 | [diff] [blame] | 7374 | } |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7375 | |
| 7376 | // If there's a constant operand, canonicalize comparisons with boundary |
| 7377 | // cases, and canonicalize *-or-equal comparisons to regular comparisons. |
| 7378 | if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7379 | const APInt &RA = RC->getAPInt(); |
Sanjoy Das | 4aeb0f2 | 2016-10-02 20:59:10 +0000 | [diff] [blame] | 7380 | |
| 7381 | bool SimplifiedByConstantRange = false; |
| 7382 | |
| 7383 | if (!ICmpInst::isEquality(Pred)) { |
| 7384 | ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); |
| 7385 | if (ExactCR.isFullSet()) |
| 7386 | goto trivially_true; |
| 7387 | else if (ExactCR.isEmptySet()) |
| 7388 | goto trivially_false; |
| 7389 | |
| 7390 | APInt NewRHS; |
| 7391 | CmpInst::Predicate NewPred; |
| 7392 | if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && |
| 7393 | ICmpInst::isEquality(NewPred)) { |
| 7394 | // We were able to convert an inequality to an equality. |
| 7395 | Pred = NewPred; |
| 7396 | RHS = getConstant(NewRHS); |
| 7397 | Changed = SimplifiedByConstantRange = true; |
| 7398 | } |
| 7399 | } |
| 7400 | |
| 7401 | if (!SimplifiedByConstantRange) { |
| 7402 | switch (Pred) { |
| 7403 | default: |
| 7404 | break; |
| 7405 | case ICmpInst::ICMP_EQ: |
| 7406 | case ICmpInst::ICMP_NE: |
| 7407 | // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. |
| 7408 | if (!RA) |
| 7409 | if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) |
| 7410 | if (const SCEVMulExpr *ME = |
| 7411 | dyn_cast<SCEVMulExpr>(AE->getOperand(0))) |
| 7412 | if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && |
| 7413 | ME->getOperand(0)->isAllOnesValue()) { |
| 7414 | RHS = AE->getOperand(1); |
| 7415 | LHS = ME->getOperand(1); |
| 7416 | Changed = true; |
| 7417 | } |
| 7418 | break; |
| 7419 | |
| 7420 | |
| 7421 | // The "Should have been caught earlier!" messages refer to the fact |
| 7422 | // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above |
| 7423 | // should have fired on the corresponding cases, and canonicalized the |
| 7424 | // check to trivially_true or trivially_false. |
| 7425 | |
| 7426 | case ICmpInst::ICMP_UGE: |
| 7427 | assert(!RA.isMinValue() && "Should have been caught earlier!"); |
| 7428 | Pred = ICmpInst::ICMP_UGT; |
Sanjoy Das | f230b0a | 2016-10-02 02:40:27 +0000 | [diff] [blame] | 7429 | RHS = getConstant(RA - 1); |
| 7430 | Changed = true; |
| 7431 | break; |
Sanjoy Das | 4aeb0f2 | 2016-10-02 20:59:10 +0000 | [diff] [blame] | 7432 | case ICmpInst::ICMP_ULE: |
| 7433 | assert(!RA.isMaxValue() && "Should have been caught earlier!"); |
| 7434 | Pred = ICmpInst::ICMP_ULT; |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7435 | RHS = getConstant(RA + 1); |
| 7436 | Changed = true; |
| 7437 | break; |
Sanjoy Das | 4aeb0f2 | 2016-10-02 20:59:10 +0000 | [diff] [blame] | 7438 | case ICmpInst::ICMP_SGE: |
| 7439 | assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); |
| 7440 | Pred = ICmpInst::ICMP_SGT; |
Sanjoy Das | f230b0a | 2016-10-02 02:40:27 +0000 | [diff] [blame] | 7441 | RHS = getConstant(RA - 1); |
| 7442 | Changed = true; |
| 7443 | break; |
Sanjoy Das | 4aeb0f2 | 2016-10-02 20:59:10 +0000 | [diff] [blame] | 7444 | case ICmpInst::ICMP_SLE: |
| 7445 | assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); |
| 7446 | Pred = ICmpInst::ICMP_SLT; |
Sanjoy Das | f230b0a | 2016-10-02 02:40:27 +0000 | [diff] [blame] | 7447 | RHS = getConstant(RA + 1); |
| 7448 | Changed = true; |
| 7449 | break; |
| 7450 | } |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7451 | } |
| 7452 | } |
| 7453 | |
| 7454 | // Check for obvious equality. |
| 7455 | if (HasSameValue(LHS, RHS)) { |
| 7456 | if (ICmpInst::isTrueWhenEqual(Pred)) |
| 7457 | goto trivially_true; |
| 7458 | if (ICmpInst::isFalseWhenEqual(Pred)) |
| 7459 | goto trivially_false; |
| 7460 | } |
| 7461 | |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7462 | // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by |
| 7463 | // adding or subtracting 1 from one of the operands. |
| 7464 | switch (Pred) { |
| 7465 | case ICmpInst::ICMP_SLE: |
| 7466 | if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { |
| 7467 | RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7468 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7469 | Pred = ICmpInst::ICMP_SLT; |
| 7470 | Changed = true; |
| 7471 | } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7472 | LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7473 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7474 | Pred = ICmpInst::ICMP_SLT; |
| 7475 | Changed = true; |
| 7476 | } |
| 7477 | break; |
| 7478 | case ICmpInst::ICMP_SGE: |
| 7479 | if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7480 | RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7481 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7482 | Pred = ICmpInst::ICMP_SGT; |
| 7483 | Changed = true; |
| 7484 | } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { |
| 7485 | LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7486 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7487 | Pred = ICmpInst::ICMP_SGT; |
| 7488 | Changed = true; |
| 7489 | } |
| 7490 | break; |
| 7491 | case ICmpInst::ICMP_ULE: |
| 7492 | if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7493 | RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7494 | SCEV::FlagNUW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7495 | Pred = ICmpInst::ICMP_ULT; |
| 7496 | Changed = true; |
| 7497 | } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { |
Peter Collingbourne | c85f4ce | 2015-11-20 01:26:13 +0000 | [diff] [blame] | 7498 | LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7499 | Pred = ICmpInst::ICMP_ULT; |
| 7500 | Changed = true; |
| 7501 | } |
| 7502 | break; |
| 7503 | case ICmpInst::ICMP_UGE: |
| 7504 | if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { |
Peter Collingbourne | c85f4ce | 2015-11-20 01:26:13 +0000 | [diff] [blame] | 7505 | RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7506 | Pred = ICmpInst::ICMP_UGT; |
| 7507 | Changed = true; |
| 7508 | } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7509 | LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7510 | SCEV::FlagNUW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7511 | Pred = ICmpInst::ICMP_UGT; |
| 7512 | Changed = true; |
| 7513 | } |
| 7514 | break; |
| 7515 | default: |
| 7516 | break; |
| 7517 | } |
| 7518 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7519 | // TODO: More simplifications are possible here. |
| 7520 | |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7521 | // Recursively simplify until we either hit a recursion limit or nothing |
| 7522 | // changes. |
| 7523 | if (Changed) |
| 7524 | return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); |
| 7525 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7526 | return Changed; |
| 7527 | |
| 7528 | trivially_true: |
| 7529 | // Return 0 == 0. |
Benjamin Kramer | ddd1b7b | 2010-11-20 18:43:35 +0000 | [diff] [blame] | 7530 | LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7531 | Pred = ICmpInst::ICMP_EQ; |
| 7532 | return true; |
| 7533 | |
| 7534 | trivially_false: |
| 7535 | // Return 0 != 0. |
Benjamin Kramer | ddd1b7b | 2010-11-20 18:43:35 +0000 | [diff] [blame] | 7536 | LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7537 | Pred = ICmpInst::ICMP_NE; |
| 7538 | return true; |
| 7539 | } |
| 7540 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7541 | bool ScalarEvolution::isKnownNegative(const SCEV *S) { |
| 7542 | return getSignedRange(S).getSignedMax().isNegative(); |
| 7543 | } |
| 7544 | |
| 7545 | bool ScalarEvolution::isKnownPositive(const SCEV *S) { |
| 7546 | return getSignedRange(S).getSignedMin().isStrictlyPositive(); |
| 7547 | } |
| 7548 | |
| 7549 | bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { |
| 7550 | return !getSignedRange(S).getSignedMin().isNegative(); |
| 7551 | } |
| 7552 | |
| 7553 | bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { |
| 7554 | return !getSignedRange(S).getSignedMax().isStrictlyPositive(); |
| 7555 | } |
| 7556 | |
| 7557 | bool ScalarEvolution::isKnownNonZero(const SCEV *S) { |
| 7558 | return isKnownNegative(S) || isKnownPositive(S); |
| 7559 | } |
| 7560 | |
| 7561 | bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, |
| 7562 | const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | 36cce7e | 2010-04-24 01:38:36 +0000 | [diff] [blame] | 7563 | // Canonicalize the inputs first. |
| 7564 | (void)SimplifyICmpOperands(Pred, LHS, RHS); |
| 7565 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7566 | // If LHS or RHS is an addrec, check to see if the condition is true in |
| 7567 | // every iteration of the loop. |
Justin Bogner | cbb8438 | 2014-05-23 00:06:56 +0000 | [diff] [blame] | 7568 | // If LHS and RHS are both addrec, both conditions must be true in |
| 7569 | // every iteration of the loop. |
| 7570 | const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); |
| 7571 | const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); |
| 7572 | bool LeftGuarded = false; |
| 7573 | bool RightGuarded = false; |
| 7574 | if (LAR) { |
| 7575 | const Loop *L = LAR->getLoop(); |
| 7576 | if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && |
| 7577 | isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { |
| 7578 | if (!RAR) return true; |
| 7579 | LeftGuarded = true; |
| 7580 | } |
| 7581 | } |
| 7582 | if (RAR) { |
| 7583 | const Loop *L = RAR->getLoop(); |
| 7584 | if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && |
| 7585 | isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { |
| 7586 | if (!LAR) return true; |
| 7587 | RightGuarded = true; |
| 7588 | } |
| 7589 | } |
| 7590 | if (LeftGuarded && RightGuarded) |
| 7591 | return true; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7592 | |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7593 | if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) |
| 7594 | return true; |
| 7595 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7596 | // Otherwise see what can be done with known constant ranges. |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7597 | return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7598 | } |
| 7599 | |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7600 | bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, |
| 7601 | ICmpInst::Predicate Pred, |
| 7602 | bool &Increasing) { |
| 7603 | bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); |
| 7604 | |
| 7605 | #ifndef NDEBUG |
| 7606 | // Verify an invariant: inverting the predicate should turn a monotonically |
| 7607 | // increasing change to a monotonically decreasing one, and vice versa. |
| 7608 | bool IncreasingSwapped; |
| 7609 | bool ResultSwapped = isMonotonicPredicateImpl( |
| 7610 | LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); |
| 7611 | |
| 7612 | assert(Result == ResultSwapped && "should be able to analyze both!"); |
| 7613 | if (ResultSwapped) |
| 7614 | assert(Increasing == !IncreasingSwapped && |
| 7615 | "monotonicity should flip as we flip the predicate"); |
| 7616 | #endif |
| 7617 | |
| 7618 | return Result; |
| 7619 | } |
| 7620 | |
| 7621 | bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, |
| 7622 | ICmpInst::Predicate Pred, |
| 7623 | bool &Increasing) { |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7624 | |
| 7625 | // A zero step value for LHS means the induction variable is essentially a |
| 7626 | // loop invariant value. We don't really depend on the predicate actually |
| 7627 | // flipping from false to true (for increasing predicates, and the other way |
| 7628 | // around for decreasing predicates), all we care about is that *if* the |
| 7629 | // predicate changes then it only changes from false to true. |
| 7630 | // |
| 7631 | // A zero step value in itself is not very useful, but there may be places |
| 7632 | // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be |
| 7633 | // as general as possible. |
| 7634 | |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7635 | switch (Pred) { |
| 7636 | default: |
| 7637 | return false; // Conservative answer |
| 7638 | |
| 7639 | case ICmpInst::ICMP_UGT: |
| 7640 | case ICmpInst::ICMP_UGE: |
| 7641 | case ICmpInst::ICMP_ULT: |
| 7642 | case ICmpInst::ICMP_ULE: |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 7643 | if (!LHS->hasNoUnsignedWrap()) |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7644 | return false; |
| 7645 | |
| 7646 | Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7647 | return true; |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7648 | |
| 7649 | case ICmpInst::ICMP_SGT: |
| 7650 | case ICmpInst::ICMP_SGE: |
| 7651 | case ICmpInst::ICMP_SLT: |
| 7652 | case ICmpInst::ICMP_SLE: { |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 7653 | if (!LHS->hasNoSignedWrap()) |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7654 | return false; |
| 7655 | |
| 7656 | const SCEV *Step = LHS->getStepRecurrence(*this); |
| 7657 | |
| 7658 | if (isKnownNonNegative(Step)) { |
| 7659 | Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; |
| 7660 | return true; |
| 7661 | } |
| 7662 | |
| 7663 | if (isKnownNonPositive(Step)) { |
| 7664 | Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; |
| 7665 | return true; |
| 7666 | } |
| 7667 | |
| 7668 | return false; |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7669 | } |
| 7670 | |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7671 | } |
| 7672 | |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7673 | llvm_unreachable("switch has default clause!"); |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7674 | } |
| 7675 | |
| 7676 | bool ScalarEvolution::isLoopInvariantPredicate( |
| 7677 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, |
| 7678 | ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, |
| 7679 | const SCEV *&InvariantRHS) { |
| 7680 | |
| 7681 | // If there is a loop-invariant, force it into the RHS, otherwise bail out. |
| 7682 | if (!isLoopInvariant(RHS, L)) { |
| 7683 | if (!isLoopInvariant(LHS, L)) |
| 7684 | return false; |
| 7685 | |
| 7686 | std::swap(LHS, RHS); |
| 7687 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7688 | } |
| 7689 | |
| 7690 | const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); |
| 7691 | if (!ArLHS || ArLHS->getLoop() != L) |
| 7692 | return false; |
| 7693 | |
| 7694 | bool Increasing; |
| 7695 | if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) |
| 7696 | return false; |
| 7697 | |
| 7698 | // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to |
| 7699 | // true as the loop iterates, and the backedge is control dependent on |
| 7700 | // "ArLHS `Pred` RHS" == true then we can reason as follows: |
| 7701 | // |
| 7702 | // * if the predicate was false in the first iteration then the predicate |
| 7703 | // is never evaluated again, since the loop exits without taking the |
| 7704 | // backedge. |
| 7705 | // * if the predicate was true in the first iteration then it will |
| 7706 | // continue to be true for all future iterations since it is |
| 7707 | // monotonically increasing. |
| 7708 | // |
| 7709 | // For both the above possibilities, we can replace the loop varying |
| 7710 | // predicate with its value on the first iteration of the loop (which is |
| 7711 | // loop invariant). |
| 7712 | // |
| 7713 | // A similar reasoning applies for a monotonically decreasing predicate, by |
| 7714 | // replacing true with false and false with true in the above two bullets. |
| 7715 | |
| 7716 | auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); |
| 7717 | |
| 7718 | if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) |
| 7719 | return false; |
| 7720 | |
| 7721 | InvariantPred = Pred; |
| 7722 | InvariantLHS = ArLHS->getStart(); |
| 7723 | InvariantRHS = RHS; |
| 7724 | return true; |
| 7725 | } |
| 7726 | |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7727 | bool ScalarEvolution::isKnownPredicateViaConstantRanges( |
| 7728 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7729 | if (HasSameValue(LHS, RHS)) |
| 7730 | return ICmpInst::isTrueWhenEqual(Pred); |
| 7731 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7732 | // This code is split out from isKnownPredicate because it is called from |
| 7733 | // within isLoopEntryGuardedByCond. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7734 | |
Sanjoy Das | 4c7b6d7 | 2016-02-01 20:48:14 +0000 | [diff] [blame] | 7735 | auto CheckRanges = |
| 7736 | [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { |
| 7737 | return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) |
| 7738 | .contains(RangeLHS); |
| 7739 | }; |
| 7740 | |
| 7741 | // The check at the top of the function catches the case where the values are |
| 7742 | // known to be equal. |
| 7743 | if (Pred == CmpInst::ICMP_EQ) |
| 7744 | return false; |
| 7745 | |
| 7746 | if (Pred == CmpInst::ICMP_NE) |
| 7747 | return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || |
| 7748 | CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || |
| 7749 | isKnownNonZero(getMinusSCEV(LHS, RHS)); |
| 7750 | |
| 7751 | if (CmpInst::isSigned(Pred)) |
| 7752 | return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); |
| 7753 | |
| 7754 | return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7755 | } |
| 7756 | |
Sanjoy Das | c1a2977 | 2015-11-05 23:45:38 +0000 | [diff] [blame] | 7757 | bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, |
| 7758 | const SCEV *LHS, |
| 7759 | const SCEV *RHS) { |
| 7760 | |
| 7761 | // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. |
| 7762 | // Return Y via OutY. |
| 7763 | auto MatchBinaryAddToConst = |
| 7764 | [this](const SCEV *Result, const SCEV *X, APInt &OutY, |
| 7765 | SCEV::NoWrapFlags ExpectedFlags) { |
| 7766 | const SCEV *NonConstOp, *ConstOp; |
| 7767 | SCEV::NoWrapFlags FlagsPresent; |
| 7768 | |
| 7769 | if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || |
| 7770 | !isa<SCEVConstant>(ConstOp) || NonConstOp != X) |
| 7771 | return false; |
| 7772 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7773 | OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); |
Sanjoy Das | c1a2977 | 2015-11-05 23:45:38 +0000 | [diff] [blame] | 7774 | return (FlagsPresent & ExpectedFlags) == ExpectedFlags; |
| 7775 | }; |
| 7776 | |
| 7777 | APInt C; |
| 7778 | |
| 7779 | switch (Pred) { |
| 7780 | default: |
| 7781 | break; |
| 7782 | |
| 7783 | case ICmpInst::ICMP_SGE: |
| 7784 | std::swap(LHS, RHS); |
| 7785 | case ICmpInst::ICMP_SLE: |
| 7786 | // X s<= (X + C)<nsw> if C >= 0 |
| 7787 | if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) |
| 7788 | return true; |
| 7789 | |
| 7790 | // (X + C)<nsw> s<= X if C <= 0 |
| 7791 | if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && |
| 7792 | !C.isStrictlyPositive()) |
| 7793 | return true; |
| 7794 | break; |
| 7795 | |
| 7796 | case ICmpInst::ICMP_SGT: |
| 7797 | std::swap(LHS, RHS); |
| 7798 | case ICmpInst::ICMP_SLT: |
| 7799 | // X s< (X + C)<nsw> if C > 0 |
| 7800 | if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && |
| 7801 | C.isStrictlyPositive()) |
| 7802 | return true; |
| 7803 | |
| 7804 | // (X + C)<nsw> s< X if C < 0 |
| 7805 | if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) |
| 7806 | return true; |
| 7807 | break; |
| 7808 | } |
| 7809 | |
| 7810 | return false; |
| 7811 | } |
| 7812 | |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7813 | bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, |
| 7814 | const SCEV *LHS, |
| 7815 | const SCEV *RHS) { |
Sanjoy Das | 10dffcb | 2015-10-08 03:46:00 +0000 | [diff] [blame] | 7816 | if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7817 | return false; |
| 7818 | |
| 7819 | // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on |
| 7820 | // the stack can result in exponential time complexity. |
| 7821 | SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); |
| 7822 | |
| 7823 | // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L |
| 7824 | // |
| 7825 | // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use |
| 7826 | // isKnownPredicate. isKnownPredicate is more powerful, but also more |
| 7827 | // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the |
| 7828 | // interesting cases seen in practice. We can consider "upgrading" L >= 0 to |
| 7829 | // use isKnownPredicate later if needed. |
Alexander Kornienko | 484e48e3 | 2015-11-05 21:07:12 +0000 | [diff] [blame] | 7830 | return isKnownNonNegative(RHS) && |
| 7831 | isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && |
| 7832 | isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7833 | } |
| 7834 | |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 7835 | bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, |
| 7836 | ICmpInst::Predicate Pred, |
| 7837 | const SCEV *LHS, const SCEV *RHS) { |
| 7838 | // No need to even try if we know the module has no guards. |
| 7839 | if (!HasGuards) |
| 7840 | return false; |
| 7841 | |
| 7842 | return any_of(*BB, [&](Instruction &I) { |
| 7843 | using namespace llvm::PatternMatch; |
| 7844 | |
| 7845 | Value *Condition; |
| 7846 | return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( |
| 7847 | m_Value(Condition))) && |
| 7848 | isImpliedCond(Pred, LHS, RHS, Condition, false); |
| 7849 | }); |
| 7850 | } |
| 7851 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7852 | /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is |
| 7853 | /// protected by a conditional between LHS and RHS. This is used to |
| 7854 | /// to eliminate casts. |
| 7855 | bool |
| 7856 | ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, |
| 7857 | ICmpInst::Predicate Pred, |
| 7858 | const SCEV *LHS, const SCEV *RHS) { |
| 7859 | // Interpret a null as meaning no loop, where there is obviously no guard |
| 7860 | // (interprocedural conditions notwithstanding). |
| 7861 | if (!L) return true; |
| 7862 | |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7863 | if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) |
| 7864 | return true; |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 7865 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7866 | BasicBlock *Latch = L->getLoopLatch(); |
| 7867 | if (!Latch) |
| 7868 | return false; |
| 7869 | |
| 7870 | BranchInst *LoopContinuePredicate = |
| 7871 | dyn_cast<BranchInst>(Latch->getTerminator()); |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 7872 | if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && |
| 7873 | isImpliedCond(Pred, LHS, RHS, |
| 7874 | LoopContinuePredicate->getCondition(), |
| 7875 | LoopContinuePredicate->getSuccessor(0) != L->getHeader())) |
| 7876 | return true; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7877 | |
Piotr Padlewski | 0dde00d2 | 2015-09-09 20:47:30 +0000 | [diff] [blame] | 7878 | // 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] | 7879 | // -- that can lead to O(n!) time complexity. |
| 7880 | if (WalkingBEDominatingConds) |
| 7881 | return false; |
| 7882 | |
Sanjoy Das | 5d9a8cb | 2015-09-22 00:10:57 +0000 | [diff] [blame] | 7883 | SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7884 | |
Sanjoy Das | b174f9a | 2015-09-25 23:53:50 +0000 | [diff] [blame] | 7885 | // See if we can exploit a trip count to prove the predicate. |
| 7886 | const auto &BETakenInfo = getBackedgeTakenInfo(L); |
| 7887 | const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); |
| 7888 | if (LatchBECount != getCouldNotCompute()) { |
| 7889 | // We know that Latch branches back to the loop header exactly |
| 7890 | // LatchBECount times. This means the backdege condition at Latch is |
| 7891 | // equivalent to "{0,+,1} u< LatchBECount". |
| 7892 | Type *Ty = LatchBECount->getType(); |
| 7893 | auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); |
| 7894 | const SCEV *LoopCounter = |
| 7895 | getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); |
| 7896 | if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, |
| 7897 | LatchBECount)) |
| 7898 | return true; |
| 7899 | } |
| 7900 | |
Piotr Padlewski | 0dde00d2 | 2015-09-09 20:47:30 +0000 | [diff] [blame] | 7901 | // Check conditions due to any @llvm.assume intrinsics. |
| 7902 | for (auto &AssumeVH : AC.assumptions()) { |
| 7903 | if (!AssumeVH) |
| 7904 | continue; |
| 7905 | auto *CI = cast<CallInst>(AssumeVH); |
| 7906 | if (!DT.dominates(CI, Latch->getTerminator())) |
| 7907 | continue; |
| 7908 | |
| 7909 | if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) |
| 7910 | return true; |
| 7911 | } |
| 7912 | |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7913 | // If the loop is not reachable from the entry block, we risk running into an |
| 7914 | // infinite loop as we walk up into the dom tree. These loops do not matter |
| 7915 | // anyway, so we just return a conservative answer when we see them. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7916 | if (!DT.isReachableFromEntry(L->getHeader())) |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7917 | return false; |
| 7918 | |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 7919 | if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) |
| 7920 | return true; |
| 7921 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7922 | for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; |
| 7923 | DTN != HeaderDTN; DTN = DTN->getIDom()) { |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7924 | |
| 7925 | assert(DTN && "should reach the loop header before reaching the root!"); |
| 7926 | |
| 7927 | BasicBlock *BB = DTN->getBlock(); |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 7928 | if (isImpliedViaGuard(BB, Pred, LHS, RHS)) |
| 7929 | return true; |
| 7930 | |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7931 | BasicBlock *PBB = BB->getSinglePredecessor(); |
| 7932 | if (!PBB) |
| 7933 | continue; |
| 7934 | |
| 7935 | BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); |
| 7936 | if (!ContinuePredicate || !ContinuePredicate->isConditional()) |
| 7937 | continue; |
| 7938 | |
| 7939 | Value *Condition = ContinuePredicate->getCondition(); |
| 7940 | |
| 7941 | // If we have an edge `E` within the loop body that dominates the only |
| 7942 | // latch, the condition guarding `E` also guards the backedge. This |
| 7943 | // reasoning works only for loops with a single latch. |
| 7944 | |
| 7945 | BasicBlockEdge DominatingEdge(PBB, BB); |
| 7946 | if (DominatingEdge.isSingleEdge()) { |
| 7947 | // We're constructively (and conservatively) enumerating edges within the |
| 7948 | // loop body that dominate the latch. The dominator tree better agree |
| 7949 | // with us on this: |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7950 | assert(DT.dominates(DominatingEdge, Latch) && "should be!"); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7951 | |
| 7952 | if (isImpliedCond(Pred, LHS, RHS, Condition, |
| 7953 | BB != ContinuePredicate->getSuccessor(0))) |
| 7954 | return true; |
| 7955 | } |
| 7956 | } |
| 7957 | |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 7958 | return false; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7959 | } |
| 7960 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7961 | bool |
Dan Gohman | b50349a | 2010-04-11 19:27:13 +0000 | [diff] [blame] | 7962 | ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, |
| 7963 | ICmpInst::Predicate Pred, |
| 7964 | const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | 9cf09f8 | 2009-05-18 16:03:58 +0000 | [diff] [blame] | 7965 | // Interpret a null as meaning no loop, where there is obviously no guard |
| 7966 | // (interprocedural conditions notwithstanding). |
| 7967 | if (!L) return false; |
| 7968 | |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7969 | if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) |
| 7970 | return true; |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 7971 | |
Dan Gohman | 8c77f1a | 2009-05-18 15:36:09 +0000 | [diff] [blame] | 7972 | // Starting at the loop predecessor, climb up the predecessor chain, as long |
| 7973 | // as there are predecessors that can be found that have unique successors |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7974 | // leading to the original header. |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7975 | for (std::pair<BasicBlock *, BasicBlock *> |
Dan Gohman | 75c6b0b | 2010-06-22 23:43:28 +0000 | [diff] [blame] | 7976 | Pair(L->getLoopPredecessor(), L->getHeader()); |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7977 | Pair.first; |
| 7978 | Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7979 | |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 7980 | if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) |
| 7981 | return true; |
| 7982 | |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7983 | BranchInst *LoopEntryPredicate = |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7984 | dyn_cast<BranchInst>(Pair.first->getTerminator()); |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7985 | if (!LoopEntryPredicate || |
| 7986 | LoopEntryPredicate->isUnconditional()) |
| 7987 | continue; |
| 7988 | |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 7989 | if (isImpliedCond(Pred, LHS, RHS, |
| 7990 | LoopEntryPredicate->getCondition(), |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7991 | LoopEntryPredicate->getSuccessor(0) != Pair.second)) |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 7992 | return true; |
Nick Lewycky | b5688cc | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 7993 | } |
| 7994 | |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 7995 | // Check conditions due to any @llvm.assume intrinsics. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7996 | for (auto &AssumeVH : AC.assumptions()) { |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 7997 | if (!AssumeVH) |
| 7998 | continue; |
| 7999 | auto *CI = cast<CallInst>(AssumeVH); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8000 | if (!DT.dominates(CI, L->getHeader())) |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 8001 | continue; |
| 8002 | |
| 8003 | if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) |
| 8004 | return true; |
| 8005 | } |
| 8006 | |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 8007 | return false; |
Nick Lewycky | b5688cc | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 8008 | } |
| 8009 | |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8010 | bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8011 | const SCEV *LHS, const SCEV *RHS, |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8012 | Value *FoundCondValue, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8013 | bool Inverse) { |
Sanjoy Das | c46bceb | 2016-09-27 18:01:42 +0000 | [diff] [blame] | 8014 | if (!PendingLoopPredicates.insert(FoundCondValue).second) |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 8015 | return false; |
| 8016 | |
Sanjoy Das | c46bceb | 2016-09-27 18:01:42 +0000 | [diff] [blame] | 8017 | auto ClearOnExit = |
| 8018 | make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); |
| 8019 | |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 8020 | // Recursively handle And and Or conditions. |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8021 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8022 | if (BO->getOpcode() == Instruction::And) { |
| 8023 | if (!Inverse) |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8024 | return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || |
| 8025 | isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8026 | } else if (BO->getOpcode() == Instruction::Or) { |
| 8027 | if (Inverse) |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8028 | return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || |
| 8029 | isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8030 | } |
| 8031 | } |
| 8032 | |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8033 | ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8034 | if (!ICI) return false; |
| 8035 | |
Andrew Trick | fa59403 | 2012-11-29 18:35:13 +0000 | [diff] [blame] | 8036 | // Now that we found a conditional branch that dominates the loop or controls |
| 8037 | // 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] | 8038 | ICmpInst::Predicate FoundPred; |
| 8039 | if (Inverse) |
| 8040 | FoundPred = ICI->getInversePredicate(); |
| 8041 | else |
| 8042 | FoundPred = ICI->getPredicate(); |
| 8043 | |
| 8044 | const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); |
| 8045 | const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8046 | |
Sanjoy Das | df1635d | 2015-09-25 19:59:52 +0000 | [diff] [blame] | 8047 | return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); |
| 8048 | } |
| 8049 | |
| 8050 | bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, |
| 8051 | const SCEV *RHS, |
| 8052 | ICmpInst::Predicate FoundPred, |
| 8053 | const SCEV *FoundLHS, |
| 8054 | const SCEV *FoundRHS) { |
Sanjoy Das | 1459883 | 2015-03-26 17:28:26 +0000 | [diff] [blame] | 8055 | // Balance the types. |
| 8056 | if (getTypeSizeInBits(LHS->getType()) < |
| 8057 | getTypeSizeInBits(FoundLHS->getType())) { |
| 8058 | if (CmpInst::isSigned(Pred)) { |
| 8059 | LHS = getSignExtendExpr(LHS, FoundLHS->getType()); |
| 8060 | RHS = getSignExtendExpr(RHS, FoundLHS->getType()); |
| 8061 | } else { |
| 8062 | LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); |
| 8063 | RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); |
| 8064 | } |
| 8065 | } else if (getTypeSizeInBits(LHS->getType()) > |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8066 | getTypeSizeInBits(FoundLHS->getType())) { |
Stepan Dyatkovskiy | 431993b | 2014-01-09 12:26:12 +0000 | [diff] [blame] | 8067 | if (CmpInst::isSigned(FoundPred)) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8068 | FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); |
| 8069 | FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); |
| 8070 | } else { |
| 8071 | FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); |
| 8072 | FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); |
| 8073 | } |
| 8074 | } |
| 8075 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8076 | // Canonicalize the query to match the way instcombine will have |
| 8077 | // canonicalized the comparison. |
Dan Gohman | 3673aa1 | 2010-04-24 01:34:53 +0000 | [diff] [blame] | 8078 | if (SimplifyICmpOperands(Pred, LHS, RHS)) |
| 8079 | if (LHS == RHS) |
Dan Gohman | b5025c7 | 2010-05-03 18:00:24 +0000 | [diff] [blame] | 8080 | return CmpInst::isTrueWhenEqual(Pred); |
Benjamin Kramer | ba11a98 | 2012-11-29 19:07:57 +0000 | [diff] [blame] | 8081 | if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) |
| 8082 | if (FoundLHS == FoundRHS) |
| 8083 | return CmpInst::isFalseWhenEqual(FoundPred); |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8084 | |
| 8085 | // Check to see if we can make the LHS or RHS match. |
| 8086 | if (LHS == FoundRHS || RHS == FoundLHS) { |
| 8087 | if (isa<SCEVConstant>(RHS)) { |
| 8088 | std::swap(FoundLHS, FoundRHS); |
| 8089 | FoundPred = ICmpInst::getSwappedPredicate(FoundPred); |
| 8090 | } else { |
| 8091 | std::swap(LHS, RHS); |
| 8092 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 8093 | } |
| 8094 | } |
| 8095 | |
| 8096 | // Check whether the found predicate is the same as the desired predicate. |
| 8097 | if (FoundPred == Pred) |
| 8098 | return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); |
| 8099 | |
| 8100 | // Check whether swapping the found predicate makes it the same as the |
| 8101 | // desired predicate. |
| 8102 | if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { |
| 8103 | if (isa<SCEVConstant>(RHS)) |
| 8104 | return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); |
| 8105 | else |
| 8106 | return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), |
| 8107 | RHS, LHS, FoundLHS, FoundRHS); |
| 8108 | } |
| 8109 | |
Sanjoy Das | 6e78b17 | 2015-10-22 19:57:34 +0000 | [diff] [blame] | 8110 | // Unsigned comparison is the same as signed comparison when both the operands |
| 8111 | // are non-negative. |
| 8112 | if (CmpInst::isUnsigned(FoundPred) && |
| 8113 | CmpInst::getSignedPredicate(FoundPred) == Pred && |
| 8114 | isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) |
| 8115 | return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); |
| 8116 | |
Sanjoy Das | c5676df | 2014-11-13 00:00:58 +0000 | [diff] [blame] | 8117 | // Check if we can make progress by sharpening ranges. |
| 8118 | if (FoundPred == ICmpInst::ICMP_NE && |
| 8119 | (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { |
| 8120 | |
| 8121 | const SCEVConstant *C = nullptr; |
| 8122 | const SCEV *V = nullptr; |
| 8123 | |
| 8124 | if (isa<SCEVConstant>(FoundLHS)) { |
| 8125 | C = cast<SCEVConstant>(FoundLHS); |
| 8126 | V = FoundRHS; |
| 8127 | } else { |
| 8128 | C = cast<SCEVConstant>(FoundRHS); |
| 8129 | V = FoundLHS; |
| 8130 | } |
| 8131 | |
| 8132 | // The guarding predicate tells us that C != V. If the known range |
| 8133 | // of V is [C, t), we can sharpen the range to [C + 1, t). The |
| 8134 | // range we consider has to correspond to same signedness as the |
| 8135 | // predicate we're interested in folding. |
| 8136 | |
| 8137 | APInt Min = ICmpInst::isSigned(Pred) ? |
| 8138 | getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); |
| 8139 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8140 | if (Min == C->getAPInt()) { |
Sanjoy Das | c5676df | 2014-11-13 00:00:58 +0000 | [diff] [blame] | 8141 | // Given (V >= Min && V != Min) we conclude V >= (Min + 1). |
| 8142 | // This is true even if (Min + 1) wraps around -- in case of |
| 8143 | // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). |
| 8144 | |
| 8145 | APInt SharperMin = Min + 1; |
| 8146 | |
| 8147 | switch (Pred) { |
| 8148 | case ICmpInst::ICMP_SGE: |
| 8149 | case ICmpInst::ICMP_UGE: |
| 8150 | // We know V `Pred` SharperMin. If this implies LHS `Pred` |
| 8151 | // RHS, we're done. |
| 8152 | if (isImpliedCondOperands(Pred, LHS, RHS, V, |
| 8153 | getConstant(SharperMin))) |
| 8154 | return true; |
| 8155 | |
| 8156 | case ICmpInst::ICMP_SGT: |
| 8157 | case ICmpInst::ICMP_UGT: |
| 8158 | // We know from the range information that (V `Pred` Min || |
| 8159 | // V == Min). We know from the guarding condition that !(V |
| 8160 | // == Min). This gives us |
| 8161 | // |
| 8162 | // V `Pred` Min || V == Min && !(V == Min) |
| 8163 | // => V `Pred` Min |
| 8164 | // |
| 8165 | // If V `Pred` Min implies LHS `Pred` RHS, we're done. |
| 8166 | |
| 8167 | if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) |
| 8168 | return true; |
| 8169 | |
| 8170 | default: |
| 8171 | // No change |
| 8172 | break; |
| 8173 | } |
| 8174 | } |
| 8175 | } |
| 8176 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8177 | // Check whether the actual condition is beyond sufficient. |
| 8178 | if (FoundPred == ICmpInst::ICMP_EQ) |
| 8179 | if (ICmpInst::isTrueWhenEqual(Pred)) |
| 8180 | if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8181 | return true; |
| 8182 | if (Pred == ICmpInst::ICMP_NE) |
| 8183 | if (!ICmpInst::isTrueWhenEqual(FoundPred)) |
| 8184 | if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8185 | return true; |
| 8186 | |
| 8187 | // Otherwise assume the worst. |
| 8188 | return false; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8189 | } |
| 8190 | |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8191 | bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, |
| 8192 | const SCEV *&L, const SCEV *&R, |
| 8193 | SCEV::NoWrapFlags &Flags) { |
| 8194 | const auto *AE = dyn_cast<SCEVAddExpr>(Expr); |
| 8195 | if (!AE || AE->getNumOperands() != 2) |
| 8196 | return false; |
| 8197 | |
| 8198 | L = AE->getOperand(0); |
| 8199 | R = AE->getOperand(1); |
| 8200 | Flags = AE->getNoWrapFlags(); |
| 8201 | return true; |
| 8202 | } |
| 8203 | |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8204 | Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, |
| 8205 | const SCEV *Less) { |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8206 | // We avoid subtracting expressions here because this function is usually |
| 8207 | // fairly deep in the call stack (i.e. is called many times). |
| 8208 | |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8209 | if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { |
| 8210 | const auto *LAR = cast<SCEVAddRecExpr>(Less); |
| 8211 | const auto *MAR = cast<SCEVAddRecExpr>(More); |
| 8212 | |
| 8213 | if (LAR->getLoop() != MAR->getLoop()) |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8214 | return None; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8215 | |
| 8216 | // We look at affine expressions only; not for correctness but to keep |
| 8217 | // getStepRecurrence cheap. |
| 8218 | if (!LAR->isAffine() || !MAR->isAffine()) |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8219 | return None; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8220 | |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8221 | if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8222 | return None; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8223 | |
| 8224 | Less = LAR->getStart(); |
| 8225 | More = MAR->getStart(); |
| 8226 | |
| 8227 | // fall through |
| 8228 | } |
| 8229 | |
| 8230 | if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8231 | const auto &M = cast<SCEVConstant>(More)->getAPInt(); |
| 8232 | const auto &L = cast<SCEVConstant>(Less)->getAPInt(); |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8233 | return M - L; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8234 | } |
| 8235 | |
| 8236 | const SCEV *L, *R; |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8237 | SCEV::NoWrapFlags Flags; |
| 8238 | if (splitBinaryAdd(Less, L, R, Flags)) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8239 | if (const auto *LC = dyn_cast<SCEVConstant>(L)) |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8240 | if (R == More) |
| 8241 | return -(LC->getAPInt()); |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8242 | |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8243 | if (splitBinaryAdd(More, L, R, Flags)) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8244 | if (const auto *LC = dyn_cast<SCEVConstant>(L)) |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8245 | if (R == Less) |
| 8246 | return LC->getAPInt(); |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8247 | |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8248 | return None; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8249 | } |
| 8250 | |
| 8251 | bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( |
| 8252 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, |
| 8253 | const SCEV *FoundLHS, const SCEV *FoundRHS) { |
| 8254 | if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) |
| 8255 | return false; |
| 8256 | |
| 8257 | const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); |
| 8258 | if (!AddRecLHS) |
| 8259 | return false; |
| 8260 | |
| 8261 | const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); |
| 8262 | if (!AddRecFoundLHS) |
| 8263 | return false; |
| 8264 | |
| 8265 | // We'd like to let SCEV reason about control dependencies, so we constrain |
| 8266 | // both the inequalities to be about add recurrences on the same loop. This |
| 8267 | // way we can use isLoopEntryGuardedByCond later. |
| 8268 | |
| 8269 | const Loop *L = AddRecFoundLHS->getLoop(); |
| 8270 | if (L != AddRecLHS->getLoop()) |
| 8271 | return false; |
| 8272 | |
| 8273 | // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) |
| 8274 | // |
| 8275 | // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) |
| 8276 | // ... (2) |
| 8277 | // |
| 8278 | // Informal proof for (2), assuming (1) [*]: |
| 8279 | // |
| 8280 | // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] |
| 8281 | // |
| 8282 | // Then |
| 8283 | // |
| 8284 | // FoundLHS s< FoundRHS s< INT_MIN - C |
| 8285 | // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] |
| 8286 | // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] |
| 8287 | // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< |
| 8288 | // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] |
| 8289 | // <=> FoundLHS + C s< FoundRHS + C |
| 8290 | // |
| 8291 | // [*]: (1) can be proved by ruling out overflow. |
| 8292 | // |
| 8293 | // [**]: This can be proved by analyzing all the four possibilities: |
| 8294 | // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and |
| 8295 | // (A s>= 0, B s>= 0). |
| 8296 | // |
| 8297 | // Note: |
| 8298 | // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" |
| 8299 | // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS |
| 8300 | // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS |
| 8301 | // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is |
| 8302 | // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + |
| 8303 | // C)". |
| 8304 | |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8305 | Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); |
| 8306 | Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); |
| 8307 | if (!LDiff || !RDiff || *LDiff != *RDiff) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8308 | return false; |
| 8309 | |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8310 | if (LDiff->isMinValue()) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8311 | return true; |
| 8312 | |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8313 | APInt FoundRHSLimit; |
| 8314 | |
| 8315 | if (Pred == CmpInst::ICMP_ULT) { |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8316 | FoundRHSLimit = -(*RDiff); |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8317 | } else { |
| 8318 | assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8319 | FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8320 | } |
| 8321 | |
| 8322 | // Try to prove (1) or (2), as needed. |
| 8323 | return isLoopEntryGuardedByCond(L, Pred, FoundRHS, |
| 8324 | getConstant(FoundRHSLimit)); |
| 8325 | } |
| 8326 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8327 | bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, |
| 8328 | const SCEV *LHS, const SCEV *RHS, |
| 8329 | const SCEV *FoundLHS, |
| 8330 | const SCEV *FoundRHS) { |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8331 | if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8332 | return true; |
| 8333 | |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8334 | if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8335 | return true; |
| 8336 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8337 | return isImpliedCondOperandsHelper(Pred, LHS, RHS, |
| 8338 | FoundLHS, FoundRHS) || |
| 8339 | // ~x < ~y --> x > y |
| 8340 | isImpliedCondOperandsHelper(Pred, LHS, RHS, |
| 8341 | getNotSCEV(FoundRHS), |
| 8342 | getNotSCEV(FoundLHS)); |
| 8343 | } |
| 8344 | |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8345 | |
| 8346 | /// If Expr computes ~A, return A else return nullptr |
| 8347 | static const SCEV *MatchNotExpr(const SCEV *Expr) { |
| 8348 | const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); |
Sanjoy Das | 16e7ff1 | 2015-10-13 23:28:31 +0000 | [diff] [blame] | 8349 | if (!Add || Add->getNumOperands() != 2 || |
| 8350 | !Add->getOperand(0)->isAllOnesValue()) |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8351 | return nullptr; |
| 8352 | |
| 8353 | const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); |
Sanjoy Das | 16e7ff1 | 2015-10-13 23:28:31 +0000 | [diff] [blame] | 8354 | if (!AddRHS || AddRHS->getNumOperands() != 2 || |
| 8355 | !AddRHS->getOperand(0)->isAllOnesValue()) |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8356 | return nullptr; |
| 8357 | |
| 8358 | return AddRHS->getOperand(1); |
| 8359 | } |
| 8360 | |
| 8361 | |
| 8362 | /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? |
| 8363 | template<typename MaxExprType> |
| 8364 | static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, |
| 8365 | const SCEV *Candidate) { |
| 8366 | const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); |
| 8367 | if (!MaxExpr) return false; |
| 8368 | |
Sanjoy Das | 347d272 | 2015-12-01 07:49:27 +0000 | [diff] [blame] | 8369 | return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8370 | } |
| 8371 | |
| 8372 | |
| 8373 | /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? |
| 8374 | template<typename MaxExprType> |
| 8375 | static bool IsMinConsistingOf(ScalarEvolution &SE, |
| 8376 | const SCEV *MaybeMinExpr, |
| 8377 | const SCEV *Candidate) { |
| 8378 | const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); |
| 8379 | if (!MaybeMaxExpr) |
| 8380 | return false; |
| 8381 | |
| 8382 | return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); |
| 8383 | } |
| 8384 | |
Hal Finkel | a8d205f | 2015-08-19 01:51:51 +0000 | [diff] [blame] | 8385 | static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, |
| 8386 | ICmpInst::Predicate Pred, |
| 8387 | const SCEV *LHS, const SCEV *RHS) { |
| 8388 | |
| 8389 | // If both sides are affine addrecs for the same loop, with equal |
| 8390 | // steps, and we know the recurrences don't wrap, then we only |
| 8391 | // need to check the predicate on the starting values. |
| 8392 | |
| 8393 | if (!ICmpInst::isRelational(Pred)) |
| 8394 | return false; |
| 8395 | |
| 8396 | const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); |
| 8397 | if (!LAR) |
| 8398 | return false; |
| 8399 | const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); |
| 8400 | if (!RAR) |
| 8401 | return false; |
| 8402 | if (LAR->getLoop() != RAR->getLoop()) |
| 8403 | return false; |
| 8404 | if (!LAR->isAffine() || !RAR->isAffine()) |
| 8405 | return false; |
| 8406 | |
| 8407 | if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) |
| 8408 | return false; |
| 8409 | |
Hal Finkel | ff08a2e | 2015-08-19 17:26:07 +0000 | [diff] [blame] | 8410 | SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? |
| 8411 | SCEV::FlagNSW : SCEV::FlagNUW; |
| 8412 | if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) |
Hal Finkel | a8d205f | 2015-08-19 01:51:51 +0000 | [diff] [blame] | 8413 | return false; |
| 8414 | |
| 8415 | return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); |
| 8416 | } |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8417 | |
| 8418 | /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max |
| 8419 | /// expression? |
| 8420 | static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, |
| 8421 | ICmpInst::Predicate Pred, |
| 8422 | const SCEV *LHS, const SCEV *RHS) { |
| 8423 | switch (Pred) { |
| 8424 | default: |
| 8425 | return false; |
| 8426 | |
| 8427 | case ICmpInst::ICMP_SGE: |
| 8428 | std::swap(LHS, RHS); |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 8429 | LLVM_FALLTHROUGH; |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8430 | case ICmpInst::ICMP_SLE: |
| 8431 | return |
| 8432 | // min(A, ...) <= A |
| 8433 | IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || |
| 8434 | // A <= max(A, ...) |
| 8435 | IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); |
| 8436 | |
| 8437 | case ICmpInst::ICMP_UGE: |
| 8438 | std::swap(LHS, RHS); |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 8439 | LLVM_FALLTHROUGH; |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8440 | case ICmpInst::ICMP_ULE: |
| 8441 | return |
| 8442 | // min(A, ...) <= A |
| 8443 | IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || |
| 8444 | // A <= max(A, ...) |
| 8445 | IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); |
| 8446 | } |
| 8447 | |
| 8448 | llvm_unreachable("covered switch fell through?!"); |
| 8449 | } |
| 8450 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8451 | bool |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8452 | ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, |
| 8453 | const SCEV *LHS, const SCEV *RHS, |
| 8454 | const SCEV *FoundLHS, |
| 8455 | const SCEV *FoundRHS) { |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8456 | auto IsKnownPredicateFull = |
| 8457 | [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 8458 | return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || |
Sanjoy Das | 1123148 | 2015-10-22 19:57:29 +0000 | [diff] [blame] | 8459 | IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || |
Sanjoy Das | c1a2977 | 2015-11-05 23:45:38 +0000 | [diff] [blame] | 8460 | IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || |
| 8461 | isKnownPredicateViaNoOverflow(Pred, LHS, RHS); |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8462 | }; |
| 8463 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8464 | switch (Pred) { |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8465 | default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); |
| 8466 | case ICmpInst::ICMP_EQ: |
| 8467 | case ICmpInst::ICMP_NE: |
| 8468 | if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) |
| 8469 | return true; |
| 8470 | break; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8471 | case ICmpInst::ICMP_SLT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8472 | case ICmpInst::ICMP_SLE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8473 | if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) && |
| 8474 | IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8475 | return true; |
| 8476 | break; |
| 8477 | case ICmpInst::ICMP_SGT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8478 | case ICmpInst::ICMP_SGE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8479 | if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) && |
| 8480 | IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8481 | return true; |
| 8482 | break; |
| 8483 | case ICmpInst::ICMP_ULT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8484 | case ICmpInst::ICMP_ULE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8485 | if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) && |
| 8486 | IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8487 | return true; |
| 8488 | break; |
| 8489 | case ICmpInst::ICMP_UGT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8490 | case ICmpInst::ICMP_UGE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8491 | if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) && |
| 8492 | IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8493 | return true; |
| 8494 | break; |
| 8495 | } |
| 8496 | |
| 8497 | return false; |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8498 | } |
| 8499 | |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8500 | bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, |
| 8501 | const SCEV *LHS, |
| 8502 | const SCEV *RHS, |
| 8503 | const SCEV *FoundLHS, |
| 8504 | const SCEV *FoundRHS) { |
| 8505 | if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) |
| 8506 | // The restriction on `FoundRHS` be lifted easily -- it exists only to |
| 8507 | // reduce the compile time impact of this optimization. |
| 8508 | return false; |
| 8509 | |
Sanjoy Das | a7d9ec8 | 2016-07-23 00:54:36 +0000 | [diff] [blame] | 8510 | Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); |
Sanjoy Das | 095f5b2 | 2016-07-22 20:47:55 +0000 | [diff] [blame] | 8511 | if (!Addend) |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8512 | return false; |
| 8513 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8514 | APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8515 | |
| 8516 | // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the |
| 8517 | // antecedent "`FoundLHS` `Pred` `FoundRHS`". |
| 8518 | ConstantRange FoundLHSRange = |
| 8519 | ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); |
| 8520 | |
Sanjoy Das | 095f5b2 | 2016-07-22 20:47:55 +0000 | [diff] [blame] | 8521 | // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: |
| 8522 | ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8523 | |
| 8524 | // We can also compute the range of values for `LHS` that satisfy the |
| 8525 | // consequent, "`LHS` `Pred` `RHS`": |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8526 | APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8527 | ConstantRange SatisfyingLHSRange = |
| 8528 | ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); |
| 8529 | |
| 8530 | // The antecedent implies the consequent if every value of `LHS` that |
| 8531 | // satisfies the antecedent also satisfies the consequent. |
| 8532 | return SatisfyingLHSRange.contains(LHSRange); |
| 8533 | } |
| 8534 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8535 | bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, |
| 8536 | bool IsSigned, bool NoWrap) { |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8537 | assert(isKnownPositive(Stride) && "Positive stride expected!"); |
| 8538 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8539 | if (NoWrap) return false; |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 8540 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8541 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8542 | const SCEV *One = getOne(Stride->getType()); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 8543 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8544 | if (IsSigned) { |
| 8545 | APInt MaxRHS = getSignedRange(RHS).getSignedMax(); |
| 8546 | APInt MaxValue = APInt::getSignedMaxValue(BitWidth); |
| 8547 | APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) |
| 8548 | .getSignedMax(); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 8549 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8550 | // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! |
| 8551 | return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 8552 | } |
Dan Gohman | 0104842 | 2009-06-21 23:46:38 +0000 | [diff] [blame] | 8553 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8554 | APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); |
| 8555 | APInt MaxValue = APInt::getMaxValue(BitWidth); |
| 8556 | APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) |
| 8557 | .getUnsignedMax(); |
| 8558 | |
| 8559 | // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! |
| 8560 | return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); |
| 8561 | } |
| 8562 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8563 | bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, |
| 8564 | bool IsSigned, bool NoWrap) { |
| 8565 | if (NoWrap) return false; |
| 8566 | |
| 8567 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8568 | const SCEV *One = getOne(Stride->getType()); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8569 | |
| 8570 | if (IsSigned) { |
| 8571 | APInt MinRHS = getSignedRange(RHS).getSignedMin(); |
| 8572 | APInt MinValue = APInt::getSignedMinValue(BitWidth); |
| 8573 | APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) |
| 8574 | .getSignedMax(); |
| 8575 | |
| 8576 | // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! |
| 8577 | return (MinValue + MaxStrideMinusOne).sgt(MinRHS); |
| 8578 | } |
| 8579 | |
| 8580 | APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); |
| 8581 | APInt MinValue = APInt::getMinValue(BitWidth); |
| 8582 | APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) |
| 8583 | .getUnsignedMax(); |
| 8584 | |
| 8585 | // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! |
| 8586 | return (MinValue + MaxStrideMinusOne).ugt(MinRHS); |
| 8587 | } |
| 8588 | |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8589 | const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8590 | bool Equality) { |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8591 | const SCEV *One = getOne(Step->getType()); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8592 | Delta = Equality ? getAddExpr(Delta, Step) |
| 8593 | : getAddExpr(Delta, getMinusSCEV(Step, One)); |
| 8594 | return getUDivExpr(Delta, Step); |
Dan Gohman | 0104842 | 2009-06-21 23:46:38 +0000 | [diff] [blame] | 8595 | } |
| 8596 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 8597 | ScalarEvolution::ExitLimit |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 8598 | ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8599 | const Loop *L, bool IsSigned, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8600 | bool ControlsExit, bool AllowPredicates) { |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 8601 | SmallPtrSet<const SCEVPredicate *, 4> Predicates; |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8602 | // We handle only IV < Invariant |
| 8603 | if (!isLoopInvariant(RHS, L)) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 8604 | return getCouldNotCompute(); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8605 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8606 | const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8607 | bool PredicatedIV = false; |
| 8608 | |
| 8609 | if (!IV && AllowPredicates) { |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8610 | // Try to make this an AddRec using runtime tests, in the first X |
| 8611 | // iterations of this loop, where X is the SCEV expression found by the |
| 8612 | // algorithm below. |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 8613 | IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8614 | PredicatedIV = true; |
| 8615 | } |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8616 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8617 | // Avoid weird loops |
| 8618 | if (!IV || IV->getLoop() != L || !IV->isAffine()) |
| 8619 | return getCouldNotCompute(); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8620 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8621 | bool NoWrap = ControlsExit && |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8622 | IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); |
Wojciech Matyjewicz | 35545fd | 2008-02-13 11:51:34 +0000 | [diff] [blame] | 8623 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8624 | const SCEV *Stride = IV->getStepRecurrence(*this); |
Wojciech Matyjewicz | 35545fd | 2008-02-13 11:51:34 +0000 | [diff] [blame] | 8625 | |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8626 | bool PositiveStride = isKnownPositive(Stride); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8627 | |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8628 | // Avoid negative or zero stride values. |
| 8629 | if (!PositiveStride) { |
| 8630 | // We can compute the correct backedge taken count for loops with unknown |
| 8631 | // strides if we can prove that the loop is not an infinite loop with side |
| 8632 | // effects. Here's the loop structure we are trying to handle - |
| 8633 | // |
| 8634 | // i = start |
| 8635 | // do { |
| 8636 | // A[i] = i; |
| 8637 | // i += s; |
| 8638 | // } while (i < end); |
| 8639 | // |
| 8640 | // The backedge taken count for such loops is evaluated as - |
| 8641 | // (max(end, start + stride) - start - 1) /u stride |
| 8642 | // |
| 8643 | // The additional preconditions that we need to check to prove correctness |
| 8644 | // of the above formula is as follows - |
| 8645 | // |
| 8646 | // a) IV is either nuw or nsw depending upon signedness (indicated by the |
| 8647 | // NoWrap flag). |
| 8648 | // b) loop is single exit with no side effects. |
| 8649 | // |
| 8650 | // |
| 8651 | // Precondition a) implies that if the stride is negative, this is a single |
| 8652 | // trip loop. The backedge taken count formula reduces to zero in this case. |
| 8653 | // |
| 8654 | // Precondition b) implies that the unknown stride cannot be zero otherwise |
| 8655 | // we have UB. |
| 8656 | // |
| 8657 | // The positive stride case is the same as isKnownPositive(Stride) returning |
| 8658 | // true (original behavior of the function). |
| 8659 | // |
| 8660 | // We want to make sure that the stride is truly unknown as there are edge |
| 8661 | // cases where ScalarEvolution propagates no wrap flags to the |
| 8662 | // post-increment/decrement IV even though the increment/decrement operation |
| 8663 | // itself is wrapping. The computed backedge taken count may be wrong in |
| 8664 | // such cases. This is prevented by checking that the stride is not known to |
| 8665 | // be either positive or non-positive. For example, no wrap flags are |
| 8666 | // propagated to the post-increment IV of this loop with a trip count of 2 - |
| 8667 | // |
| 8668 | // unsigned char i; |
| 8669 | // for(i=127; i<128; i+=129) |
| 8670 | // A[i] = i; |
| 8671 | // |
| 8672 | if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || |
| 8673 | !loopHasNoSideEffects(L)) |
| 8674 | return getCouldNotCompute(); |
| 8675 | |
| 8676 | } else if (!Stride->isOne() && |
| 8677 | doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) |
| 8678 | // Avoid proven overflow cases: this will ensure that the backedge taken |
| 8679 | // count will not generate any unsigned overflow. Relaxed no-overflow |
| 8680 | // conditions exploit NoWrapFlags, allowing to optimize in presence of |
| 8681 | // undefined behaviors like the case of C language. |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 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 | ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT |
| 8685 | : ICmpInst::ICMP_ULT; |
| 8686 | const SCEV *Start = IV->getStart(); |
| 8687 | const SCEV *End = RHS; |
John Brawn | ecf7930 | 2016-10-18 10:10:53 +0000 | [diff] [blame] | 8688 | // If the backedge is taken at least once, then it will be taken |
| 8689 | // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start |
| 8690 | // is the LHS value of the less-than comparison the first time it is evaluated |
| 8691 | // and End is the RHS. |
| 8692 | const SCEV *BECountIfBackedgeTaken = |
| 8693 | computeBECount(getMinusSCEV(End, Start), Stride, false); |
| 8694 | // If the loop entry is guarded by the result of the backedge test of the |
| 8695 | // first loop iteration, then we know the backedge will be taken at least |
| 8696 | // once and so the backedge taken count is as above. If not then we use the |
| 8697 | // expression (max(End,Start)-Start)/Stride to describe the backedge count, |
| 8698 | // as if the backedge is taken at least once max(End,Start) is End and so the |
| 8699 | // result is as above, and if not max(End,Start) is Start so we get a backedge |
| 8700 | // count of zero. |
| 8701 | const SCEV *BECount; |
| 8702 | if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) |
| 8703 | BECount = BECountIfBackedgeTaken; |
| 8704 | else { |
Sanjoy Das | e8fd956 | 2016-06-18 04:38:31 +0000 | [diff] [blame] | 8705 | End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); |
John Brawn | ecf7930 | 2016-10-18 10:10:53 +0000 | [diff] [blame] | 8706 | BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); |
| 8707 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8708 | |
Arnaud A. de Grandmaison | 75c9e6d | 2014-03-15 22:13:15 +0000 | [diff] [blame] | 8709 | const SCEV *MaxBECount; |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 8710 | bool MaxOrZero = false; |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8711 | if (isa<SCEVConstant>(BECount)) |
| 8712 | MaxBECount = BECount; |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 8713 | else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { |
John Brawn | ecf7930 | 2016-10-18 10:10:53 +0000 | [diff] [blame] | 8714 | // If we know exactly how many times the backedge will be taken if it's |
| 8715 | // taken at least once, then the backedge count will either be that or |
| 8716 | // zero. |
| 8717 | MaxBECount = BECountIfBackedgeTaken; |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 8718 | MaxOrZero = true; |
| 8719 | } else { |
John Brawn | ecf7930 | 2016-10-18 10:10:53 +0000 | [diff] [blame] | 8720 | // Calculate the maximum backedge count based on the range of values |
| 8721 | // permitted by Start, End, and Stride. |
| 8722 | APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() |
| 8723 | : getUnsignedRange(Start).getUnsignedMin(); |
| 8724 | |
| 8725 | unsigned BitWidth = getTypeSizeInBits(LHS->getType()); |
| 8726 | |
| 8727 | APInt StrideForMaxBECount; |
| 8728 | |
| 8729 | if (PositiveStride) |
| 8730 | StrideForMaxBECount = |
| 8731 | IsSigned ? getSignedRange(Stride).getSignedMin() |
| 8732 | : getUnsignedRange(Stride).getUnsignedMin(); |
| 8733 | else |
| 8734 | // Using a stride of 1 is safe when computing max backedge taken count for |
| 8735 | // a loop with unknown stride. |
| 8736 | StrideForMaxBECount = APInt(BitWidth, 1, IsSigned); |
| 8737 | |
| 8738 | APInt Limit = |
| 8739 | IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1) |
| 8740 | : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1); |
| 8741 | |
| 8742 | // Although End can be a MAX expression we estimate MaxEnd considering only |
| 8743 | // the case End = RHS. This is safe because in the other case (End - Start) |
| 8744 | // is zero, leading to a zero maximum backedge taken count. |
| 8745 | APInt MaxEnd = |
| 8746 | IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) |
| 8747 | : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); |
| 8748 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8749 | MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8750 | getConstant(StrideForMaxBECount), false); |
John Brawn | ecf7930 | 2016-10-18 10:10:53 +0000 | [diff] [blame] | 8751 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8752 | |
| 8753 | if (isa<SCEVCouldNotCompute>(MaxBECount)) |
| 8754 | MaxBECount = BECount; |
| 8755 | |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 8756 | return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8757 | } |
| 8758 | |
| 8759 | ScalarEvolution::ExitLimit |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 8760 | ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8761 | const Loop *L, bool IsSigned, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8762 | bool ControlsExit, bool AllowPredicates) { |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 8763 | SmallPtrSet<const SCEVPredicate *, 4> Predicates; |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8764 | // We handle only IV > Invariant |
| 8765 | if (!isLoopInvariant(RHS, L)) |
| 8766 | return getCouldNotCompute(); |
| 8767 | |
| 8768 | const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8769 | if (!IV && AllowPredicates) |
| 8770 | // Try to make this an AddRec using runtime tests, in the first X |
| 8771 | // iterations of this loop, where X is the SCEV expression found by the |
| 8772 | // algorithm below. |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 8773 | IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8774 | |
| 8775 | // Avoid weird loops |
| 8776 | if (!IV || IV->getLoop() != L || !IV->isAffine()) |
| 8777 | return getCouldNotCompute(); |
| 8778 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8779 | bool NoWrap = ControlsExit && |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8780 | IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); |
| 8781 | |
| 8782 | const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); |
| 8783 | |
| 8784 | // Avoid negative or zero stride values |
| 8785 | if (!isKnownPositive(Stride)) |
| 8786 | return getCouldNotCompute(); |
| 8787 | |
| 8788 | // Avoid proven overflow cases: this will ensure that the backedge taken count |
| 8789 | // will not generate any unsigned overflow. Relaxed no-overflow conditions |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8790 | // exploit NoWrapFlags, allowing to optimize in presence of undefined |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8791 | // behaviors like the case of C language. |
| 8792 | if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) |
| 8793 | return getCouldNotCompute(); |
| 8794 | |
| 8795 | ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT |
| 8796 | : ICmpInst::ICMP_UGT; |
| 8797 | |
| 8798 | const SCEV *Start = IV->getStart(); |
| 8799 | const SCEV *End = RHS; |
Sanjoy Das | e8fd956 | 2016-06-18 04:38:31 +0000 | [diff] [blame] | 8800 | if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) |
| 8801 | End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8802 | |
| 8803 | const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); |
| 8804 | |
| 8805 | APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() |
| 8806 | : getUnsignedRange(Start).getUnsignedMax(); |
| 8807 | |
| 8808 | APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() |
| 8809 | : getUnsignedRange(Stride).getUnsignedMin(); |
| 8810 | |
| 8811 | unsigned BitWidth = getTypeSizeInBits(LHS->getType()); |
| 8812 | APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) |
| 8813 | : APInt::getMinValue(BitWidth) + (MinStride - 1); |
| 8814 | |
| 8815 | // Although End can be a MIN expression we estimate MinEnd considering only |
| 8816 | // the case End = RHS. This is safe because in the other case (Start - End) |
| 8817 | // is zero, leading to a zero maximum backedge taken count. |
| 8818 | APInt MinEnd = |
| 8819 | IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) |
| 8820 | : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); |
| 8821 | |
| 8822 | |
| 8823 | const SCEV *MaxBECount = getCouldNotCompute(); |
| 8824 | if (isa<SCEVConstant>(BECount)) |
| 8825 | MaxBECount = BECount; |
| 8826 | else |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8827 | MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8828 | getConstant(MinStride), false); |
| 8829 | |
| 8830 | if (isa<SCEVCouldNotCompute>(MaxBECount)) |
| 8831 | MaxBECount = BECount; |
| 8832 | |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 8833 | return ExitLimit(BECount, MaxBECount, false, Predicates); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8834 | } |
| 8835 | |
Benjamin Kramer | c321e53 | 2016-06-08 19:09:22 +0000 | [diff] [blame] | 8836 | const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 8837 | ScalarEvolution &SE) const { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8838 | if (Range.isFullSet()) // Infinite loop. |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8839 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8840 | |
| 8841 | // 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] | 8842 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 8843 | if (!SC->getValue()->isZero()) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 8844 | SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8845 | Operands[0] = SE.getZero(SC->getType()); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 8846 | const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 8847 | getNoWrapFlags(FlagNW)); |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 8848 | if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8849 | return ShiftedAddRec->getNumIterationsInRange( |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8850 | Range.subtract(SC->getAPInt()), SE); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8851 | // This is strange and shouldn't happen. |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8852 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8853 | } |
| 8854 | |
| 8855 | // The only time we can solve this is when we have all constant indices. |
| 8856 | // Otherwise, we cannot determine the overflow conditions. |
Sanjoy Das | ff3b8b4 | 2015-12-01 07:49:23 +0000 | [diff] [blame] | 8857 | if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) |
Sanjoy Das | f07d2a7 | 2015-10-18 00:29:23 +0000 | [diff] [blame] | 8858 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8859 | |
| 8860 | // Okay at this point we know that all elements of the chrec are constants and |
| 8861 | // that the start element is zero. |
| 8862 | |
| 8863 | // First check to see if the range contains zero. If not, the first |
| 8864 | // iteration exits. |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 8865 | unsigned BitWidth = SE.getTypeSizeInBits(getType()); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 8866 | if (!Range.contains(APInt(BitWidth, 0))) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8867 | return SE.getZero(getType()); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8868 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8869 | if (isAffine()) { |
| 8870 | // If this is an affine expression then we have this situation: |
| 8871 | // Solve {0,+,A} in Range === Ax in Range |
| 8872 | |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 8873 | // We know that zero is in the range. If A is positive then we know that |
| 8874 | // the upper value of the range must be the first possible exit value. |
| 8875 | // If A is negative then the lower of the range is the last possible loop |
| 8876 | // value. Also note that we already checked for a full range. |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 8877 | APInt One(BitWidth,1); |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8878 | APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 8879 | APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8880 | |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 8881 | // The exit value should be (End+A)/A. |
Nick Lewycky | 3934961 | 2007-09-27 14:12:54 +0000 | [diff] [blame] | 8882 | APInt ExitVal = (End + A).udiv(A); |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 8883 | ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8884 | |
| 8885 | // Evaluate at the exit value. If we really did fall out of the valid |
| 8886 | // range, then we computed our trip count, otherwise wrap around or other |
| 8887 | // things must have happened. |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8888 | ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8889 | if (Range.contains(Val->getValue())) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8890 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8891 | |
| 8892 | // 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] | 8893 | assert(Range.contains( |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 8894 | EvaluateConstantChrecAtConstant(this, |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 8895 | ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8896 | "Linear scev computation is off in a bad way!"); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8897 | return SE.getConstant(ExitValue); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8898 | } else if (isQuadratic()) { |
| 8899 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the |
| 8900 | // quadratic equation to solve it. To do this, we must frame our problem in |
| 8901 | // terms of figuring out when zero is crossed, instead of when |
| 8902 | // Range.getUpper() is crossed. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 8903 | SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8904 | NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); |
Sanjoy Das | 54e6a21 | 2016-10-02 00:09:45 +0000 | [diff] [blame] | 8905 | const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), FlagAnyWrap); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8906 | |
| 8907 | // Next, solve the constructed addrec |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 8908 | if (auto Roots = |
| 8909 | SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 8910 | const SCEVConstant *R1 = Roots->first; |
| 8911 | const SCEVConstant *R2 = Roots->second; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 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()) |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +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. |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 8921 | ConstantInt *R1Val = |
| 8922 | EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8923 | if (Range.contains(R1Val->getValue())) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8924 | // The next iteration must be out of the range... |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 8925 | ConstantInt *NextVal = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8926 | ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8927 | |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8928 | R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8929 | if (!Range.contains(R1Val->getValue())) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8930 | return SE.getConstant(NextVal); |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 8931 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8932 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8933 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8934 | // If R1 was not in the range, then it is a good return value. Make |
| 8935 | // sure that R1-1 WAS in the range though, just in case. |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 8936 | ConstantInt *NextVal = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8937 | ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8938 | R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8939 | if (Range.contains(R1Val->getValue())) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8940 | return R1; |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 8941 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8942 | } |
| 8943 | } |
| 8944 | } |
| 8945 | |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8946 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8947 | } |
| 8948 | |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 8949 | // Return true when S contains at least an undef value. |
Sanjoy Das | 6b46a0d | 2016-11-09 18:22:43 +0000 | [diff] [blame] | 8950 | static inline bool containsUndefs(const SCEV *S) { |
| 8951 | return SCEVExprContains(S, [](const SCEV *S) { |
| 8952 | if (const auto *SU = dyn_cast<SCEVUnknown>(S)) |
| 8953 | return isa<UndefValue>(SU->getValue()); |
| 8954 | else if (const auto *SC = dyn_cast<SCEVConstant>(S)) |
| 8955 | return isa<UndefValue>(SC->getValue()); |
| 8956 | return false; |
| 8957 | }); |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 8958 | } |
| 8959 | |
| 8960 | namespace { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8961 | // Collect all steps of SCEV expressions. |
| 8962 | struct SCEVCollectStrides { |
| 8963 | ScalarEvolution &SE; |
| 8964 | SmallVectorImpl<const SCEV *> &Strides; |
| 8965 | |
| 8966 | SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) |
| 8967 | : SE(SE), Strides(S) {} |
| 8968 | |
| 8969 | bool follow(const SCEV *S) { |
| 8970 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) |
| 8971 | Strides.push_back(AR->getStepRecurrence(SE)); |
| 8972 | return true; |
| 8973 | } |
| 8974 | bool isDone() const { return false; } |
| 8975 | }; |
| 8976 | |
| 8977 | // Collect all SCEVUnknown and SCEVMulExpr expressions. |
| 8978 | struct SCEVCollectTerms { |
| 8979 | SmallVectorImpl<const SCEV *> &Terms; |
| 8980 | |
| 8981 | SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) |
| 8982 | : Terms(T) {} |
| 8983 | |
| 8984 | bool follow(const SCEV *S) { |
Tobias Grosser | 2bbec0e | 2016-10-17 11:56:26 +0000 | [diff] [blame] | 8985 | if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || |
| 8986 | isa<SCEVSignExtendExpr>(S)) { |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 8987 | if (!containsUndefs(S)) |
| 8988 | Terms.push_back(S); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8989 | |
| 8990 | // Stop recursion: once we collected a term, do not walk its operands. |
| 8991 | return false; |
| 8992 | } |
| 8993 | |
| 8994 | // Keep looking. |
| 8995 | return true; |
| 8996 | } |
| 8997 | bool isDone() const { return false; } |
| 8998 | }; |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 8999 | |
| 9000 | // Check if a SCEV contains an AddRecExpr. |
| 9001 | struct SCEVHasAddRec { |
| 9002 | bool &ContainsAddRec; |
| 9003 | |
| 9004 | SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { |
| 9005 | ContainsAddRec = false; |
| 9006 | } |
| 9007 | |
| 9008 | bool follow(const SCEV *S) { |
| 9009 | if (isa<SCEVAddRecExpr>(S)) { |
| 9010 | ContainsAddRec = true; |
| 9011 | |
| 9012 | // Stop recursion: once we collected a term, do not walk its operands. |
| 9013 | return false; |
| 9014 | } |
| 9015 | |
| 9016 | // Keep looking. |
| 9017 | return true; |
| 9018 | } |
| 9019 | bool isDone() const { return false; } |
| 9020 | }; |
| 9021 | |
| 9022 | // Find factors that are multiplied with an expression that (possibly as a |
| 9023 | // subexpression) contains an AddRecExpr. In the expression: |
| 9024 | // |
| 9025 | // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) |
| 9026 | // |
| 9027 | // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" |
| 9028 | // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size |
| 9029 | // parameters as they form a product with an induction variable. |
| 9030 | // |
| 9031 | // This collector expects all array size parameters to be in the same MulExpr. |
| 9032 | // It might be necessary to later add support for collecting parameters that are |
| 9033 | // spread over different nested MulExpr. |
| 9034 | struct SCEVCollectAddRecMultiplies { |
| 9035 | SmallVectorImpl<const SCEV *> &Terms; |
| 9036 | ScalarEvolution &SE; |
| 9037 | |
| 9038 | SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) |
| 9039 | : Terms(T), SE(SE) {} |
| 9040 | |
| 9041 | bool follow(const SCEV *S) { |
| 9042 | if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { |
| 9043 | bool HasAddRec = false; |
| 9044 | SmallVector<const SCEV *, 0> Operands; |
| 9045 | for (auto Op : Mul->operands()) { |
| 9046 | if (isa<SCEVUnknown>(Op)) { |
| 9047 | Operands.push_back(Op); |
| 9048 | } else { |
| 9049 | bool ContainsAddRec; |
| 9050 | SCEVHasAddRec ContiansAddRec(ContainsAddRec); |
| 9051 | visitAll(Op, ContiansAddRec); |
| 9052 | HasAddRec |= ContainsAddRec; |
| 9053 | } |
| 9054 | } |
| 9055 | if (Operands.size() == 0) |
| 9056 | return true; |
| 9057 | |
| 9058 | if (!HasAddRec) |
| 9059 | return false; |
| 9060 | |
| 9061 | Terms.push_back(SE.getMulExpr(Operands)); |
| 9062 | // Stop recursion: once we collected a term, do not walk its operands. |
| 9063 | return false; |
| 9064 | } |
| 9065 | |
| 9066 | // Keep looking. |
| 9067 | return true; |
| 9068 | } |
| 9069 | bool isDone() const { return false; } |
| 9070 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 9071 | } |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9072 | |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9073 | /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in |
| 9074 | /// two places: |
| 9075 | /// 1) The strides of AddRec expressions. |
| 9076 | /// 2) Unknowns that are multiplied with AddRec expressions. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9077 | void ScalarEvolution::collectParametricTerms(const SCEV *Expr, |
| 9078 | SmallVectorImpl<const SCEV *> &Terms) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9079 | SmallVector<const SCEV *, 4> Strides; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9080 | SCEVCollectStrides StrideCollector(*this, Strides); |
| 9081 | visitAll(Expr, StrideCollector); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9082 | |
| 9083 | DEBUG({ |
| 9084 | dbgs() << "Strides:\n"; |
| 9085 | for (const SCEV *S : Strides) |
| 9086 | dbgs() << *S << "\n"; |
| 9087 | }); |
| 9088 | |
| 9089 | for (const SCEV *S : Strides) { |
| 9090 | SCEVCollectTerms TermCollector(Terms); |
| 9091 | visitAll(S, TermCollector); |
| 9092 | } |
| 9093 | |
| 9094 | DEBUG({ |
| 9095 | dbgs() << "Terms:\n"; |
| 9096 | for (const SCEV *T : Terms) |
| 9097 | dbgs() << *T << "\n"; |
| 9098 | }); |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9099 | |
| 9100 | SCEVCollectAddRecMultiplies MulCollector(Terms, *this); |
| 9101 | visitAll(Expr, MulCollector); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9102 | } |
| 9103 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9104 | static bool findArrayDimensionsRec(ScalarEvolution &SE, |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9105 | SmallVectorImpl<const SCEV *> &Terms, |
Sebastian Pop | 47fe7de | 2014-05-09 22:45:07 +0000 | [diff] [blame] | 9106 | SmallVectorImpl<const SCEV *> &Sizes) { |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9107 | int Last = Terms.size() - 1; |
| 9108 | const SCEV *Step = Terms[Last]; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9109 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9110 | // End of recursion. |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9111 | if (Last == 0) { |
| 9112 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9113 | SmallVector<const SCEV *, 2> Qs; |
| 9114 | for (const SCEV *Op : M->operands()) |
| 9115 | if (!isa<SCEVConstant>(Op)) |
| 9116 | Qs.push_back(Op); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9117 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9118 | Step = SE.getMulExpr(Qs); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9119 | } |
| 9120 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9121 | Sizes.push_back(Step); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9122 | return true; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9123 | } |
| 9124 | |
Benjamin Kramer | 8cff45a | 2014-05-10 17:47:18 +0000 | [diff] [blame] | 9125 | for (const SCEV *&Term : Terms) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9126 | // Normalize the terms before the next call to findArrayDimensionsRec. |
| 9127 | const SCEV *Q, *R; |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 9128 | SCEVDivision::divide(SE, Term, Step, &Q, &R); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9129 | |
| 9130 | // Bail out when GCD does not evenly divide one of the terms. |
| 9131 | if (!R->isZero()) |
| 9132 | return false; |
| 9133 | |
Benjamin Kramer | 8cff45a | 2014-05-10 17:47:18 +0000 | [diff] [blame] | 9134 | Term = Q; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9135 | } |
| 9136 | |
Tobias Grosser | 3080cf1 | 2014-05-08 07:55:34 +0000 | [diff] [blame] | 9137 | // Remove all SCEVConstants. |
David Majnemer | c700490 | 2016-08-12 04:32:37 +0000 | [diff] [blame] | 9138 | Terms.erase( |
| 9139 | remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), |
| 9140 | Terms.end()); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9141 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9142 | if (Terms.size() > 0) |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9143 | if (!findArrayDimensionsRec(SE, Terms, Sizes)) |
| 9144 | return false; |
| 9145 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9146 | Sizes.push_back(Step); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9147 | return true; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9148 | } |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9149 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9150 | |
| 9151 | // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. |
Sanjoy Das | 6b46a0d | 2016-11-09 18:22:43 +0000 | [diff] [blame] | 9152 | static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9153 | for (const SCEV *T : Terms) |
Sanjoy Das | 0ae390a | 2016-11-10 06:33:54 +0000 | [diff] [blame] | 9154 | if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9155 | return true; |
| 9156 | return false; |
| 9157 | } |
| 9158 | |
| 9159 | // Return the number of product terms in S. |
| 9160 | static inline int numberOfTerms(const SCEV *S) { |
| 9161 | if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) |
| 9162 | return Expr->getNumOperands(); |
| 9163 | return 1; |
| 9164 | } |
| 9165 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9166 | static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { |
| 9167 | if (isa<SCEVConstant>(T)) |
| 9168 | return nullptr; |
| 9169 | |
| 9170 | if (isa<SCEVUnknown>(T)) |
| 9171 | return T; |
| 9172 | |
| 9173 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { |
| 9174 | SmallVector<const SCEV *, 2> Factors; |
| 9175 | for (const SCEV *Op : M->operands()) |
| 9176 | if (!isa<SCEVConstant>(Op)) |
| 9177 | Factors.push_back(Op); |
| 9178 | |
| 9179 | return SE.getMulExpr(Factors); |
| 9180 | } |
| 9181 | |
| 9182 | return T; |
| 9183 | } |
| 9184 | |
| 9185 | /// Return the size of an element read or written by Inst. |
| 9186 | const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { |
| 9187 | Type *Ty; |
| 9188 | if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) |
| 9189 | Ty = Store->getValueOperand()->getType(); |
| 9190 | else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) |
Tobias Grosser | 40ac100 | 2014-06-08 19:21:20 +0000 | [diff] [blame] | 9191 | Ty = Load->getType(); |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9192 | else |
| 9193 | return nullptr; |
| 9194 | |
| 9195 | Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); |
| 9196 | return getSizeOfExpr(ETy, Ty); |
| 9197 | } |
| 9198 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9199 | void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, |
| 9200 | SmallVectorImpl<const SCEV *> &Sizes, |
| 9201 | const SCEV *ElementSize) const { |
Sebastian Pop | 5352408 | 2014-05-29 19:44:05 +0000 | [diff] [blame] | 9202 | if (Terms.size() < 1 || !ElementSize) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9203 | return; |
| 9204 | |
| 9205 | // Early return when Terms do not contain parameters: we do not delinearize |
| 9206 | // non parametric SCEVs. |
| 9207 | if (!containsParameters(Terms)) |
| 9208 | return; |
| 9209 | |
| 9210 | DEBUG({ |
| 9211 | dbgs() << "Terms:\n"; |
| 9212 | for (const SCEV *T : Terms) |
| 9213 | dbgs() << *T << "\n"; |
| 9214 | }); |
| 9215 | |
| 9216 | // Remove duplicates. |
| 9217 | std::sort(Terms.begin(), Terms.end()); |
| 9218 | Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); |
| 9219 | |
| 9220 | // Put larger terms first. |
| 9221 | std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { |
| 9222 | return numberOfTerms(LHS) > numberOfTerms(RHS); |
| 9223 | }); |
| 9224 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9225 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
| 9226 | |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9227 | // Try to divide all terms by the element size. If term is not divisible by |
| 9228 | // element size, proceed with the original term. |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9229 | for (const SCEV *&Term : Terms) { |
| 9230 | const SCEV *Q, *R; |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 9231 | SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9232 | if (!Q->isZero()) |
| 9233 | Term = Q; |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9234 | } |
| 9235 | |
| 9236 | SmallVector<const SCEV *, 4> NewTerms; |
| 9237 | |
| 9238 | // Remove constant factors. |
| 9239 | for (const SCEV *T : Terms) |
| 9240 | if (const SCEV *NewT = removeConstantFactors(SE, T)) |
| 9241 | NewTerms.push_back(NewT); |
| 9242 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9243 | DEBUG({ |
| 9244 | dbgs() << "Terms after sorting:\n"; |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9245 | for (const SCEV *T : NewTerms) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9246 | dbgs() << *T << "\n"; |
| 9247 | }); |
| 9248 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9249 | if (NewTerms.empty() || |
| 9250 | !findArrayDimensionsRec(SE, NewTerms, Sizes)) { |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9251 | Sizes.clear(); |
| 9252 | return; |
| 9253 | } |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9254 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9255 | // The last element to be pushed into Sizes is the size of an element. |
| 9256 | Sizes.push_back(ElementSize); |
| 9257 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9258 | DEBUG({ |
| 9259 | dbgs() << "Sizes:\n"; |
| 9260 | for (const SCEV *S : Sizes) |
| 9261 | dbgs() << *S << "\n"; |
| 9262 | }); |
| 9263 | } |
| 9264 | |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9265 | void ScalarEvolution::computeAccessFunctions( |
| 9266 | const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, |
| 9267 | SmallVectorImpl<const SCEV *> &Sizes) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9268 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9269 | // Early exit in case this SCEV is not an affine multivariate function. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9270 | if (Sizes.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9271 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9272 | |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 9273 | if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9274 | if (!AR->isAffine()) |
| 9275 | return; |
| 9276 | |
| 9277 | const SCEV *Res = Expr; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9278 | int Last = Sizes.size() - 1; |
| 9279 | for (int i = Last; i >= 0; i--) { |
| 9280 | const SCEV *Q, *R; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9281 | SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9282 | |
| 9283 | DEBUG({ |
| 9284 | dbgs() << "Res: " << *Res << "\n"; |
| 9285 | dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; |
| 9286 | dbgs() << "Res divided by Sizes[i]:\n"; |
| 9287 | dbgs() << "Quotient: " << *Q << "\n"; |
| 9288 | dbgs() << "Remainder: " << *R << "\n"; |
| 9289 | }); |
| 9290 | |
| 9291 | Res = Q; |
| 9292 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9293 | // Do not record the last subscript corresponding to the size of elements in |
| 9294 | // the array. |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9295 | if (i == Last) { |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9296 | |
| 9297 | // Bail out if the remainder is too complex. |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9298 | if (isa<SCEVAddRecExpr>(R)) { |
| 9299 | Subscripts.clear(); |
| 9300 | Sizes.clear(); |
| 9301 | return; |
| 9302 | } |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9303 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9304 | continue; |
| 9305 | } |
| 9306 | |
| 9307 | // Record the access function for the current subscript. |
| 9308 | Subscripts.push_back(R); |
| 9309 | } |
| 9310 | |
| 9311 | // Also push in last position the remainder of the last division: it will be |
| 9312 | // the access function of the innermost dimension. |
| 9313 | Subscripts.push_back(Res); |
| 9314 | |
| 9315 | std::reverse(Subscripts.begin(), Subscripts.end()); |
| 9316 | |
| 9317 | DEBUG({ |
| 9318 | dbgs() << "Subscripts:\n"; |
| 9319 | for (const SCEV *S : Subscripts) |
| 9320 | dbgs() << *S << "\n"; |
| 9321 | }); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9322 | } |
| 9323 | |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9324 | /// Splits the SCEV into two vectors of SCEVs representing the subscripts and |
| 9325 | /// sizes of an array access. Returns the remainder of the delinearization that |
Sebastian Pop | 7ee1472 | 2013-11-13 22:37:58 +0000 | [diff] [blame] | 9326 | /// is the offset start of the array. The SCEV->delinearize algorithm computes |
| 9327 | /// the multiples of SCEV coefficients: that is a pattern matching of sub |
| 9328 | /// expressions in the stride and base of a SCEV corresponding to the |
| 9329 | /// computation of a GCD (greatest common divisor) of base and stride. When |
| 9330 | /// SCEV->delinearize fails, it returns the SCEV unchanged. |
| 9331 | /// |
| 9332 | /// For example: when analyzing the memory access A[i][j][k] in this loop nest |
| 9333 | /// |
| 9334 | /// void foo(long n, long m, long o, double A[n][m][o]) { |
| 9335 | /// |
| 9336 | /// for (long i = 0; i < n; i++) |
| 9337 | /// for (long j = 0; j < m; j++) |
| 9338 | /// for (long k = 0; k < o; k++) |
| 9339 | /// A[i][j][k] = 1.0; |
| 9340 | /// } |
| 9341 | /// |
| 9342 | /// the delinearization input is the following AddRec SCEV: |
| 9343 | /// |
| 9344 | /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> |
| 9345 | /// |
| 9346 | /// From this SCEV, we are able to say that the base offset of the access is %A |
| 9347 | /// because it appears as an offset that does not divide any of the strides in |
| 9348 | /// the loops: |
| 9349 | /// |
| 9350 | /// CHECK: Base offset: %A |
| 9351 | /// |
| 9352 | /// and then SCEV->delinearize determines the size of some of the dimensions of |
| 9353 | /// the array as these are the multiples by which the strides are happening: |
| 9354 | /// |
| 9355 | /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. |
| 9356 | /// |
| 9357 | /// Note that the outermost dimension remains of UnknownSize because there are |
| 9358 | /// no strides that would help identifying the size of the last dimension: when |
| 9359 | /// the array has been statically allocated, one could compute the size of that |
| 9360 | /// dimension by dividing the overall size of the array by the size of the known |
| 9361 | /// dimensions: %m * %o * 8. |
| 9362 | /// |
| 9363 | /// Finally delinearize provides the access functions for the array reference |
| 9364 | /// that does correspond to A[i][j][k] of the above C testcase: |
| 9365 | /// |
| 9366 | /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] |
| 9367 | /// |
| 9368 | /// The testcases are checking the output of a function pass: |
| 9369 | /// DelinearizationPass that walks through all loads and stores of a function |
| 9370 | /// asking for the SCEV of the memory access with respect to all enclosing |
| 9371 | /// loops, calling SCEV->delinearize on that and printing the results. |
| 9372 | |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9373 | void ScalarEvolution::delinearize(const SCEV *Expr, |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9374 | SmallVectorImpl<const SCEV *> &Subscripts, |
| 9375 | SmallVectorImpl<const SCEV *> &Sizes, |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9376 | const SCEV *ElementSize) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9377 | // First step: collect parametric terms. |
| 9378 | SmallVector<const SCEV *, 4> Terms; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9379 | collectParametricTerms(Expr, Terms); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9380 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9381 | if (Terms.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9382 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9383 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9384 | // Second step: find subscript sizes. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9385 | findArrayDimensions(Terms, Sizes, ElementSize); |
Sebastian Pop | 7ee1472 | 2013-11-13 22:37:58 +0000 | [diff] [blame] | 9386 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9387 | if (Sizes.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9388 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9389 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9390 | // Third step: compute the access functions for each subscript. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9391 | computeAccessFunctions(Expr, Subscripts, Sizes); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9392 | |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9393 | if (Subscripts.empty()) |
| 9394 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9395 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9396 | DEBUG({ |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9397 | dbgs() << "succeeded to delinearize " << *Expr << "\n"; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9398 | dbgs() << "ArrayDecl[UnknownSize]"; |
| 9399 | for (const SCEV *S : Sizes) |
| 9400 | dbgs() << "[" << *S << "]"; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9401 | |
Sebastian Pop | 444621a | 2014-05-09 22:45:02 +0000 | [diff] [blame] | 9402 | dbgs() << "\nArrayRef"; |
| 9403 | for (const SCEV *S : Subscripts) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9404 | dbgs() << "[" << *S << "]"; |
| 9405 | dbgs() << "\n"; |
| 9406 | }); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9407 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9408 | |
| 9409 | //===----------------------------------------------------------------------===// |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9410 | // SCEVCallbackVH Class Implementation |
| 9411 | //===----------------------------------------------------------------------===// |
| 9412 | |
Dan Gohman | d33a090 | 2009-05-19 19:22:47 +0000 | [diff] [blame] | 9413 | void ScalarEvolution::SCEVCallbackVH::deleted() { |
Dan Gohman | dd707af | 2009-07-13 22:20:53 +0000 | [diff] [blame] | 9414 | assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9415 | if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) |
| 9416 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9417 | SE->eraseValueFromMap(getValPtr()); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9418 | // this now dangles! |
| 9419 | } |
| 9420 | |
Dan Gohman | 7a06672 | 2010-07-28 01:09:07 +0000 | [diff] [blame] | 9421 | void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { |
Dan Gohman | dd707af | 2009-07-13 22:20:53 +0000 | [diff] [blame] | 9422 | assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); |
Eric Christopher | ef6d593 | 2010-07-29 01:25:38 +0000 | [diff] [blame] | 9423 | |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9424 | // Forget all the expressions associated with users of the old value, |
| 9425 | // so that future queries will recompute the expressions using the new |
| 9426 | // value. |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 9427 | Value *Old = getValPtr(); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 9428 | SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); |
Dan Gohman | f34f863 | 2009-07-14 14:34:04 +0000 | [diff] [blame] | 9429 | SmallPtrSet<User *, 8> Visited; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9430 | while (!Worklist.empty()) { |
| 9431 | User *U = Worklist.pop_back_val(); |
| 9432 | // Deleting the Old value will cause this to dangle. Postpone |
| 9433 | // that until everything else is done. |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 9434 | if (U == Old) |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9435 | continue; |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 9436 | if (!Visited.insert(U).second) |
Dan Gohman | f34f863 | 2009-07-14 14:34:04 +0000 | [diff] [blame] | 9437 | continue; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9438 | if (PHINode *PN = dyn_cast<PHINode>(U)) |
| 9439 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9440 | SE->eraseValueFromMap(U); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 9441 | Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9442 | } |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 9443 | // Delete the Old value. |
| 9444 | if (PHINode *PN = dyn_cast<PHINode>(Old)) |
| 9445 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9446 | SE->eraseValueFromMap(Old); |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 9447 | // this now dangles! |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9448 | } |
| 9449 | |
Dan Gohman | d33a090 | 2009-05-19 19:22:47 +0000 | [diff] [blame] | 9450 | ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9451 | : CallbackVH(V), SE(se) {} |
| 9452 | |
| 9453 | //===----------------------------------------------------------------------===// |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9454 | // ScalarEvolution Class Implementation |
| 9455 | //===----------------------------------------------------------------------===// |
| 9456 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9457 | ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, |
| 9458 | AssumptionCache &AC, DominatorTree &DT, |
| 9459 | LoopInfo &LI) |
| 9460 | : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), |
| 9461 | CouldNotCompute(new SCEVCouldNotCompute()), |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 9462 | WalkingBEDominatingConds(false), ProvingSplitPredicate(false), |
| 9463 | ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 9464 | FirstUnknown(nullptr) { |
| 9465 | |
| 9466 | // To use guards for proving predicates, we need to scan every instruction in |
| 9467 | // relevant basic blocks, and not just terminators. Doing this is a waste of |
| 9468 | // time if the IR does not actually contain any calls to |
| 9469 | // @llvm.experimental.guard, so do a quick check and remember this beforehand. |
| 9470 | // |
| 9471 | // This pessimizes the case where a pass that preserves ScalarEvolution wants |
| 9472 | // to _add_ guards to the module when there weren't any before, and wants |
| 9473 | // ScalarEvolution to optimize based on those guards. For now we prefer to be |
| 9474 | // efficient in lieu of being smart in that rather obscure case. |
| 9475 | |
| 9476 | auto *GuardDecl = F.getParent()->getFunction( |
| 9477 | Intrinsic::getName(Intrinsic::experimental_guard)); |
| 9478 | HasGuards = GuardDecl && !GuardDecl->use_empty(); |
| 9479 | } |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9480 | |
| 9481 | ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 9482 | : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), |
| 9483 | LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9484 | ValueExprMap(std::move(Arg.ValueExprMap)), |
Sanjoy Das | db93375 | 2016-09-27 18:01:38 +0000 | [diff] [blame] | 9485 | PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 9486 | WalkingBEDominatingConds(false), ProvingSplitPredicate(false), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9487 | BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 9488 | PredicatedBackedgeTakenCounts( |
| 9489 | std::move(Arg.PredicatedBackedgeTakenCounts)), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9490 | ConstantEvolutionLoopExitValue( |
| 9491 | std::move(Arg.ConstantEvolutionLoopExitValue)), |
| 9492 | ValuesAtScopes(std::move(Arg.ValuesAtScopes)), |
| 9493 | LoopDispositions(std::move(Arg.LoopDispositions)), |
Sanjoy Das | 5cb11b6 | 2016-09-26 02:44:10 +0000 | [diff] [blame] | 9494 | LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), |
Chandler Carruth | 68abda5 | 2016-09-26 04:49:58 +0000 | [diff] [blame] | 9495 | BlockDispositions(std::move(Arg.BlockDispositions)), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9496 | UnsignedRanges(std::move(Arg.UnsignedRanges)), |
| 9497 | SignedRanges(std::move(Arg.SignedRanges)), |
| 9498 | UniqueSCEVs(std::move(Arg.UniqueSCEVs)), |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9499 | UniquePreds(std::move(Arg.UniquePreds)), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9500 | SCEVAllocator(std::move(Arg.SCEVAllocator)), |
| 9501 | FirstUnknown(Arg.FirstUnknown) { |
| 9502 | Arg.FirstUnknown = nullptr; |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9503 | } |
| 9504 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9505 | ScalarEvolution::~ScalarEvolution() { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 9506 | // Iterate through all the SCEVUnknown instances and call their |
| 9507 | // destructors, so that they release their references to their values. |
Naomi Musgrave | f90c1be | 2015-09-16 23:46:40 +0000 | [diff] [blame] | 9508 | for (SCEVUnknown *U = FirstUnknown; U;) { |
| 9509 | SCEVUnknown *Tmp = U; |
| 9510 | U = U->Next; |
| 9511 | Tmp->~SCEVUnknown(); |
| 9512 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 9513 | FirstUnknown = nullptr; |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 9514 | |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9515 | ExprValueMap.clear(); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 9516 | ValueExprMap.clear(); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9517 | HasRecMap.clear(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 9518 | |
| 9519 | // Free any extra memory created for ExitNotTakenInfo in the unlikely event |
| 9520 | // that a loop had multiple computable exits. |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9521 | for (auto &BTCI : BackedgeTakenCounts) |
| 9522 | BTCI.second.clear(); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 9523 | for (auto &BTCI : PredicatedBackedgeTakenCounts) |
| 9524 | BTCI.second.clear(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 9525 | |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 9526 | assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 9527 | assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 9528 | assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 9529 | } |
| 9530 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9531 | bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 9532 | return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9533 | } |
| 9534 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9535 | static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9536 | const Loop *L) { |
| 9537 | // Print all inner loops first |
Benjamin Kramer | aa20915 | 2016-06-26 17:27:42 +0000 | [diff] [blame] | 9538 | for (Loop *I : *L) |
| 9539 | PrintLoopInfo(OS, SE, I); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 9540 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9541 | OS << "Loop "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 9542 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9543 | OS << ": "; |
Chris Lattner | d72c3eb | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 9544 | |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 9545 | SmallVector<BasicBlock *, 8> ExitBlocks; |
Chris Lattner | d72c3eb | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 9546 | L->getExitBlocks(ExitBlocks); |
| 9547 | if (ExitBlocks.size() != 1) |
Nick Lewycky | d1200b0 | 2008-01-02 02:49:20 +0000 | [diff] [blame] | 9548 | OS << "<multiple exits> "; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9549 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 9550 | if (SE->hasLoopInvariantBackedgeTakenCount(L)) { |
| 9551 | OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9552 | } else { |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 9553 | OS << "Unpredictable backedge-taken count. "; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9554 | } |
| 9555 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9556 | OS << "\n" |
| 9557 | "Loop "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 9558 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9559 | OS << ": "; |
Dan Gohman | 6994293 | 2009-06-24 00:33:16 +0000 | [diff] [blame] | 9560 | |
| 9561 | if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { |
| 9562 | OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); |
John Brawn | 84b2183 | 2016-10-21 11:08:48 +0000 | [diff] [blame] | 9563 | if (SE->isBackedgeTakenCountMaxOrZero(L)) |
| 9564 | OS << ", actual taken count either this or zero."; |
Dan Gohman | 6994293 | 2009-06-24 00:33:16 +0000 | [diff] [blame] | 9565 | } else { |
| 9566 | OS << "Unpredictable max backedge-taken count. "; |
| 9567 | } |
| 9568 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 9569 | OS << "\n" |
| 9570 | "Loop "; |
| 9571 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
| 9572 | OS << ": "; |
| 9573 | |
| 9574 | SCEVUnionPredicate Pred; |
| 9575 | auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); |
| 9576 | if (!isa<SCEVCouldNotCompute>(PBT)) { |
| 9577 | OS << "Predicated backedge-taken count is " << *PBT << "\n"; |
| 9578 | OS << " Predicates:\n"; |
| 9579 | Pred.print(OS, 4); |
| 9580 | } else { |
| 9581 | OS << "Unpredictable predicated backedge-taken count. "; |
| 9582 | } |
Dan Gohman | 6994293 | 2009-06-24 00:33:16 +0000 | [diff] [blame] | 9583 | OS << "\n"; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9584 | } |
| 9585 | |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9586 | static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { |
| 9587 | switch (LD) { |
| 9588 | case ScalarEvolution::LoopVariant: |
| 9589 | return "Variant"; |
| 9590 | case ScalarEvolution::LoopInvariant: |
| 9591 | return "Invariant"; |
| 9592 | case ScalarEvolution::LoopComputable: |
| 9593 | return "Computable"; |
| 9594 | } |
Simon Pilgrim | 33ae13d | 2016-05-01 15:52:31 +0000 | [diff] [blame] | 9595 | llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9596 | } |
| 9597 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9598 | void ScalarEvolution::print(raw_ostream &OS) const { |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 9599 | // ScalarEvolution's implementation of the print method is to print |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9600 | // out SCEV values of all instructions that are interesting. Doing |
| 9601 | // this potentially causes it to create new SCEV objects though, |
| 9602 | // which technically conflicts with the const qualifier. This isn't |
Dan Gohman | 028e615 | 2009-07-10 20:25:29 +0000 | [diff] [blame] | 9603 | // observable from outside the class though, so casting away the |
| 9604 | // const isn't dangerous. |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 9605 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9606 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9607 | OS << "Classifying expressions for: "; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9608 | F.printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9609 | OS << "\n"; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9610 | for (Instruction &I : instructions(F)) |
| 9611 | if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { |
| 9612 | OS << I << '\n'; |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 9613 | OS << " --> "; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9614 | const SCEV *SV = SE.getSCEV(&I); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9615 | SV->print(OS); |
Sanjoy Das | f257452 | 2015-03-09 21:43:39 +0000 | [diff] [blame] | 9616 | if (!isa<SCEVCouldNotCompute>(SV)) { |
| 9617 | OS << " U: "; |
| 9618 | SE.getUnsignedRange(SV).print(OS); |
| 9619 | OS << " S: "; |
| 9620 | SE.getSignedRange(SV).print(OS); |
| 9621 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 9622 | |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9623 | const Loop *L = LI.getLoopFor(I.getParent()); |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 9624 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 9625 | const SCEV *AtUse = SE.getSCEVAtScope(SV, L); |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 9626 | if (AtUse != SV) { |
| 9627 | OS << " --> "; |
| 9628 | AtUse->print(OS); |
Sanjoy Das | f257452 | 2015-03-09 21:43:39 +0000 | [diff] [blame] | 9629 | if (!isa<SCEVCouldNotCompute>(AtUse)) { |
| 9630 | OS << " U: "; |
| 9631 | SE.getUnsignedRange(AtUse).print(OS); |
| 9632 | OS << " S: "; |
| 9633 | SE.getSignedRange(AtUse).print(OS); |
| 9634 | } |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 9635 | } |
| 9636 | |
| 9637 | if (L) { |
Dan Gohman | 94c468f | 2009-06-18 00:37:45 +0000 | [diff] [blame] | 9638 | OS << "\t\t" "Exits: "; |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 9639 | const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9640 | if (!SE.isLoopInvariant(ExitValue, L)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9641 | OS << "<<Unknown>>"; |
| 9642 | } else { |
| 9643 | OS << *ExitValue; |
| 9644 | } |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9645 | |
| 9646 | bool First = true; |
| 9647 | for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { |
| 9648 | if (First) { |
Sanjoy Das | 013a4ac | 2016-05-03 17:49:57 +0000 | [diff] [blame] | 9649 | OS << "\t\t" "LoopDispositions: { "; |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9650 | First = false; |
| 9651 | } else { |
| 9652 | OS << ", "; |
| 9653 | } |
| 9654 | |
Sanjoy Das | 013a4ac | 2016-05-03 17:49:57 +0000 | [diff] [blame] | 9655 | Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
| 9656 | OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9657 | } |
| 9658 | |
Sanjoy Das | 013a4ac | 2016-05-03 17:49:57 +0000 | [diff] [blame] | 9659 | for (auto *InnerL : depth_first(L)) { |
| 9660 | if (InnerL == L) |
| 9661 | continue; |
| 9662 | if (First) { |
| 9663 | OS << "\t\t" "LoopDispositions: { "; |
| 9664 | First = false; |
| 9665 | } else { |
| 9666 | OS << ", "; |
| 9667 | } |
| 9668 | |
| 9669 | InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
| 9670 | OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); |
| 9671 | } |
| 9672 | |
| 9673 | OS << " }"; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9674 | } |
| 9675 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9676 | OS << "\n"; |
| 9677 | } |
| 9678 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9679 | OS << "Determining loop execution counts for: "; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9680 | F.printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9681 | OS << "\n"; |
Benjamin Kramer | aa20915 | 2016-06-26 17:27:42 +0000 | [diff] [blame] | 9682 | for (Loop *I : LI) |
| 9683 | PrintLoopInfo(OS, &SE, I); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9684 | } |
Dan Gohman | e20f824 | 2009-04-21 00:47:46 +0000 | [diff] [blame] | 9685 | |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9686 | ScalarEvolution::LoopDisposition |
| 9687 | ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9688 | auto &Values = LoopDispositions[S]; |
| 9689 | for (auto &V : Values) { |
| 9690 | if (V.getPointer() == L) |
| 9691 | return V.getInt(); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9692 | } |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9693 | Values.emplace_back(L, LoopVariant); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9694 | LoopDisposition D = computeLoopDisposition(S, L); |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9695 | auto &Values2 = LoopDispositions[S]; |
| 9696 | for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { |
| 9697 | if (V.getPointer() == L) { |
| 9698 | V.setInt(D); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9699 | break; |
| 9700 | } |
| 9701 | } |
| 9702 | return D; |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9703 | } |
| 9704 | |
| 9705 | ScalarEvolution::LoopDisposition |
| 9706 | ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9707 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9708 | case scConstant: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9709 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9710 | case scTruncate: |
| 9711 | case scZeroExtend: |
| 9712 | case scSignExtend: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9713 | return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9714 | case scAddRecExpr: { |
| 9715 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); |
| 9716 | |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9717 | // If L is the addrec's loop, it's computable. |
| 9718 | if (AR->getLoop() == L) |
| 9719 | return LoopComputable; |
| 9720 | |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9721 | // Add recurrences are never invariant in the function-body (null loop). |
| 9722 | if (!L) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9723 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9724 | |
| 9725 | // This recurrence is variant w.r.t. L if L contains AR's loop. |
| 9726 | if (L->contains(AR->getLoop())) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9727 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9728 | |
| 9729 | // This recurrence is invariant w.r.t. L if AR's loop contains L. |
| 9730 | if (AR->getLoop()->contains(L)) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9731 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9732 | |
| 9733 | // This recurrence is variant w.r.t. L if any of its operands |
| 9734 | // are variant. |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 9735 | for (auto *Op : AR->operands()) |
| 9736 | if (!isLoopInvariant(Op, L)) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9737 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9738 | |
| 9739 | // Otherwise it's loop-invariant. |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9740 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9741 | } |
| 9742 | case scAddExpr: |
| 9743 | case scMulExpr: |
| 9744 | case scUMaxExpr: |
| 9745 | case scSMaxExpr: { |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9746 | bool HasVarying = false; |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 9747 | for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { |
| 9748 | LoopDisposition D = getLoopDisposition(Op, L); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9749 | if (D == LoopVariant) |
| 9750 | return LoopVariant; |
| 9751 | if (D == LoopComputable) |
| 9752 | HasVarying = true; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9753 | } |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9754 | return HasVarying ? LoopComputable : LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9755 | } |
| 9756 | case scUDivExpr: { |
| 9757 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9758 | LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); |
| 9759 | if (LD == LoopVariant) |
| 9760 | return LoopVariant; |
| 9761 | LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); |
| 9762 | if (RD == LoopVariant) |
| 9763 | return LoopVariant; |
| 9764 | return (LD == LoopInvariant && RD == LoopInvariant) ? |
| 9765 | LoopInvariant : LoopComputable; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9766 | } |
| 9767 | case scUnknown: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9768 | // All non-instruction values are loop invariant. All instructions are loop |
| 9769 | // invariant if they are not contained in the specified loop. |
| 9770 | // Instructions are never considered invariant in the function body |
| 9771 | // (null loop) because they are defined within the "loop". |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 9772 | if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9773 | return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; |
| 9774 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9775 | case scCouldNotCompute: |
| 9776 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9777 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9778 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9779 | } |
| 9780 | |
| 9781 | bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { |
| 9782 | return getLoopDisposition(S, L) == LoopInvariant; |
| 9783 | } |
| 9784 | |
| 9785 | bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { |
| 9786 | return getLoopDisposition(S, L) == LoopComputable; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9787 | } |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9788 | |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9789 | ScalarEvolution::BlockDisposition |
| 9790 | ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9791 | auto &Values = BlockDispositions[S]; |
| 9792 | for (auto &V : Values) { |
| 9793 | if (V.getPointer() == BB) |
| 9794 | return V.getInt(); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9795 | } |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9796 | Values.emplace_back(BB, DoesNotDominateBlock); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9797 | BlockDisposition D = computeBlockDisposition(S, BB); |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9798 | auto &Values2 = BlockDispositions[S]; |
| 9799 | for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { |
| 9800 | if (V.getPointer() == BB) { |
| 9801 | V.setInt(D); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9802 | break; |
| 9803 | } |
| 9804 | } |
| 9805 | return D; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9806 | } |
| 9807 | |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9808 | ScalarEvolution::BlockDisposition |
| 9809 | ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9810 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9811 | case scConstant: |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9812 | return ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9813 | case scTruncate: |
| 9814 | case scZeroExtend: |
| 9815 | case scSignExtend: |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9816 | return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9817 | case scAddRecExpr: { |
| 9818 | // This uses a "dominates" query instead of "properly dominates" query |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9819 | // to test for proper dominance too, because the instruction which |
| 9820 | // produces the addrec's value is a PHI, and a PHI effectively properly |
| 9821 | // dominates its entire containing block. |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9822 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9823 | if (!DT.dominates(AR->getLoop()->getHeader(), BB)) |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9824 | return DoesNotDominateBlock; |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 9825 | |
| 9826 | // Fall through into SCEVNAryExpr handling. |
| 9827 | LLVM_FALLTHROUGH; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9828 | } |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9829 | case scAddExpr: |
| 9830 | case scMulExpr: |
| 9831 | case scUMaxExpr: |
| 9832 | case scSMaxExpr: { |
| 9833 | const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9834 | bool Proper = true; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 9835 | for (const SCEV *NAryOp : NAry->operands()) { |
| 9836 | BlockDisposition D = getBlockDisposition(NAryOp, BB); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9837 | if (D == DoesNotDominateBlock) |
| 9838 | return DoesNotDominateBlock; |
| 9839 | if (D == DominatesBlock) |
| 9840 | Proper = false; |
| 9841 | } |
| 9842 | return Proper ? ProperlyDominatesBlock : DominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9843 | } |
| 9844 | case scUDivExpr: { |
| 9845 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9846 | const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); |
| 9847 | BlockDisposition LD = getBlockDisposition(LHS, BB); |
| 9848 | if (LD == DoesNotDominateBlock) |
| 9849 | return DoesNotDominateBlock; |
| 9850 | BlockDisposition RD = getBlockDisposition(RHS, BB); |
| 9851 | if (RD == DoesNotDominateBlock) |
| 9852 | return DoesNotDominateBlock; |
| 9853 | return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? |
| 9854 | ProperlyDominatesBlock : DominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9855 | } |
| 9856 | case scUnknown: |
| 9857 | if (Instruction *I = |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9858 | dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { |
| 9859 | if (I->getParent() == BB) |
| 9860 | return DominatesBlock; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9861 | if (DT.properlyDominates(I->getParent(), BB)) |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9862 | return ProperlyDominatesBlock; |
| 9863 | return DoesNotDominateBlock; |
| 9864 | } |
| 9865 | return ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9866 | case scCouldNotCompute: |
| 9867 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9868 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9869 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9870 | } |
| 9871 | |
| 9872 | bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { |
| 9873 | return getBlockDisposition(S, BB) >= DominatesBlock; |
| 9874 | } |
| 9875 | |
| 9876 | bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { |
| 9877 | return getBlockDisposition(S, BB) == ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9878 | } |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 9879 | |
| 9880 | bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { |
Sanjoy Das | 6b46a0d | 2016-11-09 18:22:43 +0000 | [diff] [blame] | 9881 | return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 9882 | } |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 9883 | |
| 9884 | void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { |
| 9885 | ValuesAtScopes.erase(S); |
| 9886 | LoopDispositions.erase(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9887 | BlockDispositions.erase(S); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 9888 | UnsignedRanges.erase(S); |
| 9889 | SignedRanges.erase(S); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9890 | ExprValueMap.erase(S); |
| 9891 | HasRecMap.erase(S); |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 9892 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 9893 | auto RemoveSCEVFromBackedgeMap = |
| 9894 | [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { |
| 9895 | for (auto I = Map.begin(), E = Map.end(); I != E;) { |
| 9896 | BackedgeTakenInfo &BEInfo = I->second; |
| 9897 | if (BEInfo.hasOperand(S, this)) { |
| 9898 | BEInfo.clear(); |
| 9899 | Map.erase(I++); |
| 9900 | } else |
| 9901 | ++I; |
| 9902 | } |
| 9903 | }; |
| 9904 | |
| 9905 | RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); |
| 9906 | RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 9907 | } |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9908 | |
| 9909 | typedef DenseMap<const Loop *, std::string> VerifyMap; |
Benjamin Kramer | 24d270d | 2012-10-27 10:45:01 +0000 | [diff] [blame] | 9910 | |
Alp Toker | cb40291 | 2014-01-24 17:20:08 +0000 | [diff] [blame] | 9911 | /// replaceSubString - Replaces all occurrences of From in Str with To. |
Benjamin Kramer | 24d270d | 2012-10-27 10:45:01 +0000 | [diff] [blame] | 9912 | static void replaceSubString(std::string &Str, StringRef From, StringRef To) { |
| 9913 | size_t Pos = 0; |
| 9914 | while ((Pos = Str.find(From, Pos)) != std::string::npos) { |
| 9915 | Str.replace(Pos, From.size(), To.data(), To.size()); |
| 9916 | Pos += To.size(); |
| 9917 | } |
| 9918 | } |
| 9919 | |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9920 | /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis. |
| 9921 | static void |
| 9922 | getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) { |
Sanjoy Das | 2fbfb25 | 2015-12-23 17:48:14 +0000 | [diff] [blame] | 9923 | std::string &S = Map[L]; |
| 9924 | if (S.empty()) { |
| 9925 | raw_string_ostream OS(S); |
| 9926 | SE.getBackedgeTakenCount(L)->print(OS); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9927 | |
Sanjoy Das | 2fbfb25 | 2015-12-23 17:48:14 +0000 | [diff] [blame] | 9928 | // false and 0 are semantically equivalent. This can happen in dead loops. |
| 9929 | replaceSubString(OS.str(), "false", "0"); |
| 9930 | // Remove wrap flags, their use in SCEV is highly fragile. |
| 9931 | // FIXME: Remove this when SCEV gets smarter about them. |
| 9932 | replaceSubString(OS.str(), "<nw>", ""); |
| 9933 | replaceSubString(OS.str(), "<nsw>", ""); |
| 9934 | replaceSubString(OS.str(), "<nuw>", ""); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9935 | } |
Sanjoy Das | 2fbfb25 | 2015-12-23 17:48:14 +0000 | [diff] [blame] | 9936 | |
JF Bastien | 61ad8b3 | 2015-12-23 18:18:53 +0000 | [diff] [blame] | 9937 | for (auto *R : reverse(*L)) |
| 9938 | getLoopBackedgeTakenCounts(R, Map, SE); // recurse. |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9939 | } |
| 9940 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9941 | void ScalarEvolution::verify() const { |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9942 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
| 9943 | |
| 9944 | // Gather stringified backedge taken counts for all loops using SCEV's caches. |
| 9945 | // FIXME: It would be much better to store actual values instead of strings, |
| 9946 | // but SCEV pointers will change if we drop the caches. |
| 9947 | VerifyMap BackedgeDumpsOld, BackedgeDumpsNew; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9948 | 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] | 9949 | getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE); |
| 9950 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9951 | // Gather stringified backedge taken counts for all loops using a fresh |
| 9952 | // ScalarEvolution object. |
| 9953 | ScalarEvolution SE2(F, TLI, AC, DT, LI); |
| 9954 | for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) |
| 9955 | getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9956 | |
| 9957 | // Now compare whether they're the same with and without caches. This allows |
| 9958 | // verifying that no pass changed the cache. |
| 9959 | assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() && |
| 9960 | "New loops suddenly appeared!"); |
| 9961 | |
| 9962 | for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(), |
| 9963 | OldE = BackedgeDumpsOld.end(), |
| 9964 | NewI = BackedgeDumpsNew.begin(); |
| 9965 | OldI != OldE; ++OldI, ++NewI) { |
| 9966 | assert(OldI->first == NewI->first && "Loop order changed!"); |
| 9967 | |
| 9968 | // Compare the stringified SCEVs. We don't care if undef backedgetaken count |
| 9969 | // changes. |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 9970 | // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9971 | // means that a pass is buggy or SCEV has to learn a new pattern but is |
| 9972 | // usually not harmful. |
| 9973 | if (OldI->second != NewI->second && |
| 9974 | OldI->second.find("undef") == std::string::npos && |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 9975 | NewI->second.find("undef") == std::string::npos && |
| 9976 | OldI->second != "***COULDNOTCOMPUTE***" && |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9977 | NewI->second != "***COULDNOTCOMPUTE***") { |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 9978 | dbgs() << "SCEVValidator: SCEV for loop '" |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9979 | << OldI->first->getHeader()->getName() |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 9980 | << "' changed from '" << OldI->second |
| 9981 | << "' to '" << NewI->second << "'!\n"; |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9982 | std::abort(); |
| 9983 | } |
| 9984 | } |
| 9985 | |
| 9986 | // TODO: Verify more things. |
| 9987 | } |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9988 | |
Chandler Carruth | b4faf13 | 2016-03-11 10:22:49 +0000 | [diff] [blame] | 9989 | char ScalarEvolutionAnalysis::PassID; |
NAKAMURA Takumi | df0cd72 | 2016-02-28 17:17:00 +0000 | [diff] [blame] | 9990 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9991 | ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, |
Sean Silva | 36e0d01 | 2016-08-09 00:28:15 +0000 | [diff] [blame] | 9992 | FunctionAnalysisManager &AM) { |
Chandler Carruth | b47f801 | 2016-03-11 11:05:24 +0000 | [diff] [blame] | 9993 | return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), |
| 9994 | AM.getResult<AssumptionAnalysis>(F), |
| 9995 | AM.getResult<DominatorTreeAnalysis>(F), |
| 9996 | AM.getResult<LoopAnalysis>(F)); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9997 | } |
| 9998 | |
| 9999 | PreservedAnalyses |
Sean Silva | 36e0d01 | 2016-08-09 00:28:15 +0000 | [diff] [blame] | 10000 | ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { |
Chandler Carruth | b47f801 | 2016-03-11 11:05:24 +0000 | [diff] [blame] | 10001 | AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10002 | return PreservedAnalyses::all(); |
| 10003 | } |
| 10004 | |
| 10005 | INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", |
| 10006 | "Scalar Evolution Analysis", false, true) |
| 10007 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) |
| 10008 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
| 10009 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 10010 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
| 10011 | INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", |
| 10012 | "Scalar Evolution Analysis", false, true) |
| 10013 | char ScalarEvolutionWrapperPass::ID = 0; |
| 10014 | |
| 10015 | ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { |
| 10016 | initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); |
| 10017 | } |
| 10018 | |
| 10019 | bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { |
| 10020 | SE.reset(new ScalarEvolution( |
| 10021 | F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), |
| 10022 | getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), |
| 10023 | getAnalysis<DominatorTreeWrapperPass>().getDomTree(), |
| 10024 | getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); |
| 10025 | return false; |
| 10026 | } |
| 10027 | |
| 10028 | void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } |
| 10029 | |
| 10030 | void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { |
| 10031 | SE->print(OS); |
| 10032 | } |
| 10033 | |
| 10034 | void ScalarEvolutionWrapperPass::verifyAnalysis() const { |
| 10035 | if (!VerifySCEV) |
| 10036 | return; |
| 10037 | |
| 10038 | SE->verify(); |
| 10039 | } |
| 10040 | |
| 10041 | void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { |
| 10042 | AU.setPreservesAll(); |
| 10043 | AU.addRequiredTransitive<AssumptionCacheTracker>(); |
| 10044 | AU.addRequiredTransitive<LoopInfoWrapperPass>(); |
| 10045 | AU.addRequiredTransitive<DominatorTreeWrapperPass>(); |
| 10046 | AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); |
| 10047 | } |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10048 | |
| 10049 | const SCEVPredicate * |
| 10050 | ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS, |
| 10051 | const SCEVConstant *RHS) { |
| 10052 | FoldingSetNodeID ID; |
| 10053 | // Unique this node based on the arguments |
| 10054 | ID.AddInteger(SCEVPredicate::P_Equal); |
| 10055 | ID.AddPointer(LHS); |
| 10056 | ID.AddPointer(RHS); |
| 10057 | void *IP = nullptr; |
| 10058 | if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) |
| 10059 | return S; |
| 10060 | SCEVEqualPredicate *Eq = new (SCEVAllocator) |
| 10061 | SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); |
| 10062 | UniquePreds.InsertNode(Eq, IP); |
| 10063 | return Eq; |
| 10064 | } |
| 10065 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10066 | const SCEVPredicate *ScalarEvolution::getWrapPredicate( |
| 10067 | const SCEVAddRecExpr *AR, |
| 10068 | SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { |
| 10069 | FoldingSetNodeID ID; |
| 10070 | // Unique this node based on the arguments |
| 10071 | ID.AddInteger(SCEVPredicate::P_Wrap); |
| 10072 | ID.AddPointer(AR); |
| 10073 | ID.AddInteger(AddedFlags); |
| 10074 | void *IP = nullptr; |
| 10075 | if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) |
| 10076 | return S; |
| 10077 | auto *OF = new (SCEVAllocator) |
| 10078 | SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); |
| 10079 | UniquePreds.InsertNode(OF, IP); |
| 10080 | return OF; |
| 10081 | } |
| 10082 | |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 10083 | namespace { |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10084 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10085 | class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { |
| 10086 | public: |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10087 | /// Rewrites \p S in the context of a loop L and the SCEV predication |
| 10088 | /// infrastructure. |
| 10089 | /// |
| 10090 | /// If \p Pred is non-null, the SCEV expression is rewritten to respect the |
| 10091 | /// equivalences present in \p Pred. |
| 10092 | /// |
| 10093 | /// If \p NewPreds is non-null, rewrite is free to add further predicates to |
| 10094 | /// \p NewPreds such that the result will be an AddRecExpr. |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 10095 | static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10096 | SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, |
| 10097 | SCEVUnionPredicate *Pred) { |
| 10098 | SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 10099 | return Rewriter.visit(S); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10100 | } |
| 10101 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10102 | SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10103 | SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, |
| 10104 | SCEVUnionPredicate *Pred) |
| 10105 | : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10106 | |
| 10107 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10108 | if (Pred) { |
| 10109 | auto ExprPreds = Pred->getPredicatesForExpr(Expr); |
| 10110 | for (auto *Pred : ExprPreds) |
| 10111 | if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) |
| 10112 | if (IPred->getLHS() == Expr) |
| 10113 | return IPred->getRHS(); |
| 10114 | } |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10115 | |
| 10116 | return Expr; |
| 10117 | } |
| 10118 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10119 | const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { |
| 10120 | const SCEV *Operand = visit(Expr->getOperand()); |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 10121 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10122 | if (AR && AR->getLoop() == L && AR->isAffine()) { |
| 10123 | // This couldn't be folded because the operand didn't have the nuw |
| 10124 | // flag. Add the nusw flag as an assumption that we could make. |
| 10125 | const SCEV *Step = AR->getStepRecurrence(SE); |
| 10126 | Type *Ty = Expr->getType(); |
| 10127 | if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) |
| 10128 | return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), |
| 10129 | SE.getSignExtendExpr(Step, Ty), L, |
| 10130 | AR->getNoWrapFlags()); |
| 10131 | } |
| 10132 | return SE.getZeroExtendExpr(Operand, Expr->getType()); |
| 10133 | } |
| 10134 | |
| 10135 | const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { |
| 10136 | const SCEV *Operand = visit(Expr->getOperand()); |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 10137 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10138 | if (AR && AR->getLoop() == L && AR->isAffine()) { |
| 10139 | // This couldn't be folded because the operand didn't have the nsw |
| 10140 | // flag. Add the nssw flag as an assumption that we could make. |
| 10141 | const SCEV *Step = AR->getStepRecurrence(SE); |
| 10142 | Type *Ty = Expr->getType(); |
| 10143 | if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) |
| 10144 | return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), |
| 10145 | SE.getSignExtendExpr(Step, Ty), L, |
| 10146 | AR->getNoWrapFlags()); |
| 10147 | } |
| 10148 | return SE.getSignExtendExpr(Operand, Expr->getType()); |
| 10149 | } |
| 10150 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10151 | private: |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10152 | bool addOverflowAssumption(const SCEVAddRecExpr *AR, |
| 10153 | SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { |
| 10154 | auto *A = SE.getWrapPredicate(AR, AddedFlags); |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10155 | if (!NewPreds) { |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10156 | // Check if we've already made this assumption. |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10157 | return Pred && Pred->implies(A); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10158 | } |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10159 | NewPreds->insert(A); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10160 | return true; |
| 10161 | } |
| 10162 | |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10163 | SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; |
| 10164 | SCEVUnionPredicate *Pred; |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10165 | const Loop *L; |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10166 | }; |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 10167 | } // end anonymous namespace |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10168 | |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 10169 | const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10170 | SCEVUnionPredicate &Preds) { |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10171 | return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10172 | } |
| 10173 | |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10174 | const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( |
| 10175 | const SCEV *S, const Loop *L, |
| 10176 | SmallPtrSetImpl<const SCEVPredicate *> &Preds) { |
| 10177 | |
| 10178 | SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; |
| 10179 | S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 10180 | auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); |
| 10181 | |
| 10182 | if (!AddRec) |
| 10183 | return nullptr; |
| 10184 | |
| 10185 | // Since the transformation was successful, we can now transfer the SCEV |
| 10186 | // predicates. |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10187 | for (auto *P : TransformPreds) |
| 10188 | Preds.insert(P); |
| 10189 | |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 10190 | return AddRec; |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10191 | } |
| 10192 | |
| 10193 | /// SCEV predicates |
| 10194 | SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, |
| 10195 | SCEVPredicateKind Kind) |
| 10196 | : FastID(ID), Kind(Kind) {} |
| 10197 | |
| 10198 | SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, |
| 10199 | const SCEVUnknown *LHS, |
| 10200 | const SCEVConstant *RHS) |
| 10201 | : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {} |
| 10202 | |
| 10203 | bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 10204 | const auto *Op = dyn_cast<SCEVEqualPredicate>(N); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10205 | |
| 10206 | if (!Op) |
| 10207 | return false; |
| 10208 | |
| 10209 | return Op->LHS == LHS && Op->RHS == RHS; |
| 10210 | } |
| 10211 | |
| 10212 | bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } |
| 10213 | |
| 10214 | const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } |
| 10215 | |
| 10216 | void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { |
| 10217 | OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; |
| 10218 | } |
| 10219 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10220 | SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, |
| 10221 | const SCEVAddRecExpr *AR, |
| 10222 | IncrementWrapFlags Flags) |
| 10223 | : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} |
| 10224 | |
| 10225 | const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } |
| 10226 | |
| 10227 | bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { |
| 10228 | const auto *Op = dyn_cast<SCEVWrapPredicate>(N); |
| 10229 | |
| 10230 | return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; |
| 10231 | } |
| 10232 | |
| 10233 | bool SCEVWrapPredicate::isAlwaysTrue() const { |
| 10234 | SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); |
| 10235 | IncrementWrapFlags IFlags = Flags; |
| 10236 | |
| 10237 | if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) |
| 10238 | IFlags = clearFlags(IFlags, IncrementNSSW); |
| 10239 | |
| 10240 | return IFlags == IncrementAnyWrap; |
| 10241 | } |
| 10242 | |
| 10243 | void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { |
| 10244 | OS.indent(Depth) << *getExpr() << " Added Flags: "; |
| 10245 | if (SCEVWrapPredicate::IncrementNUSW & getFlags()) |
| 10246 | OS << "<nusw>"; |
| 10247 | if (SCEVWrapPredicate::IncrementNSSW & getFlags()) |
| 10248 | OS << "<nssw>"; |
| 10249 | OS << "\n"; |
| 10250 | } |
| 10251 | |
| 10252 | SCEVWrapPredicate::IncrementWrapFlags |
| 10253 | SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, |
| 10254 | ScalarEvolution &SE) { |
| 10255 | IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; |
| 10256 | SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); |
| 10257 | |
| 10258 | // We can safely transfer the NSW flag as NSSW. |
| 10259 | if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) |
| 10260 | ImpliedFlags = IncrementNSSW; |
| 10261 | |
| 10262 | if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { |
| 10263 | // If the increment is positive, the SCEV NUW flag will also imply the |
| 10264 | // WrapPredicate NUSW flag. |
| 10265 | if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) |
| 10266 | if (Step->getValue()->getValue().isNonNegative()) |
| 10267 | ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); |
| 10268 | } |
| 10269 | |
| 10270 | return ImpliedFlags; |
| 10271 | } |
| 10272 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10273 | /// Union predicates don't get cached so create a dummy set ID for it. |
| 10274 | SCEVUnionPredicate::SCEVUnionPredicate() |
| 10275 | : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} |
| 10276 | |
| 10277 | bool SCEVUnionPredicate::isAlwaysTrue() const { |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 10278 | return all_of(Preds, |
| 10279 | [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10280 | } |
| 10281 | |
| 10282 | ArrayRef<const SCEVPredicate *> |
| 10283 | SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { |
| 10284 | auto I = SCEVToPreds.find(Expr); |
| 10285 | if (I == SCEVToPreds.end()) |
| 10286 | return ArrayRef<const SCEVPredicate *>(); |
| 10287 | return I->second; |
| 10288 | } |
| 10289 | |
| 10290 | bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 10291 | if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 10292 | return all_of(Set->Preds, |
| 10293 | [this](const SCEVPredicate *I) { return this->implies(I); }); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10294 | |
| 10295 | auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); |
| 10296 | if (ScevPredsIt == SCEVToPreds.end()) |
| 10297 | return false; |
| 10298 | auto &SCEVPreds = ScevPredsIt->second; |
| 10299 | |
Sanjoy Das | ff3b8b4 | 2015-12-01 07:49:23 +0000 | [diff] [blame] | 10300 | return any_of(SCEVPreds, |
| 10301 | [N](const SCEVPredicate *I) { return I->implies(N); }); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10302 | } |
| 10303 | |
| 10304 | const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } |
| 10305 | |
| 10306 | void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { |
| 10307 | for (auto Pred : Preds) |
| 10308 | Pred->print(OS, Depth); |
| 10309 | } |
| 10310 | |
| 10311 | void SCEVUnionPredicate::add(const SCEVPredicate *N) { |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 10312 | if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10313 | for (auto Pred : Set->Preds) |
| 10314 | add(Pred); |
| 10315 | return; |
| 10316 | } |
| 10317 | |
| 10318 | if (implies(N)) |
| 10319 | return; |
| 10320 | |
| 10321 | const SCEV *Key = N->getExpr(); |
| 10322 | assert(Key && "Only SCEVUnionPredicate doesn't have an " |
| 10323 | " associated expression!"); |
| 10324 | |
| 10325 | SCEVToPreds[Key].push_back(N); |
| 10326 | Preds.push_back(N); |
| 10327 | } |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10328 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10329 | PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, |
| 10330 | Loop &L) |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 10331 | : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {} |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10332 | |
| 10333 | const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { |
| 10334 | const SCEV *Expr = SE.getSCEV(V); |
| 10335 | RewriteEntry &Entry = RewriteMap[Expr]; |
| 10336 | |
| 10337 | // If we already have an entry and the version matches, return it. |
| 10338 | if (Entry.second && Generation == Entry.first) |
| 10339 | return Entry.second; |
| 10340 | |
| 10341 | // We found an entry but it's stale. Rewrite the stale entry |
| 10342 | // acording to the current predicate. |
| 10343 | if (Entry.second) |
| 10344 | Expr = Entry.second; |
| 10345 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10346 | const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10347 | Entry = {Generation, NewSCEV}; |
| 10348 | |
| 10349 | return NewSCEV; |
| 10350 | } |
| 10351 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 10352 | const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { |
| 10353 | if (!BackedgeCount) { |
| 10354 | SCEVUnionPredicate BackedgePred; |
| 10355 | BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); |
| 10356 | addPredicate(BackedgePred); |
| 10357 | } |
| 10358 | return BackedgeCount; |
| 10359 | } |
| 10360 | |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10361 | void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { |
| 10362 | if (Preds.implies(&Pred)) |
| 10363 | return; |
| 10364 | Preds.add(&Pred); |
| 10365 | updateGeneration(); |
| 10366 | } |
| 10367 | |
| 10368 | const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { |
| 10369 | return Preds; |
| 10370 | } |
| 10371 | |
| 10372 | void PredicatedScalarEvolution::updateGeneration() { |
| 10373 | // If the generation number wrapped recompute everything. |
| 10374 | if (++Generation == 0) { |
| 10375 | for (auto &II : RewriteMap) { |
| 10376 | const SCEV *Rewritten = II.second.second; |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10377 | II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10378 | } |
| 10379 | } |
| 10380 | } |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10381 | |
| 10382 | void PredicatedScalarEvolution::setNoOverflow( |
| 10383 | Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { |
| 10384 | const SCEV *Expr = getSCEV(V); |
| 10385 | const auto *AR = cast<SCEVAddRecExpr>(Expr); |
| 10386 | |
| 10387 | auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); |
| 10388 | |
| 10389 | // Clear the statically implied flags. |
| 10390 | Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); |
| 10391 | addPredicate(*SE.getWrapPredicate(AR, Flags)); |
| 10392 | |
| 10393 | auto II = FlagsMap.insert({V, Flags}); |
| 10394 | if (!II.second) |
| 10395 | II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); |
| 10396 | } |
| 10397 | |
| 10398 | bool PredicatedScalarEvolution::hasNoOverflow( |
| 10399 | Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { |
| 10400 | const SCEV *Expr = getSCEV(V); |
| 10401 | const auto *AR = cast<SCEVAddRecExpr>(Expr); |
| 10402 | |
| 10403 | Flags = SCEVWrapPredicate::clearFlags( |
| 10404 | Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); |
| 10405 | |
| 10406 | auto II = FlagsMap.find(V); |
| 10407 | |
| 10408 | if (II != FlagsMap.end()) |
| 10409 | Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); |
| 10410 | |
| 10411 | return Flags == SCEVWrapPredicate::IncrementAnyWrap; |
| 10412 | } |
| 10413 | |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 10414 | const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10415 | const SCEV *Expr = this->getSCEV(V); |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10416 | SmallPtrSet<const SCEVPredicate *, 4> NewPreds; |
| 10417 | auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 10418 | |
| 10419 | if (!New) |
| 10420 | return nullptr; |
| 10421 | |
Sanjoy Das | f002212 | 2016-09-28 17:14:58 +0000 | [diff] [blame] | 10422 | for (auto *P : NewPreds) |
| 10423 | Preds.add(P); |
| 10424 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10425 | updateGeneration(); |
| 10426 | RewriteMap[SE.getSCEV(V)] = {Generation, New}; |
| 10427 | return New; |
| 10428 | } |
| 10429 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 10430 | PredicatedScalarEvolution::PredicatedScalarEvolution( |
| 10431 | const PredicatedScalarEvolution &Init) |
| 10432 | : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), |
| 10433 | Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { |
Benjamin Kramer | aa20915 | 2016-06-26 17:27:42 +0000 | [diff] [blame] | 10434 | for (const auto &I : Init.FlagsMap) |
| 10435 | FlagsMap.insert(I); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10436 | } |
Silviu Baranga | b77365b | 2016-04-14 16:08:45 +0000 | [diff] [blame] | 10437 | |
| 10438 | void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { |
| 10439 | // For each block. |
| 10440 | for (auto *BB : L.getBlocks()) |
| 10441 | for (auto &I : *BB) { |
| 10442 | if (!SE.isSCEVable(I.getType())) |
| 10443 | continue; |
| 10444 | |
| 10445 | auto *Expr = SE.getSCEV(&I); |
| 10446 | auto II = RewriteMap.find(Expr); |
| 10447 | |
| 10448 | if (II == RewriteMap.end()) |
| 10449 | continue; |
| 10450 | |
| 10451 | // Don't print things that are not interesting. |
| 10452 | if (II->second.second == Expr) |
| 10453 | continue; |
| 10454 | |
| 10455 | OS.indent(Depth) << "[PSE]" << I << ":\n"; |
| 10456 | OS.indent(Depth + 2) << *Expr << "\n"; |
| 10457 | OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; |
| 10458 | } |
| 10459 | } |