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" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 65 | #include "llvm/ADT/SmallPtrSet.h" |
| 66 | #include "llvm/ADT/Statistic.h" |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 67 | #include "llvm/Analysis/AssumptionCache.h" |
John Criswell | fe5f33b | 2005-10-27 15:54:34 +0000 | [diff] [blame] | 68 | #include "llvm/Analysis/ConstantFolding.h" |
Duncan Sands | d06f50e | 2010-11-17 04:18:45 +0000 | [diff] [blame] | 69 | #include "llvm/Analysis/InstructionSimplify.h" |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 70 | #include "llvm/Analysis/LoopInfo.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 71 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Chandler Carruth | 62d4215 | 2015-01-15 02:16:27 +0000 | [diff] [blame] | 72 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Dan Gohman | 1ee696d | 2009-06-16 19:52:01 +0000 | [diff] [blame] | 73 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 8cd041e | 2014-03-04 12:24:34 +0000 | [diff] [blame] | 74 | #include "llvm/IR/ConstantRange.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 75 | #include "llvm/IR/Constants.h" |
| 76 | #include "llvm/IR/DataLayout.h" |
| 77 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 78 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 79 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 80 | #include "llvm/IR/GlobalAlias.h" |
| 81 | #include "llvm/IR/GlobalVariable.h" |
Chandler Carruth | 8394857 | 2014-03-04 10:30:26 +0000 | [diff] [blame] | 82 | #include "llvm/IR/InstIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 83 | #include "llvm/IR/Instructions.h" |
| 84 | #include "llvm/IR/LLVMContext.h" |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 85 | #include "llvm/IR/Metadata.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 86 | #include "llvm/IR/Operator.h" |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 87 | #include "llvm/IR/PatternMatch.h" |
Chris Lattner | 996795b | 2006-06-28 23:17:24 +0000 | [diff] [blame] | 88 | #include "llvm/Support/CommandLine.h" |
David Greene | 2330f78 | 2009-12-23 22:58:38 +0000 | [diff] [blame] | 89 | #include "llvm/Support/Debug.h" |
Torok Edwin | 56d0659 | 2009-07-11 20:10:48 +0000 | [diff] [blame] | 90 | #include "llvm/Support/ErrorHandling.h" |
Chris Lattner | 0a1e993 | 2006-12-19 01:16:02 +0000 | [diff] [blame] | 91 | #include "llvm/Support/MathExtras.h" |
Dan Gohman | e20f824 | 2009-04-21 00:47:46 +0000 | [diff] [blame] | 92 | #include "llvm/Support/raw_ostream.h" |
Sanjoy Das | 5d9a8cb | 2015-09-22 00:10:57 +0000 | [diff] [blame] | 93 | #include "llvm/Support/SaveAndRestore.h" |
Alkis Evlogimenos | a5c04ee | 2004-09-03 18:19:51 +0000 | [diff] [blame] | 94 | #include <algorithm> |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 95 | using namespace llvm; |
| 96 | |
Chandler Carruth | f1221bd | 2014-04-22 02:48:03 +0000 | [diff] [blame] | 97 | #define DEBUG_TYPE "scalar-evolution" |
| 98 | |
Chris Lattner | 57ef942 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 99 | STATISTIC(NumArrayLenItCounts, |
| 100 | "Number of trip counts computed with array length"); |
| 101 | STATISTIC(NumTripCountsComputed, |
| 102 | "Number of loops with predictable loop counts"); |
| 103 | STATISTIC(NumTripCountsNotComputed, |
| 104 | "Number of loops without predictable loop counts"); |
| 105 | STATISTIC(NumBruteForceTripCountsComputed, |
| 106 | "Number of loops with trip counts computed by force"); |
| 107 | |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 108 | static cl::opt<unsigned> |
Chris Lattner | 57ef942 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 109 | MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, |
| 110 | cl::desc("Maximum number of iterations SCEV will " |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 111 | "symbolically execute a constant " |
| 112 | "derived loop"), |
Chris Lattner | 57ef942 | 2006-12-19 22:30:33 +0000 | [diff] [blame] | 113 | cl::init(100)); |
| 114 | |
Filipe Cabecinhas | 0da9937 | 2016-04-29 15:22:48 +0000 | [diff] [blame] | 115 | // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 116 | static cl::opt<bool> |
| 117 | VerifySCEV("verify-scev", |
| 118 | cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 119 | static cl::opt<bool> |
| 120 | VerifySCEVMap("verify-scev-maps", |
Jeroen Ketema | e48e393 | 2016-04-12 23:21:46 +0000 | [diff] [blame] | 121 | cl::desc("Verify no dangling value in ScalarEvolution's " |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 122 | "ExprValueMap (slow)")); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 123 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 124 | //===----------------------------------------------------------------------===// |
| 125 | // SCEV class definitions |
| 126 | //===----------------------------------------------------------------------===// |
| 127 | |
| 128 | //===----------------------------------------------------------------------===// |
| 129 | // Implementation of the SCEV class. |
| 130 | // |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 131 | |
Davide Italiano | 2071f4c | 2015-10-25 19:55:24 +0000 | [diff] [blame] | 132 | LLVM_DUMP_METHOD |
| 133 | void SCEV::dump() const { |
| 134 | print(dbgs()); |
| 135 | dbgs() << '\n'; |
| 136 | } |
| 137 | |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 138 | void SCEV::print(raw_ostream &OS) const { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 139 | switch (static_cast<SCEVTypes>(getSCEVType())) { |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 140 | case scConstant: |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 141 | cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 142 | return; |
| 143 | case scTruncate: { |
| 144 | const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); |
| 145 | const SCEV *Op = Trunc->getOperand(); |
| 146 | OS << "(trunc " << *Op->getType() << " " << *Op << " to " |
| 147 | << *Trunc->getType() << ")"; |
| 148 | return; |
| 149 | } |
| 150 | case scZeroExtend: { |
| 151 | const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); |
| 152 | const SCEV *Op = ZExt->getOperand(); |
| 153 | OS << "(zext " << *Op->getType() << " " << *Op << " to " |
| 154 | << *ZExt->getType() << ")"; |
| 155 | return; |
| 156 | } |
| 157 | case scSignExtend: { |
| 158 | const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); |
| 159 | const SCEV *Op = SExt->getOperand(); |
| 160 | OS << "(sext " << *Op->getType() << " " << *Op << " to " |
| 161 | << *SExt->getType() << ")"; |
| 162 | return; |
| 163 | } |
| 164 | case scAddRecExpr: { |
| 165 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); |
| 166 | OS << "{" << *AR->getOperand(0); |
| 167 | for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) |
| 168 | OS << ",+," << *AR->getOperand(i); |
| 169 | OS << "}<"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 170 | if (AR->hasNoUnsignedWrap()) |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 171 | OS << "nuw><"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 172 | if (AR->hasNoSignedWrap()) |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 173 | OS << "nsw><"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 174 | if (AR->hasNoSelfWrap() && |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 175 | !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) |
| 176 | OS << "nw><"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 177 | AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 178 | OS << ">"; |
| 179 | return; |
| 180 | } |
| 181 | case scAddExpr: |
| 182 | case scMulExpr: |
| 183 | case scUMaxExpr: |
| 184 | case scSMaxExpr: { |
| 185 | const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 186 | const char *OpStr = nullptr; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 187 | switch (NAry->getSCEVType()) { |
| 188 | case scAddExpr: OpStr = " + "; break; |
| 189 | case scMulExpr: OpStr = " * "; break; |
| 190 | case scUMaxExpr: OpStr = " umax "; break; |
| 191 | case scSMaxExpr: OpStr = " smax "; break; |
| 192 | } |
| 193 | OS << "("; |
| 194 | for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); |
| 195 | I != E; ++I) { |
| 196 | OS << **I; |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 197 | if (std::next(I) != E) |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 198 | OS << OpStr; |
| 199 | } |
| 200 | OS << ")"; |
Andrew Trick | d912a5b | 2011-11-29 02:06:35 +0000 | [diff] [blame] | 201 | switch (NAry->getSCEVType()) { |
| 202 | case scAddExpr: |
| 203 | case scMulExpr: |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 204 | if (NAry->hasNoUnsignedWrap()) |
Andrew Trick | d912a5b | 2011-11-29 02:06:35 +0000 | [diff] [blame] | 205 | OS << "<nuw>"; |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 206 | if (NAry->hasNoSignedWrap()) |
Andrew Trick | d912a5b | 2011-11-29 02:06:35 +0000 | [diff] [blame] | 207 | OS << "<nsw>"; |
| 208 | } |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 209 | return; |
| 210 | } |
| 211 | case scUDivExpr: { |
| 212 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); |
| 213 | OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; |
| 214 | return; |
| 215 | } |
| 216 | case scUnknown: { |
| 217 | const SCEVUnknown *U = cast<SCEVUnknown>(this); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 218 | Type *AllocTy; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 219 | if (U->isSizeOf(AllocTy)) { |
| 220 | OS << "sizeof(" << *AllocTy << ")"; |
| 221 | return; |
| 222 | } |
| 223 | if (U->isAlignOf(AllocTy)) { |
| 224 | OS << "alignof(" << *AllocTy << ")"; |
| 225 | return; |
| 226 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 227 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 228 | Type *CTy; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 229 | Constant *FieldNo; |
| 230 | if (U->isOffsetOf(CTy, FieldNo)) { |
| 231 | OS << "offsetof(" << *CTy << ", "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 232 | FieldNo->printAsOperand(OS, false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 233 | OS << ")"; |
| 234 | return; |
| 235 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 236 | |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 237 | // Otherwise just print it normally. |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 238 | U->getValue()->printAsOperand(OS, false); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 239 | return; |
| 240 | } |
| 241 | case scCouldNotCompute: |
| 242 | OS << "***COULDNOTCOMPUTE***"; |
| 243 | return; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 244 | } |
| 245 | llvm_unreachable("Unknown SCEV kind!"); |
| 246 | } |
| 247 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 248 | Type *SCEV::getType() const { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 249 | switch (static_cast<SCEVTypes>(getSCEVType())) { |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 250 | case scConstant: |
| 251 | return cast<SCEVConstant>(this)->getType(); |
| 252 | case scTruncate: |
| 253 | case scZeroExtend: |
| 254 | case scSignExtend: |
| 255 | return cast<SCEVCastExpr>(this)->getType(); |
| 256 | case scAddRecExpr: |
| 257 | case scMulExpr: |
| 258 | case scUMaxExpr: |
| 259 | case scSMaxExpr: |
| 260 | return cast<SCEVNAryExpr>(this)->getType(); |
| 261 | case scAddExpr: |
| 262 | return cast<SCEVAddExpr>(this)->getType(); |
| 263 | case scUDivExpr: |
| 264 | return cast<SCEVUDivExpr>(this)->getType(); |
| 265 | case scUnknown: |
| 266 | return cast<SCEVUnknown>(this)->getType(); |
| 267 | case scCouldNotCompute: |
| 268 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 269 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 270 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 271 | } |
| 272 | |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 273 | bool SCEV::isZero() const { |
| 274 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 275 | return SC->getValue()->isZero(); |
| 276 | return false; |
| 277 | } |
| 278 | |
Dan Gohman | ba7f6d8 | 2009-05-18 15:22:39 +0000 | [diff] [blame] | 279 | bool SCEV::isOne() const { |
| 280 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 281 | return SC->getValue()->isOne(); |
| 282 | return false; |
| 283 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 284 | |
Dan Gohman | 18a96bb | 2009-06-24 00:30:26 +0000 | [diff] [blame] | 285 | bool SCEV::isAllOnesValue() const { |
| 286 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) |
| 287 | return SC->getValue()->isAllOnesValue(); |
| 288 | return false; |
| 289 | } |
| 290 | |
Andrew Trick | 881a776 | 2012-01-07 00:27:31 +0000 | [diff] [blame] | 291 | bool SCEV::isNonConstantNegative() const { |
| 292 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); |
| 293 | if (!Mul) return false; |
| 294 | |
| 295 | // If there is a constant factor, it will be first. |
| 296 | const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); |
| 297 | if (!SC) return false; |
| 298 | |
| 299 | // 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] | 300 | return SC->getAPInt().isNegative(); |
Andrew Trick | 881a776 | 2012-01-07 00:27:31 +0000 | [diff] [blame] | 301 | } |
| 302 | |
Owen Anderson | 04052ec | 2009-06-22 21:57:23 +0000 | [diff] [blame] | 303 | SCEVCouldNotCompute::SCEVCouldNotCompute() : |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 304 | SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {} |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 305 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 306 | bool SCEVCouldNotCompute::classof(const SCEV *S) { |
| 307 | return S->getSCEVType() == scCouldNotCompute; |
| 308 | } |
| 309 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 310 | const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 311 | FoldingSetNodeID ID; |
| 312 | ID.AddInteger(scConstant); |
| 313 | ID.AddPointer(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 314 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 315 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 316 | SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 317 | UniqueSCEVs.InsertNode(S, IP); |
| 318 | return S; |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 319 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 320 | |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 321 | const SCEV *ScalarEvolution::getConstant(const APInt &Val) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 322 | return getConstant(ConstantInt::get(getContext(), Val)); |
Dan Gohman | 0a76e7f | 2007-07-09 15:25:17 +0000 | [diff] [blame] | 323 | } |
| 324 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 325 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 326 | ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { |
| 327 | IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); |
Dan Gohman | a029cbe | 2010-04-21 16:04:04 +0000 | [diff] [blame] | 328 | return getConstant(ConstantInt::get(ITy, V, isSigned)); |
Dan Gohman | 7ccc52f | 2009-06-15 22:12:54 +0000 | [diff] [blame] | 329 | } |
| 330 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 331 | SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 332 | unsigned SCEVTy, const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 333 | : SCEV(ID, SCEVTy), Op(op), Ty(ty) {} |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 334 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 335 | SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 336 | const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 337 | : SCEVCastExpr(ID, scTruncate, op, ty) { |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 338 | assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && |
| 339 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 340 | "Cannot truncate non-integer value!"); |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 341 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 342 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 343 | SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 344 | const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 345 | : SCEVCastExpr(ID, scZeroExtend, op, ty) { |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 346 | assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && |
| 347 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 348 | "Cannot zero extend non-integer value!"); |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 349 | } |
| 350 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 351 | SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 352 | const SCEV *op, Type *ty) |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 353 | : SCEVCastExpr(ID, scSignExtend, op, ty) { |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 354 | assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) && |
| 355 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 356 | "Cannot sign extend non-integer value!"); |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 357 | } |
| 358 | |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 359 | void SCEVUnknown::deleted() { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 360 | // Clear this SCEVUnknown from various maps. |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 361 | SE->forgetMemoizedResults(this); |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 362 | |
| 363 | // Remove this SCEVUnknown from the uniquing map. |
| 364 | SE->UniqueSCEVs.RemoveNode(this); |
| 365 | |
| 366 | // Release the value. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 367 | setValPtr(nullptr); |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 368 | } |
| 369 | |
| 370 | void SCEVUnknown::allUsesReplacedWith(Value *New) { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 371 | // Clear this SCEVUnknown from various maps. |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 372 | SE->forgetMemoizedResults(this); |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 373 | |
| 374 | // Remove this SCEVUnknown from the uniquing map. |
| 375 | SE->UniqueSCEVs.RemoveNode(this); |
| 376 | |
| 377 | // Update this SCEVUnknown to point to the new value. This is needed |
| 378 | // because there may still be outstanding SCEVs which still point to |
| 379 | // this SCEVUnknown. |
| 380 | setValPtr(New); |
| 381 | } |
| 382 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 383 | bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 384 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 385 | if (VCE->getOpcode() == Instruction::PtrToInt) |
| 386 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 387 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 388 | CE->getOperand(0)->isNullValue() && |
| 389 | CE->getNumOperands() == 2) |
| 390 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) |
| 391 | if (CI->isOne()) { |
| 392 | AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) |
| 393 | ->getElementType(); |
| 394 | return true; |
| 395 | } |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 396 | |
| 397 | return false; |
| 398 | } |
| 399 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 400 | bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 401 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 402 | if (VCE->getOpcode() == Instruction::PtrToInt) |
| 403 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 404 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 405 | CE->getOperand(0)->isNullValue()) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 406 | Type *Ty = |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 407 | cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 408 | if (StructType *STy = dyn_cast<StructType>(Ty)) |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 409 | if (!STy->isPacked() && |
| 410 | CE->getNumOperands() == 3 && |
| 411 | CE->getOperand(1)->isNullValue()) { |
| 412 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) |
| 413 | if (CI->isOne() && |
| 414 | STy->getNumElements() == 2 && |
Duncan Sands | 9dff9be | 2010-02-15 16:12:20 +0000 | [diff] [blame] | 415 | STy->getElementType(0)->isIntegerTy(1)) { |
Dan Gohman | 7e5f1b2 | 2010-02-02 01:38:49 +0000 | [diff] [blame] | 416 | AllocTy = STy->getElementType(1); |
| 417 | return true; |
| 418 | } |
| 419 | } |
| 420 | } |
Dan Gohman | cf91383 | 2010-01-28 02:15:55 +0000 | [diff] [blame] | 421 | |
| 422 | return false; |
| 423 | } |
| 424 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 425 | bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 426 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 427 | if (VCE->getOpcode() == Instruction::PtrToInt) |
| 428 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) |
| 429 | if (CE->getOpcode() == Instruction::GetElementPtr && |
| 430 | CE->getNumOperands() == 3 && |
| 431 | CE->getOperand(0)->isNullValue() && |
| 432 | CE->getOperand(1)->isNullValue()) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 433 | Type *Ty = |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 434 | cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); |
| 435 | // Ignore vector types here so that ScalarEvolutionExpander doesn't |
| 436 | // emit getelementptrs that index into vectors. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 437 | if (Ty->isStructTy() || Ty->isArrayTy()) { |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 438 | CTy = Ty; |
| 439 | FieldNo = CE->getOperand(2); |
| 440 | return true; |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | return false; |
| 445 | } |
| 446 | |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 447 | //===----------------------------------------------------------------------===// |
| 448 | // SCEV Utilities |
| 449 | //===----------------------------------------------------------------------===// |
| 450 | |
| 451 | namespace { |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 452 | /// SCEVComplexityCompare - Return true if the complexity of the LHS is less |
| 453 | /// than the complexity of the RHS. This comparator is used to canonicalize |
| 454 | /// expressions. |
| 455 | class SCEVComplexityCompare { |
| 456 | const LoopInfo *const LI; |
| 457 | public: |
| 458 | explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {} |
Dan Gohman | 9ba542c | 2009-05-07 14:39:04 +0000 | [diff] [blame] | 459 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 460 | // Return true or false if LHS is less than, or at least RHS, respectively. |
| 461 | bool operator()(const SCEV *LHS, const SCEV *RHS) const { |
| 462 | return compare(LHS, RHS) < 0; |
| 463 | } |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 464 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 465 | // Return negative, zero, or positive, if LHS is less than, equal to, or |
| 466 | // greater than RHS, respectively. A three-way result allows recursive |
| 467 | // comparisons to be more efficient. |
| 468 | int compare(const SCEV *LHS, const SCEV *RHS) const { |
| 469 | // Fast-path: SCEVs are uniqued so we can do a quick equality check. |
| 470 | if (LHS == RHS) |
| 471 | return 0; |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 472 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 473 | // Primarily, sort the SCEVs by their getSCEVType(). |
| 474 | unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); |
| 475 | if (LType != RType) |
| 476 | return (int)LType - (int)RType; |
Dan Gohman | 9ba542c | 2009-05-07 14:39:04 +0000 | [diff] [blame] | 477 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 478 | // Aside from the getSCEVType() ordering, the particular ordering |
| 479 | // isn't very important except that it's beneficial to be consistent, |
| 480 | // so that (a + b) and (b + a) don't end up as different expressions. |
| 481 | switch (static_cast<SCEVTypes>(LType)) { |
| 482 | case scUnknown: { |
| 483 | const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); |
| 484 | const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 485 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 486 | // Sort SCEVUnknown values with some loose heuristics. TODO: This is |
| 487 | // not as complete as it could be. |
| 488 | const Value *LV = LU->getValue(), *RV = RU->getValue(); |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 489 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 490 | // Order pointer values after integer values. This helps SCEVExpander |
| 491 | // form GEPs. |
| 492 | bool LIsPointer = LV->getType()->isPointerTy(), |
| 493 | RIsPointer = RV->getType()->isPointerTy(); |
| 494 | if (LIsPointer != RIsPointer) |
| 495 | return (int)LIsPointer - (int)RIsPointer; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 496 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 497 | // Compare getValueID values. |
| 498 | unsigned LID = LV->getValueID(), |
| 499 | RID = RV->getValueID(); |
| 500 | if (LID != RID) |
| 501 | return (int)LID - (int)RID; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 502 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 503 | // Sort arguments by their position. |
| 504 | if (const Argument *LA = dyn_cast<Argument>(LV)) { |
| 505 | const Argument *RA = cast<Argument>(RV); |
| 506 | unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); |
| 507 | return (int)LArgNo - (int)RArgNo; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 508 | } |
| 509 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 510 | // For instructions, compare their loop depth, and their operand |
| 511 | // count. This is pretty loose. |
| 512 | if (const Instruction *LInst = dyn_cast<Instruction>(LV)) { |
| 513 | const Instruction *RInst = cast<Instruction>(RV); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 514 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 515 | // Compare loop depths. |
| 516 | const BasicBlock *LParent = LInst->getParent(), |
| 517 | *RParent = RInst->getParent(); |
| 518 | if (LParent != RParent) { |
| 519 | unsigned LDepth = LI->getLoopDepth(LParent), |
| 520 | RDepth = LI->getLoopDepth(RParent); |
Dan Gohman | 0c436ab | 2010-08-13 21:24:58 +0000 | [diff] [blame] | 521 | if (LDepth != RDepth) |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 522 | return (int)LDepth - (int)RDepth; |
Dan Gohman | 0c436ab | 2010-08-13 21:24:58 +0000 | [diff] [blame] | 523 | } |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 524 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 525 | // Compare the number of operands. |
| 526 | unsigned LNumOps = LInst->getNumOperands(), |
| 527 | RNumOps = RInst->getNumOperands(); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 528 | return (int)LNumOps - (int)RNumOps; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 529 | } |
| 530 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 531 | return 0; |
| 532 | } |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 533 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 534 | case scConstant: { |
| 535 | const SCEVConstant *LC = cast<SCEVConstant>(LHS); |
| 536 | const SCEVConstant *RC = cast<SCEVConstant>(RHS); |
| 537 | |
| 538 | // Compare constant values. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 539 | const APInt &LA = LC->getAPInt(); |
| 540 | const APInt &RA = RC->getAPInt(); |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 541 | unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); |
| 542 | if (LBitWidth != RBitWidth) |
| 543 | return (int)LBitWidth - (int)RBitWidth; |
| 544 | return LA.ult(RA) ? -1 : 1; |
| 545 | } |
| 546 | |
| 547 | case scAddRecExpr: { |
| 548 | const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); |
| 549 | const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); |
| 550 | |
| 551 | // Compare addrec loop depths. |
| 552 | const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); |
| 553 | if (LLoop != RLoop) { |
| 554 | unsigned LDepth = LLoop->getLoopDepth(), |
| 555 | RDepth = RLoop->getLoopDepth(); |
| 556 | if (LDepth != RDepth) |
| 557 | return (int)LDepth - (int)RDepth; |
| 558 | } |
| 559 | |
| 560 | // Addrec complexity grows with operand count. |
| 561 | unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); |
| 562 | if (LNumOps != RNumOps) |
| 563 | return (int)LNumOps - (int)RNumOps; |
| 564 | |
| 565 | // Lexicographically compare. |
| 566 | for (unsigned i = 0; i != LNumOps; ++i) { |
| 567 | long X = compare(LA->getOperand(i), RA->getOperand(i)); |
Dan Gohman | 2706567 | 2010-08-27 15:26:01 +0000 | [diff] [blame] | 568 | if (X != 0) |
| 569 | return X; |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 570 | } |
| 571 | |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 572 | return 0; |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 573 | } |
Sanjoy Das | 7881abd | 2015-12-08 04:32:51 +0000 | [diff] [blame] | 574 | |
| 575 | case scAddExpr: |
| 576 | case scMulExpr: |
| 577 | case scSMaxExpr: |
| 578 | case scUMaxExpr: { |
| 579 | const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); |
| 580 | const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); |
| 581 | |
| 582 | // Lexicographically compare n-ary expressions. |
| 583 | unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); |
| 584 | if (LNumOps != RNumOps) |
| 585 | return (int)LNumOps - (int)RNumOps; |
| 586 | |
| 587 | for (unsigned i = 0; i != LNumOps; ++i) { |
| 588 | if (i >= RNumOps) |
| 589 | return 1; |
| 590 | long X = compare(LC->getOperand(i), RC->getOperand(i)); |
| 591 | if (X != 0) |
| 592 | return X; |
| 593 | } |
| 594 | return (int)LNumOps - (int)RNumOps; |
| 595 | } |
| 596 | |
| 597 | case scUDivExpr: { |
| 598 | const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); |
| 599 | const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); |
| 600 | |
| 601 | // Lexicographically compare udiv expressions. |
| 602 | long X = compare(LC->getLHS(), RC->getLHS()); |
| 603 | if (X != 0) |
| 604 | return X; |
| 605 | return compare(LC->getRHS(), RC->getRHS()); |
| 606 | } |
| 607 | |
| 608 | case scTruncate: |
| 609 | case scZeroExtend: |
| 610 | case scSignExtend: { |
| 611 | const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); |
| 612 | const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); |
| 613 | |
| 614 | // Compare cast expressions by operand. |
| 615 | return compare(LC->getOperand(), RC->getOperand()); |
| 616 | } |
| 617 | |
| 618 | case scCouldNotCompute: |
| 619 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
| 620 | } |
| 621 | llvm_unreachable("Unknown SCEV kind!"); |
| 622 | } |
| 623 | }; |
| 624 | } // end anonymous namespace |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 625 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 626 | /// Given a list of SCEV objects, order them by their complexity, and group |
| 627 | /// objects of the same complexity together by value. When this routine is |
| 628 | /// finished, we know that any duplicates in the vector are consecutive and that |
| 629 | /// complexity is monotonically increasing. |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 630 | /// |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 631 | /// 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] | 632 | /// results from this routine. In other words, we don't want the results of |
| 633 | /// this to depend on where the addresses of various SCEV objects happened to |
| 634 | /// land in memory. |
| 635 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 636 | static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, |
Dan Gohman | 9ba542c | 2009-05-07 14:39:04 +0000 | [diff] [blame] | 637 | LoopInfo *LI) { |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 638 | if (Ops.size() < 2) return; // Noop |
| 639 | if (Ops.size() == 2) { |
| 640 | // This is the common case, which also happens to be trivially simple. |
| 641 | // Special case it. |
Dan Gohman | 7712d29 | 2010-08-29 15:07:13 +0000 | [diff] [blame] | 642 | const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; |
| 643 | if (SCEVComplexityCompare(LI)(RHS, LHS)) |
| 644 | std::swap(LHS, RHS); |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 645 | return; |
| 646 | } |
| 647 | |
Dan Gohman | 24ceda8 | 2010-06-18 19:54:20 +0000 | [diff] [blame] | 648 | // Do the rough sort by complexity. |
| 649 | std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI)); |
| 650 | |
| 651 | // Now that we are sorted by complexity, group elements of the same |
| 652 | // complexity. Note that this is, at worst, N^2, but the vector is likely to |
| 653 | // be extremely short in practice. Note that we take this approach because we |
| 654 | // do not want to depend on the addresses of the objects we are grouping. |
| 655 | for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { |
| 656 | const SCEV *S = Ops[i]; |
| 657 | unsigned Complexity = S->getSCEVType(); |
| 658 | |
| 659 | // If there are any objects of the same complexity and same value as this |
| 660 | // one, group them. |
| 661 | for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { |
| 662 | if (Ops[j] == S) { // Found a duplicate. |
| 663 | // Move it to immediately after i'th element. |
| 664 | std::swap(Ops[i+1], Ops[j]); |
| 665 | ++i; // no need to rescan it. |
| 666 | if (i == e-2) return; // Done! |
| 667 | } |
| 668 | } |
| 669 | } |
Chris Lattner | eb3e840 | 2004-06-20 06:23:15 +0000 | [diff] [blame] | 670 | } |
| 671 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 672 | // Returns the size of the SCEV S. |
| 673 | static inline int sizeOfSCEV(const SCEV *S) { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 674 | struct FindSCEVSize { |
| 675 | int Size; |
| 676 | FindSCEVSize() : Size(0) {} |
| 677 | |
| 678 | bool follow(const SCEV *S) { |
| 679 | ++Size; |
| 680 | // Keep looking at all operands of S. |
| 681 | return true; |
| 682 | } |
| 683 | bool isDone() const { |
| 684 | return false; |
| 685 | } |
| 686 | }; |
| 687 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 688 | FindSCEVSize F; |
| 689 | SCEVTraversal<FindSCEVSize> ST(F); |
| 690 | ST.visitAll(S); |
| 691 | return F.Size; |
| 692 | } |
| 693 | |
| 694 | namespace { |
| 695 | |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 696 | struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 697 | public: |
| 698 | // Computes the Quotient and Remainder of the division of Numerator by |
| 699 | // Denominator. |
| 700 | static void divide(ScalarEvolution &SE, const SCEV *Numerator, |
| 701 | const SCEV *Denominator, const SCEV **Quotient, |
| 702 | const SCEV **Remainder) { |
| 703 | assert(Numerator && Denominator && "Uninitialized SCEV"); |
| 704 | |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 705 | SCEVDivision D(SE, Numerator, Denominator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 706 | |
| 707 | // Check for the trivial case here to avoid having to check for it in the |
| 708 | // rest of the code. |
| 709 | if (Numerator == Denominator) { |
| 710 | *Quotient = D.One; |
| 711 | *Remainder = D.Zero; |
| 712 | return; |
| 713 | } |
| 714 | |
| 715 | if (Numerator->isZero()) { |
| 716 | *Quotient = D.Zero; |
| 717 | *Remainder = D.Zero; |
| 718 | return; |
| 719 | } |
| 720 | |
Brendon Cahoon | a57cc8b | 2015-04-20 16:03:28 +0000 | [diff] [blame] | 721 | // A simple case when N/1. The quotient is N. |
| 722 | if (Denominator->isOne()) { |
| 723 | *Quotient = Numerator; |
| 724 | *Remainder = D.Zero; |
| 725 | return; |
| 726 | } |
| 727 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 728 | // Split the Denominator when it is a product. |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 729 | if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 730 | const SCEV *Q, *R; |
| 731 | *Quotient = Numerator; |
| 732 | for (const SCEV *Op : T->operands()) { |
| 733 | divide(SE, *Quotient, Op, &Q, &R); |
| 734 | *Quotient = Q; |
| 735 | |
| 736 | // Bail out when the Numerator is not divisible by one of the terms of |
| 737 | // the Denominator. |
| 738 | if (!R->isZero()) { |
| 739 | *Quotient = D.Zero; |
| 740 | *Remainder = Numerator; |
| 741 | return; |
| 742 | } |
| 743 | } |
| 744 | *Remainder = D.Zero; |
| 745 | return; |
| 746 | } |
| 747 | |
| 748 | D.visit(Numerator); |
| 749 | *Quotient = D.Quotient; |
| 750 | *Remainder = D.Remainder; |
| 751 | } |
| 752 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 753 | // Except in the trivial case described above, we do not know how to divide |
| 754 | // Expr by Denominator for the following functions with empty implementation. |
| 755 | void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} |
| 756 | void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} |
| 757 | void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} |
| 758 | void visitUDivExpr(const SCEVUDivExpr *Numerator) {} |
| 759 | void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} |
| 760 | void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} |
| 761 | void visitUnknown(const SCEVUnknown *Numerator) {} |
| 762 | void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} |
| 763 | |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 764 | void visitConstant(const SCEVConstant *Numerator) { |
| 765 | if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 766 | APInt NumeratorVal = Numerator->getAPInt(); |
| 767 | APInt DenominatorVal = D->getAPInt(); |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 768 | uint32_t NumeratorBW = NumeratorVal.getBitWidth(); |
| 769 | uint32_t DenominatorBW = DenominatorVal.getBitWidth(); |
| 770 | |
| 771 | if (NumeratorBW > DenominatorBW) |
| 772 | DenominatorVal = DenominatorVal.sext(NumeratorBW); |
| 773 | else if (NumeratorBW < DenominatorBW) |
| 774 | NumeratorVal = NumeratorVal.sext(DenominatorBW); |
| 775 | |
| 776 | APInt QuotientVal(NumeratorVal.getBitWidth(), 0); |
| 777 | APInt RemainderVal(NumeratorVal.getBitWidth(), 0); |
| 778 | APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); |
| 779 | Quotient = SE.getConstant(QuotientVal); |
| 780 | Remainder = SE.getConstant(RemainderVal); |
| 781 | return; |
| 782 | } |
| 783 | } |
| 784 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 785 | void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { |
| 786 | const SCEV *StartQ, *StartR, *StepQ, *StepR; |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 787 | if (!Numerator->isAffine()) |
| 788 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 789 | divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); |
| 790 | divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); |
Brendon Cahoon | f9751ad | 2015-04-22 15:06:40 +0000 | [diff] [blame] | 791 | // Bail out if the types do not match. |
| 792 | Type *Ty = Denominator->getType(); |
| 793 | if (Ty != StartQ->getType() || Ty != StartR->getType() || |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 794 | Ty != StepQ->getType() || Ty != StepR->getType()) |
| 795 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 796 | Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), |
| 797 | Numerator->getNoWrapFlags()); |
| 798 | Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), |
| 799 | Numerator->getNoWrapFlags()); |
| 800 | } |
| 801 | |
| 802 | void visitAddExpr(const SCEVAddExpr *Numerator) { |
| 803 | SmallVector<const SCEV *, 2> Qs, Rs; |
| 804 | Type *Ty = Denominator->getType(); |
| 805 | |
| 806 | for (const SCEV *Op : Numerator->operands()) { |
| 807 | const SCEV *Q, *R; |
| 808 | divide(SE, Op, Denominator, &Q, &R); |
| 809 | |
| 810 | // Bail out if types do not match. |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 811 | if (Ty != Q->getType() || Ty != R->getType()) |
| 812 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 813 | |
| 814 | Qs.push_back(Q); |
| 815 | Rs.push_back(R); |
| 816 | } |
| 817 | |
| 818 | if (Qs.size() == 1) { |
| 819 | Quotient = Qs[0]; |
| 820 | Remainder = Rs[0]; |
| 821 | return; |
| 822 | } |
| 823 | |
| 824 | Quotient = SE.getAddExpr(Qs); |
| 825 | Remainder = SE.getAddExpr(Rs); |
| 826 | } |
| 827 | |
| 828 | void visitMulExpr(const SCEVMulExpr *Numerator) { |
| 829 | SmallVector<const SCEV *, 2> Qs; |
| 830 | Type *Ty = Denominator->getType(); |
| 831 | |
| 832 | bool FoundDenominatorTerm = false; |
| 833 | for (const SCEV *Op : Numerator->operands()) { |
| 834 | // Bail out if types do not match. |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 835 | if (Ty != Op->getType()) |
| 836 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 837 | |
| 838 | if (FoundDenominatorTerm) { |
| 839 | Qs.push_back(Op); |
| 840 | continue; |
| 841 | } |
| 842 | |
| 843 | // Check whether Denominator divides one of the product operands. |
| 844 | const SCEV *Q, *R; |
| 845 | divide(SE, Op, Denominator, &Q, &R); |
| 846 | if (!R->isZero()) { |
| 847 | Qs.push_back(Op); |
| 848 | continue; |
| 849 | } |
| 850 | |
| 851 | // Bail out if types do not match. |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 852 | if (Ty != Q->getType()) |
| 853 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 854 | |
| 855 | FoundDenominatorTerm = true; |
| 856 | Qs.push_back(Q); |
| 857 | } |
| 858 | |
| 859 | if (FoundDenominatorTerm) { |
| 860 | Remainder = Zero; |
| 861 | if (Qs.size() == 1) |
| 862 | Quotient = Qs[0]; |
| 863 | else |
| 864 | Quotient = SE.getMulExpr(Qs); |
| 865 | return; |
| 866 | } |
| 867 | |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 868 | if (!isa<SCEVUnknown>(Denominator)) |
| 869 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 870 | |
| 871 | // The Remainder is obtained by replacing Denominator by 0 in Numerator. |
| 872 | ValueToValueMap RewriteMap; |
| 873 | RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = |
| 874 | cast<SCEVConstant>(Zero)->getValue(); |
| 875 | Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); |
| 876 | |
| 877 | if (Remainder->isZero()) { |
| 878 | // The Quotient is obtained by replacing Denominator by 1 in Numerator. |
| 879 | RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = |
| 880 | cast<SCEVConstant>(One)->getValue(); |
| 881 | Quotient = |
| 882 | SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); |
| 883 | return; |
| 884 | } |
| 885 | |
| 886 | // Quotient is (Numerator - Remainder) divided by Denominator. |
| 887 | const SCEV *Q, *R; |
| 888 | const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 889 | // This SCEV does not seem to simplify: fail the division here. |
| 890 | if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) |
| 891 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 892 | divide(SE, Diff, Denominator, &Q, &R); |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 893 | if (R != Zero) |
| 894 | return cannotDivide(Numerator); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 895 | Quotient = Q; |
| 896 | } |
| 897 | |
| 898 | private: |
David Majnemer | 5d2670c | 2014-11-17 11:27:45 +0000 | [diff] [blame] | 899 | SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, |
| 900 | const SCEV *Denominator) |
| 901 | : SE(S), Denominator(Denominator) { |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 902 | Zero = SE.getZero(Denominator->getType()); |
| 903 | One = SE.getOne(Denominator->getType()); |
David Majnemer | 5d2670c | 2014-11-17 11:27:45 +0000 | [diff] [blame] | 904 | |
Matthew Simpson | ddb4d97 | 2015-09-10 18:12:47 +0000 | [diff] [blame] | 905 | // We generally do not know how to divide Expr by Denominator. We |
| 906 | // initialize the division to a "cannot divide" state to simplify the rest |
| 907 | // of the code. |
| 908 | cannotDivide(Numerator); |
| 909 | } |
| 910 | |
| 911 | // Convenience function for giving up on the division. We set the quotient to |
| 912 | // be equal to zero and the remainder to be equal to the numerator. |
| 913 | void cannotDivide(const SCEV *Numerator) { |
David Majnemer | 5d2670c | 2014-11-17 11:27:45 +0000 | [diff] [blame] | 914 | Quotient = Zero; |
| 915 | Remainder = Numerator; |
| 916 | } |
| 917 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 918 | ScalarEvolution &SE; |
| 919 | const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; |
David Majnemer | 32b8ccf | 2014-11-16 20:35:19 +0000 | [diff] [blame] | 920 | }; |
| 921 | |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 922 | } |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 923 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 924 | //===----------------------------------------------------------------------===// |
| 925 | // Simple SCEV method implementations |
| 926 | //===----------------------------------------------------------------------===// |
| 927 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 928 | /// Compute BC(It, K). The result has width W. Assume, K > 0. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 929 | static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, |
Dan Gohman | 32291b1 | 2009-07-21 00:38:55 +0000 | [diff] [blame] | 930 | ScalarEvolution &SE, |
Nick Lewycky | 702cf1e | 2011-09-06 06:39:54 +0000 | [diff] [blame] | 931 | Type *ResultTy) { |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 932 | // Handle the simplest case efficiently. |
| 933 | if (K == 1) |
| 934 | return SE.getTruncateOrZeroExtend(It, ResultTy); |
| 935 | |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 936 | // We are using the following formula for BC(It, K): |
| 937 | // |
| 938 | // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! |
| 939 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 940 | // Suppose, W is the bitwidth of the return value. We must be prepared for |
| 941 | // overflow. Hence, we must assure that the result of our computation is |
| 942 | // equal to the accurate one modulo 2^W. Unfortunately, division isn't |
| 943 | // safe in modular arithmetic. |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 944 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 945 | // 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] | 946 | // 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] | 947 | // K! (i.e. trailing zeros in the binary representation of K!), and ^ is |
| 948 | // exponentiation: |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 949 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 950 | // 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] | 951 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 952 | // This formula is trivially equivalent to the previous formula. However, |
| 953 | // this formula can be implemented much more efficiently. The trick is that |
| 954 | // K! / 2^T is odd, and exact division by an odd number *is* safe in modular |
| 955 | // arithmetic. To do exact division in modular arithmetic, all we have |
| 956 | // to do is multiply by the inverse. Therefore, this step can be done at |
| 957 | // width W. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 958 | // |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 959 | // The next issue is how to safely do the division by 2^T. The way this |
| 960 | // is done is by doing the multiplication step at a width of at least W + T |
| 961 | // bits. This way, the bottom W+T bits of the product are accurate. Then, |
| 962 | // when we perform the division by 2^T (which is equivalent to a right shift |
| 963 | // by T), the bottom W bits are accurate. Extra bits are okay; they'll get |
| 964 | // truncated out after the division by 2^T. |
| 965 | // |
| 966 | // In comparison to just directly using the first formula, this technique |
| 967 | // is much more efficient; using the first formula requires W * K bits, |
| 968 | // but this formula less than W + K bits. Also, the first formula requires |
| 969 | // a division step, whereas this formula only requires multiplies and shifts. |
| 970 | // |
| 971 | // It doesn't matter whether the subtraction step is done in the calculation |
| 972 | // width or the input iteration count's width; if the subtraction overflows, |
| 973 | // the result must be zero anyway. We prefer here to do it in the width of |
| 974 | // the induction variable because it helps a lot for certain cases; CodeGen |
| 975 | // isn't smart enough to ignore the overflow, which leads to much less |
| 976 | // efficient code if the width of the subtraction is wider than the native |
| 977 | // register width. |
| 978 | // |
| 979 | // (It's possible to not widen at all by pulling out factors of 2 before |
| 980 | // the multiplication; for example, K=2 can be calculated as |
| 981 | // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires |
| 982 | // extra arithmetic, so it's not an obvious win, and it gets |
| 983 | // much more complicated for K > 3.) |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 984 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 985 | // Protection from insane SCEVs; this bound is conservative, |
| 986 | // but it probably doesn't matter. |
| 987 | if (K > 1000) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 988 | return SE.getCouldNotCompute(); |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 989 | |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 990 | unsigned W = SE.getTypeSizeInBits(ResultTy); |
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 | // Calculate K! / 2^T and T; we divide out the factors of two before |
| 993 | // multiplying for calculating K! / 2^T to avoid overflow. |
| 994 | // Other overflow doesn't matter because we only care about the bottom |
| 995 | // W bits of the result. |
| 996 | APInt OddFactorial(W, 1); |
| 997 | unsigned T = 1; |
| 998 | for (unsigned i = 3; i <= K; ++i) { |
| 999 | APInt Mult(W, i); |
| 1000 | unsigned TwoFactors = Mult.countTrailingZeros(); |
| 1001 | T += TwoFactors; |
| 1002 | Mult = Mult.lshr(TwoFactors); |
| 1003 | OddFactorial *= Mult; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1004 | } |
Nick Lewycky | ed169d5 | 2008-06-13 04:38:55 +0000 | [diff] [blame] | 1005 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1006 | // We need at least W + T bits for the multiplication step |
Nick Lewycky | 21add8f | 2009-01-25 08:16:27 +0000 | [diff] [blame] | 1007 | unsigned CalculationBits = W + T; |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1008 | |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 1009 | // Calculate 2^T, at width T+W. |
Benjamin Kramer | fc3ea6f | 2013-07-11 16:05:50 +0000 | [diff] [blame] | 1010 | APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1011 | |
| 1012 | // Calculate the multiplicative inverse of K! / 2^T; |
| 1013 | // this multiplication factor will perform the exact division by |
| 1014 | // K! / 2^T. |
| 1015 | APInt Mod = APInt::getSignedMinValue(W+1); |
| 1016 | APInt MultiplyFactor = OddFactorial.zext(W+1); |
| 1017 | MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); |
| 1018 | MultiplyFactor = MultiplyFactor.trunc(W); |
| 1019 | |
| 1020 | // Calculate the product, at width T+W |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1021 | IntegerType *CalculationTy = IntegerType::get(SE.getContext(), |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1022 | CalculationBits); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1023 | const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1024 | for (unsigned i = 1; i != K; ++i) { |
Dan Gohman | 1d2ded7 | 2010-05-03 22:09:21 +0000 | [diff] [blame] | 1025 | const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1026 | Dividend = SE.getMulExpr(Dividend, |
| 1027 | SE.getTruncateOrZeroExtend(S, CalculationTy)); |
| 1028 | } |
| 1029 | |
| 1030 | // Divide by 2^T |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1031 | const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 1032 | |
| 1033 | // Truncate the result, and divide by K! / 2^T. |
| 1034 | |
| 1035 | return SE.getMulExpr(SE.getConstant(MultiplyFactor), |
| 1036 | SE.getTruncateOrZeroExtend(DivResult, ResultTy)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1037 | } |
| 1038 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 1039 | /// Return the value of this chain of recurrences at the specified iteration |
| 1040 | /// number. We can evaluate this recurrence by multiplying each element in the |
| 1041 | /// chain by the binomial coefficient corresponding to it. In other words, we |
| 1042 | /// can evaluate {A,+,B,+,C,+,D} as: |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1043 | /// |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1044 | /// 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] | 1045 | /// |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1046 | /// where BC(It, k) stands for binomial coefficient. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1047 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1048 | const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, |
Dan Gohman | 32291b1 | 2009-07-21 00:38:55 +0000 | [diff] [blame] | 1049 | ScalarEvolution &SE) const { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1050 | const SCEV *Result = getStart(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1051 | for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { |
Wojciech Matyjewicz | d2d9764 | 2008-02-11 11:03:14 +0000 | [diff] [blame] | 1052 | // The computation is correct in the face of overflow provided that the |
| 1053 | // multiplication is performed _after_ the evaluation of the binomial |
| 1054 | // coefficient. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1055 | const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); |
Nick Lewycky | 707663e | 2008-10-13 03:58:02 +0000 | [diff] [blame] | 1056 | if (isa<SCEVCouldNotCompute>(Coeff)) |
| 1057 | return Coeff; |
| 1058 | |
| 1059 | Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1060 | } |
| 1061 | return Result; |
| 1062 | } |
| 1063 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1064 | //===----------------------------------------------------------------------===// |
| 1065 | // SCEV Expression folder implementations |
| 1066 | //===----------------------------------------------------------------------===// |
| 1067 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1068 | const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1069 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1070 | assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1071 | "This is not a truncating conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1072 | assert(isSCEVable(Ty) && |
| 1073 | "This is not a conversion to a SCEVable type!"); |
| 1074 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1075 | |
Dan Gohman | 3a302cb | 2009-07-13 20:50:19 +0000 | [diff] [blame] | 1076 | FoldingSetNodeID ID; |
| 1077 | ID.AddInteger(scTruncate); |
| 1078 | ID.AddPointer(Op); |
| 1079 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1080 | void *IP = nullptr; |
Dan Gohman | 3a302cb | 2009-07-13 20:50:19 +0000 | [diff] [blame] | 1081 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1082 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1083 | // Fold if the operand is constant. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1084 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
Dan Gohman | 8d7576e | 2009-06-24 00:38:39 +0000 | [diff] [blame] | 1085 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1086 | cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1087 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1088 | // trunc(trunc(x)) --> trunc(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1089 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1090 | return getTruncateExpr(ST->getOperand(), Ty); |
| 1091 | |
Nick Lewycky | b4d9f7a | 2009-04-23 05:15:08 +0000 | [diff] [blame] | 1092 | // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1093 | if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) |
Nick Lewycky | b4d9f7a | 2009-04-23 05:15:08 +0000 | [diff] [blame] | 1094 | return getTruncateOrSignExtend(SS->getOperand(), Ty); |
| 1095 | |
| 1096 | // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1097 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
Nick Lewycky | b4d9f7a | 2009-04-23 05:15:08 +0000 | [diff] [blame] | 1098 | return getTruncateOrZeroExtend(SZ->getOperand(), Ty); |
| 1099 | |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1100 | // 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] | 1101 | // eliminate all the truncates, or we replace other casts with truncates. |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1102 | if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) { |
| 1103 | SmallVector<const SCEV *, 4> Operands; |
| 1104 | bool hasTrunc = false; |
| 1105 | for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) { |
| 1106 | const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty); |
Nick Lewycky | be8af48 | 2015-03-20 02:25:00 +0000 | [diff] [blame] | 1107 | if (!isa<SCEVCastExpr>(SA->getOperand(i))) |
| 1108 | hasTrunc = isa<SCEVTruncateExpr>(S); |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1109 | Operands.push_back(S); |
| 1110 | } |
| 1111 | if (!hasTrunc) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1112 | return getAddExpr(Operands); |
Nick Lewycky | d9e6b4a | 2011-01-26 08:40:22 +0000 | [diff] [blame] | 1113 | UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. |
Nick Lewycky | 5143f0f | 2011-01-19 16:59:46 +0000 | [diff] [blame] | 1114 | } |
| 1115 | |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1116 | // 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] | 1117 | // eliminate all the truncates, or we replace other casts with truncates. |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1118 | if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) { |
| 1119 | SmallVector<const SCEV *, 4> Operands; |
| 1120 | bool hasTrunc = false; |
| 1121 | for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) { |
| 1122 | const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty); |
Nick Lewycky | be8af48 | 2015-03-20 02:25:00 +0000 | [diff] [blame] | 1123 | if (!isa<SCEVCastExpr>(SM->getOperand(i))) |
| 1124 | hasTrunc = isa<SCEVTruncateExpr>(S); |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1125 | Operands.push_back(S); |
| 1126 | } |
| 1127 | if (!hasTrunc) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1128 | return getMulExpr(Operands); |
Nick Lewycky | d9e6b4a | 2011-01-26 08:40:22 +0000 | [diff] [blame] | 1129 | UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL. |
Nick Lewycky | 5c901f3 | 2011-01-19 18:56:00 +0000 | [diff] [blame] | 1130 | } |
| 1131 | |
Dan Gohman | 5a728c9 | 2009-06-18 16:24:47 +0000 | [diff] [blame] | 1132 | // 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] | 1133 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1134 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 1135 | for (const SCEV *Op : AddRec->operands()) |
| 1136 | Operands.push_back(getTruncateExpr(Op, Ty)); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 1137 | return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1138 | } |
| 1139 | |
Dan Gohman | 89dd42a | 2010-06-25 18:47:08 +0000 | [diff] [blame] | 1140 | // The cast wasn't folded; create an explicit cast node. We can reuse |
| 1141 | // the existing insert position since if we get here, we won't have |
| 1142 | // made any changes which would invalidate it. |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1143 | SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), |
| 1144 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1145 | UniqueSCEVs.InsertNode(S, IP); |
| 1146 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1147 | } |
| 1148 | |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1149 | // Get the limit of a recurrence such that incrementing by Step cannot cause |
| 1150 | // signed overflow as long as the value of the recurrence within the |
| 1151 | // loop does not exceed this limit before incrementing. |
| 1152 | static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, |
| 1153 | ICmpInst::Predicate *Pred, |
| 1154 | ScalarEvolution *SE) { |
| 1155 | unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); |
| 1156 | if (SE->isKnownPositive(Step)) { |
| 1157 | *Pred = ICmpInst::ICMP_SLT; |
| 1158 | return SE->getConstant(APInt::getSignedMinValue(BitWidth) - |
| 1159 | SE->getSignedRange(Step).getSignedMax()); |
| 1160 | } |
| 1161 | if (SE->isKnownNegative(Step)) { |
| 1162 | *Pred = ICmpInst::ICMP_SGT; |
| 1163 | return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - |
| 1164 | SE->getSignedRange(Step).getSignedMin()); |
| 1165 | } |
| 1166 | return nullptr; |
| 1167 | } |
| 1168 | |
| 1169 | // Get the limit of a recurrence such that incrementing by Step cannot cause |
| 1170 | // unsigned overflow as long as the value of the recurrence within the loop does |
| 1171 | // not exceed this limit before incrementing. |
| 1172 | static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, |
| 1173 | ICmpInst::Predicate *Pred, |
| 1174 | ScalarEvolution *SE) { |
| 1175 | unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); |
| 1176 | *Pred = ICmpInst::ICMP_ULT; |
| 1177 | |
| 1178 | return SE->getConstant(APInt::getMinValue(BitWidth) - |
| 1179 | SE->getUnsignedRange(Step).getUnsignedMax()); |
| 1180 | } |
| 1181 | |
| 1182 | namespace { |
| 1183 | |
| 1184 | struct ExtendOpTraitsBase { |
| 1185 | typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *); |
| 1186 | }; |
| 1187 | |
| 1188 | // Used to make code generic over signed and unsigned overflow. |
| 1189 | template <typename ExtendOp> struct ExtendOpTraits { |
| 1190 | // Members present: |
| 1191 | // |
| 1192 | // static const SCEV::NoWrapFlags WrapType; |
| 1193 | // |
| 1194 | // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; |
| 1195 | // |
| 1196 | // static const SCEV *getOverflowLimitForStep(const SCEV *Step, |
| 1197 | // ICmpInst::Predicate *Pred, |
| 1198 | // ScalarEvolution *SE); |
| 1199 | }; |
| 1200 | |
| 1201 | template <> |
| 1202 | struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { |
| 1203 | static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; |
| 1204 | |
| 1205 | static const GetExtendExprTy GetExtendExpr; |
| 1206 | |
| 1207 | static const SCEV *getOverflowLimitForStep(const SCEV *Step, |
| 1208 | ICmpInst::Predicate *Pred, |
| 1209 | ScalarEvolution *SE) { |
| 1210 | return getSignedOverflowLimitForStep(Step, Pred, SE); |
| 1211 | } |
| 1212 | }; |
| 1213 | |
Sanjoy Das | c1065b9 | 2015-02-18 08:03:22 +0000 | [diff] [blame] | 1214 | const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1215 | SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; |
| 1216 | |
| 1217 | template <> |
| 1218 | struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { |
| 1219 | static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; |
| 1220 | |
| 1221 | static const GetExtendExprTy GetExtendExpr; |
| 1222 | |
| 1223 | static const SCEV *getOverflowLimitForStep(const SCEV *Step, |
| 1224 | ICmpInst::Predicate *Pred, |
| 1225 | ScalarEvolution *SE) { |
| 1226 | return getUnsignedOverflowLimitForStep(Step, Pred, SE); |
| 1227 | } |
| 1228 | }; |
| 1229 | |
Sanjoy Das | c1065b9 | 2015-02-18 08:03:22 +0000 | [diff] [blame] | 1230 | const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1231 | SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 1232 | } |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1233 | |
| 1234 | // The recurrence AR has been shown to have no signed/unsigned wrap or something |
| 1235 | // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as |
| 1236 | // easily prove NSW/NUW for its preincrement or postincrement sibling. This |
| 1237 | // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + |
| 1238 | // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the |
| 1239 | // expression "Step + sext/zext(PreIncAR)" is congruent with |
| 1240 | // "sext/zext(PostIncAR)" |
| 1241 | template <typename ExtendOpTy> |
| 1242 | static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, |
| 1243 | ScalarEvolution *SE) { |
| 1244 | auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; |
| 1245 | auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; |
| 1246 | |
| 1247 | const Loop *L = AR->getLoop(); |
| 1248 | const SCEV *Start = AR->getStart(); |
| 1249 | const SCEV *Step = AR->getStepRecurrence(*SE); |
| 1250 | |
| 1251 | // Check for a simple looking step prior to loop entry. |
| 1252 | const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); |
| 1253 | if (!SA) |
| 1254 | return nullptr; |
| 1255 | |
| 1256 | // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV |
| 1257 | // subtraction is expensive. For this purpose, perform a quick and dirty |
| 1258 | // difference, by checking for Step in the operand list. |
| 1259 | SmallVector<const SCEV *, 4> DiffOps; |
| 1260 | for (const SCEV *Op : SA->operands()) |
| 1261 | if (Op != Step) |
| 1262 | DiffOps.push_back(Op); |
| 1263 | |
| 1264 | if (DiffOps.size() == SA->getNumOperands()) |
| 1265 | return nullptr; |
| 1266 | |
| 1267 | // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + |
| 1268 | // `Step`: |
| 1269 | |
| 1270 | // 1. NSW/NUW flags on the step increment. |
Sanjoy Das | 0714e3e | 2015-10-23 06:33:47 +0000 | [diff] [blame] | 1271 | auto PreStartFlags = |
| 1272 | ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); |
| 1273 | const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1274 | const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( |
| 1275 | SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); |
| 1276 | |
Sanjoy Das | b14010d | 2015-02-24 01:02:42 +0000 | [diff] [blame] | 1277 | // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies |
| 1278 | // "S+X does not sign/unsign-overflow". |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1279 | // |
| 1280 | |
Sanjoy Das | b14010d | 2015-02-24 01:02:42 +0000 | [diff] [blame] | 1281 | const SCEV *BECount = SE->getBackedgeTakenCount(L); |
| 1282 | if (PreAR && PreAR->getNoWrapFlags(WrapType) && |
| 1283 | !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1284 | return PreStart; |
| 1285 | |
| 1286 | // 2. Direct overflow check on the step operation's expression. |
| 1287 | unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); |
| 1288 | Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); |
| 1289 | const SCEV *OperandExtendedStart = |
| 1290 | SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy), |
| 1291 | (SE->*GetExtendExpr)(Step, WideTy)); |
| 1292 | if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) { |
| 1293 | if (PreAR && AR->getNoWrapFlags(WrapType)) { |
| 1294 | // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW |
| 1295 | // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then |
| 1296 | // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. |
| 1297 | const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); |
| 1298 | } |
| 1299 | return PreStart; |
| 1300 | } |
| 1301 | |
| 1302 | // 3. Loop precondition. |
| 1303 | ICmpInst::Predicate Pred; |
| 1304 | const SCEV *OverflowLimit = |
| 1305 | ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); |
| 1306 | |
| 1307 | if (OverflowLimit && |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 1308 | SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1309 | return PreStart; |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 1310 | |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1311 | return nullptr; |
| 1312 | } |
| 1313 | |
| 1314 | // Get the normalized zero or sign extended expression for this AddRec's Start. |
| 1315 | template <typename ExtendOpTy> |
| 1316 | static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, |
| 1317 | ScalarEvolution *SE) { |
| 1318 | auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; |
| 1319 | |
| 1320 | const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE); |
| 1321 | if (!PreStart) |
| 1322 | return (SE->*GetExtendExpr)(AR->getStart(), Ty); |
| 1323 | |
| 1324 | return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty), |
| 1325 | (SE->*GetExtendExpr)(PreStart, Ty)); |
| 1326 | } |
| 1327 | |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1328 | // Try to prove away overflow by looking at "nearby" add recurrences. A |
| 1329 | // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it |
| 1330 | // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. |
| 1331 | // |
| 1332 | // Formally: |
| 1333 | // |
| 1334 | // {S,+,X} == {S-T,+,X} + T |
| 1335 | // => Ext({S,+,X}) == Ext({S-T,+,X} + T) |
| 1336 | // |
| 1337 | // If ({S-T,+,X} + T) does not overflow ... (1) |
| 1338 | // |
| 1339 | // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) |
| 1340 | // |
| 1341 | // If {S-T,+,X} does not overflow ... (2) |
| 1342 | // |
| 1343 | // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) |
| 1344 | // == {Ext(S-T)+Ext(T),+,Ext(X)} |
| 1345 | // |
| 1346 | // If (S-T)+T does not overflow ... (3) |
| 1347 | // |
| 1348 | // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} |
| 1349 | // == {Ext(S),+,Ext(X)} == LHS |
| 1350 | // |
| 1351 | // Thus, if (1), (2) and (3) are true for some T, then |
| 1352 | // Ext({S,+,X}) == {Ext(S),+,Ext(X)} |
| 1353 | // |
| 1354 | // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) |
| 1355 | // does not overflow" restricted to the 0th iteration. Therefore we only need |
| 1356 | // to check for (1) and (2). |
| 1357 | // |
| 1358 | // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T |
| 1359 | // is `Delta` (defined below). |
| 1360 | // |
| 1361 | template <typename ExtendOpTy> |
| 1362 | bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, |
| 1363 | const SCEV *Step, |
| 1364 | const Loop *L) { |
| 1365 | auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; |
| 1366 | |
| 1367 | // We restrict `Start` to a constant to prevent SCEV from spending too much |
| 1368 | // time here. It is correct (but more expensive) to continue with a |
| 1369 | // non-constant `Start` and do a general SCEV subtraction to compute |
| 1370 | // `PreStart` below. |
| 1371 | // |
| 1372 | const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); |
| 1373 | if (!StartC) |
| 1374 | return false; |
| 1375 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1376 | APInt StartAI = StartC->getAPInt(); |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1377 | |
| 1378 | for (unsigned Delta : {-2, -1, 1, 2}) { |
| 1379 | const SCEV *PreStart = getConstant(StartAI - Delta); |
| 1380 | |
Sanjoy Das | 4280110 | 2015-10-23 06:57:21 +0000 | [diff] [blame] | 1381 | FoldingSetNodeID ID; |
| 1382 | ID.AddInteger(scAddRecExpr); |
| 1383 | ID.AddPointer(PreStart); |
| 1384 | ID.AddPointer(Step); |
| 1385 | ID.AddPointer(L); |
| 1386 | void *IP = nullptr; |
| 1387 | const auto *PreAR = |
| 1388 | static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 1389 | |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1390 | // Give up if we don't already have the add recurrence we need because |
| 1391 | // actually constructing an add recurrence is relatively expensive. |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1392 | if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) |
| 1393 | const SCEV *DeltaS = getConstant(StartC->getType(), Delta); |
| 1394 | ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; |
| 1395 | const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( |
| 1396 | DeltaS, &Pred, this); |
| 1397 | if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) |
| 1398 | return true; |
| 1399 | } |
| 1400 | } |
| 1401 | |
| 1402 | return false; |
| 1403 | } |
| 1404 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1405 | const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1406 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1407 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
Dan Gohman | c1c2ba7 | 2009-04-16 19:25:55 +0000 | [diff] [blame] | 1408 | "This is not an extending conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1409 | assert(isSCEVable(Ty) && |
| 1410 | "This is not a conversion to a SCEVable type!"); |
| 1411 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | c1c2ba7 | 2009-04-16 19:25:55 +0000 | [diff] [blame] | 1412 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1413 | // Fold if the operand is constant. |
Dan Gohman | 5235cc2 | 2010-06-24 16:47:03 +0000 | [diff] [blame] | 1414 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
| 1415 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1416 | cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1417 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1418 | // zext(zext(x)) --> zext(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1419 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1420 | return getZeroExtendExpr(SZ->getOperand(), Ty); |
| 1421 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1422 | // Before doing any expensive analysis, check to see if we've already |
| 1423 | // computed a SCEV for this Op and Ty. |
| 1424 | FoldingSetNodeID ID; |
| 1425 | ID.AddInteger(scZeroExtend); |
| 1426 | ID.AddPointer(Op); |
| 1427 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1428 | void *IP = nullptr; |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1429 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1430 | |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1431 | // zext(trunc(x)) --> zext(x) or x or trunc(x) |
| 1432 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { |
| 1433 | // It's possible the bits taken off by the truncate were all zero bits. If |
| 1434 | // so, we should be able to simplify this further. |
| 1435 | const SCEV *X = ST->getOperand(); |
| 1436 | ConstantRange CR = getUnsignedRange(X); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1437 | unsigned TruncBits = getTypeSizeInBits(ST->getType()); |
| 1438 | unsigned NewBits = getTypeSizeInBits(Ty); |
| 1439 | if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( |
Nick Lewycky | d4192f7 | 2011-01-23 20:06:05 +0000 | [diff] [blame] | 1440 | CR.zextOrTrunc(NewBits))) |
| 1441 | return getTruncateOrZeroExtend(X, Ty); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1442 | } |
| 1443 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1444 | // 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] | 1445 | // 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] | 1446 | // operands (often constants). This allows analysis of something like |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1447 | // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1448 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1449 | if (AR->isAffine()) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1450 | const SCEV *Start = AR->getStart(); |
| 1451 | const SCEV *Step = AR->getStepRecurrence(*this); |
| 1452 | unsigned BitWidth = getTypeSizeInBits(AR->getType()); |
| 1453 | const Loop *L = AR->getLoop(); |
| 1454 | |
Sanjoy Das | 724f5cf | 2016-03-03 18:31:29 +0000 | [diff] [blame] | 1455 | if (!AR->hasNoUnsignedWrap()) { |
| 1456 | auto NewFlags = proveNoWrapViaConstantRanges(AR); |
| 1457 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); |
| 1458 | } |
| 1459 | |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1460 | // If we have special knowledge that this addrec won't overflow, |
| 1461 | // we don't need to do any further analysis. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1462 | if (AR->hasNoUnsignedWrap()) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1463 | return getAddRecExpr( |
| 1464 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1465 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1466 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1467 | // Check whether the backedge-taken count is SCEVCouldNotCompute. |
| 1468 | // Note that this serves two purposes: It filters out loops that are |
| 1469 | // simply not analyzable, and it covers the case where this code is |
| 1470 | // being called from within backedge-taken count analysis, such that |
| 1471 | // attempting to ask for the backedge-taken count would likely result |
| 1472 | // in infinite recursion. In the later case, the analysis code will |
| 1473 | // cope with a conservative value, and it will take care to purge |
| 1474 | // that value once it has finished. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1475 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1476 | if (!isa<SCEVCouldNotCompute>(MaxBECount)) { |
Dan Gohman | 95c5b0e | 2009-04-29 01:54:20 +0000 | [diff] [blame] | 1477 | // Manually compute the final value for AR, checking for |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1478 | // overflow. |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1479 | |
| 1480 | // Check whether the backedge-taken count can be losslessly casted to |
| 1481 | // the addrec's type. The count is always unsigned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1482 | const SCEV *CastedMaxBECount = |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1483 | getTruncateOrZeroExtend(MaxBECount, Start->getType()); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1484 | const SCEV *RecastedMaxBECount = |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1485 | getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); |
| 1486 | if (MaxBECount == RecastedMaxBECount) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1487 | Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1488 | // Check whether Start+Step*MaxBECount has no unsigned overflow. |
Dan Gohman | 007f504 | 2010-02-24 19:31:06 +0000 | [diff] [blame] | 1489 | const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1490 | const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy); |
| 1491 | const SCEV *WideStart = getZeroExtendExpr(Start, WideTy); |
| 1492 | const SCEV *WideMaxBECount = |
| 1493 | getZeroExtendExpr(CastedMaxBECount, WideTy); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1494 | const SCEV *OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1495 | getAddExpr(WideStart, |
| 1496 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1497 | getZeroExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1498 | if (ZAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1499 | // Cache knowledge of AR NUW, which is propagated to this AddRec. |
| 1500 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1501 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1502 | return getAddRecExpr( |
| 1503 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1504 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1505 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1506 | // Similar to above, only this time treat the step value as signed. |
| 1507 | // This covers loops that count down. |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1508 | OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1509 | getAddExpr(WideStart, |
| 1510 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1511 | getSignExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1512 | if (ZAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1513 | // Cache knowledge of AR NW, which is propagated to this AddRec. |
| 1514 | // Negative step causes unsigned wrap, but it still can't self-wrap. |
| 1515 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1516 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1517 | return getAddRecExpr( |
| 1518 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1519 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1520 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1521 | } |
Sanjoy Das | f5d40d5 | 2016-05-17 17:51:14 +0000 | [diff] [blame] | 1522 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1523 | |
Sanjoy Das | f5d40d5 | 2016-05-17 17:51:14 +0000 | [diff] [blame] | 1524 | // Normally, in the cases we can prove no-overflow via a |
| 1525 | // backedge guarding condition, we can also compute a backedge |
| 1526 | // taken count for the loop. The exceptions are assumptions and |
| 1527 | // guards present in the loop -- SCEV is not great at exploiting |
| 1528 | // these to compute max backedge taken counts, but can still use |
| 1529 | // these to prove lack of overflow. Use this fact to avoid |
| 1530 | // doing extra work that may not pay off. |
| 1531 | if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || |
| 1532 | !AC.assumptions().empty()) { |
| 1533 | // If the backedge is guarded by a comparison with the pre-inc |
| 1534 | // value the addrec is safe. Also, if the entry is guarded by |
| 1535 | // a comparison with the start value and the backedge is |
| 1536 | // guarded by a comparison with the post-inc value, the addrec |
| 1537 | // is safe. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1538 | if (isKnownPositive(Step)) { |
| 1539 | const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - |
| 1540 | getUnsignedRange(Step).getUnsignedMax()); |
| 1541 | if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || |
Dan Gohman | b50349a | 2010-04-11 19:27:13 +0000 | [diff] [blame] | 1542 | (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) && |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1543 | isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1544 | AR->getPostIncExpr(*this), N))) { |
Sanjoy Das | f5d40d5 | 2016-05-17 17:51:14 +0000 | [diff] [blame] | 1545 | // Cache knowledge of AR NUW, which is propagated to this |
| 1546 | // AddRec. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1547 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1548 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1549 | return getAddRecExpr( |
| 1550 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1551 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1552 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1553 | } else if (isKnownNegative(Step)) { |
| 1554 | const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - |
| 1555 | getSignedRange(Step).getSignedMin()); |
Dan Gohman | 5f18c54 | 2010-05-04 01:11:15 +0000 | [diff] [blame] | 1556 | if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || |
| 1557 | (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) && |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1558 | isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1559 | AR->getPostIncExpr(*this), N))) { |
Sanjoy Das | f5d40d5 | 2016-05-17 17:51:14 +0000 | [diff] [blame] | 1560 | // Cache knowledge of AR NW, which is propagated to this |
| 1561 | // AddRec. Negative step causes unsigned wrap, but it |
| 1562 | // still can't self-wrap. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1563 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
| 1564 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1565 | return getAddRecExpr( |
| 1566 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1567 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1568 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1569 | } |
| 1570 | } |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1571 | |
| 1572 | if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { |
| 1573 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); |
| 1574 | return getAddRecExpr( |
| 1575 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this), |
| 1576 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
| 1577 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1578 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1579 | |
Sanjoy Das | eeca9f6 | 2015-10-22 19:57:38 +0000 | [diff] [blame] | 1580 | if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { |
| 1581 | // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1582 | if (SA->hasNoUnsignedWrap()) { |
Sanjoy Das | eeca9f6 | 2015-10-22 19:57:38 +0000 | [diff] [blame] | 1583 | // If the addition does not unsign overflow then we can, by definition, |
| 1584 | // commute the zero extension with the addition operation. |
| 1585 | SmallVector<const SCEV *, 4> Ops; |
| 1586 | for (const auto *Op : SA->operands()) |
| 1587 | Ops.push_back(getZeroExtendExpr(Op, Ty)); |
| 1588 | return getAddExpr(Ops, SCEV::FlagNUW); |
| 1589 | } |
| 1590 | } |
| 1591 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1592 | // The cast wasn't folded; create an explicit cast node. |
| 1593 | // Recompute the insert position, as it may have been invalidated. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1594 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1595 | SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), |
| 1596 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1597 | UniqueSCEVs.InsertNode(S, IP); |
| 1598 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 1599 | } |
| 1600 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1601 | const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1602 | Type *Ty) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 1603 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1604 | "This is not an extending conversion!"); |
Dan Gohman | 194e42c | 2009-05-01 16:44:18 +0000 | [diff] [blame] | 1605 | assert(isSCEVable(Ty) && |
| 1606 | "This is not a conversion to a SCEVable type!"); |
| 1607 | Ty = getEffectiveSCEVType(Ty); |
Dan Gohman | 413e91f | 2009-04-21 00:55:22 +0000 | [diff] [blame] | 1608 | |
Dan Gohman | 3423e72 | 2009-06-30 20:13:32 +0000 | [diff] [blame] | 1609 | // Fold if the operand is constant. |
Dan Gohman | 5235cc2 | 2010-06-24 16:47:03 +0000 | [diff] [blame] | 1610 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
| 1611 | return getConstant( |
Nuno Lopes | ab5c924 | 2012-05-15 15:44:38 +0000 | [diff] [blame] | 1612 | cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1613 | |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1614 | // sext(sext(x)) --> sext(x) |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1615 | if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) |
Dan Gohman | 79af854 | 2009-04-22 16:20:48 +0000 | [diff] [blame] | 1616 | return getSignExtendExpr(SS->getOperand(), Ty); |
| 1617 | |
Nick Lewycky | e9ea75e | 2011-01-19 15:56:12 +0000 | [diff] [blame] | 1618 | // sext(zext(x)) --> zext(x) |
| 1619 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) |
| 1620 | return getZeroExtendExpr(SZ->getOperand(), Ty); |
| 1621 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1622 | // Before doing any expensive analysis, check to see if we've already |
| 1623 | // computed a SCEV for this Op and Ty. |
| 1624 | FoldingSetNodeID ID; |
| 1625 | ID.AddInteger(scSignExtend); |
| 1626 | ID.AddPointer(Op); |
| 1627 | ID.AddPointer(Ty); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 1628 | void *IP = nullptr; |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1629 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
| 1630 | |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1631 | // sext(trunc(x)) --> sext(x) or x or trunc(x) |
| 1632 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { |
| 1633 | // It's possible the bits taken off by the truncate were all sign bits. If |
| 1634 | // so, we should be able to simplify this further. |
| 1635 | const SCEV *X = ST->getOperand(); |
| 1636 | ConstantRange CR = getSignedRange(X); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1637 | unsigned TruncBits = getTypeSizeInBits(ST->getType()); |
| 1638 | unsigned NewBits = getTypeSizeInBits(Ty); |
| 1639 | if (CR.truncate(TruncBits).signExtend(NewBits).contains( |
Nick Lewycky | d4192f7 | 2011-01-23 20:06:05 +0000 | [diff] [blame] | 1640 | CR.sextOrTrunc(NewBits))) |
| 1641 | return getTruncateOrSignExtend(X, Ty); |
Nick Lewycky | bc98f5b | 2011-01-23 06:20:19 +0000 | [diff] [blame] | 1642 | } |
| 1643 | |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1644 | // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2 |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1645 | if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1646 | if (SA->getNumOperands() == 2) { |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1647 | auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0)); |
| 1648 | auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1)); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1649 | if (SMul && SC1) { |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1650 | if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1651 | const APInt &C1 = SC1->getAPInt(); |
| 1652 | const APInt &C2 = SC2->getAPInt(); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1653 | if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && |
Michael Zolotukhin | 265dfa4 | 2014-05-26 14:49:46 +0000 | [diff] [blame] | 1654 | C2.ugt(C1) && C2.isPowerOf2()) |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1655 | return getAddExpr(getSignExtendExpr(SC1, Ty), |
| 1656 | getSignExtendExpr(SMul, Ty)); |
| 1657 | } |
| 1658 | } |
| 1659 | } |
Sanjoy Das | a060e60 | 2015-10-22 19:57:25 +0000 | [diff] [blame] | 1660 | |
| 1661 | // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1662 | if (SA->hasNoSignedWrap()) { |
Sanjoy Das | a060e60 | 2015-10-22 19:57:25 +0000 | [diff] [blame] | 1663 | // If the addition does not sign overflow then we can, by definition, |
| 1664 | // commute the sign extension with the addition operation. |
| 1665 | SmallVector<const SCEV *, 4> Ops; |
| 1666 | for (const auto *Op : SA->operands()) |
| 1667 | Ops.push_back(getSignExtendExpr(Op, Ty)); |
| 1668 | return getAddExpr(Ops, SCEV::FlagNSW); |
| 1669 | } |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1670 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1671 | // 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] | 1672 | // 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] | 1673 | // operands (often constants). This allows analysis of something like |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1674 | // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 1675 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1676 | if (AR->isAffine()) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1677 | const SCEV *Start = AR->getStart(); |
| 1678 | const SCEV *Step = AR->getStepRecurrence(*this); |
| 1679 | unsigned BitWidth = getTypeSizeInBits(AR->getType()); |
| 1680 | const Loop *L = AR->getLoop(); |
| 1681 | |
Sanjoy Das | 724f5cf | 2016-03-03 18:31:29 +0000 | [diff] [blame] | 1682 | if (!AR->hasNoSignedWrap()) { |
| 1683 | auto NewFlags = proveNoWrapViaConstantRanges(AR); |
| 1684 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); |
| 1685 | } |
| 1686 | |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1687 | // If we have special knowledge that this addrec won't overflow, |
| 1688 | // we don't need to do any further analysis. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 1689 | if (AR->hasNoSignedWrap()) |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1690 | return getAddRecExpr( |
| 1691 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1692 | getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW); |
Dan Gohman | 62ef6a7 | 2009-07-25 01:22:26 +0000 | [diff] [blame] | 1693 | |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1694 | // Check whether the backedge-taken count is SCEVCouldNotCompute. |
| 1695 | // Note that this serves two purposes: It filters out loops that are |
| 1696 | // simply not analyzable, and it covers the case where this code is |
| 1697 | // being called from within backedge-taken count analysis, such that |
| 1698 | // attempting to ask for the backedge-taken count would likely result |
| 1699 | // in infinite recursion. In the later case, the analysis code will |
| 1700 | // cope with a conservative value, and it will take care to purge |
| 1701 | // that value once it has finished. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1702 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(L); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1703 | if (!isa<SCEVCouldNotCompute>(MaxBECount)) { |
Dan Gohman | 95c5b0e | 2009-04-29 01:54:20 +0000 | [diff] [blame] | 1704 | // Manually compute the final value for AR, checking for |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1705 | // overflow. |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1706 | |
| 1707 | // Check whether the backedge-taken count can be losslessly casted to |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1708 | // the addrec's type. The count is always unsigned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1709 | const SCEV *CastedMaxBECount = |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1710 | getTruncateOrZeroExtend(MaxBECount, Start->getType()); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1711 | const SCEV *RecastedMaxBECount = |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1712 | getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType()); |
| 1713 | if (MaxBECount == RecastedMaxBECount) { |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1714 | Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 1715 | // Check whether Start+Step*MaxBECount has no signed overflow. |
Dan Gohman | 007f504 | 2010-02-24 19:31:06 +0000 | [diff] [blame] | 1716 | const SCEV *SMul = getMulExpr(CastedMaxBECount, Step); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1717 | const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy); |
| 1718 | const SCEV *WideStart = getSignExtendExpr(Start, WideTy); |
| 1719 | const SCEV *WideMaxBECount = |
| 1720 | getZeroExtendExpr(CastedMaxBECount, WideTy); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1721 | const SCEV *OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1722 | getAddExpr(WideStart, |
| 1723 | getMulExpr(WideMaxBECount, |
Dan Gohman | 4fc3668 | 2009-05-18 15:58:39 +0000 | [diff] [blame] | 1724 | getSignExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1725 | if (SAdd == OperandExtendedAdd) { |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1726 | // Cache knowledge of AR NSW, which is propagated to this AddRec. |
| 1727 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
Dan Gohman | 494dac3 | 2009-04-29 22:28:28 +0000 | [diff] [blame] | 1728 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1729 | return getAddRecExpr( |
| 1730 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1731 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1732 | } |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1733 | // Similar to above, only this time treat the step value as unsigned. |
| 1734 | // This covers loops that count up with an unsigned step. |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1735 | OperandExtendedAdd = |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1736 | getAddExpr(WideStart, |
| 1737 | getMulExpr(WideMaxBECount, |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1738 | getZeroExtendExpr(Step, WideTy))); |
Nuno Lopes | c2a170e | 2012-05-15 20:20:14 +0000 | [diff] [blame] | 1739 | if (SAdd == OperandExtendedAdd) { |
Sanjoy Das | bf5d870 | 2015-02-09 18:34:55 +0000 | [diff] [blame] | 1740 | // If AR wraps around then |
| 1741 | // |
| 1742 | // abs(Step) * MaxBECount > unsigned-max(AR->getType()) |
| 1743 | // => SAdd != OperandExtendedAdd |
| 1744 | // |
| 1745 | // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> |
| 1746 | // (SAdd == OperandExtendedAdd => AR is NW) |
| 1747 | |
| 1748 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); |
| 1749 | |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 1750 | // Return the expression with the addrec on the outside. |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1751 | return getAddRecExpr( |
| 1752 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1753 | getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1754 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1755 | } |
Sanjoy Das | 787c246 | 2016-05-11 17:41:26 +0000 | [diff] [blame] | 1756 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 1757 | |
Sanjoy Das | 787c246 | 2016-05-11 17:41:26 +0000 | [diff] [blame] | 1758 | // Normally, in the cases we can prove no-overflow via a |
| 1759 | // backedge guarding condition, we can also compute a backedge |
| 1760 | // taken count for the loop. The exceptions are assumptions and |
| 1761 | // guards present in the loop -- SCEV is not great at exploiting |
| 1762 | // these to compute max backedge taken counts, but can still use |
| 1763 | // these to prove lack of overflow. Use this fact to avoid |
| 1764 | // doing extra work that may not pay off. |
| 1765 | |
| 1766 | if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || |
| 1767 | !AC.assumptions().empty()) { |
| 1768 | // If the backedge is guarded by a comparison with the pre-inc |
| 1769 | // value the addrec is safe. Also, if the entry is guarded by |
| 1770 | // a comparison with the start value and the backedge is |
| 1771 | // guarded by a comparison with the post-inc value, the addrec |
| 1772 | // is safe. |
Andrew Trick | 812276e | 2011-05-31 21:17:47 +0000 | [diff] [blame] | 1773 | ICmpInst::Predicate Pred; |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1774 | const SCEV *OverflowLimit = |
| 1775 | getSignedOverflowLimitForStep(Step, &Pred, this); |
Andrew Trick | 812276e | 2011-05-31 21:17:47 +0000 | [diff] [blame] | 1776 | if (OverflowLimit && |
| 1777 | (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || |
| 1778 | (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) && |
| 1779 | isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this), |
| 1780 | OverflowLimit)))) { |
| 1781 | // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. |
| 1782 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
Sanjoy Das | 4153f47 | 2015-02-18 01:47:07 +0000 | [diff] [blame] | 1783 | return getAddRecExpr( |
| 1784 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1785 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1786 | } |
| 1787 | } |
Sanjoy Das | 787c246 | 2016-05-11 17:41:26 +0000 | [diff] [blame] | 1788 | |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1789 | // If Start and Step are constants, check if we can apply this |
| 1790 | // transformation: |
| 1791 | // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2 |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 1792 | auto *SC1 = dyn_cast<SCEVConstant>(Start); |
| 1793 | auto *SC2 = dyn_cast<SCEVConstant>(Step); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1794 | if (SC1 && SC2) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1795 | const APInt &C1 = SC1->getAPInt(); |
| 1796 | const APInt &C2 = SC2->getAPInt(); |
Michael Zolotukhin | 265dfa4 | 2014-05-26 14:49:46 +0000 | [diff] [blame] | 1797 | if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) && |
| 1798 | C2.isPowerOf2()) { |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1799 | Start = getSignExtendExpr(Start, Ty); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 1800 | const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L, |
| 1801 | AR->getNoWrapFlags()); |
Michael Zolotukhin | d4c7246 | 2014-05-24 08:09:57 +0000 | [diff] [blame] | 1802 | return getAddExpr(Start, getSignExtendExpr(NewAR, Ty)); |
| 1803 | } |
| 1804 | } |
Sanjoy Das | 9e2c501 | 2015-03-04 22:24:17 +0000 | [diff] [blame] | 1805 | |
| 1806 | if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { |
| 1807 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); |
| 1808 | return getAddRecExpr( |
| 1809 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this), |
| 1810 | getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags()); |
| 1811 | } |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 1812 | } |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1813 | |
Sanjoy Das | 11ef606 | 2016-03-03 18:31:23 +0000 | [diff] [blame] | 1814 | // If the input value is provably positive and we could not simplify |
| 1815 | // away the sext build a zext instead. |
| 1816 | if (isKnownNonNegative(Op)) |
| 1817 | return getZeroExtendExpr(Op, Ty); |
| 1818 | |
Dan Gohman | 74a0ba1 | 2009-07-13 20:55:53 +0000 | [diff] [blame] | 1819 | // The cast wasn't folded; create an explicit cast node. |
| 1820 | // Recompute the insert position, as it may have been invalidated. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1821 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 1822 | SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), |
| 1823 | Op, Ty); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 1824 | UniqueSCEVs.InsertNode(S, IP); |
| 1825 | return S; |
Dan Gohman | cb9e09a | 2007-06-15 14:38:12 +0000 | [diff] [blame] | 1826 | } |
| 1827 | |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1828 | /// getAnyExtendExpr - Return a SCEV for the given operand extended with |
| 1829 | /// unspecified bits out to the given type. |
| 1830 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1831 | const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1832 | Type *Ty) { |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1833 | assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && |
| 1834 | "This is not an extending conversion!"); |
| 1835 | assert(isSCEVable(Ty) && |
| 1836 | "This is not a conversion to a SCEVable type!"); |
| 1837 | Ty = getEffectiveSCEVType(Ty); |
| 1838 | |
| 1839 | // Sign-extend negative constants. |
| 1840 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1841 | if (SC->getAPInt().isNegative()) |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1842 | return getSignExtendExpr(Op, Ty); |
| 1843 | |
| 1844 | // Peel off a truncate cast. |
| 1845 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1846 | const SCEV *NewOp = T->getOperand(); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1847 | if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) |
| 1848 | return getAnyExtendExpr(NewOp, Ty); |
| 1849 | return getTruncateOrNoop(NewOp, Ty); |
| 1850 | } |
| 1851 | |
| 1852 | // Next try a zext cast. If the cast is folded, use it. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1853 | const SCEV *ZExt = getZeroExtendExpr(Op, Ty); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1854 | if (!isa<SCEVZeroExtendExpr>(ZExt)) |
| 1855 | return ZExt; |
| 1856 | |
| 1857 | // Next try a sext cast. If the cast is folded, use it. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1858 | const SCEV *SExt = getSignExtendExpr(Op, Ty); |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1859 | if (!isa<SCEVSignExtendExpr>(SExt)) |
| 1860 | return SExt; |
| 1861 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1862 | // Force the cast to be folded into the operands of an addrec. |
| 1863 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { |
| 1864 | SmallVector<const SCEV *, 4> Ops; |
Tobias Grosser | 924221c | 2014-05-07 06:07:47 +0000 | [diff] [blame] | 1865 | for (const SCEV *Op : AR->operands()) |
| 1866 | Ops.push_back(getAnyExtendExpr(Op, Ty)); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 1867 | return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 1868 | } |
| 1869 | |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 1870 | // If the expression is obviously signed, use the sext cast value. |
| 1871 | if (isa<SCEVSMaxExpr>(Op)) |
| 1872 | return SExt; |
| 1873 | |
| 1874 | // Absent any other information, use the zext cast value. |
| 1875 | return ZExt; |
| 1876 | } |
| 1877 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 1878 | /// Process the given Ops list, which is a list of operands to be added under |
| 1879 | /// the given scale, update the given map. This is a helper function for |
| 1880 | /// getAddRecExpr. As an example of what it does, given a sequence of operands |
| 1881 | /// that would form an add expression like this: |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1882 | /// |
Tobias Grosser | ba49e42 | 2014-03-05 10:37:17 +0000 | [diff] [blame] | 1883 | /// 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] | 1884 | /// |
| 1885 | /// where A and B are constants, update the map with these values: |
| 1886 | /// |
| 1887 | /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) |
| 1888 | /// |
| 1889 | /// and add 13 + A*B*29 to AccumulatedConstant. |
| 1890 | /// This will allow getAddRecExpr to produce this: |
| 1891 | /// |
| 1892 | /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) |
| 1893 | /// |
| 1894 | /// This form often exposes folding opportunities that are hidden in |
| 1895 | /// the original operand list. |
| 1896 | /// |
Sylvestre Ledru | 91ce36c | 2012-09-27 10:14:43 +0000 | [diff] [blame] | 1897 | /// Return true iff it appears that any interesting folding opportunities |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1898 | /// may be exposed. This helps getAddRecExpr short-circuit extra work in |
| 1899 | /// the common case where no interesting opportunities are present, and |
| 1900 | /// is also used as a check to avoid infinite recursion. |
| 1901 | /// |
| 1902 | static bool |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1903 | CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, |
Craig Topper | 2cd5ff8 | 2013-07-11 16:22:38 +0000 | [diff] [blame] | 1904 | SmallVectorImpl<const SCEV *> &NewOps, |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1905 | APInt &AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1906 | const SCEV *const *Ops, size_t NumOperands, |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1907 | const APInt &Scale, |
| 1908 | ScalarEvolution &SE) { |
| 1909 | bool Interesting = false; |
| 1910 | |
Dan Gohman | 4507304 | 2010-06-18 19:12:32 +0000 | [diff] [blame] | 1911 | // Iterate over the add operands. They are sorted, with constants first. |
| 1912 | unsigned i = 0; |
| 1913 | while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { |
| 1914 | ++i; |
| 1915 | // Pull a buried constant out to the outside. |
| 1916 | if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) |
| 1917 | Interesting = true; |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1918 | AccumulatedConstant += Scale * C->getAPInt(); |
Dan Gohman | 4507304 | 2010-06-18 19:12:32 +0000 | [diff] [blame] | 1919 | } |
| 1920 | |
| 1921 | // Next comes everything else. We're especially interested in multiplies |
| 1922 | // here, but they're in the middle, so just visit the rest with one loop. |
| 1923 | for (; i != NumOperands; ++i) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1924 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); |
| 1925 | if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { |
| 1926 | APInt NewScale = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 1927 | Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1928 | if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { |
| 1929 | // A multiplication of a constant with another add; recurse. |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1930 | const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1931 | Interesting |= |
| 1932 | CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 1933 | Add->op_begin(), Add->getNumOperands(), |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1934 | NewScale, SE); |
| 1935 | } else { |
| 1936 | // A multiplication of a constant with some other value. Update |
| 1937 | // the map. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1938 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); |
| 1939 | const SCEV *Key = SE.getMulExpr(MulOps); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 1940 | auto Pair = M.insert({Key, NewScale}); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1941 | if (Pair.second) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1942 | NewOps.push_back(Pair.first->first); |
| 1943 | } else { |
| 1944 | Pair.first->second += NewScale; |
| 1945 | // The map already had an entry for this value, which may indicate |
| 1946 | // a folding opportunity. |
| 1947 | Interesting = true; |
| 1948 | } |
| 1949 | } |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1950 | } else { |
| 1951 | // An ordinary operand. Update the map. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 1952 | std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 1953 | M.insert({Ops[i], Scale}); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1954 | if (Pair.second) { |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 1955 | NewOps.push_back(Pair.first->first); |
| 1956 | } else { |
| 1957 | Pair.first->second += Scale; |
| 1958 | // The map already had an entry for this value, which may indicate |
| 1959 | // a folding opportunity. |
| 1960 | Interesting = true; |
| 1961 | } |
| 1962 | } |
| 1963 | } |
| 1964 | |
| 1965 | return Interesting; |
| 1966 | } |
| 1967 | |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1968 | // We're trying to construct a SCEV of type `Type' with `Ops' as operands and |
| 1969 | // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of |
| 1970 | // can't-overflow flags for the operation if possible. |
| 1971 | static SCEV::NoWrapFlags |
| 1972 | StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, |
| 1973 | const SmallVectorImpl<const SCEV *> &Ops, |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1974 | SCEV::NoWrapFlags Flags) { |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1975 | using namespace std::placeholders; |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1976 | typedef OverflowingBinaryOperator OBO; |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1977 | |
| 1978 | bool CanAnalyze = |
| 1979 | Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; |
| 1980 | (void)CanAnalyze; |
| 1981 | assert(CanAnalyze && "don't call from other places!"); |
| 1982 | |
| 1983 | int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; |
| 1984 | SCEV::NoWrapFlags SignOrUnsignWrap = |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1985 | ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1986 | |
| 1987 | // 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] | 1988 | auto IsKnownNonNegative = [&](const SCEV *S) { |
| 1989 | return SE->isKnownNonNegative(S); |
| 1990 | }; |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1991 | |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 1992 | if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1993 | Flags = |
| 1994 | ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 1995 | |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 1996 | SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); |
| 1997 | |
| 1998 | if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr && |
| 1999 | Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) { |
| 2000 | |
| 2001 | // (A + C) --> (A + C)<nsw> if the addition does not sign overflow |
| 2002 | // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow |
| 2003 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2004 | const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2005 | if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { |
Sanjoy Das | 5079f62 | 2016-02-22 16:13:02 +0000 | [diff] [blame] | 2006 | auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 2007 | Instruction::Add, C, OBO::NoSignedWrap); |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2008 | if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) |
| 2009 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); |
| 2010 | } |
| 2011 | if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { |
Sanjoy Das | 5079f62 | 2016-02-22 16:13:02 +0000 | [diff] [blame] | 2012 | auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 2013 | Instruction::Add, C, OBO::NoUnsignedWrap); |
Sanjoy Das | 8f27415 | 2015-10-22 19:57:19 +0000 | [diff] [blame] | 2014 | if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) |
| 2015 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); |
| 2016 | } |
| 2017 | } |
| 2018 | |
| 2019 | return Flags; |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2020 | } |
| 2021 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 2022 | /// Get a canonical add expression, or something simpler if possible. |
Dan Gohman | 816fe0a | 2009-10-09 00:10:36 +0000 | [diff] [blame] | 2023 | const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2024 | SCEV::NoWrapFlags Flags) { |
| 2025 | assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && |
| 2026 | "only nuw or nsw allowed"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2027 | assert(!Ops.empty() && "Cannot get empty add!"); |
Chris Lattner | 74498e1 | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 2028 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2029 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2030 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2031 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | 9136d9f | 2010-06-18 19:09:27 +0000 | [diff] [blame] | 2032 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2033 | "SCEVAddExpr operand types don't match!"); |
| 2034 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2035 | |
| 2036 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2037 | GroupByComplexity(Ops, &LI); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2038 | |
Sanjoy Das | 6489561 | 2015-10-09 02:44:45 +0000 | [diff] [blame] | 2039 | Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); |
| 2040 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2041 | // If there are any constants, fold them together. |
| 2042 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2043 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2044 | ++Idx; |
Chris Lattner | 74498e1 | 2004-04-07 16:16:11 +0000 | [diff] [blame] | 2045 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2046 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2047 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2048 | Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); |
Dan Gohman | 011cf68 | 2009-06-14 22:53:57 +0000 | [diff] [blame] | 2049 | if (Ops.size() == 2) return Ops[0]; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2050 | Ops.erase(Ops.begin()+1); // Erase the folded element |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2051 | LHSC = cast<SCEVConstant>(Ops[0]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2052 | } |
| 2053 | |
| 2054 | // 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] | 2055 | if (LHSC->getValue()->isZero()) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2056 | Ops.erase(Ops.begin()); |
| 2057 | --Idx; |
| 2058 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2059 | |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 2060 | if (Ops.size() == 1) return Ops[0]; |
| 2061 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2062 | |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2063 | // Okay, check to see if the same value occurs in the operand list more than |
| 2064 | // once. If so, merge them together into an multiply expression. Since we |
| 2065 | // sorted the list, these values are required to be adjacent. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2066 | Type *Ty = Ops[0]->getType(); |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2067 | bool FoundMatch = false; |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2068 | for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2069 | if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2070 | // Scan ahead to count how many equal operands there are. |
| 2071 | unsigned Count = 2; |
| 2072 | while (i+Count != e && Ops[i+Count] == Ops[i]) |
| 2073 | ++Count; |
| 2074 | // Merge the values into a multiply. |
| 2075 | const SCEV *Scale = getConstant(Ty, Count); |
| 2076 | const SCEV *Mul = getMulExpr(Scale, Ops[i]); |
| 2077 | if (Ops.size() == Count) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2078 | return Mul; |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2079 | Ops[i] = Mul; |
Dan Gohman | 15871f2 | 2010-08-27 21:39:59 +0000 | [diff] [blame] | 2080 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); |
Dan Gohman | fe22f1d | 2010-08-28 00:39:27 +0000 | [diff] [blame] | 2081 | --i; e -= Count - 1; |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2082 | FoundMatch = true; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2083 | } |
Dan Gohman | e67b287 | 2010-08-12 14:46:54 +0000 | [diff] [blame] | 2084 | if (FoundMatch) |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2085 | return getAddExpr(Ops, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2086 | |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2087 | // Check for truncates. If all the operands are truncated from the same |
| 2088 | // type, see if factoring out the truncate would permit the result to be |
| 2089 | // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n) |
| 2090 | // if the contents of the resulting outer trunc fold to something simple. |
| 2091 | for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) { |
| 2092 | const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2093 | Type *DstType = Trunc->getType(); |
| 2094 | Type *SrcType = Trunc->getOperand()->getType(); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2095 | SmallVector<const SCEV *, 8> LargeOps; |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2096 | bool Ok = true; |
| 2097 | // Check all the operands to see if they can be represented in the |
| 2098 | // source type of the truncate. |
| 2099 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) { |
| 2100 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { |
| 2101 | if (T->getOperand()->getType() != SrcType) { |
| 2102 | Ok = false; |
| 2103 | break; |
| 2104 | } |
| 2105 | LargeOps.push_back(T->getOperand()); |
| 2106 | } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { |
Dan Gohman | ff3174e | 2010-04-23 01:51:29 +0000 | [diff] [blame] | 2107 | LargeOps.push_back(getAnyExtendExpr(C, SrcType)); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2108 | } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2109 | SmallVector<const SCEV *, 8> LargeMulOps; |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2110 | for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { |
| 2111 | if (const SCEVTruncateExpr *T = |
| 2112 | dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { |
| 2113 | if (T->getOperand()->getType() != SrcType) { |
| 2114 | Ok = false; |
| 2115 | break; |
| 2116 | } |
| 2117 | LargeMulOps.push_back(T->getOperand()); |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 2118 | } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { |
Dan Gohman | ff3174e | 2010-04-23 01:51:29 +0000 | [diff] [blame] | 2119 | LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2120 | } else { |
| 2121 | Ok = false; |
| 2122 | break; |
| 2123 | } |
| 2124 | } |
| 2125 | if (Ok) |
| 2126 | LargeOps.push_back(getMulExpr(LargeMulOps)); |
| 2127 | } else { |
| 2128 | Ok = false; |
| 2129 | break; |
| 2130 | } |
| 2131 | } |
| 2132 | if (Ok) { |
| 2133 | // Evaluate the expression in the larger type. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2134 | const SCEV *Fold = getAddExpr(LargeOps, Flags); |
Dan Gohman | 2e55cc5 | 2009-05-08 21:03:19 +0000 | [diff] [blame] | 2135 | // If it folds to something simple, use it. Otherwise, don't. |
| 2136 | if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) |
| 2137 | return getTruncateExpr(Fold, DstType); |
| 2138 | } |
| 2139 | } |
| 2140 | |
| 2141 | // Skip past any other cast SCEVs. |
Dan Gohman | eed125f | 2007-06-18 19:30:09 +0000 | [diff] [blame] | 2142 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) |
| 2143 | ++Idx; |
| 2144 | |
| 2145 | // If there are add operands they would be next. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2146 | if (Idx < Ops.size()) { |
| 2147 | bool DeletedAdd = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2148 | while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2149 | // If we have an add, expand the add operands onto the end of the operands |
| 2150 | // list. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2151 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2152 | Ops.append(Add->op_begin(), Add->op_end()); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2153 | DeletedAdd = true; |
| 2154 | } |
| 2155 | |
| 2156 | // If we deleted at least one add, we added operands to the end of the list, |
| 2157 | // and they are not necessarily sorted. Recurse to resort and resimplify |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 2158 | // any operands we just acquired. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2159 | if (DeletedAdd) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2160 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2161 | } |
| 2162 | |
| 2163 | // Skip over the add expression until we get to a multiply. |
| 2164 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) |
| 2165 | ++Idx; |
| 2166 | |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2167 | // Check to see if there are any folding opportunities present with |
| 2168 | // operands multiplied by constant values. |
| 2169 | if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { |
| 2170 | uint64_t BitWidth = getTypeSizeInBits(Ty); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2171 | DenseMap<const SCEV *, APInt> M; |
| 2172 | SmallVector<const SCEV *, 8> NewOps; |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2173 | APInt AccumulatedConstant(BitWidth, 0); |
| 2174 | if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2175 | Ops.data(), Ops.size(), |
| 2176 | APInt(BitWidth, 1), *this)) { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 2177 | struct APIntCompare { |
| 2178 | bool operator()(const APInt &LHS, const APInt &RHS) const { |
| 2179 | return LHS.ult(RHS); |
| 2180 | } |
| 2181 | }; |
| 2182 | |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2183 | // Some interesting folding opportunity is present, so its worthwhile to |
| 2184 | // re-generate the operands list. Group the operands by constant scale, |
| 2185 | // to avoid multiplying by the same constant scale multiple times. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2186 | std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; |
Sanjoy Das | f25d25a | 2015-10-31 23:21:32 +0000 | [diff] [blame] | 2187 | for (const SCEV *NewOp : NewOps) |
| 2188 | MulOpLists[M.find(NewOp)->second].push_back(NewOp); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2189 | // Re-generate the operands list. |
| 2190 | Ops.clear(); |
| 2191 | if (AccumulatedConstant != 0) |
| 2192 | Ops.push_back(getConstant(AccumulatedConstant)); |
Sanjoy Das | f25d25a | 2015-10-31 23:21:32 +0000 | [diff] [blame] | 2193 | for (auto &MulOp : MulOpLists) |
| 2194 | if (MulOp.first != 0) |
| 2195 | Ops.push_back(getMulExpr(getConstant(MulOp.first), |
| 2196 | getAddExpr(MulOp.second))); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2197 | if (Ops.empty()) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2198 | return getZero(Ty); |
Dan Gohman | 038d02e | 2009-06-14 22:58:51 +0000 | [diff] [blame] | 2199 | if (Ops.size() == 1) |
| 2200 | return Ops[0]; |
| 2201 | return getAddExpr(Ops); |
| 2202 | } |
| 2203 | } |
| 2204 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2205 | // If we are adding something to a multiply expression, make sure the |
| 2206 | // something is not already an operand of the multiply. If so, merge it into |
| 2207 | // the multiply. |
| 2208 | for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2209 | const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2210 | for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2211 | const SCEV *MulOpSCEV = Mul->getOperand(MulOp); |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2212 | if (isa<SCEVConstant>(MulOpSCEV)) |
| 2213 | continue; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2214 | for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2215 | if (MulOpSCEV == Ops[AddOp]) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2216 | // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2217 | const SCEV *InnerMul = Mul->getOperand(MulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2218 | if (Mul->getNumOperands() != 2) { |
| 2219 | // If the multiply has more than two operands, we must get the |
| 2220 | // Y*Z term. |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2221 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), |
| 2222 | Mul->op_begin()+MulOp); |
| 2223 | MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2224 | InnerMul = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2225 | } |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2226 | const SCEV *One = getOne(Ty); |
Dan Gohman | cf32f2b | 2010-08-13 20:17:14 +0000 | [diff] [blame] | 2227 | const SCEV *AddOne = getAddExpr(One, InnerMul); |
Dan Gohman | 157847f | 2010-08-12 14:52:55 +0000 | [diff] [blame] | 2228 | const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2229 | if (Ops.size() == 2) return OuterMul; |
| 2230 | if (AddOp < Idx) { |
| 2231 | Ops.erase(Ops.begin()+AddOp); |
| 2232 | Ops.erase(Ops.begin()+Idx-1); |
| 2233 | } else { |
| 2234 | Ops.erase(Ops.begin()+Idx); |
| 2235 | Ops.erase(Ops.begin()+AddOp-1); |
| 2236 | } |
| 2237 | Ops.push_back(OuterMul); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2238 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2239 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 2240 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2241 | // Check this multiply against other multiplies being added together. |
| 2242 | for (unsigned OtherMulIdx = Idx+1; |
| 2243 | OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); |
| 2244 | ++OtherMulIdx) { |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2245 | const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2246 | // If MulOp occurs in OtherMul, we can fold the two multiplies |
| 2247 | // together. |
| 2248 | for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); |
| 2249 | OMulOp != e; ++OMulOp) |
| 2250 | if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { |
| 2251 | // 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] | 2252 | const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2253 | if (Mul->getNumOperands() != 2) { |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2254 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2255 | Mul->op_begin()+MulOp); |
| 2256 | MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2257 | InnerMul1 = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2258 | } |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2259 | const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2260 | if (OtherMul->getNumOperands() != 2) { |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2261 | SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), |
Dan Gohman | 797a1db | 2010-08-16 16:57:24 +0000 | [diff] [blame] | 2262 | OtherMul->op_begin()+OMulOp); |
| 2263 | MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2264 | InnerMul2 = getMulExpr(MulOps); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2265 | } |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2266 | const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2); |
| 2267 | const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2268 | if (Ops.size() == 2) return OuterMul; |
Dan Gohman | aabfc52 | 2010-08-31 22:50:31 +0000 | [diff] [blame] | 2269 | Ops.erase(Ops.begin()+Idx); |
| 2270 | Ops.erase(Ops.begin()+OtherMulIdx-1); |
| 2271 | Ops.push_back(OuterMul); |
| 2272 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2273 | } |
| 2274 | } |
| 2275 | } |
| 2276 | } |
| 2277 | |
| 2278 | // If there are any add recurrences in the operands list, see if any other |
| 2279 | // added values are loop invariant. If so, we can fold them into the |
| 2280 | // recurrence. |
| 2281 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) |
| 2282 | ++Idx; |
| 2283 | |
| 2284 | // Scan over all recurrences, trying to fold loop invariants into them. |
| 2285 | for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { |
| 2286 | // Scan all of the other operands to this add and add them to the vector if |
| 2287 | // they are loop invariant w.r.t. the recurrence. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2288 | SmallVector<const SCEV *, 8> LIOps; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2289 | const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 2290 | const Loop *AddRecLoop = AddRec->getLoop(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2291 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2292 | if (isLoopInvariant(Ops[i], AddRecLoop)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2293 | LIOps.push_back(Ops[i]); |
| 2294 | Ops.erase(Ops.begin()+i); |
| 2295 | --i; --e; |
| 2296 | } |
| 2297 | |
| 2298 | // If we found some loop invariants, fold them into the recurrence. |
| 2299 | if (!LIOps.empty()) { |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 2300 | // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2301 | LIOps.push_back(AddRec->getStart()); |
| 2302 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2303 | SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), |
Dan Gohman | 7a2dab8 | 2009-12-18 03:57:04 +0000 | [diff] [blame] | 2304 | AddRec->op_end()); |
Oleg Ranevskyy | eb4ecca | 2016-05-25 13:01:33 +0000 | [diff] [blame] | 2305 | // This follows from the fact that the no-wrap flags on the outer add |
| 2306 | // expression are applicable on the 0th iteration, when the add recurrence |
| 2307 | // will be equal to its start value. |
| 2308 | AddRecOps[0] = getAddExpr(LIOps, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2309 | |
Dan Gohman | 1620613 | 2010-06-30 07:16:37 +0000 | [diff] [blame] | 2310 | // 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] | 2311 | // outer add and the inner addrec are guaranteed to have no overflow. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2312 | // Always propagate NW. |
| 2313 | Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2314 | const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); |
Dan Gohman | 51f1305 | 2009-12-18 18:45:31 +0000 | [diff] [blame] | 2315 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2316 | // If all of the other operands were loop invariant, we are done. |
| 2317 | if (Ops.size() == 1) return NewRec; |
| 2318 | |
Nick Lewycky | db66b82 | 2011-09-06 05:08:09 +0000 | [diff] [blame] | 2319 | // Otherwise, add the folded AddRec by the non-invariant parts. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2320 | for (unsigned i = 0;; ++i) |
| 2321 | if (Ops[i] == AddRec) { |
| 2322 | Ops[i] = NewRec; |
| 2323 | break; |
| 2324 | } |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2325 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2326 | } |
| 2327 | |
| 2328 | // Okay, if there weren't any loop invariants to be folded, check to see if |
| 2329 | // there are multiple AddRec's with the same loop induction variable being |
| 2330 | // added together. If so, we can fold them. |
| 2331 | for (unsigned OtherIdx = Idx+1; |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2332 | OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2333 | ++OtherIdx) |
| 2334 | if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { |
| 2335 | // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> |
| 2336 | SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), |
| 2337 | AddRec->op_end()); |
| 2338 | for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2339 | ++OtherIdx) |
Sanjoy Das | f25d25a | 2015-10-31 23:21:32 +0000 | [diff] [blame] | 2340 | if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx])) |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2341 | if (OtherAddRec->getLoop() == AddRecLoop) { |
| 2342 | for (unsigned i = 0, e = OtherAddRec->getNumOperands(); |
| 2343 | i != e; ++i) { |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2344 | if (i >= AddRecOps.size()) { |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2345 | AddRecOps.append(OtherAddRec->op_begin()+i, |
| 2346 | OtherAddRec->op_end()); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2347 | break; |
| 2348 | } |
Dan Gohman | 028c181 | 2010-08-29 14:53:34 +0000 | [diff] [blame] | 2349 | AddRecOps[i] = getAddExpr(AddRecOps[i], |
| 2350 | OtherAddRec->getOperand(i)); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2351 | } |
| 2352 | Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2353 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2354 | // Step size has changed, so we cannot guarantee no self-wraparound. |
| 2355 | Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); |
Dan Gohman | c866bf4 | 2010-08-27 20:45:56 +0000 | [diff] [blame] | 2356 | return getAddExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2357 | } |
| 2358 | |
| 2359 | // Otherwise couldn't fold anything into this recurrence. Move onto the |
| 2360 | // next one. |
| 2361 | } |
| 2362 | |
| 2363 | // Okay, it looks like we really DO need an add expr. Check to see if we |
| 2364 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2365 | FoldingSetNodeID ID; |
| 2366 | ID.AddInteger(scAddExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2367 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 2368 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2369 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2370 | SCEVAddExpr *S = |
| 2371 | static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2372 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2373 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 2374 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2375 | S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator), |
| 2376 | O, Ops.size()); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2377 | UniqueSCEVs.InsertNode(S, IP); |
| 2378 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2379 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2380 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2381 | } |
| 2382 | |
Nick Lewycky | 287682e | 2011-10-04 06:51:26 +0000 | [diff] [blame] | 2383 | static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { |
| 2384 | uint64_t k = i*j; |
| 2385 | if (j > 1 && k / j != i) Overflow = true; |
| 2386 | return k; |
| 2387 | } |
| 2388 | |
| 2389 | /// Compute the result of "n choose k", the binomial coefficient. If an |
| 2390 | /// intermediate computation overflows, Overflow will be set and the return will |
Benjamin Kramer | bde9176 | 2012-06-02 10:20:22 +0000 | [diff] [blame] | 2391 | /// be garbage. Overflow is not cleared on absence of overflow. |
Nick Lewycky | 287682e | 2011-10-04 06:51:26 +0000 | [diff] [blame] | 2392 | static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { |
| 2393 | // We use the multiplicative formula: |
| 2394 | // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . |
| 2395 | // At each iteration, we take the n-th term of the numeral and divide by the |
| 2396 | // (k-n)th term of the denominator. This division will always produce an |
| 2397 | // integral result, and helps reduce the chance of overflow in the |
| 2398 | // intermediate computations. However, we can still overflow even when the |
| 2399 | // final result would fit. |
| 2400 | |
| 2401 | if (n == 0 || n == k) return 1; |
| 2402 | if (k > n) return 0; |
| 2403 | |
| 2404 | if (k > n/2) |
| 2405 | k = n-k; |
| 2406 | |
| 2407 | uint64_t r = 1; |
| 2408 | for (uint64_t i = 1; i <= k; ++i) { |
| 2409 | r = umul_ov(r, n-(i-1), Overflow); |
| 2410 | r /= i; |
| 2411 | } |
| 2412 | return r; |
| 2413 | } |
| 2414 | |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2415 | /// Determine if any of the operands in this SCEV are a constant or if |
| 2416 | /// any of the add or multiply expressions in this SCEV contain a constant. |
| 2417 | static bool containsConstantSomewhere(const SCEV *StartExpr) { |
| 2418 | SmallVector<const SCEV *, 4> Ops; |
| 2419 | Ops.push_back(StartExpr); |
| 2420 | while (!Ops.empty()) { |
| 2421 | const SCEV *CurrentExpr = Ops.pop_back_val(); |
| 2422 | if (isa<SCEVConstant>(*CurrentExpr)) |
| 2423 | return true; |
| 2424 | |
| 2425 | if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) { |
| 2426 | const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr); |
Benjamin Kramer | 6cd780f | 2015-02-17 15:29:18 +0000 | [diff] [blame] | 2427 | Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end()); |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2428 | } |
| 2429 | } |
| 2430 | return false; |
| 2431 | } |
| 2432 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 2433 | /// Get a canonical multiply expression, or something simpler if possible. |
Dan Gohman | 816fe0a | 2009-10-09 00:10:36 +0000 | [diff] [blame] | 2434 | const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2435 | SCEV::NoWrapFlags Flags) { |
| 2436 | assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && |
| 2437 | "only nuw or nsw allowed"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2438 | assert(!Ops.empty() && "Cannot get empty mul!"); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2439 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2440 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2441 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2442 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 2443 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2444 | "SCEVMulExpr operand types don't match!"); |
| 2445 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2446 | |
| 2447 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2448 | GroupByComplexity(Ops, &LI); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2449 | |
Sanjoy Das | 6489561 | 2015-10-09 02:44:45 +0000 | [diff] [blame] | 2450 | Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); |
| 2451 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2452 | // If there are any constants, fold them together. |
| 2453 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2454 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2455 | |
| 2456 | // C1*(C2+V) -> C1*C2 + C1*V |
| 2457 | if (Ops.size() == 2) |
Nick Lewycky | 05044c2 | 2014-12-06 00:45:50 +0000 | [diff] [blame] | 2458 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) |
| 2459 | // If any of Add's ops are Adds or Muls with a constant, |
| 2460 | // apply this transformation as well. |
| 2461 | if (Add->getNumOperands() == 2) |
| 2462 | if (containsConstantSomewhere(Add)) |
| 2463 | return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)), |
| 2464 | getMulExpr(LHSC, Add->getOperand(1))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2465 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2466 | ++Idx; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2467 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2468 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2469 | ConstantInt *Fold = |
| 2470 | ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 2471 | Ops[0] = getConstant(Fold); |
| 2472 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 2473 | if (Ops.size() == 1) return Ops[0]; |
| 2474 | LHSC = cast<SCEVConstant>(Ops[0]); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2475 | } |
| 2476 | |
| 2477 | // If we are left with a constant one being multiplied, strip it off. |
| 2478 | if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) { |
| 2479 | Ops.erase(Ops.begin()); |
| 2480 | --Idx; |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 2481 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2482 | // If we have a multiply of zero, it will always be zero. |
| 2483 | return Ops[0]; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2484 | } else if (Ops[0]->isAllOnesValue()) { |
| 2485 | // If we have a mul by -1 of an add, try distributing the -1 among the |
| 2486 | // add operands. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2487 | if (Ops.size() == 2) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2488 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { |
| 2489 | SmallVector<const SCEV *, 4> NewOps; |
| 2490 | bool AnyFolded = false; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 2491 | for (const SCEV *AddOp : Add->operands()) { |
| 2492 | const SCEV *Mul = getMulExpr(Ops[0], AddOp); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2493 | if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; |
| 2494 | NewOps.push_back(Mul); |
| 2495 | } |
| 2496 | if (AnyFolded) |
| 2497 | return getAddExpr(NewOps); |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 2498 | } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { |
Andrew Trick | e92dcce | 2011-03-14 17:38:54 +0000 | [diff] [blame] | 2499 | // Negation preserves a recurrence's no self-wrap property. |
| 2500 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 2501 | for (const SCEV *AddRecOp : AddRec->operands()) |
| 2502 | Operands.push_back(getMulExpr(Ops[0], AddRecOp)); |
| 2503 | |
Andrew Trick | e92dcce | 2011-03-14 17:38:54 +0000 | [diff] [blame] | 2504 | return getAddRecExpr(Operands, AddRec->getLoop(), |
| 2505 | AddRec->getNoWrapFlags(SCEV::FlagNW)); |
| 2506 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2507 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2508 | } |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 2509 | |
| 2510 | if (Ops.size() == 1) |
| 2511 | return Ops[0]; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2512 | } |
| 2513 | |
| 2514 | // Skip over the add expression until we get to a multiply. |
| 2515 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) |
| 2516 | ++Idx; |
| 2517 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2518 | // If there are mul operands inline them all into this expression. |
| 2519 | if (Idx < Ops.size()) { |
| 2520 | bool DeletedMul = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2521 | while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2522 | // If we have an mul, expand the mul operands onto the end of the operands |
| 2523 | // list. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2524 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2525 | Ops.append(Mul->op_begin(), Mul->op_end()); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2526 | DeletedMul = true; |
| 2527 | } |
| 2528 | |
| 2529 | // If we deleted at least one mul, we added operands to the end of the list, |
| 2530 | // and they are not necessarily sorted. Recurse to resort and resimplify |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 2531 | // any operands we just acquired. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2532 | if (DeletedMul) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2533 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2534 | } |
| 2535 | |
| 2536 | // If there are any add recurrences in the operands list, see if any other |
| 2537 | // added values are loop invariant. If so, we can fold them into the |
| 2538 | // recurrence. |
| 2539 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) |
| 2540 | ++Idx; |
| 2541 | |
| 2542 | // Scan over all recurrences, trying to fold loop invariants into them. |
| 2543 | for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { |
| 2544 | // Scan all of the other operands to this mul and add them to the vector if |
| 2545 | // they are loop invariant w.r.t. the recurrence. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2546 | SmallVector<const SCEV *, 8> LIOps; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 2547 | const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); |
Dan Gohman | 0f2de01 | 2010-08-29 14:55:19 +0000 | [diff] [blame] | 2548 | const Loop *AddRecLoop = AddRec->getLoop(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2549 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2550 | if (isLoopInvariant(Ops[i], AddRecLoop)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2551 | LIOps.push_back(Ops[i]); |
| 2552 | Ops.erase(Ops.begin()+i); |
| 2553 | --i; --e; |
| 2554 | } |
| 2555 | |
| 2556 | // If we found some loop invariants, fold them into the recurrence. |
| 2557 | if (!LIOps.empty()) { |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 2558 | // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2559 | SmallVector<const SCEV *, 4> NewOps; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2560 | NewOps.reserve(AddRec->getNumOperands()); |
Dan Gohman | 8f5954f | 2010-06-17 23:34:09 +0000 | [diff] [blame] | 2561 | const SCEV *Scale = getMulExpr(LIOps); |
| 2562 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) |
| 2563 | NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i))); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2564 | |
Dan Gohman | 1620613 | 2010-06-30 07:16:37 +0000 | [diff] [blame] | 2565 | // Build the new addrec. Propagate the NUW and NSW flags if both the |
| 2566 | // outer mul and the inner addrec are guaranteed to have no overflow. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2567 | // |
| 2568 | // No self-wrap cannot be guaranteed after changing the step size, but |
Chris Lattner | 0ab5e2c | 2011-04-15 05:18:47 +0000 | [diff] [blame] | 2569 | // will be inferred if either NUW or NSW is true. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2570 | Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); |
| 2571 | const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2572 | |
| 2573 | // If all of the other operands were loop invariant, we are done. |
| 2574 | if (Ops.size() == 1) return NewRec; |
| 2575 | |
Nick Lewycky | db66b82 | 2011-09-06 05:08:09 +0000 | [diff] [blame] | 2576 | // Otherwise, multiply the folded AddRec by the non-invariant parts. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2577 | for (unsigned i = 0;; ++i) |
| 2578 | if (Ops[i] == AddRec) { |
| 2579 | Ops[i] = NewRec; |
| 2580 | break; |
| 2581 | } |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 2582 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2583 | } |
| 2584 | |
| 2585 | // Okay, if there weren't any loop invariants to be folded, check to see if |
| 2586 | // there are multiple AddRec's with the same loop induction variable being |
| 2587 | // multiplied together. If so, we can fold them. |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2588 | |
| 2589 | // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> |
| 2590 | // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ |
| 2591 | // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z |
| 2592 | // ]]],+,...up to x=2n}. |
| 2593 | // Note that the arguments to choose() are always integers with values |
| 2594 | // known at compile time, never SCEV objects. |
| 2595 | // |
| 2596 | // The implementation avoids pointless extra computations when the two |
| 2597 | // addrec's are of different length (mathematically, it's equivalent to |
| 2598 | // an infinite stream of zeros on the right). |
| 2599 | bool OpsModified = false; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2600 | for (unsigned OtherIdx = Idx+1; |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2601 | OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); |
Nick Lewycky | e0aa54b | 2011-09-06 21:42:18 +0000 | [diff] [blame] | 2602 | ++OtherIdx) { |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2603 | const SCEVAddRecExpr *OtherAddRec = |
| 2604 | dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); |
| 2605 | if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2606 | continue; |
| 2607 | |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2608 | bool Overflow = false; |
| 2609 | Type *Ty = AddRec->getType(); |
| 2610 | bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; |
| 2611 | SmallVector<const SCEV*, 7> AddRecOps; |
| 2612 | for (int x = 0, xe = AddRec->getNumOperands() + |
| 2613 | OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2614 | const SCEV *Term = getZero(Ty); |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2615 | for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { |
| 2616 | uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); |
| 2617 | for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), |
| 2618 | ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); |
| 2619 | z < ze && !Overflow; ++z) { |
| 2620 | uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); |
| 2621 | uint64_t Coeff; |
| 2622 | if (LargerThan64Bits) |
| 2623 | Coeff = umul_ov(Coeff1, Coeff2, Overflow); |
| 2624 | else |
| 2625 | Coeff = Coeff1*Coeff2; |
| 2626 | const SCEV *CoeffTerm = getConstant(Ty, Coeff); |
| 2627 | const SCEV *Term1 = AddRec->getOperand(y-z); |
| 2628 | const SCEV *Term2 = OtherAddRec->getOperand(z); |
| 2629 | Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2)); |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2630 | } |
Andrew Trick | 946f76b | 2012-05-30 03:35:17 +0000 | [diff] [blame] | 2631 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2632 | AddRecOps.push_back(Term); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2633 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2634 | if (!Overflow) { |
| 2635 | const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(), |
| 2636 | SCEV::FlagAnyWrap); |
| 2637 | if (Ops.size() == 2) return NewAddRec; |
| 2638 | Ops[Idx] = NewAddRec; |
| 2639 | Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; |
| 2640 | OpsModified = true; |
| 2641 | AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); |
| 2642 | if (!AddRec) |
| 2643 | break; |
| 2644 | } |
Nick Lewycky | e0aa54b | 2011-09-06 21:42:18 +0000 | [diff] [blame] | 2645 | } |
Nick Lewycky | 9775640 | 2014-09-01 05:17:15 +0000 | [diff] [blame] | 2646 | if (OpsModified) |
| 2647 | return getMulExpr(Ops); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2648 | |
| 2649 | // Otherwise couldn't fold anything into this recurrence. Move onto the |
| 2650 | // next one. |
| 2651 | } |
| 2652 | |
| 2653 | // Okay, it looks like we really DO need an mul expr. Check to see if we |
| 2654 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2655 | FoldingSetNodeID ID; |
| 2656 | ID.AddInteger(scMulExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2657 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 2658 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2659 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2660 | SCEVMulExpr *S = |
| 2661 | static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2662 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2663 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 2664 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2665 | S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), |
| 2666 | O, Ops.size()); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2667 | UniqueSCEVs.InsertNode(S, IP); |
| 2668 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2669 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2670 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2671 | } |
| 2672 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 2673 | /// Get a canonical unsigned division expression, or something simpler if |
| 2674 | /// possible. |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 2675 | const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, |
| 2676 | const SCEV *RHS) { |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2677 | assert(getEffectiveSCEVType(LHS->getType()) == |
| 2678 | getEffectiveSCEVType(RHS->getType()) && |
| 2679 | "SCEVUDivExpr operand types don't match!"); |
| 2680 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2681 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2682 | if (RHSC->getValue()->equalsInt(1)) |
Dan Gohman | 8a8ad7d | 2009-08-20 16:42:55 +0000 | [diff] [blame] | 2683 | return LHS; // X udiv 1 --> x |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2684 | // If the denominator is zero, the result of the udiv is undefined. Don't |
| 2685 | // try to analyze it, because the resolution chosen here may differ from |
| 2686 | // the resolution chosen in other parts of the compiler. |
| 2687 | if (!RHSC->getValue()->isZero()) { |
| 2688 | // Determine if the division can be folded into the operands of |
| 2689 | // its operands. |
| 2690 | // TODO: Generalize this to non-constants by using known-bits information. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2691 | Type *Ty = LHS->getType(); |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2692 | unsigned LZ = RHSC->getAPInt().countLeadingZeros(); |
Dan Gohman | db764c6 | 2010-08-04 19:52:50 +0000 | [diff] [blame] | 2693 | unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2694 | // For non-power-of-two values, effectively round the value up to the |
| 2695 | // nearest power of two. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2696 | if (!RHSC->getAPInt().isPowerOf2()) |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2697 | ++MaxShiftAmt; |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2698 | IntegerType *ExtTy = |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2699 | IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2700 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) |
| 2701 | if (const SCEVConstant *Step = |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2702 | dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { |
| 2703 | // {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] | 2704 | const APInt &StepInt = Step->getAPInt(); |
| 2705 | const APInt &DivInt = RHSC->getAPInt(); |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2706 | if (!StepInt.urem(DivInt) && |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2707 | getZeroExtendExpr(AR, ExtTy) == |
| 2708 | getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), |
| 2709 | getZeroExtendExpr(Step, ExtTy), |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2710 | AR->getLoop(), SCEV::FlagAnyWrap)) { |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2711 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 2712 | for (const SCEV *Op : AR->operands()) |
| 2713 | Operands.push_back(getUDivExpr(Op, RHS)); |
| 2714 | return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2715 | } |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2716 | /// Get a canonical UDivExpr for a recurrence. |
| 2717 | /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. |
| 2718 | // We can currently only fold X%N if X is constant. |
| 2719 | const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); |
| 2720 | if (StartC && !DivInt.urem(StepInt) && |
| 2721 | getZeroExtendExpr(AR, ExtTy) == |
| 2722 | getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), |
| 2723 | getZeroExtendExpr(Step, ExtTy), |
| 2724 | AR->getLoop(), SCEV::FlagAnyWrap)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2725 | const APInt &StartInt = StartC->getAPInt(); |
Andrew Trick | 6d45a01 | 2011-08-06 07:00:37 +0000 | [diff] [blame] | 2726 | const APInt &StartRem = StartInt.urem(StepInt); |
| 2727 | if (StartRem != 0) |
| 2728 | LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, |
| 2729 | AR->getLoop(), SCEV::FlagNW); |
| 2730 | } |
| 2731 | } |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2732 | // (A*B)/C --> A*(B/C) if safe and B/C can be folded. |
| 2733 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { |
| 2734 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 2735 | for (const SCEV *Op : M->operands()) |
| 2736 | Operands.push_back(getZeroExtendExpr(Op, ExtTy)); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2737 | if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) |
| 2738 | // Find an operand that's safely divisible. |
| 2739 | for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { |
| 2740 | const SCEV *Op = M->getOperand(i); |
| 2741 | const SCEV *Div = getUDivExpr(Op, RHSC); |
| 2742 | if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { |
| 2743 | Operands = SmallVector<const SCEV *, 4>(M->op_begin(), |
| 2744 | M->op_end()); |
| 2745 | Operands[i] = Div; |
| 2746 | return getMulExpr(Operands); |
| 2747 | } |
| 2748 | } |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2749 | } |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2750 | // (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] | 2751 | if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2752 | SmallVector<const SCEV *, 4> Operands; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 2753 | for (const SCEV *Op : A->operands()) |
| 2754 | Operands.push_back(getZeroExtendExpr(Op, ExtTy)); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2755 | if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { |
| 2756 | Operands.clear(); |
| 2757 | for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { |
| 2758 | const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); |
| 2759 | if (isa<SCEVUDivExpr>(Op) || |
| 2760 | getMulExpr(Op, RHS) != A->getOperand(i)) |
| 2761 | break; |
| 2762 | Operands.push_back(Op); |
| 2763 | } |
| 2764 | if (Operands.size() == A->getNumOperands()) |
| 2765 | return getAddExpr(Operands); |
| 2766 | } |
| 2767 | } |
Dan Gohman | c3a3cb4 | 2009-05-08 20:18:49 +0000 | [diff] [blame] | 2768 | |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 2769 | // Fold if both operands are constant. |
| 2770 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { |
| 2771 | Constant *LHSCV = LHSC->getValue(); |
| 2772 | Constant *RHSCV = RHSC->getValue(); |
| 2773 | return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, |
| 2774 | RHSCV))); |
| 2775 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2776 | } |
| 2777 | } |
| 2778 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2779 | FoldingSetNodeID ID; |
| 2780 | ID.AddInteger(scUDivExpr); |
| 2781 | ID.AddPointer(LHS); |
| 2782 | ID.AddPointer(RHS); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2783 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2784 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2785 | SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), |
| 2786 | LHS, RHS); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2787 | UniqueSCEVs.InsertNode(S, IP); |
| 2788 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2789 | } |
| 2790 | |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2791 | static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2792 | APInt A = C1->getAPInt().abs(); |
| 2793 | APInt B = C2->getAPInt().abs(); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2794 | uint32_t ABW = A.getBitWidth(); |
| 2795 | uint32_t BBW = B.getBitWidth(); |
| 2796 | |
| 2797 | if (ABW > BBW) |
| 2798 | B = B.zext(ABW); |
| 2799 | else if (ABW < BBW) |
| 2800 | A = A.zext(BBW); |
| 2801 | |
| 2802 | return APIntOps::GreatestCommonDivisor(A, B); |
| 2803 | } |
| 2804 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 2805 | /// Get a canonical unsigned division expression, or something simpler if |
| 2806 | /// possible. There is no representation for an exact udiv in SCEV IR, but we |
| 2807 | /// can attempt to remove factors from the LHS and RHS. We can't do this when |
| 2808 | /// it's not exact because the udiv may be clearing bits. |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2809 | const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, |
| 2810 | const SCEV *RHS) { |
| 2811 | // TODO: we could try to find factors in all sorts of things, but for now we |
| 2812 | // just deal with u/exact (multiply, constant). See SCEVDivision towards the |
| 2813 | // end of this file for inspiration. |
| 2814 | |
| 2815 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); |
| 2816 | if (!Mul) |
| 2817 | return getUDivExpr(LHS, RHS); |
| 2818 | |
| 2819 | if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { |
| 2820 | // If the mulexpr multiplies by a constant, then that constant must be the |
| 2821 | // first element of the mulexpr. |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 2822 | if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2823 | if (LHSCst == RHSCst) { |
| 2824 | SmallVector<const SCEV *, 2> Operands; |
| 2825 | Operands.append(Mul->op_begin() + 1, Mul->op_end()); |
| 2826 | return getMulExpr(Operands); |
| 2827 | } |
| 2828 | |
| 2829 | // We can't just assume that LHSCst divides RHSCst cleanly, it could be |
| 2830 | // that there's a factor provided by one of the other terms. We need to |
| 2831 | // check. |
| 2832 | APInt Factor = gcd(LHSCst, RHSCst); |
| 2833 | if (!Factor.isIntN(1)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 2834 | LHSCst = |
| 2835 | cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); |
| 2836 | RHSCst = |
| 2837 | cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2838 | SmallVector<const SCEV *, 2> Operands; |
| 2839 | Operands.push_back(LHSCst); |
| 2840 | Operands.append(Mul->op_begin() + 1, Mul->op_end()); |
| 2841 | LHS = getMulExpr(Operands); |
| 2842 | RHS = RHSCst; |
Nick Lewycky | 629199c | 2014-01-27 10:47:44 +0000 | [diff] [blame] | 2843 | Mul = dyn_cast<SCEVMulExpr>(LHS); |
| 2844 | if (!Mul) |
| 2845 | return getUDivExactExpr(LHS, RHS); |
Nick Lewycky | 31eaca5 | 2014-01-27 10:04:03 +0000 | [diff] [blame] | 2846 | } |
| 2847 | } |
| 2848 | } |
| 2849 | |
| 2850 | for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { |
| 2851 | if (Mul->getOperand(i) == RHS) { |
| 2852 | SmallVector<const SCEV *, 2> Operands; |
| 2853 | Operands.append(Mul->op_begin(), Mul->op_begin() + i); |
| 2854 | Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); |
| 2855 | return getMulExpr(Operands); |
| 2856 | } |
| 2857 | } |
| 2858 | |
| 2859 | return getUDivExpr(LHS, RHS); |
| 2860 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2861 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 2862 | /// Get an add recurrence expression for the specified loop. Simplify the |
| 2863 | /// expression as much as possible. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2864 | const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, |
| 2865 | const Loop *L, |
| 2866 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2867 | SmallVector<const SCEV *, 4> Operands; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2868 | Operands.push_back(Start); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2869 | if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2870 | if (StepChrec->getLoop() == L) { |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 2871 | Operands.append(StepChrec->op_begin(), StepChrec->op_end()); |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2872 | return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2873 | } |
| 2874 | |
| 2875 | Operands.push_back(Step); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2876 | return getAddRecExpr(Operands, L, Flags); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2877 | } |
| 2878 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 2879 | /// Get an add recurrence expression for the specified loop. Simplify the |
| 2880 | /// expression as much as possible. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 2881 | const SCEV * |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2882 | ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2883 | const Loop *L, SCEV::NoWrapFlags Flags) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2884 | if (Operands.size() == 1) return Operands[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2885 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2886 | Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2887 | for (unsigned i = 1, e = Operands.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 2888 | assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2889 | "SCEVAddRecExpr operand types don't match!"); |
Dan Gohman | d3a32ae | 2010-11-17 20:48:38 +0000 | [diff] [blame] | 2890 | for (unsigned i = 0, e = Operands.size(); i != e; ++i) |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 2891 | assert(isLoopInvariant(Operands[i], L) && |
Dan Gohman | d3a32ae | 2010-11-17 20:48:38 +0000 | [diff] [blame] | 2892 | "SCEVAddRecExpr operand is not loop-invariant!"); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 2893 | #endif |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2894 | |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 2895 | if (Operands.back()->isZero()) { |
| 2896 | Operands.pop_back(); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2897 | return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 2898 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2899 | |
Dan Gohman | cf9c64e | 2010-02-19 18:49:22 +0000 | [diff] [blame] | 2900 | // It's tempting to want to call getMaxBackedgeTakenCount count here and |
| 2901 | // use that information to infer NUW and NSW flags. However, computing a |
| 2902 | // BE count requires calling getAddRecExpr, so we may not yet have a |
| 2903 | // meaningful BE count at this point (and if we don't, we'd be stuck |
| 2904 | // with a SCEVCouldNotCompute as the cached BE count). |
| 2905 | |
Sanjoy Das | 81401d4 | 2015-01-10 23:41:24 +0000 | [diff] [blame] | 2906 | Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2907 | |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2908 | // Canonicalize nested AddRecs in by nesting them in order of loop depth. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 2909 | if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 2910 | const Loop *NestedLoop = NestedAR->getLoop(); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 2911 | if (L->contains(NestedLoop) |
| 2912 | ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) |
| 2913 | : (!NestedLoop->contains(L) && |
| 2914 | DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 2915 | SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 2916 | NestedAR->op_end()); |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2917 | Operands[0] = NestedAR->getStart(); |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2918 | // AddRecs require their operands be loop-invariant with respect to their |
| 2919 | // loops. Don't perform this transformation if it would break this |
| 2920 | // requirement. |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 2921 | bool AllInvariant = all_of( |
| 2922 | Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); |
Sanjoy Das | f07d2a7 | 2015-10-18 00:29:23 +0000 | [diff] [blame] | 2923 | |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2924 | if (AllInvariant) { |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2925 | // Create a recurrence for the outer loop with the same step size. |
| 2926 | // |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2927 | // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the |
| 2928 | // inner recurrence has the same property. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2929 | SCEV::NoWrapFlags OuterFlags = |
| 2930 | maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2931 | |
| 2932 | NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 2933 | AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { |
| 2934 | return isLoopInvariant(Op, NestedLoop); |
| 2935 | }); |
Sanjoy Das | f07d2a7 | 2015-10-18 00:29:23 +0000 | [diff] [blame] | 2936 | |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2937 | if (AllInvariant) { |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2938 | // Ok, both add recurrences are valid after the transformation. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2939 | // |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2940 | // The inner recurrence keeps its NW flag but only keeps NUW/NSW if |
| 2941 | // the outer recurrence has the same property. |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 2942 | SCEV::NoWrapFlags InnerFlags = |
| 2943 | maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2944 | return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); |
| 2945 | } |
Dan Gohman | cc030b7 | 2009-06-26 22:36:20 +0000 | [diff] [blame] | 2946 | } |
| 2947 | // Reset Operands to its original state. |
| 2948 | Operands[0] = NestedAR; |
Dan Gohman | 223a5d2 | 2008-08-08 18:33:12 +0000 | [diff] [blame] | 2949 | } |
| 2950 | } |
| 2951 | |
Dan Gohman | 8d67d2f | 2010-01-19 22:27:22 +0000 | [diff] [blame] | 2952 | // Okay, it looks like we really DO need an addrec expr. Check to see if we |
| 2953 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2954 | FoldingSetNodeID ID; |
| 2955 | ID.AddInteger(scAddRecExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2956 | for (unsigned i = 0, e = Operands.size(); i != e; ++i) |
| 2957 | ID.AddPointer(Operands[i]); |
| 2958 | ID.AddPointer(L); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 2959 | void *IP = nullptr; |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2960 | SCEVAddRecExpr *S = |
| 2961 | static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); |
| 2962 | if (!S) { |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 2963 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size()); |
| 2964 | std::uninitialized_copy(Operands.begin(), Operands.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 2965 | S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator), |
| 2966 | O, Operands.size(), L); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 2967 | UniqueSCEVs.InsertNode(S, IP); |
| 2968 | } |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 2969 | S->setNoWrapFlags(Flags); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 2970 | return S; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 2971 | } |
| 2972 | |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 2973 | const SCEV * |
| 2974 | ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr, |
| 2975 | const SmallVectorImpl<const SCEV *> &IndexExprs, |
| 2976 | bool InBounds) { |
| 2977 | // getSCEV(Base)->getType() has the same address space as Base->getType() |
| 2978 | // because SCEV::getType() preserves the address space. |
| 2979 | Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); |
| 2980 | // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP |
| 2981 | // instruction to its SCEV, because the Instruction may be guarded by control |
| 2982 | // 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] | 2983 | // context. This can be fixed similarly to how these flags are handled for |
| 2984 | // adds. |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 2985 | SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap; |
| 2986 | |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 2987 | const SCEV *TotalOffset = getZero(IntPtrTy); |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 2988 | // The address space is unimportant. The first thing we do on CurTy is getting |
| 2989 | // its element type. |
| 2990 | Type *CurTy = PointerType::getUnqual(PointeeType); |
| 2991 | for (const SCEV *IndexExpr : IndexExprs) { |
| 2992 | // Compute the (potentially symbolic) offset in bytes for this index. |
| 2993 | if (StructType *STy = dyn_cast<StructType>(CurTy)) { |
| 2994 | // For a struct, add the member offset. |
| 2995 | ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); |
| 2996 | unsigned FieldNo = Index->getZExtValue(); |
| 2997 | const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); |
| 2998 | |
| 2999 | // Add the field offset to the running total offset. |
| 3000 | TotalOffset = getAddExpr(TotalOffset, FieldOffset); |
| 3001 | |
| 3002 | // Update CurTy to the type of the field at Index. |
| 3003 | CurTy = STy->getTypeAtIndex(Index); |
| 3004 | } else { |
| 3005 | // Update CurTy to its element type. |
| 3006 | CurTy = cast<SequentialType>(CurTy)->getElementType(); |
| 3007 | // For an array, add the element offset, explicitly scaled. |
| 3008 | const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); |
| 3009 | // Getelementptr indices are signed. |
| 3010 | IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); |
| 3011 | |
| 3012 | // Multiply the index by the element size to compute the element offset. |
| 3013 | const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); |
| 3014 | |
| 3015 | // Add the element offset to the running total offset. |
| 3016 | TotalOffset = getAddExpr(TotalOffset, LocalOffset); |
| 3017 | } |
| 3018 | } |
| 3019 | |
| 3020 | // Add the total offset from all the GEP indices to the base. |
| 3021 | return getAddExpr(BaseExpr, TotalOffset, Wrap); |
| 3022 | } |
| 3023 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3024 | const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, |
| 3025 | const SCEV *RHS) { |
Benjamin Kramer | 3bc1edf | 2016-07-02 11:41:39 +0000 | [diff] [blame] | 3026 | SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3027 | return getSMaxExpr(Ops); |
| 3028 | } |
| 3029 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3030 | const SCEV * |
| 3031 | ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3032 | assert(!Ops.empty() && "Cannot get empty smax!"); |
| 3033 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3034 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3035 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3036 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 3037 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3038 | "SCEVSMaxExpr operand types don't match!"); |
| 3039 | #endif |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3040 | |
| 3041 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3042 | GroupByComplexity(Ops, &LI); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3043 | |
| 3044 | // If there are any constants, fold them together. |
| 3045 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3046 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3047 | ++Idx; |
| 3048 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3049 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3050 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 3051 | ConstantInt *Fold = ConstantInt::get( |
| 3052 | getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt())); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3053 | Ops[0] = getConstant(Fold); |
| 3054 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 3055 | if (Ops.size() == 1) return Ops[0]; |
| 3056 | LHSC = cast<SCEVConstant>(Ops[0]); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3057 | } |
| 3058 | |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3059 | // If we are left with a constant minimum-int, strip it off. |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3060 | if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) { |
| 3061 | Ops.erase(Ops.begin()); |
| 3062 | --Idx; |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3063 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) { |
| 3064 | // If we have an smax with a constant maximum-int, it will always be |
| 3065 | // maximum-int. |
| 3066 | return Ops[0]; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3067 | } |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3068 | |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 3069 | if (Ops.size() == 1) return Ops[0]; |
| 3070 | } |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3071 | |
| 3072 | // Find the first SMax |
| 3073 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr) |
| 3074 | ++Idx; |
| 3075 | |
| 3076 | // Check to see if one of the operands is an SMax. If so, expand its operands |
| 3077 | // onto our operand list, and recurse to simplify. |
| 3078 | if (Idx < Ops.size()) { |
| 3079 | bool DeletedSMax = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3080 | while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3081 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 3082 | Ops.append(SMax->op_begin(), SMax->op_end()); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3083 | DeletedSMax = true; |
| 3084 | } |
| 3085 | |
| 3086 | if (DeletedSMax) |
| 3087 | return getSMaxExpr(Ops); |
| 3088 | } |
| 3089 | |
| 3090 | // Okay, check to see if the same value occurs in the operand list twice. If |
| 3091 | // so, delete one. Since we sorted the list, these values are required to |
| 3092 | // be adjacent. |
| 3093 | for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) |
Dan Gohman | 7ef0dc2 | 2010-04-13 16:51:03 +0000 | [diff] [blame] | 3094 | // X smax Y smax Y --> X smax Y |
| 3095 | // X smax Y --> X, if X is always greater than Y |
| 3096 | if (Ops[i] == Ops[i+1] || |
| 3097 | isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) { |
| 3098 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); |
| 3099 | --i; --e; |
| 3100 | } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3101 | Ops.erase(Ops.begin()+i, Ops.begin()+i+1); |
| 3102 | --i; --e; |
| 3103 | } |
| 3104 | |
| 3105 | if (Ops.size() == 1) return Ops[0]; |
| 3106 | |
| 3107 | assert(!Ops.empty() && "Reduced smax down to nothing!"); |
| 3108 | |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3109 | // 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] | 3110 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3111 | FoldingSetNodeID ID; |
| 3112 | ID.AddInteger(scSMaxExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3113 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 3114 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3115 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3116 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 3117 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 3118 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 3119 | SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator), |
| 3120 | O, Ops.size()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3121 | UniqueSCEVs.InsertNode(S, IP); |
| 3122 | return S; |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 3123 | } |
| 3124 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3125 | const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, |
| 3126 | const SCEV *RHS) { |
Benjamin Kramer | 3bc1edf | 2016-07-02 11:41:39 +0000 | [diff] [blame] | 3127 | SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3128 | return getUMaxExpr(Ops); |
| 3129 | } |
| 3130 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3131 | const SCEV * |
| 3132 | ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3133 | assert(!Ops.empty() && "Cannot get empty umax!"); |
| 3134 | if (Ops.size() == 1) return Ops[0]; |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3135 | #ifndef NDEBUG |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3136 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3137 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) |
Dan Gohman | b6c773e | 2010-08-16 16:13:54 +0000 | [diff] [blame] | 3138 | assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && |
Dan Gohman | d33f36e | 2009-05-18 15:44:58 +0000 | [diff] [blame] | 3139 | "SCEVUMaxExpr operand types don't match!"); |
| 3140 | #endif |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3141 | |
| 3142 | // Sort by complexity, this groups all similar expression types together. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3143 | GroupByComplexity(Ops, &LI); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3144 | |
| 3145 | // If there are any constants, fold them together. |
| 3146 | unsigned Idx = 0; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3147 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3148 | ++Idx; |
| 3149 | assert(Idx < Ops.size()); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3150 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3151 | // We found two constants, fold them together! |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 3152 | ConstantInt *Fold = ConstantInt::get( |
| 3153 | getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt())); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3154 | Ops[0] = getConstant(Fold); |
| 3155 | Ops.erase(Ops.begin()+1); // Erase the folded element |
| 3156 | if (Ops.size() == 1) return Ops[0]; |
| 3157 | LHSC = cast<SCEVConstant>(Ops[0]); |
| 3158 | } |
| 3159 | |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3160 | // If we are left with a constant minimum-int, strip it off. |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3161 | if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) { |
| 3162 | Ops.erase(Ops.begin()); |
| 3163 | --Idx; |
Dan Gohman | f57bdb7 | 2009-06-24 14:46:22 +0000 | [diff] [blame] | 3164 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) { |
| 3165 | // If we have an umax with a constant maximum-int, it will always be |
| 3166 | // maximum-int. |
| 3167 | return Ops[0]; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3168 | } |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3169 | |
Dan Gohman | fe4b291 | 2010-04-13 16:49:23 +0000 | [diff] [blame] | 3170 | if (Ops.size() == 1) return Ops[0]; |
| 3171 | } |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3172 | |
| 3173 | // Find the first UMax |
| 3174 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr) |
| 3175 | ++Idx; |
| 3176 | |
| 3177 | // Check to see if one of the operands is a UMax. If so, expand its operands |
| 3178 | // onto our operand list, and recurse to simplify. |
| 3179 | if (Idx < Ops.size()) { |
| 3180 | bool DeletedUMax = false; |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3181 | while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3182 | Ops.erase(Ops.begin()+Idx); |
Dan Gohman | dd41bba | 2010-06-21 19:47:52 +0000 | [diff] [blame] | 3183 | Ops.append(UMax->op_begin(), UMax->op_end()); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3184 | DeletedUMax = true; |
| 3185 | } |
| 3186 | |
| 3187 | if (DeletedUMax) |
| 3188 | return getUMaxExpr(Ops); |
| 3189 | } |
| 3190 | |
| 3191 | // Okay, check to see if the same value occurs in the operand list twice. If |
| 3192 | // so, delete one. Since we sorted the list, these values are required to |
| 3193 | // be adjacent. |
| 3194 | for (unsigned i = 0, e = Ops.size()-1; i != e; ++i) |
Dan Gohman | 7ef0dc2 | 2010-04-13 16:51:03 +0000 | [diff] [blame] | 3195 | // X umax Y umax Y --> X umax Y |
| 3196 | // X umax Y --> X, if X is always greater than Y |
| 3197 | if (Ops[i] == Ops[i+1] || |
| 3198 | isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) { |
| 3199 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2); |
| 3200 | --i; --e; |
| 3201 | } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3202 | Ops.erase(Ops.begin()+i, Ops.begin()+i+1); |
| 3203 | --i; --e; |
| 3204 | } |
| 3205 | |
| 3206 | if (Ops.size() == 1) return Ops[0]; |
| 3207 | |
| 3208 | assert(!Ops.empty() && "Reduced umax down to nothing!"); |
| 3209 | |
| 3210 | // Okay, it looks like we really DO need a umax expr. Check to see if we |
| 3211 | // already have one, otherwise create a new one. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3212 | FoldingSetNodeID ID; |
| 3213 | ID.AddInteger(scUMaxExpr); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3214 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) |
| 3215 | ID.AddPointer(Ops[i]); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3216 | void *IP = nullptr; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3217 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; |
Dan Gohman | 0052449 | 2010-03-18 01:17:13 +0000 | [diff] [blame] | 3218 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); |
| 3219 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); |
Dan Gohman | 01c65a2 | 2010-03-18 18:49:47 +0000 | [diff] [blame] | 3220 | SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator), |
| 3221 | O, Ops.size()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3222 | UniqueSCEVs.InsertNode(S, IP); |
| 3223 | return S; |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 3224 | } |
| 3225 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3226 | const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, |
| 3227 | const SCEV *RHS) { |
Dan Gohman | 692b468 | 2009-06-22 03:18:45 +0000 | [diff] [blame] | 3228 | // ~smax(~x, ~y) == smin(x, y). |
| 3229 | return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); |
| 3230 | } |
| 3231 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3232 | const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, |
| 3233 | const SCEV *RHS) { |
Dan Gohman | 692b468 | 2009-06-22 03:18:45 +0000 | [diff] [blame] | 3234 | // ~umax(~x, ~y) == umin(x, y) |
| 3235 | return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS))); |
| 3236 | } |
| 3237 | |
Matt Arsenault | a90a18e | 2013-09-10 19:55:24 +0000 | [diff] [blame] | 3238 | const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3239 | // We can bypass creating a target-independent |
Dan Gohman | 11862a6 | 2010-04-12 23:03:26 +0000 | [diff] [blame] | 3240 | // constant expression and then folding it back into a ConstantInt. |
| 3241 | // This is just a compile-time optimization. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3242 | return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 3243 | } |
| 3244 | |
Matt Arsenault | a90a18e | 2013-09-10 19:55:24 +0000 | [diff] [blame] | 3245 | const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, |
| 3246 | StructType *STy, |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 3247 | unsigned FieldNo) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3248 | // We can bypass creating a target-independent |
Dan Gohman | 11862a6 | 2010-04-12 23:03:26 +0000 | [diff] [blame] | 3249 | // constant expression and then folding it back into a ConstantInt. |
| 3250 | // This is just a compile-time optimization. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 3251 | return getConstant( |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3252 | IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3253 | } |
| 3254 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3255 | const SCEV *ScalarEvolution::getUnknown(Value *V) { |
Dan Gohman | f436bac | 2009-06-24 00:54:57 +0000 | [diff] [blame] | 3256 | // Don't attempt to do anything other than create a SCEVUnknown object |
| 3257 | // here. createSCEV only calls getUnknown after checking for all other |
| 3258 | // interesting possibilities, and any other code that calls getUnknown |
| 3259 | // is doing so in order to hide a value from SCEV canonicalization. |
| 3260 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3261 | FoldingSetNodeID ID; |
| 3262 | ID.AddInteger(scUnknown); |
| 3263 | ID.AddPointer(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3264 | void *IP = nullptr; |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 3265 | if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { |
| 3266 | assert(cast<SCEVUnknown>(S)->getValue() == V && |
| 3267 | "Stale SCEVUnknown in uniquing map!"); |
| 3268 | return S; |
| 3269 | } |
| 3270 | SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, |
| 3271 | FirstUnknown); |
| 3272 | FirstUnknown = cast<SCEVUnknown>(S); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 3273 | UniqueSCEVs.InsertNode(S, IP); |
| 3274 | return S; |
Chris Lattner | b4f681b | 2004-04-15 15:07:24 +0000 | [diff] [blame] | 3275 | } |
| 3276 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3277 | //===----------------------------------------------------------------------===// |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3278 | // Basic SCEV Analysis and PHI Idiom Recognition Code |
| 3279 | // |
| 3280 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3281 | /// Test if values of the given type are analyzable within the SCEV |
| 3282 | /// framework. This primarily includes integer types, and it can optionally |
| 3283 | /// include pointer types if the ScalarEvolution class has access to |
| 3284 | /// target-specific information. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3285 | bool ScalarEvolution::isSCEVable(Type *Ty) const { |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3286 | // Integers and pointers are always SCEVable. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3287 | return Ty->isIntegerTy() || Ty->isPointerTy(); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3288 | } |
| 3289 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3290 | /// Return the size in bits of the specified type, for which isSCEVable must |
| 3291 | /// return true. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3292 | uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3293 | assert(isSCEVable(Ty) && "Type is not SCEVable!"); |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3294 | return getDataLayout().getTypeSizeInBits(Ty); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3295 | } |
| 3296 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3297 | /// Return a type with the same bitwidth as the given type and which represents |
| 3298 | /// how SCEV will treat the given type, for which isSCEVable must return |
| 3299 | /// true. For pointer types, this is the pointer-sized integer type. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3300 | Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3301 | assert(isSCEVable(Ty) && "Type is not SCEVable!"); |
| 3302 | |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 3303 | if (Ty->isIntegerTy()) |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3304 | return Ty; |
| 3305 | |
Dan Gohman | bf2a9ae | 2009-08-18 16:46:41 +0000 | [diff] [blame] | 3306 | // The only other support type is pointer. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3307 | assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 3308 | return getDataLayout().getIntPtrType(Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3309 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3310 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3311 | const SCEV *ScalarEvolution::getCouldNotCompute() { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 3312 | return CouldNotCompute.get(); |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 3313 | } |
| 3314 | |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 3315 | |
| 3316 | bool ScalarEvolution::checkValidity(const SCEV *S) const { |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3317 | // Helper class working with SCEVTraversal to figure out if a SCEV contains |
| 3318 | // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne |
| 3319 | // is set iff if find such SCEVUnknown. |
| 3320 | // |
| 3321 | struct FindInvalidSCEVUnknown { |
| 3322 | bool FindOne; |
| 3323 | FindInvalidSCEVUnknown() { FindOne = false; } |
| 3324 | bool follow(const SCEV *S) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 3325 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3326 | case scConstant: |
| 3327 | return false; |
| 3328 | case scUnknown: |
Shuxin Yang | 23773b3 | 2013-07-12 07:25:38 +0000 | [diff] [blame] | 3329 | if (!cast<SCEVUnknown>(S)->getValue()) |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3330 | FindOne = true; |
| 3331 | return false; |
| 3332 | default: |
| 3333 | return true; |
| 3334 | } |
| 3335 | } |
| 3336 | bool isDone() const { return FindOne; } |
| 3337 | }; |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3338 | |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3339 | FindInvalidSCEVUnknown F; |
| 3340 | SCEVTraversal<FindInvalidSCEVUnknown> ST(F); |
| 3341 | ST.visitAll(S); |
| 3342 | |
| 3343 | return !F.FindOne; |
| 3344 | } |
| 3345 | |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3346 | bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { |
Sanjoy Das | c220ac7 | 2016-09-27 18:01:44 +0000 | [diff] [blame] | 3347 | // Helper class working with SCEVTraversal to figure out if a SCEV contains a |
| 3348 | // sub SCEV of scAddRecExpr type. FindInvalidSCEVUnknown::FoundOne is set iff |
| 3349 | // if such sub scAddRecExpr type SCEV is found. |
| 3350 | struct FindAddRecurrence { |
| 3351 | bool FoundOne; |
| 3352 | FindAddRecurrence() : FoundOne(false) {} |
| 3353 | |
| 3354 | bool follow(const SCEV *S) { |
| 3355 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
| 3356 | case scAddRecExpr: |
| 3357 | FoundOne = true; |
| 3358 | case scConstant: |
| 3359 | case scUnknown: |
| 3360 | case scCouldNotCompute: |
| 3361 | return false; |
| 3362 | default: |
| 3363 | return true; |
| 3364 | } |
| 3365 | } |
| 3366 | bool isDone() const { return FoundOne; } |
| 3367 | }; |
| 3368 | |
Sanjoy Das | a260214 | 2016-09-27 18:01:46 +0000 | [diff] [blame^] | 3369 | HasRecMapType::iterator I = HasRecMap.find(S); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3370 | if (I != HasRecMap.end()) |
| 3371 | return I->second; |
| 3372 | |
| 3373 | FindAddRecurrence F; |
| 3374 | SCEVTraversal<FindAddRecurrence> ST(F); |
| 3375 | ST.visitAll(S); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 3376 | HasRecMap.insert({S, F.FoundOne}); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3377 | return F.FoundOne; |
| 3378 | } |
| 3379 | |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3380 | /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. |
| 3381 | /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an |
| 3382 | /// offset I, then return {S', I}, else return {\p S, nullptr}. |
| 3383 | static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { |
| 3384 | const auto *Add = dyn_cast<SCEVAddExpr>(S); |
| 3385 | if (!Add) |
| 3386 | return {S, nullptr}; |
| 3387 | |
| 3388 | if (Add->getNumOperands() != 2) |
| 3389 | return {S, nullptr}; |
| 3390 | |
| 3391 | auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); |
| 3392 | if (!ConstOp) |
| 3393 | return {S, nullptr}; |
| 3394 | |
| 3395 | return {Add->getOperand(1), ConstOp->getValue()}; |
| 3396 | } |
| 3397 | |
| 3398 | /// Return the ValueOffsetPair set for \p S. \p S can be represented |
| 3399 | /// by the value and offset from any ValueOffsetPair in the set. |
| 3400 | SetVector<ScalarEvolution::ValueOffsetPair> * |
| 3401 | ScalarEvolution::getSCEVValues(const SCEV *S) { |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3402 | ExprValueMapType::iterator SI = ExprValueMap.find_as(S); |
| 3403 | if (SI == ExprValueMap.end()) |
| 3404 | return nullptr; |
| 3405 | #ifndef NDEBUG |
| 3406 | if (VerifySCEVMap) { |
| 3407 | // Check there is no dangling Value in the set returned. |
| 3408 | for (const auto &VE : SI->second) |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3409 | assert(ValueExprMap.count(VE.first)); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3410 | } |
| 3411 | #endif |
| 3412 | return &SI->second; |
| 3413 | } |
| 3414 | |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3415 | /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) |
| 3416 | /// cannot be used separately. eraseValueFromMap should be used to remove |
| 3417 | /// V from ValueExprMap and ExprValueMap at the same time. |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3418 | void ScalarEvolution::eraseValueFromMap(Value *V) { |
| 3419 | ValueExprMapType::iterator I = ValueExprMap.find_as(V); |
| 3420 | if (I != ValueExprMap.end()) { |
| 3421 | const SCEV *S = I->second; |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3422 | // Remove {V, 0} from the set of ExprValueMap[S] |
| 3423 | if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) |
| 3424 | SV->remove({V, nullptr}); |
| 3425 | |
| 3426 | // Remove {V, Offset} from the set of ExprValueMap[Stripped] |
| 3427 | const SCEV *Stripped; |
| 3428 | ConstantInt *Offset; |
| 3429 | std::tie(Stripped, Offset) = splitAddExpr(S); |
| 3430 | if (Offset != nullptr) { |
| 3431 | if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) |
| 3432 | SV->remove({V, Offset}); |
| 3433 | } |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3434 | ValueExprMap.erase(V); |
| 3435 | } |
| 3436 | } |
| 3437 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3438 | /// Return an existing SCEV if it exists, otherwise analyze the expression and |
| 3439 | /// create a new one. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3440 | const SCEV *ScalarEvolution::getSCEV(Value *V) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3441 | assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3442 | |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3443 | const SCEV *S = getExistingSCEV(V); |
| 3444 | if (S == nullptr) { |
| 3445 | S = createSCEV(V); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3446 | // During PHI resolution, it is possible to create two SCEVs for the same |
| 3447 | // 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] | 3448 | // ValueExprMap before insert S->{V, 0} into ExprValueMap. |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3449 | std::pair<ValueExprMapType::iterator, bool> Pair = |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 3450 | ValueExprMap.insert({SCEVCallbackVH(V, this), S}); |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3451 | if (Pair.second) { |
| 3452 | ExprValueMap[S].insert({V, nullptr}); |
| 3453 | |
| 3454 | // If S == Stripped + Offset, add Stripped -> {V, Offset} into |
| 3455 | // ExprValueMap. |
| 3456 | const SCEV *Stripped = S; |
| 3457 | ConstantInt *Offset = nullptr; |
| 3458 | std::tie(Stripped, Offset) = splitAddExpr(S); |
| 3459 | // If stripped is SCEVUnknown, don't bother to save |
| 3460 | // Stripped -> {V, offset}. It doesn't simplify and sometimes even |
| 3461 | // increase the complexity of the expansion code. |
| 3462 | // If V is GetElementPtrInst, don't save Stripped -> {V, offset} |
| 3463 | // because it may generate add/sub instead of GEP in SCEV expansion. |
| 3464 | if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && |
| 3465 | !isa<GetElementPtrInst>(V)) |
| 3466 | ExprValueMap[Stripped].insert({V, Offset}); |
| 3467 | } |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3468 | } |
| 3469 | return S; |
| 3470 | } |
| 3471 | |
| 3472 | const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { |
| 3473 | assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); |
| 3474 | |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3475 | ValueExprMapType::iterator I = ValueExprMap.find_as(V); |
| 3476 | if (I != ValueExprMap.end()) { |
| 3477 | const SCEV *S = I->second; |
Shuxin Yang | 23773b3 | 2013-07-12 07:25:38 +0000 | [diff] [blame] | 3478 | if (checkValidity(S)) |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3479 | return S; |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3480 | eraseValueFromMap(V); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 3481 | forgetMemoizedResults(S); |
Shuxin Yang | efc4c01 | 2013-07-08 17:33:13 +0000 | [diff] [blame] | 3482 | } |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 3483 | return nullptr; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3484 | } |
| 3485 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3486 | /// Return a SCEV corresponding to -V = -1*V |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3487 | /// |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3488 | const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, |
| 3489 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3490 | if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) |
Owen Anderson | 53a5221 | 2009-07-13 04:09:18 +0000 | [diff] [blame] | 3491 | return getConstant( |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 3492 | cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3493 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3494 | Type *Ty = V->getType(); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3495 | Ty = getEffectiveSCEVType(Ty); |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3496 | return getMulExpr( |
| 3497 | V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3498 | } |
| 3499 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3500 | /// Return a SCEV corresponding to ~V = -1-V |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3501 | const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 3502 | if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) |
Owen Anderson | 542619e | 2009-07-13 20:58:05 +0000 | [diff] [blame] | 3503 | return getConstant( |
Owen Anderson | 487375e | 2009-07-29 18:55:55 +0000 | [diff] [blame] | 3504 | cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3505 | |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3506 | Type *Ty = V->getType(); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3507 | Ty = getEffectiveSCEVType(Ty); |
Owen Anderson | 542619e | 2009-07-13 20:58:05 +0000 | [diff] [blame] | 3508 | const SCEV *AllOnes = |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 3509 | getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3510 | return getMinusSCEV(AllOnes, V); |
| 3511 | } |
| 3512 | |
Chris Lattner | fc87752 | 2011-01-09 22:26:35 +0000 | [diff] [blame] | 3513 | const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 3514 | SCEV::NoWrapFlags Flags) { |
Dan Gohman | 46f00a2 | 2010-07-20 16:53:00 +0000 | [diff] [blame] | 3515 | // Fast path: X - X --> 0. |
| 3516 | if (LHS == RHS) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 3517 | return getZero(LHS->getType()); |
Dan Gohman | 46f00a2 | 2010-07-20 16:53:00 +0000 | [diff] [blame] | 3518 | |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 3519 | // We represent LHS - RHS as LHS + (-1)*RHS. This transformation |
| 3520 | // makes it so that we cannot make much use of NUW. |
| 3521 | auto AddFlags = SCEV::FlagAnyWrap; |
| 3522 | const bool RHSIsNotMinSigned = |
| 3523 | !getSignedRange(RHS).getSignedMin().isMinSignedValue(); |
| 3524 | if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { |
| 3525 | // Let M be the minimum representable signed value. Then (-1)*RHS |
| 3526 | // signed-wraps if and only if RHS is M. That can happen even for |
| 3527 | // a NSW subtraction because e.g. (-1)*M signed-wraps even though |
| 3528 | // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + |
| 3529 | // (-1)*RHS, we need to prove that RHS != M. |
| 3530 | // |
| 3531 | // If LHS is non-negative and we know that LHS - RHS does not |
| 3532 | // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap |
| 3533 | // either by proving that RHS > M or that LHS >= 0. |
| 3534 | if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { |
| 3535 | AddFlags = SCEV::FlagNSW; |
| 3536 | } |
| 3537 | } |
| 3538 | |
| 3539 | // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - |
| 3540 | // RHS is NSW and LHS >= 0. |
| 3541 | // |
| 3542 | // The difficulty here is that the NSW flag may have been proven |
| 3543 | // relative to a loop that is to be found in a recurrence in LHS and |
| 3544 | // not in RHS. Applying NSW to (-1)*M may then let the NSW have a |
| 3545 | // larger scope than intended. |
| 3546 | auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; |
| 3547 | |
| 3548 | return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3549 | } |
| 3550 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3551 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3552 | ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) { |
| 3553 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3554 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3555 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3556 | "Cannot truncate or zero extend with non-integer arguments!"); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3557 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3558 | return V; // No conversion |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3559 | if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3560 | return getTruncateExpr(V, Ty); |
| 3561 | return getZeroExtendExpr(V, Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3562 | } |
| 3563 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3564 | const SCEV * |
| 3565 | ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3566 | Type *Ty) { |
| 3567 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3568 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3569 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3570 | "Cannot truncate or zero extend with non-integer arguments!"); |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3571 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3572 | return V; // No conversion |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 3573 | if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 3574 | return getTruncateExpr(V, Ty); |
| 3575 | return getSignExtendExpr(V, Ty); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 3576 | } |
| 3577 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3578 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3579 | ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { |
| 3580 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3581 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3582 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3583 | "Cannot noop or zero extend with non-integer arguments!"); |
| 3584 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3585 | "getNoopOrZeroExtend cannot truncate!"); |
| 3586 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3587 | return V; // No conversion |
| 3588 | return getZeroExtendExpr(V, Ty); |
| 3589 | } |
| 3590 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3591 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3592 | ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { |
| 3593 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3594 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3595 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3596 | "Cannot noop or sign extend with non-integer arguments!"); |
| 3597 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3598 | "getNoopOrSignExtend cannot truncate!"); |
| 3599 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3600 | return V; // No conversion |
| 3601 | return getSignExtendExpr(V, Ty); |
| 3602 | } |
| 3603 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3604 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3605 | ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { |
| 3606 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3607 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3608 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | 8db2edc | 2009-06-13 15:56:47 +0000 | [diff] [blame] | 3609 | "Cannot noop or any extend with non-integer arguments!"); |
| 3610 | assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && |
| 3611 | "getNoopOrAnyExtend cannot truncate!"); |
| 3612 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3613 | return V; // No conversion |
| 3614 | return getAnyExtendExpr(V, Ty); |
| 3615 | } |
| 3616 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3617 | const SCEV * |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 3618 | ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { |
| 3619 | Type *SrcTy = V->getType(); |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3620 | assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && |
| 3621 | (Ty->isIntegerTy() || Ty->isPointerTy()) && |
Dan Gohman | e712a2f | 2009-05-13 03:46:30 +0000 | [diff] [blame] | 3622 | "Cannot truncate or noop with non-integer arguments!"); |
| 3623 | assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && |
| 3624 | "getTruncateOrNoop cannot extend!"); |
| 3625 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) |
| 3626 | return V; // No conversion |
| 3627 | return getTruncateExpr(V, Ty); |
| 3628 | } |
| 3629 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3630 | const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, |
| 3631 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3632 | const SCEV *PromotedLHS = LHS; |
| 3633 | const SCEV *PromotedRHS = RHS; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 3634 | |
| 3635 | if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) |
| 3636 | PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); |
| 3637 | else |
| 3638 | PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); |
| 3639 | |
| 3640 | return getUMaxExpr(PromotedLHS, PromotedRHS); |
| 3641 | } |
| 3642 | |
Dan Gohman | abd1709 | 2009-06-24 14:49:00 +0000 | [diff] [blame] | 3643 | const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, |
| 3644 | const SCEV *RHS) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 3645 | const SCEV *PromotedLHS = LHS; |
| 3646 | const SCEV *PromotedRHS = RHS; |
Dan Gohman | 2bc2230 | 2009-06-22 15:03:27 +0000 | [diff] [blame] | 3647 | |
| 3648 | if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) |
| 3649 | PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); |
| 3650 | else |
| 3651 | PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); |
| 3652 | |
| 3653 | return getUMinExpr(PromotedLHS, PromotedRHS); |
| 3654 | } |
| 3655 | |
Andrew Trick | 87716c9 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 3656 | const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { |
| 3657 | // A pointer operand may evaluate to a nonpointer expression, such as null. |
| 3658 | if (!V->getType()->isPointerTy()) |
| 3659 | return V; |
| 3660 | |
| 3661 | if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { |
| 3662 | return getPointerBase(Cast->getOperand()); |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 3663 | } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 3664 | const SCEV *PtrOp = nullptr; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 3665 | for (const SCEV *NAryOp : NAry->operands()) { |
| 3666 | if (NAryOp->getType()->isPointerTy()) { |
Andrew Trick | 87716c9 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 3667 | // Cannot find the base of an expression with multiple pointer operands. |
| 3668 | if (PtrOp) |
| 3669 | return V; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 3670 | PtrOp = NAryOp; |
Andrew Trick | 87716c9 | 2011-03-17 23:51:11 +0000 | [diff] [blame] | 3671 | } |
| 3672 | } |
| 3673 | if (!PtrOp) |
| 3674 | return V; |
| 3675 | return getPointerBase(PtrOp); |
| 3676 | } |
| 3677 | return V; |
| 3678 | } |
| 3679 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 3680 | /// Push users of the given Instruction onto the given Worklist. |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3681 | static void |
| 3682 | PushDefUseChildren(Instruction *I, |
| 3683 | SmallVectorImpl<Instruction *> &Worklist) { |
| 3684 | // Push the def-use children onto the Worklist stack. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3685 | for (User *U : I->users()) |
| 3686 | Worklist.push_back(cast<Instruction>(U)); |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3687 | } |
| 3688 | |
Sanjoy Das | f1e9cae0 | 2016-03-01 19:28:01 +0000 | [diff] [blame] | 3689 | void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3690 | SmallVector<Instruction *, 16> Worklist; |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3691 | PushDefUseChildren(PN, Worklist); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3692 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3693 | SmallPtrSet<Instruction *, 8> Visited; |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3694 | Visited.insert(PN); |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3695 | while (!Worklist.empty()) { |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3696 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3697 | if (!Visited.insert(I).second) |
| 3698 | continue; |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3699 | |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 3700 | auto It = ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 3701 | if (It != ValueExprMap.end()) { |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 3702 | const SCEV *Old = It->second; |
| 3703 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3704 | // Short-circuit the def-use traversal if the symbolic name |
| 3705 | // ceases to appear in expressions. |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 3706 | if (Old != SymName && !hasOperand(Old, SymName)) |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3707 | continue; |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3708 | |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3709 | // SCEVUnknown for a PHI either means that it has an unrecognized |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 3710 | // structure, it's a PHI that's in the progress of being computed |
| 3711 | // by createNodeForPHI, or it's a single-value PHI. In the first case, |
| 3712 | // additional loop trip count information isn't going to change anything. |
| 3713 | // In the second case, createNodeForPHI will perform the necessary |
| 3714 | // updates on its own when it gets to that point. In the third, we do |
| 3715 | // want to forget the SCEVUnknown. |
| 3716 | if (!isa<PHINode>(I) || |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 3717 | !isa<SCEVUnknown>(Old) || |
| 3718 | (I != PN && Old == SymName)) { |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 3719 | eraseValueFromMap(It->first); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 3720 | forgetMemoizedResults(Old); |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 3721 | } |
Dan Gohman | 0b89dff | 2009-07-25 01:13:03 +0000 | [diff] [blame] | 3722 | } |
| 3723 | |
| 3724 | PushDefUseChildren(I, Worklist); |
| 3725 | } |
Chris Lattner | 7b0fbe7 | 2005-02-13 04:37:18 +0000 | [diff] [blame] | 3726 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 3727 | |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 3728 | namespace { |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3729 | class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { |
| 3730 | public: |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3731 | static const SCEV *rewrite(const SCEV *S, const Loop *L, |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3732 | ScalarEvolution &SE) { |
| 3733 | SCEVInitRewriter Rewriter(L, SE); |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3734 | const SCEV *Result = Rewriter.visit(S); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3735 | return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); |
| 3736 | } |
| 3737 | |
| 3738 | SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) |
| 3739 | : SCEVRewriteVisitor(SE), L(L), Valid(true) {} |
| 3740 | |
| 3741 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { |
| 3742 | if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) |
| 3743 | Valid = false; |
| 3744 | return Expr; |
| 3745 | } |
| 3746 | |
| 3747 | const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { |
| 3748 | // Only allow AddRecExprs for this loop. |
| 3749 | if (Expr->getLoop() == L) |
| 3750 | return Expr->getStart(); |
| 3751 | Valid = false; |
| 3752 | return Expr; |
| 3753 | } |
| 3754 | |
| 3755 | bool isValid() { return Valid; } |
| 3756 | |
| 3757 | private: |
| 3758 | const Loop *L; |
| 3759 | bool Valid; |
| 3760 | }; |
| 3761 | |
| 3762 | class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { |
| 3763 | public: |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3764 | static const SCEV *rewrite(const SCEV *S, const Loop *L, |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3765 | ScalarEvolution &SE) { |
| 3766 | SCEVShiftRewriter Rewriter(L, SE); |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 3767 | const SCEV *Result = Rewriter.visit(S); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3768 | return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); |
| 3769 | } |
| 3770 | |
| 3771 | SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) |
| 3772 | : SCEVRewriteVisitor(SE), L(L), Valid(true) {} |
| 3773 | |
| 3774 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { |
| 3775 | // Only allow AddRecExprs for this loop. |
| 3776 | if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant)) |
| 3777 | Valid = false; |
| 3778 | return Expr; |
| 3779 | } |
| 3780 | |
| 3781 | const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { |
| 3782 | if (Expr->getLoop() == L && Expr->isAffine()) |
| 3783 | return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); |
| 3784 | Valid = false; |
| 3785 | return Expr; |
| 3786 | } |
| 3787 | bool isValid() { return Valid; } |
| 3788 | |
| 3789 | private: |
| 3790 | const Loop *L; |
| 3791 | bool Valid; |
| 3792 | }; |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 3793 | } // end anonymous namespace |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 3794 | |
Sanjoy Das | 724f5cf | 2016-03-03 18:31:29 +0000 | [diff] [blame] | 3795 | SCEV::NoWrapFlags |
| 3796 | ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { |
| 3797 | if (!AR->isAffine()) |
| 3798 | return SCEV::FlagAnyWrap; |
| 3799 | |
| 3800 | typedef OverflowingBinaryOperator OBO; |
| 3801 | SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; |
| 3802 | |
| 3803 | if (!AR->hasNoSignedWrap()) { |
| 3804 | ConstantRange AddRecRange = getSignedRange(AR); |
| 3805 | ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); |
| 3806 | |
| 3807 | auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 3808 | Instruction::Add, IncRange, OBO::NoSignedWrap); |
| 3809 | if (NSWRegion.contains(AddRecRange)) |
| 3810 | Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); |
| 3811 | } |
| 3812 | |
| 3813 | if (!AR->hasNoUnsignedWrap()) { |
| 3814 | ConstantRange AddRecRange = getUnsignedRange(AR); |
| 3815 | ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); |
| 3816 | |
| 3817 | auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( |
| 3818 | Instruction::Add, IncRange, OBO::NoUnsignedWrap); |
| 3819 | if (NUWRegion.contains(AddRecRange)) |
| 3820 | Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); |
| 3821 | } |
| 3822 | |
| 3823 | return Result; |
| 3824 | } |
| 3825 | |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3826 | namespace { |
| 3827 | /// Represents an abstract binary operation. This may exist as a |
| 3828 | /// normal instruction or constant expression, or may have been |
| 3829 | /// derived from an expression tree. |
| 3830 | struct BinaryOp { |
| 3831 | unsigned Opcode; |
| 3832 | Value *LHS; |
| 3833 | Value *RHS; |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 3834 | bool IsNSW; |
| 3835 | bool IsNUW; |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3836 | |
| 3837 | /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or |
| 3838 | /// constant expression. |
| 3839 | Operator *Op; |
| 3840 | |
| 3841 | explicit BinaryOp(Operator *Op) |
| 3842 | : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 3843 | IsNSW(false), IsNUW(false), Op(Op) { |
| 3844 | if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { |
| 3845 | IsNSW = OBO->hasNoSignedWrap(); |
| 3846 | IsNUW = OBO->hasNoUnsignedWrap(); |
| 3847 | } |
| 3848 | } |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3849 | |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 3850 | explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, |
| 3851 | bool IsNUW = false) |
| 3852 | : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), |
| 3853 | Op(nullptr) {} |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3854 | }; |
| 3855 | } |
| 3856 | |
| 3857 | |
| 3858 | /// 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] | 3859 | static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3860 | auto *Op = dyn_cast<Operator>(V); |
| 3861 | if (!Op) |
| 3862 | return None; |
| 3863 | |
| 3864 | // Implementation detail: all the cleverness here should happen without |
| 3865 | // creating new SCEV expressions -- our caller knowns tricks to avoid creating |
| 3866 | // SCEV expressions when possible, and we should not break that. |
| 3867 | |
| 3868 | switch (Op->getOpcode()) { |
| 3869 | case Instruction::Add: |
| 3870 | case Instruction::Sub: |
| 3871 | case Instruction::Mul: |
| 3872 | case Instruction::UDiv: |
| 3873 | case Instruction::And: |
| 3874 | case Instruction::Or: |
| 3875 | case Instruction::AShr: |
| 3876 | case Instruction::Shl: |
| 3877 | return BinaryOp(Op); |
| 3878 | |
| 3879 | case Instruction::Xor: |
| 3880 | if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) |
| 3881 | // If the RHS of the xor is a signbit, then this is just an add. |
| 3882 | // Instcombine turns add of signbit into xor as a strength reduction step. |
| 3883 | if (RHSC->getValue().isSignBit()) |
| 3884 | return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); |
| 3885 | return BinaryOp(Op); |
| 3886 | |
| 3887 | case Instruction::LShr: |
| 3888 | // Turn logical shift right of a constant into a unsigned divide. |
| 3889 | if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { |
| 3890 | uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); |
| 3891 | |
| 3892 | // If the shift count is not less than the bitwidth, the result of |
| 3893 | // the shift is undefined. Don't try to analyze it, because the |
| 3894 | // resolution chosen here may differ from the resolution chosen in |
| 3895 | // other parts of the compiler. |
| 3896 | if (SA->getValue().ult(BitWidth)) { |
| 3897 | Constant *X = |
| 3898 | ConstantInt::get(SA->getContext(), |
| 3899 | APInt::getOneBitSet(BitWidth, SA->getZExtValue())); |
| 3900 | return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); |
| 3901 | } |
| 3902 | } |
| 3903 | return BinaryOp(Op); |
| 3904 | |
Sanjoy Das | f49ca52 | 2016-05-29 00:34:42 +0000 | [diff] [blame] | 3905 | case Instruction::ExtractValue: { |
| 3906 | auto *EVI = cast<ExtractValueInst>(Op); |
| 3907 | if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) |
| 3908 | break; |
| 3909 | |
| 3910 | auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand()); |
| 3911 | if (!CI) |
| 3912 | break; |
| 3913 | |
| 3914 | if (auto *F = CI->getCalledFunction()) |
| 3915 | switch (F->getIntrinsicID()) { |
| 3916 | case Intrinsic::sadd_with_overflow: |
| 3917 | case Intrinsic::uadd_with_overflow: { |
| 3918 | if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT)) |
| 3919 | return BinaryOp(Instruction::Add, CI->getArgOperand(0), |
| 3920 | CI->getArgOperand(1)); |
| 3921 | |
| 3922 | // Now that we know that all uses of the arithmetic-result component of |
| 3923 | // CI are guarded by the overflow check, we can go ahead and pretend |
| 3924 | // that the arithmetic is non-overflowing. |
| 3925 | if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow) |
| 3926 | return BinaryOp(Instruction::Add, CI->getArgOperand(0), |
| 3927 | CI->getArgOperand(1), /* IsNSW = */ true, |
| 3928 | /* IsNUW = */ false); |
| 3929 | else |
| 3930 | return BinaryOp(Instruction::Add, CI->getArgOperand(0), |
| 3931 | CI->getArgOperand(1), /* IsNSW = */ false, |
| 3932 | /* IsNUW*/ true); |
| 3933 | } |
| 3934 | |
| 3935 | case Intrinsic::ssub_with_overflow: |
| 3936 | case Intrinsic::usub_with_overflow: |
| 3937 | return BinaryOp(Instruction::Sub, CI->getArgOperand(0), |
| 3938 | CI->getArgOperand(1)); |
| 3939 | |
| 3940 | case Intrinsic::smul_with_overflow: |
| 3941 | case Intrinsic::umul_with_overflow: |
| 3942 | return BinaryOp(Instruction::Mul, CI->getArgOperand(0), |
| 3943 | CI->getArgOperand(1)); |
| 3944 | default: |
| 3945 | break; |
| 3946 | } |
| 3947 | } |
| 3948 | |
Sanjoy Das | 118d919 | 2016-03-31 05:14:22 +0000 | [diff] [blame] | 3949 | default: |
| 3950 | break; |
| 3951 | } |
| 3952 | |
| 3953 | return None; |
| 3954 | } |
| 3955 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3956 | const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { |
| 3957 | const Loop *L = LI.getLoopFor(PN->getParent()); |
| 3958 | if (!L || L->getHeader() != PN->getParent()) |
| 3959 | return nullptr; |
| 3960 | |
| 3961 | // The loop may have multiple entrances or multiple exits; we can analyze |
| 3962 | // this phi as an addrec if it has a unique entry value and a unique |
| 3963 | // backedge value. |
| 3964 | Value *BEValueV = nullptr, *StartValueV = nullptr; |
| 3965 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 3966 | Value *V = PN->getIncomingValue(i); |
| 3967 | if (L->contains(PN->getIncomingBlock(i))) { |
| 3968 | if (!BEValueV) { |
| 3969 | BEValueV = V; |
| 3970 | } else if (BEValueV != V) { |
| 3971 | BEValueV = nullptr; |
| 3972 | break; |
| 3973 | } |
| 3974 | } else if (!StartValueV) { |
| 3975 | StartValueV = V; |
| 3976 | } else if (StartValueV != V) { |
| 3977 | StartValueV = nullptr; |
| 3978 | break; |
| 3979 | } |
| 3980 | } |
| 3981 | if (BEValueV && StartValueV) { |
| 3982 | // While we are analyzing this PHI node, handle its value symbolically. |
| 3983 | const SCEV *SymbolicName = getUnknown(PN); |
| 3984 | assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && |
| 3985 | "PHI node already processed?"); |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 3986 | ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 3987 | |
| 3988 | // Using this symbolic name for the PHI, analyze the value coming around |
| 3989 | // the back-edge. |
| 3990 | const SCEV *BEValue = getSCEV(BEValueV); |
| 3991 | |
| 3992 | // NOTE: If BEValue is loop invariant, we know that the PHI node just |
| 3993 | // has a special value for the first iteration of the loop. |
| 3994 | |
| 3995 | // If the value coming around the backedge is an add with the symbolic |
| 3996 | // value we just inserted, then we found a simple induction variable! |
| 3997 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { |
| 3998 | // If there is a single occurrence of the symbolic value, replace it |
| 3999 | // with a recurrence. |
| 4000 | unsigned FoundIndex = Add->getNumOperands(); |
| 4001 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) |
| 4002 | if (Add->getOperand(i) == SymbolicName) |
| 4003 | if (FoundIndex == e) { |
| 4004 | FoundIndex = i; |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 4005 | break; |
| 4006 | } |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4007 | |
| 4008 | if (FoundIndex != Add->getNumOperands()) { |
| 4009 | // Create an add with everything but the specified operand. |
| 4010 | SmallVector<const SCEV *, 8> Ops; |
| 4011 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) |
| 4012 | if (i != FoundIndex) |
| 4013 | Ops.push_back(Add->getOperand(i)); |
| 4014 | const SCEV *Accum = getAddExpr(Ops); |
| 4015 | |
| 4016 | // This is not a valid addrec if the step amount is varying each |
| 4017 | // loop iteration, but is not itself an addrec in this loop. |
| 4018 | if (isLoopInvariant(Accum, L) || |
| 4019 | (isa<SCEVAddRecExpr>(Accum) && |
| 4020 | cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { |
| 4021 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
| 4022 | |
Sanjoy Das | f49ca52 | 2016-05-29 00:34:42 +0000 | [diff] [blame] | 4023 | if (auto BO = MatchBinaryOp(BEValueV, DT)) { |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 4024 | if (BO->Opcode == Instruction::Add && BO->LHS == PN) { |
| 4025 | if (BO->IsNUW) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4026 | Flags = setFlags(Flags, SCEV::FlagNUW); |
Sanjoy Das | e12c0e5 | 2016-03-31 05:14:26 +0000 | [diff] [blame] | 4027 | if (BO->IsNSW) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4028 | Flags = setFlags(Flags, SCEV::FlagNSW); |
| 4029 | } |
| 4030 | } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { |
| 4031 | // If the increment is an inbounds GEP, then we know the address |
| 4032 | // space cannot be wrapped around. We cannot make any guarantee |
| 4033 | // about signed or unsigned overflow because pointers are |
| 4034 | // unsigned but we may have a negative index from the base |
| 4035 | // pointer. We can guarantee that no unsigned wrap occurs if the |
| 4036 | // indices form a positive value. |
| 4037 | if (GEP->isInBounds() && GEP->getOperand(0) == PN) { |
| 4038 | Flags = setFlags(Flags, SCEV::FlagNW); |
| 4039 | |
| 4040 | const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); |
| 4041 | if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) |
| 4042 | Flags = setFlags(Flags, SCEV::FlagNUW); |
| 4043 | } |
| 4044 | |
| 4045 | // We cannot transfer nuw and nsw flags from subtraction |
| 4046 | // operations -- sub nuw X, Y is not the same as add nuw X, -Y |
| 4047 | // for instance. |
| 4048 | } |
| 4049 | |
| 4050 | const SCEV *StartVal = getSCEV(StartValueV); |
| 4051 | const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); |
| 4052 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4053 | // Okay, for the entire analysis of this edge we assumed the PHI |
| 4054 | // to be symbolic. We now need to go back and purge all of the |
| 4055 | // entries for the scalars that use the symbolic expression. |
Sanjoy Das | f1e9cae0 | 2016-03-01 19:28:01 +0000 | [diff] [blame] | 4056 | forgetSymbolicName(PN, SymbolicName); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4057 | ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4058 | |
| 4059 | // We can add Flags to the post-inc expression only if we |
| 4060 | // know that it us *undefined behavior* for BEValueV to |
| 4061 | // overflow. |
| 4062 | if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) |
| 4063 | if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) |
| 4064 | (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); |
| 4065 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4066 | return PHISCEV; |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 4067 | } |
| 4068 | } |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 4069 | } else { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4070 | // Otherwise, this could be a loop like this: |
| 4071 | // i = 0; for (j = 1; ..; ++j) { .... i = j; } |
| 4072 | // In this case, j = {1,+,1} and BEValue is j. |
| 4073 | // Because the other in-value of i (0) fits the evolution of BEValue |
| 4074 | // i really is an addrec evolution. |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 4075 | // |
| 4076 | // We can generalize this saying that i is the shifted value of BEValue |
| 4077 | // by one iteration: |
| 4078 | // PHI(f(0), f({1,+,1})) --> f({0,+,1}) |
| 4079 | const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); |
| 4080 | const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this); |
| 4081 | if (Shifted != getCouldNotCompute() && |
| 4082 | Start != getCouldNotCompute()) { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4083 | const SCEV *StartVal = getSCEV(StartValueV); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 4084 | if (Start == StartVal) { |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4085 | // Okay, for the entire analysis of this edge we assumed the PHI |
| 4086 | // to be symbolic. We now need to go back and purge all of the |
| 4087 | // entries for the scalars that use the symbolic expression. |
Sanjoy Das | f1e9cae0 | 2016-03-01 19:28:01 +0000 | [diff] [blame] | 4088 | forgetSymbolicName(PN, SymbolicName); |
Silviu Baranga | f91c807 | 2015-10-30 15:02:28 +0000 | [diff] [blame] | 4089 | ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; |
| 4090 | return Shifted; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4091 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4092 | } |
Dan Gohman | 6635bb2 | 2010-04-12 07:49:36 +0000 | [diff] [blame] | 4093 | } |
Tobias Grosser | 934fcf4 | 2016-02-21 18:50:09 +0000 | [diff] [blame] | 4094 | |
| 4095 | // Remove the temporary PHI node SCEV that has been inserted while intending |
| 4096 | // to create an AddRecExpr for this PHI node. We can not keep this temporary |
| 4097 | // as it will prevent later (possibly simpler) SCEV expressions to be added |
| 4098 | // to the ValueExprMap. |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 4099 | eraseValueFromMap(PN); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4100 | } |
| 4101 | |
| 4102 | return nullptr; |
| 4103 | } |
| 4104 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4105 | // Checks if the SCEV S is available at BB. S is considered available at BB |
| 4106 | // if S can be materialized at BB without introducing a fault. |
| 4107 | static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, |
| 4108 | BasicBlock *BB) { |
| 4109 | struct CheckAvailable { |
| 4110 | bool TraversalDone = false; |
| 4111 | bool Available = true; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4112 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4113 | const Loop *L = nullptr; // The loop BB is in (can be nullptr) |
| 4114 | BasicBlock *BB = nullptr; |
| 4115 | DominatorTree &DT; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4116 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4117 | CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) |
| 4118 | : L(L), BB(BB), DT(DT) {} |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4119 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4120 | bool setUnavailable() { |
| 4121 | TraversalDone = true; |
| 4122 | Available = false; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4123 | return false; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4124 | } |
| 4125 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4126 | bool follow(const SCEV *S) { |
| 4127 | switch (S->getSCEVType()) { |
| 4128 | case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: |
| 4129 | case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: |
Sanjoy Das | bb5ffc5 | 2015-10-24 05:37:28 +0000 | [diff] [blame] | 4130 | // These expressions are available if their operand(s) is/are. |
| 4131 | return true; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4132 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4133 | case scAddRecExpr: { |
| 4134 | // We allow add recurrences that are on the loop BB is in, or some |
| 4135 | // outer loop. This guarantees availability because the value of the |
| 4136 | // add recurrence at BB is simply the "current" value of the induction |
| 4137 | // variable. We can relax this in the future; for instance an add |
| 4138 | // recurrence on a sibling dominating loop is also available at BB. |
| 4139 | const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); |
| 4140 | if (L && (ARLoop == L || ARLoop->contains(L))) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4141 | return true; |
| 4142 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4143 | return setUnavailable(); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4144 | } |
| 4145 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4146 | case scUnknown: { |
| 4147 | // For SCEVUnknown, we check for simple dominance. |
| 4148 | const auto *SU = cast<SCEVUnknown>(S); |
| 4149 | Value *V = SU->getValue(); |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4150 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4151 | if (isa<Argument>(V)) |
| 4152 | return false; |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4153 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4154 | if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) |
| 4155 | return false; |
| 4156 | |
| 4157 | return setUnavailable(); |
| 4158 | } |
| 4159 | |
| 4160 | case scUDivExpr: |
| 4161 | case scCouldNotCompute: |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 4162 | // We do not try to smart about these at all. |
| 4163 | return setUnavailable(); |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4164 | } |
| 4165 | llvm_unreachable("switch should be fully covered!"); |
| 4166 | } |
| 4167 | |
| 4168 | bool isDone() { return TraversalDone; } |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4169 | }; |
| 4170 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4171 | CheckAvailable CA(L, BB, DT); |
| 4172 | SCEVTraversal<CheckAvailable> ST(CA); |
| 4173 | |
| 4174 | ST.visitAll(S); |
| 4175 | return CA.Available; |
| 4176 | } |
| 4177 | |
| 4178 | // Try to match a control flow sequence that branches out at BI and merges back |
| 4179 | // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful |
| 4180 | // match. |
| 4181 | static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, |
| 4182 | Value *&C, Value *&LHS, Value *&RHS) { |
| 4183 | C = BI->getCondition(); |
| 4184 | |
| 4185 | BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); |
| 4186 | BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); |
| 4187 | |
| 4188 | if (!LeftEdge.isSingleEdge()) |
| 4189 | return false; |
| 4190 | |
| 4191 | assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); |
| 4192 | |
| 4193 | Use &LeftUse = Merge->getOperandUse(0); |
| 4194 | Use &RightUse = Merge->getOperandUse(1); |
| 4195 | |
| 4196 | if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { |
| 4197 | LHS = LeftUse; |
| 4198 | RHS = RightUse; |
| 4199 | return true; |
| 4200 | } |
| 4201 | |
| 4202 | if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { |
| 4203 | LHS = RightUse; |
| 4204 | RHS = LeftUse; |
| 4205 | return true; |
| 4206 | } |
| 4207 | |
| 4208 | return false; |
| 4209 | } |
| 4210 | |
| 4211 | const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { |
Sanjoy Das | b0b4e86 | 2016-08-05 18:34:14 +0000 | [diff] [blame] | 4212 | auto IsReachable = |
| 4213 | [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; |
| 4214 | if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4215 | const Loop *L = LI.getLoopFor(PN->getParent()); |
| 4216 | |
Sanjoy Das | 337d478 | 2015-10-31 23:21:40 +0000 | [diff] [blame] | 4217 | // We don't want to break LCSSA, even in a SCEV expression tree. |
| 4218 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
| 4219 | if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) |
| 4220 | return nullptr; |
| 4221 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4222 | // Try to match |
| 4223 | // |
| 4224 | // br %cond, label %left, label %right |
| 4225 | // left: |
| 4226 | // br label %merge |
| 4227 | // right: |
| 4228 | // br label %merge |
| 4229 | // merge: |
| 4230 | // V = phi [ %x, %left ], [ %y, %right ] |
| 4231 | // |
| 4232 | // as "select %cond, %x, %y" |
| 4233 | |
| 4234 | BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); |
| 4235 | assert(IDom && "At least the entry block should dominate PN"); |
| 4236 | |
| 4237 | auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); |
| 4238 | Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; |
| 4239 | |
Sanjoy Das | 1cd930b | 2015-10-03 00:34:19 +0000 | [diff] [blame] | 4240 | if (BI && BI->isConditional() && |
| 4241 | BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && |
| 4242 | IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && |
| 4243 | IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4244 | return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); |
| 4245 | } |
| 4246 | |
| 4247 | return nullptr; |
| 4248 | } |
| 4249 | |
| 4250 | const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { |
| 4251 | if (const SCEV *S = createAddRecFromPHI(PN)) |
| 4252 | return S; |
| 4253 | |
| 4254 | if (const SCEV *S = createNodeFromSelectLikePHI(PN)) |
| 4255 | return S; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 4256 | |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 4257 | // If the PHI has a single incoming value, follow that value, unless the |
| 4258 | // PHI's incoming blocks are in a different loop, in which case doing so |
| 4259 | // risks breaking LCSSA form. Instcombine would normally zap these, but |
| 4260 | // it doesn't have DominatorTree information, so it may miss cases. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 4261 | if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC)) |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4262 | if (LI.replacementPreservesLCSSAForm(PN, V)) |
Dan Gohman | a9c205c | 2010-02-25 06:57:05 +0000 | [diff] [blame] | 4263 | return getSCEV(V); |
Duncan Sands | 39d77131 | 2010-11-17 20:49:12 +0000 | [diff] [blame] | 4264 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4265 | // 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] | 4266 | return getUnknown(PN); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4267 | } |
| 4268 | |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 4269 | const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, |
| 4270 | Value *Cond, |
| 4271 | Value *TrueVal, |
| 4272 | Value *FalseVal) { |
Mehdi Amini | 044cb34 | 2015-10-07 18:14:25 +0000 | [diff] [blame] | 4273 | // Handle "constant" branch or select. This can occur for instance when a |
| 4274 | // loop pass transforms an inner loop and moves on to process the outer loop. |
| 4275 | if (auto *CI = dyn_cast<ConstantInt>(Cond)) |
| 4276 | return getSCEV(CI->isOne() ? TrueVal : FalseVal); |
| 4277 | |
Sanjoy Das | d067134 | 2015-10-02 19:39:59 +0000 | [diff] [blame] | 4278 | // Try to match some simple smax or umax patterns. |
| 4279 | auto *ICI = dyn_cast<ICmpInst>(Cond); |
| 4280 | if (!ICI) |
| 4281 | return getUnknown(I); |
| 4282 | |
| 4283 | Value *LHS = ICI->getOperand(0); |
| 4284 | Value *RHS = ICI->getOperand(1); |
| 4285 | |
| 4286 | switch (ICI->getPredicate()) { |
| 4287 | case ICmpInst::ICMP_SLT: |
| 4288 | case ICmpInst::ICMP_SLE: |
| 4289 | std::swap(LHS, RHS); |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 4290 | LLVM_FALLTHROUGH; |
Sanjoy Das | d067134 | 2015-10-02 19:39:59 +0000 | [diff] [blame] | 4291 | case ICmpInst::ICMP_SGT: |
| 4292 | case ICmpInst::ICMP_SGE: |
| 4293 | // a >s b ? a+x : b+x -> smax(a, b)+x |
| 4294 | // a >s b ? b+x : a+x -> smin(a, b)+x |
| 4295 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { |
| 4296 | const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); |
| 4297 | const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); |
| 4298 | const SCEV *LA = getSCEV(TrueVal); |
| 4299 | const SCEV *RA = getSCEV(FalseVal); |
| 4300 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4301 | const SCEV *RDiff = getMinusSCEV(RA, RS); |
| 4302 | if (LDiff == RDiff) |
| 4303 | return getAddExpr(getSMaxExpr(LS, RS), LDiff); |
| 4304 | LDiff = getMinusSCEV(LA, RS); |
| 4305 | RDiff = getMinusSCEV(RA, LS); |
| 4306 | if (LDiff == RDiff) |
| 4307 | return getAddExpr(getSMinExpr(LS, RS), LDiff); |
| 4308 | } |
| 4309 | break; |
| 4310 | case ICmpInst::ICMP_ULT: |
| 4311 | case ICmpInst::ICMP_ULE: |
| 4312 | std::swap(LHS, RHS); |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 4313 | LLVM_FALLTHROUGH; |
Sanjoy Das | d067134 | 2015-10-02 19:39:59 +0000 | [diff] [blame] | 4314 | case ICmpInst::ICMP_UGT: |
| 4315 | case ICmpInst::ICMP_UGE: |
| 4316 | // a >u b ? a+x : b+x -> umax(a, b)+x |
| 4317 | // a >u b ? b+x : a+x -> umin(a, b)+x |
| 4318 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { |
| 4319 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); |
| 4320 | const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); |
| 4321 | const SCEV *LA = getSCEV(TrueVal); |
| 4322 | const SCEV *RA = getSCEV(FalseVal); |
| 4323 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4324 | const SCEV *RDiff = getMinusSCEV(RA, RS); |
| 4325 | if (LDiff == RDiff) |
| 4326 | return getAddExpr(getUMaxExpr(LS, RS), LDiff); |
| 4327 | LDiff = getMinusSCEV(LA, RS); |
| 4328 | RDiff = getMinusSCEV(RA, LS); |
| 4329 | if (LDiff == RDiff) |
| 4330 | return getAddExpr(getUMinExpr(LS, RS), LDiff); |
| 4331 | } |
| 4332 | break; |
| 4333 | case ICmpInst::ICMP_NE: |
| 4334 | // n != 0 ? n+x : 1+x -> umax(n, 1)+x |
| 4335 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && |
| 4336 | isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { |
| 4337 | const SCEV *One = getOne(I->getType()); |
| 4338 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); |
| 4339 | const SCEV *LA = getSCEV(TrueVal); |
| 4340 | const SCEV *RA = getSCEV(FalseVal); |
| 4341 | const SCEV *LDiff = getMinusSCEV(LA, LS); |
| 4342 | const SCEV *RDiff = getMinusSCEV(RA, One); |
| 4343 | if (LDiff == RDiff) |
| 4344 | return getAddExpr(getUMaxExpr(One, LS), LDiff); |
| 4345 | } |
| 4346 | break; |
| 4347 | case ICmpInst::ICMP_EQ: |
| 4348 | // n == 0 ? 1+x : n+x -> umax(n, 1)+x |
| 4349 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && |
| 4350 | isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { |
| 4351 | const SCEV *One = getOne(I->getType()); |
| 4352 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); |
| 4353 | const SCEV *LA = getSCEV(TrueVal); |
| 4354 | const SCEV *RA = getSCEV(FalseVal); |
| 4355 | const SCEV *LDiff = getMinusSCEV(LA, One); |
| 4356 | const SCEV *RDiff = getMinusSCEV(RA, LS); |
| 4357 | if (LDiff == RDiff) |
| 4358 | return getAddExpr(getUMaxExpr(One, LS), LDiff); |
| 4359 | } |
| 4360 | break; |
| 4361 | default: |
| 4362 | break; |
| 4363 | } |
| 4364 | |
| 4365 | return getUnknown(I); |
| 4366 | } |
| 4367 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 4368 | /// Expand GEP instructions into add and multiply operations. This allows them |
| 4369 | /// to be analyzed by regular SCEV code. |
Dan Gohman | b256ccf | 2009-12-18 02:09:29 +0000 | [diff] [blame] | 4370 | const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { |
Dan Gohman | 30f24fe | 2009-05-09 00:14:52 +0000 | [diff] [blame] | 4371 | // Don't attempt to analyze GEPs over unsized objects. |
Eduard Burtescu | 19eb031 | 2016-01-19 17:28:00 +0000 | [diff] [blame] | 4372 | if (!GEP->getSourceElementType()->isSized()) |
Dan Gohman | 30f24fe | 2009-05-09 00:14:52 +0000 | [diff] [blame] | 4373 | return getUnknown(GEP); |
Matt Arsenault | 4c26590 | 2013-09-27 22:38:23 +0000 | [diff] [blame] | 4374 | |
Jingyue Wu | 2982d4d | 2015-05-18 17:03:25 +0000 | [diff] [blame] | 4375 | SmallVector<const SCEV *, 4> IndexExprs; |
| 4376 | for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) |
| 4377 | IndexExprs.push_back(getSCEV(*Index)); |
Eduard Burtescu | 19eb031 | 2016-01-19 17:28:00 +0000 | [diff] [blame] | 4378 | return getGEPExpr(GEP->getSourceElementType(), |
| 4379 | getSCEV(GEP->getPointerOperand()), |
| 4380 | IndexExprs, GEP->isInBounds()); |
Dan Gohman | ee750d1 | 2009-05-08 20:26:55 +0000 | [diff] [blame] | 4381 | } |
| 4382 | |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4383 | uint32_t |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4384 | ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4385 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 4386 | return C->getAPInt().countTrailingZeros(); |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4387 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4388 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4389 | return std::min(GetMinTrailingZeros(T->getOperand()), |
| 4390 | (uint32_t)getTypeSizeInBits(T->getType())); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4391 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4392 | if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4393 | uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); |
| 4394 | return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? |
| 4395 | getTypeSizeInBits(E->getType()) : OpRes; |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4396 | } |
| 4397 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4398 | if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4399 | uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); |
| 4400 | return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ? |
| 4401 | getTypeSizeInBits(E->getType()) : OpRes; |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4402 | } |
| 4403 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4404 | if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4405 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4406 | uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4407 | for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4408 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4409 | return MinOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4410 | } |
| 4411 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4412 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4413 | // The result is the sum of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4414 | uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); |
| 4415 | uint32_t BitWidth = getTypeSizeInBits(M->getType()); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4416 | for (unsigned i = 1, e = M->getNumOperands(); |
| 4417 | SumOpRes != BitWidth && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4418 | SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4419 | BitWidth); |
| 4420 | return SumOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4421 | } |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4422 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4423 | if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4424 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4425 | uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4426 | for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4427 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4428 | return MinOpRes; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4429 | } |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4430 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4431 | if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 4432 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4433 | uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 4434 | for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4435 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 4436 | return MinOpRes; |
| 4437 | } |
| 4438 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 4439 | if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 4440 | // The result is the min of all operands results. |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4441 | uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 4442 | for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4443 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 4444 | return MinOpRes; |
| 4445 | } |
| 4446 | |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4447 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { |
| 4448 | // For a SCEVUnknown, ask ValueTracking. |
| 4449 | unsigned BitWidth = getTypeSizeInBits(U->getType()); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4450 | APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 4451 | computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC, |
| 4452 | nullptr, &DT); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4453 | return Zeros.countTrailingOnes(); |
| 4454 | } |
| 4455 | |
| 4456 | // SCEVUDivExpr |
Nick Lewycky | 3783b46 | 2007-11-22 07:59:40 +0000 | [diff] [blame] | 4457 | return 0; |
Chris Lattner | 49b090e | 2006-12-12 02:26:09 +0000 | [diff] [blame] | 4458 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 4459 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 4460 | /// 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] | 4461 | static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { |
Sanjoy Das | a7e1378 | 2015-10-24 05:37:35 +0000 | [diff] [blame] | 4462 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 4463 | if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) |
| 4464 | return getConstantRangeFromMetadata(*MD); |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 4465 | |
| 4466 | return None; |
| 4467 | } |
| 4468 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 4469 | /// Determine the range for a particular SCEV. If SignHint is |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4470 | /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges |
| 4471 | /// with a "cleaner" unsigned (resp. signed) representation. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4472 | ConstantRange |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4473 | ScalarEvolution::getRange(const SCEV *S, |
| 4474 | ScalarEvolution::RangeSignHint SignHint) { |
| 4475 | DenseMap<const SCEV *, ConstantRange> &Cache = |
| 4476 | SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges |
| 4477 | : SignedRanges; |
| 4478 | |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 4479 | // See if we've computed this range already. |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4480 | DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); |
| 4481 | if (I != Cache.end()) |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 4482 | return I->second; |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4483 | |
| 4484 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 4485 | return setRange(C, SignHint, ConstantRange(C->getAPInt())); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4486 | |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4487 | unsigned BitWidth = getTypeSizeInBits(S->getType()); |
| 4488 | ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); |
| 4489 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4490 | // If the value has known zeros, the maximum value will have those known zeros |
| 4491 | // as well. |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4492 | uint32_t TZ = GetMinTrailingZeros(S); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4493 | if (TZ != 0) { |
| 4494 | if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) |
| 4495 | ConservativeResult = |
| 4496 | ConstantRange(APInt::getMinValue(BitWidth), |
| 4497 | APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); |
| 4498 | else |
| 4499 | ConservativeResult = ConstantRange( |
| 4500 | APInt::getSignedMinValue(BitWidth), |
| 4501 | APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); |
| 4502 | } |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4503 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4504 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4505 | ConstantRange X = getRange(Add->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4506 | for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4507 | X = X.add(getRange(Add->getOperand(i), SignHint)); |
| 4508 | return setRange(Add, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4509 | } |
| 4510 | |
| 4511 | if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4512 | ConstantRange X = getRange(Mul->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4513 | for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4514 | X = X.multiply(getRange(Mul->getOperand(i), SignHint)); |
| 4515 | return setRange(Mul, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4516 | } |
| 4517 | |
| 4518 | if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4519 | ConstantRange X = getRange(SMax->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4520 | for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4521 | X = X.smax(getRange(SMax->getOperand(i), SignHint)); |
| 4522 | return setRange(SMax, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4523 | } |
| 4524 | |
| 4525 | if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4526 | ConstantRange X = getRange(UMax->getOperand(0), SignHint); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4527 | for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4528 | X = X.umax(getRange(UMax->getOperand(i), SignHint)); |
| 4529 | return setRange(UMax, SignHint, ConservativeResult.intersectWith(X)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4530 | } |
| 4531 | |
| 4532 | if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4533 | ConstantRange X = getRange(UDiv->getLHS(), SignHint); |
| 4534 | ConstantRange Y = getRange(UDiv->getRHS(), SignHint); |
| 4535 | return setRange(UDiv, SignHint, |
| 4536 | ConservativeResult.intersectWith(X.udiv(Y))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4537 | } |
| 4538 | |
| 4539 | if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4540 | ConstantRange X = getRange(ZExt->getOperand(), SignHint); |
| 4541 | return setRange(ZExt, SignHint, |
| 4542 | ConservativeResult.intersectWith(X.zeroExtend(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4543 | } |
| 4544 | |
| 4545 | if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4546 | ConstantRange X = getRange(SExt->getOperand(), SignHint); |
| 4547 | return setRange(SExt, SignHint, |
| 4548 | ConservativeResult.intersectWith(X.signExtend(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4549 | } |
| 4550 | |
| 4551 | if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4552 | ConstantRange X = getRange(Trunc->getOperand(), SignHint); |
| 4553 | return setRange(Trunc, SignHint, |
| 4554 | ConservativeResult.intersectWith(X.truncate(BitWidth))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4555 | } |
| 4556 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4557 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4558 | // If there's no unsigned wrap, the value will never be less than its |
| 4559 | // initial value. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 4560 | if (AddRec->hasNoUnsignedWrap()) |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4561 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) |
Dan Gohman | ebbd05f | 2010-04-12 23:08:18 +0000 | [diff] [blame] | 4562 | if (!C->getValue()->isZero()) |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 4563 | ConservativeResult = ConservativeResult.intersectWith( |
| 4564 | ConstantRange(C->getAPInt(), APInt(BitWidth, 0))); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4565 | |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4566 | // If there's no signed wrap, and all the operands have the same sign or |
| 4567 | // zero, the value won't ever change sign. |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 4568 | if (AddRec->hasNoSignedWrap()) { |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4569 | bool AllNonNeg = true; |
| 4570 | bool AllNonPos = true; |
| 4571 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { |
| 4572 | if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; |
| 4573 | if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; |
| 4574 | } |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4575 | if (AllNonNeg) |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 4576 | ConservativeResult = ConservativeResult.intersectWith( |
| 4577 | ConstantRange(APInt(BitWidth, 0), |
| 4578 | APInt::getSignedMinValue(BitWidth))); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4579 | else if (AllNonPos) |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 4580 | ConservativeResult = ConservativeResult.intersectWith( |
| 4581 | ConstantRange(APInt::getSignedMinValue(BitWidth), |
| 4582 | APInt(BitWidth, 1))); |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4583 | } |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4584 | |
| 4585 | // TODO: non-affine addrec |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4586 | if (AddRec->isAffine()) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 4587 | const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop()); |
Dan Gohman | 85be433 | 2010-01-26 19:19:05 +0000 | [diff] [blame] | 4588 | if (!isa<SCEVCouldNotCompute>(MaxBECount) && |
| 4589 | getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { |
Sanjoy Das | b765b63 | 2016-03-02 00:57:39 +0000 | [diff] [blame] | 4590 | auto RangeFromAffine = getRangeForAffineAR( |
| 4591 | AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, |
| 4592 | BitWidth); |
| 4593 | if (!RangeFromAffine.isFullSet()) |
| 4594 | ConservativeResult = |
| 4595 | ConservativeResult.intersectWith(RangeFromAffine); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4596 | |
| 4597 | auto RangeFromFactoring = getRangeViaFactoring( |
| 4598 | AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, |
| 4599 | BitWidth); |
| 4600 | if (!RangeFromFactoring.isFullSet()) |
| 4601 | ConservativeResult = |
| 4602 | ConservativeResult.intersectWith(RangeFromFactoring); |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4603 | } |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4604 | } |
Dan Gohman | 51ad99d | 2010-01-21 02:09:26 +0000 | [diff] [blame] | 4605 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4606 | return setRange(AddRec, SignHint, ConservativeResult); |
Dan Gohman | d261d27 | 2009-06-24 01:05:09 +0000 | [diff] [blame] | 4607 | } |
| 4608 | |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4609 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 4610 | // Check if the IR explicitly contains !range metadata. |
| 4611 | Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); |
| 4612 | if (MDRange.hasValue()) |
| 4613 | ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue()); |
| 4614 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4615 | // Split here to avoid paying the compile-time cost of calling both |
| 4616 | // computeKnownBits and ComputeNumSignBits. This restriction can be lifted |
| 4617 | // if needed. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 4618 | const DataLayout &DL = getDataLayout(); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4619 | if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { |
| 4620 | // For a SCEVUnknown, ask ValueTracking. |
| 4621 | APInt Zeros(BitWidth, 0), Ones(BitWidth, 0); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4622 | computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4623 | if (Ones != ~Zeros + 1) |
| 4624 | ConservativeResult = |
| 4625 | ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)); |
| 4626 | } else { |
| 4627 | assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && |
| 4628 | "generalize as needed!"); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4629 | unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 4630 | if (NS > 1) |
| 4631 | ConservativeResult = ConservativeResult.intersectWith( |
| 4632 | ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), |
| 4633 | APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1)); |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4634 | } |
| 4635 | |
| 4636 | return setRange(U, SignHint, ConservativeResult); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4637 | } |
| 4638 | |
Sanjoy Das | 91b5477 | 2015-03-09 21:43:43 +0000 | [diff] [blame] | 4639 | return setRange(S, SignHint, ConservativeResult); |
Dan Gohman | c702fc0 | 2009-06-19 23:29:04 +0000 | [diff] [blame] | 4640 | } |
| 4641 | |
Sanjoy Das | b765b63 | 2016-03-02 00:57:39 +0000 | [diff] [blame] | 4642 | ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, |
| 4643 | const SCEV *Step, |
| 4644 | const SCEV *MaxBECount, |
| 4645 | unsigned BitWidth) { |
| 4646 | assert(!isa<SCEVCouldNotCompute>(MaxBECount) && |
| 4647 | getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && |
| 4648 | "Precondition!"); |
| 4649 | |
| 4650 | ConstantRange Result(BitWidth, /* isFullSet = */ true); |
| 4651 | |
| 4652 | // Check for overflow. This must be done with ConstantRange arithmetic |
| 4653 | // because we could be called from within the ScalarEvolution overflow |
| 4654 | // checking code. |
| 4655 | |
| 4656 | MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); |
| 4657 | ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount); |
| 4658 | ConstantRange ZExtMaxBECountRange = |
| 4659 | MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1); |
| 4660 | |
| 4661 | ConstantRange StepSRange = getSignedRange(Step); |
| 4662 | ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1); |
| 4663 | |
| 4664 | ConstantRange StartURange = getUnsignedRange(Start); |
| 4665 | ConstantRange EndURange = |
| 4666 | StartURange.add(MaxBECountRange.multiply(StepSRange)); |
| 4667 | |
| 4668 | // Check for unsigned overflow. |
| 4669 | ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1); |
| 4670 | ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1); |
| 4671 | if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == |
| 4672 | ZExtEndURange) { |
| 4673 | APInt Min = APIntOps::umin(StartURange.getUnsignedMin(), |
| 4674 | EndURange.getUnsignedMin()); |
| 4675 | APInt Max = APIntOps::umax(StartURange.getUnsignedMax(), |
| 4676 | EndURange.getUnsignedMax()); |
| 4677 | bool IsFullRange = Min.isMinValue() && Max.isMaxValue(); |
| 4678 | if (!IsFullRange) |
| 4679 | Result = |
| 4680 | Result.intersectWith(ConstantRange(Min, Max + 1)); |
| 4681 | } |
| 4682 | |
| 4683 | ConstantRange StartSRange = getSignedRange(Start); |
| 4684 | ConstantRange EndSRange = |
| 4685 | StartSRange.add(MaxBECountRange.multiply(StepSRange)); |
| 4686 | |
| 4687 | // Check for signed overflow. This must be done with ConstantRange |
| 4688 | // arithmetic because we could be called from within the ScalarEvolution |
| 4689 | // overflow checking code. |
| 4690 | ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1); |
| 4691 | ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1); |
| 4692 | if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) == |
| 4693 | SExtEndSRange) { |
| 4694 | APInt Min = |
| 4695 | APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin()); |
| 4696 | APInt Max = |
| 4697 | APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax()); |
| 4698 | bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue(); |
| 4699 | if (!IsFullRange) |
| 4700 | Result = |
| 4701 | Result.intersectWith(ConstantRange(Min, Max + 1)); |
| 4702 | } |
| 4703 | |
| 4704 | return Result; |
| 4705 | } |
| 4706 | |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4707 | ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, |
| 4708 | const SCEV *Step, |
| 4709 | const SCEV *MaxBECount, |
| 4710 | unsigned BitWidth) { |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4711 | // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) |
| 4712 | // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) |
| 4713 | |
| 4714 | struct SelectPattern { |
| 4715 | Value *Condition = nullptr; |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4716 | APInt TrueValue; |
| 4717 | APInt FalseValue; |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4718 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4719 | explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, |
| 4720 | const SCEV *S) { |
| 4721 | Optional<unsigned> CastOp; |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4722 | APInt Offset(BitWidth, 0); |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4723 | |
| 4724 | assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && |
| 4725 | "Should be!"); |
| 4726 | |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4727 | // Peel off a constant offset: |
| 4728 | if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { |
| 4729 | // In the future we could consider being smarter here and handle |
| 4730 | // {Start+Step,+,Step} too. |
| 4731 | if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) |
| 4732 | return; |
| 4733 | |
| 4734 | Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); |
| 4735 | S = SA->getOperand(1); |
| 4736 | } |
| 4737 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4738 | // Peel off a cast operation |
| 4739 | if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { |
| 4740 | CastOp = SCast->getSCEVType(); |
| 4741 | S = SCast->getOperand(); |
| 4742 | } |
| 4743 | |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4744 | using namespace llvm::PatternMatch; |
| 4745 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4746 | auto *SU = dyn_cast<SCEVUnknown>(S); |
| 4747 | const APInt *TrueVal, *FalseVal; |
| 4748 | if (!SU || |
| 4749 | !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), |
| 4750 | m_APInt(FalseVal)))) { |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4751 | Condition = nullptr; |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4752 | return; |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4753 | } |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4754 | |
| 4755 | TrueValue = *TrueVal; |
| 4756 | FalseValue = *FalseVal; |
| 4757 | |
| 4758 | // Re-apply the cast we peeled off earlier |
| 4759 | if (CastOp.hasValue()) |
| 4760 | switch (*CastOp) { |
| 4761 | default: |
| 4762 | llvm_unreachable("Unknown SCEV cast type!"); |
| 4763 | |
| 4764 | case scTruncate: |
| 4765 | TrueValue = TrueValue.trunc(BitWidth); |
| 4766 | FalseValue = FalseValue.trunc(BitWidth); |
| 4767 | break; |
| 4768 | case scZeroExtend: |
| 4769 | TrueValue = TrueValue.zext(BitWidth); |
| 4770 | FalseValue = FalseValue.zext(BitWidth); |
| 4771 | break; |
| 4772 | case scSignExtend: |
| 4773 | TrueValue = TrueValue.sext(BitWidth); |
| 4774 | FalseValue = FalseValue.sext(BitWidth); |
| 4775 | break; |
| 4776 | } |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4777 | |
| 4778 | // Re-apply the constant offset we peeled off earlier |
| 4779 | TrueValue += Offset; |
| 4780 | FalseValue += Offset; |
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 | bool isRecognized() { return Condition != nullptr; } |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4784 | }; |
| 4785 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4786 | SelectPattern StartPattern(*this, BitWidth, Start); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4787 | if (!StartPattern.isRecognized()) |
| 4788 | return ConstantRange(BitWidth, /* isFullSet = */ true); |
| 4789 | |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4790 | SelectPattern StepPattern(*this, BitWidth, Step); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4791 | if (!StepPattern.isRecognized()) |
| 4792 | return ConstantRange(BitWidth, /* isFullSet = */ true); |
| 4793 | |
| 4794 | if (StartPattern.Condition != StepPattern.Condition) { |
| 4795 | // We don't handle this case today; but we could, by considering four |
| 4796 | // possibilities below instead of two. I'm not sure if there are cases where |
| 4797 | // that will help over what getRange already does, though. |
| 4798 | return ConstantRange(BitWidth, /* isFullSet = */ true); |
| 4799 | } |
| 4800 | |
| 4801 | // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to |
| 4802 | // construct arbitrary general SCEV expressions here. This function is called |
| 4803 | // from deep in the call stack, and calling getSCEV (on a sext instruction, |
| 4804 | // say) can end up caching a suboptimal value. |
| 4805 | |
Sanjoy Das | 6b017a1 | 2016-03-02 02:56:29 +0000 | [diff] [blame] | 4806 | // FIXME: without the explicit `this` receiver below, MSVC errors out with |
| 4807 | // C2352 and C2512 (otherwise it isn't needed). |
| 4808 | |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4809 | const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4810 | const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); |
Sanjoy Das | 97d19bd | 2016-03-09 01:51:02 +0000 | [diff] [blame] | 4811 | const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); |
Sanjoy Das | d3488c6 | 2016-03-09 01:50:57 +0000 | [diff] [blame] | 4812 | const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); |
Sanjoy Das | 62a1c33 | 2016-03-02 02:15:42 +0000 | [diff] [blame] | 4813 | |
Sanjoy Das | 1168f93 | 2016-03-02 02:34:20 +0000 | [diff] [blame] | 4814 | ConstantRange TrueRange = |
Sanjoy Das | eca1b53 | 2016-03-02 02:44:08 +0000 | [diff] [blame] | 4815 | this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); |
Sanjoy Das | 1168f93 | 2016-03-02 02:34:20 +0000 | [diff] [blame] | 4816 | ConstantRange FalseRange = |
Sanjoy Das | eca1b53 | 2016-03-02 02:44:08 +0000 | [diff] [blame] | 4817 | this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); |
Sanjoy Das | bf73098 | 2016-03-02 00:57:54 +0000 | [diff] [blame] | 4818 | |
| 4819 | return TrueRange.unionWith(FalseRange); |
| 4820 | } |
| 4821 | |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4822 | SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 4823 | if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4824 | const BinaryOperator *BinOp = cast<BinaryOperator>(V); |
| 4825 | |
| 4826 | // Return early if there are no flags to propagate to the SCEV. |
| 4827 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
| 4828 | if (BinOp->hasNoUnsignedWrap()) |
| 4829 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); |
| 4830 | if (BinOp->hasNoSignedWrap()) |
| 4831 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); |
Sanjoy Das | dcd3a88 | 2016-03-02 04:52:22 +0000 | [diff] [blame] | 4832 | if (Flags == SCEV::FlagAnyWrap) |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4833 | return SCEV::FlagAnyWrap; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4834 | |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4835 | return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; |
| 4836 | } |
| 4837 | |
| 4838 | bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { |
| 4839 | // Here we check that I is in the header of the innermost loop containing I, |
| 4840 | // since we only deal with instructions in the loop header. The actual loop we |
| 4841 | // need to check later will come from an add recurrence, but getting that |
| 4842 | // requires computing the SCEV of the operands, which can be expensive. This |
| 4843 | // check we can do cheaply to rule out some cases early. |
| 4844 | Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); |
Sanjoy Das | dcd3a88 | 2016-03-02 04:52:22 +0000 | [diff] [blame] | 4845 | if (InnermostContainingLoop == nullptr || |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4846 | InnermostContainingLoop->getHeader() != I->getParent()) |
| 4847 | 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 | // Only proceed if we can prove that I does not yield poison. |
| 4850 | if (!isKnownNotFullPoison(I)) return false; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4851 | |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4852 | // At this point we know that if I is executed, then it does not wrap |
| 4853 | // according to at least one of NSW or NUW. If I is not executed, then we do |
| 4854 | // not know if the calculation that I represents would wrap. Multiple |
| 4855 | // 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] | 4856 | // the SCEV, we must guarantee no wrapping for that SCEV also when it is |
| 4857 | // 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] | 4858 | // that guarantee for cases where I is not executed. So we need to find the |
| 4859 | // loop that I is considered in relation to and prove that I is executed for |
| 4860 | // every iteration of that loop. That implies that the value that I |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4861 | // calculates does not wrap anywhere in the loop, so then we can apply the |
| 4862 | // flags to the SCEV. |
| 4863 | // |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4864 | // We check isLoopInvariant to disambiguate in case we are adding recurrences |
| 4865 | // from different loops, so that we know which loop to prove that I is |
| 4866 | // executed in. |
| 4867 | for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { |
Hans Wennborg | 3879035 | 2016-08-17 22:50:18 +0000 | [diff] [blame] | 4868 | // I could be an extractvalue from a call to an overflow intrinsic. |
| 4869 | // TODO: We can do better here in some cases. |
| 4870 | if (!isSCEVable(I->getOperand(OpIndex)->getType())) |
| 4871 | return false; |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4872 | const SCEV *Op = getSCEV(I->getOperand(OpIndex)); |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4873 | if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4874 | bool AllOtherOpsLoopInvariant = true; |
| 4875 | for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); |
| 4876 | ++OtherOpIndex) { |
| 4877 | if (OtherOpIndex != OpIndex) { |
| 4878 | const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); |
| 4879 | if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { |
| 4880 | AllOtherOpsLoopInvariant = false; |
| 4881 | break; |
| 4882 | } |
| 4883 | } |
| 4884 | } |
| 4885 | if (AllOtherOpsLoopInvariant && |
| 4886 | isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) |
| 4887 | return true; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4888 | } |
| 4889 | } |
Sanjoy Das | efdeb45 | 2016-04-22 05:38:54 +0000 | [diff] [blame] | 4890 | return false; |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 4891 | } |
| 4892 | |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4893 | bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { |
| 4894 | // If we know that \c I can never be poison period, then that's enough. |
| 4895 | if (isSCEVExprNeverPoison(I)) |
| 4896 | return true; |
| 4897 | |
| 4898 | // For an add recurrence specifically, we assume that infinite loops without |
| 4899 | // side effects are undefined behavior, and then reason as follows: |
| 4900 | // |
| 4901 | // If the add recurrence is poison in any iteration, it is poison on all |
| 4902 | // future iterations (since incrementing poison yields poison). If the result |
| 4903 | // of the add recurrence is fed into the loop latch condition and the loop |
| 4904 | // does not contain any throws or exiting blocks other than the latch, we now |
| 4905 | // have the ability to "choose" whether the backedge is taken or not (by |
| 4906 | // choosing a sufficiently evil value for the poison feeding into the branch) |
| 4907 | // for every iteration including and after the one in which \p I first became |
| 4908 | // poison. There are two possibilities (let's call the iteration in which \p |
| 4909 | // I first became poison as K): |
| 4910 | // |
| 4911 | // 1. In the set of iterations including and after K, the loop body executes |
| 4912 | // no side effects. In this case executing the backege an infinte number |
| 4913 | // of times will yield undefined behavior. |
| 4914 | // |
| 4915 | // 2. In the set of iterations including and after K, the loop body executes |
| 4916 | // at least one side effect. In this case, that specific instance of side |
| 4917 | // effect is control dependent on poison, which also yields undefined |
| 4918 | // behavior. |
| 4919 | |
| 4920 | auto *ExitingBB = L->getExitingBlock(); |
| 4921 | auto *LatchBB = L->getLoopLatch(); |
| 4922 | if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) |
| 4923 | return false; |
| 4924 | |
| 4925 | SmallPtrSet<const Instruction *, 16> Pushed; |
Sanjoy Das | a19edc4 | 2016-06-08 17:48:31 +0000 | [diff] [blame] | 4926 | SmallVector<const Instruction *, 8> PoisonStack; |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4927 | |
Sanjoy Das | a19edc4 | 2016-06-08 17:48:31 +0000 | [diff] [blame] | 4928 | // We start by assuming \c I, the post-inc add recurrence, is poison. Only |
| 4929 | // things that are known to be fully poison under that assumption go on the |
| 4930 | // PoisonStack. |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4931 | Pushed.insert(I); |
Sanjoy Das | a19edc4 | 2016-06-08 17:48:31 +0000 | [diff] [blame] | 4932 | PoisonStack.push_back(I); |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4933 | |
| 4934 | bool LatchControlDependentOnPoison = false; |
Sanjoy Das | 2401c98 | 2016-06-08 17:48:46 +0000 | [diff] [blame] | 4935 | while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { |
Sanjoy Das | a19edc4 | 2016-06-08 17:48:31 +0000 | [diff] [blame] | 4936 | const Instruction *Poison = PoisonStack.pop_back_val(); |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4937 | |
Sanjoy Das | a19edc4 | 2016-06-08 17:48:31 +0000 | [diff] [blame] | 4938 | for (auto *PoisonUser : Poison->users()) { |
| 4939 | if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { |
| 4940 | if (Pushed.insert(cast<Instruction>(PoisonUser)).second) |
| 4941 | PoisonStack.push_back(cast<Instruction>(PoisonUser)); |
| 4942 | } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4943 | assert(BI->isConditional() && "Only possibility!"); |
| 4944 | if (BI->getParent() == LatchBB) { |
| 4945 | LatchControlDependentOnPoison = true; |
| 4946 | break; |
| 4947 | } |
| 4948 | } |
| 4949 | } |
| 4950 | } |
| 4951 | |
Sanjoy Das | 97cd7d5 | 2016-06-09 01:13:54 +0000 | [diff] [blame] | 4952 | return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); |
| 4953 | } |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4954 | |
Sanjoy Das | 5603fc0 | 2016-09-26 02:44:07 +0000 | [diff] [blame] | 4955 | ScalarEvolution::LoopProperties |
| 4956 | ScalarEvolution::getLoopProperties(const Loop *L) { |
| 4957 | typedef ScalarEvolution::LoopProperties LoopProperties; |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 4958 | |
Sanjoy Das | 5603fc0 | 2016-09-26 02:44:07 +0000 | [diff] [blame] | 4959 | auto Itr = LoopPropertiesCache.find(L); |
| 4960 | if (Itr == LoopPropertiesCache.end()) { |
| 4961 | auto HasSideEffects = [](Instruction *I) { |
| 4962 | if (auto *SI = dyn_cast<StoreInst>(I)) |
| 4963 | return !SI->isSimple(); |
| 4964 | |
| 4965 | return I->mayHaveSideEffects(); |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 4966 | }; |
| 4967 | |
Sanjoy Das | 5603fc0 | 2016-09-26 02:44:07 +0000 | [diff] [blame] | 4968 | LoopProperties LP = {/* HasNoAbnormalExits */ true, |
| 4969 | /*HasNoSideEffects*/ true}; |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 4970 | |
Sanjoy Das | 5603fc0 | 2016-09-26 02:44:07 +0000 | [diff] [blame] | 4971 | for (auto *BB : L->getBlocks()) |
| 4972 | for (auto &I : *BB) { |
| 4973 | if (!isGuaranteedToTransferExecutionToSuccessor(&I)) |
| 4974 | LP.HasNoAbnormalExits = false; |
| 4975 | if (HasSideEffects(&I)) |
| 4976 | LP.HasNoSideEffects = false; |
| 4977 | if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) |
| 4978 | break; // We're already as pessimistic as we can get. |
| 4979 | } |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 4980 | |
Sanjoy Das | 5603fc0 | 2016-09-26 02:44:07 +0000 | [diff] [blame] | 4981 | auto InsertPair = LoopPropertiesCache.insert({L, LP}); |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4982 | assert(InsertPair.second && "We just checked!"); |
| 4983 | Itr = InsertPair.first; |
| 4984 | } |
| 4985 | |
Sanjoy Das | 97cd7d5 | 2016-06-09 01:13:54 +0000 | [diff] [blame] | 4986 | return Itr->second; |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 4987 | } |
| 4988 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 4989 | const SCEV *ScalarEvolution::createSCEV(Value *V) { |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 4990 | if (!isSCEVable(V->getType())) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 4991 | return getUnknown(V); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 4992 | |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 4993 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 4994 | // Don't attempt to analyze instructions in blocks that aren't |
| 4995 | // reachable. Such instructions don't matter, and they aren't required |
| 4996 | // to obey basic rules for definitions dominating uses which this |
| 4997 | // analysis depends on. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 4998 | if (!DT.isReachableFromEntry(I->getParent())) |
Dan Gohman | 69451a0 | 2010-03-09 23:46:50 +0000 | [diff] [blame] | 4999 | return getUnknown(V); |
Sanjoy Das | 260ad4d | 2016-03-29 16:40:39 +0000 | [diff] [blame] | 5000 | } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) |
Dan Gohman | f436bac | 2009-06-24 00:54:57 +0000 | [diff] [blame] | 5001 | return getConstant(CI); |
| 5002 | else if (isa<ConstantPointerNull>(V)) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 5003 | return getZero(V->getType()); |
Dan Gohman | f161e06e | 2009-08-25 17:49:57 +0000 | [diff] [blame] | 5004 | else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) |
Sanjoy Das | 5ce3272 | 2016-04-08 00:48:30 +0000 | [diff] [blame] | 5005 | return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); |
Sanjoy Das | 260ad4d | 2016-03-29 16:40:39 +0000 | [diff] [blame] | 5006 | else if (!isa<ConstantExpr>(V)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5007 | return getUnknown(V); |
Chris Lattner | a3e0bb4 | 2007-04-02 05:41:38 +0000 | [diff] [blame] | 5008 | |
Dan Gohman | 80ca01c | 2009-07-17 20:47:02 +0000 | [diff] [blame] | 5009 | Operator *U = cast<Operator>(V); |
Sanjoy Das | f49ca52 | 2016-05-29 00:34:42 +0000 | [diff] [blame] | 5010 | if (auto BO = MatchBinaryOp(U, DT)) { |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5011 | switch (BO->Opcode) { |
| 5012 | case Instruction::Add: { |
| 5013 | // The simple thing to do would be to just call getSCEV on both operands |
| 5014 | // and call getAddExpr with the result. However if we're looking at a |
| 5015 | // bunch of things all added together, this can be quite inefficient, |
| 5016 | // because it leads to N-1 getAddExpr calls for N ultimate operands. |
| 5017 | // Instead, gather up all the operands and make a single getAddExpr call. |
| 5018 | // LLVM IR canonical form means we need only traverse the left operands. |
| 5019 | SmallVector<const SCEV *, 4> AddOps; |
| 5020 | do { |
| 5021 | if (BO->Op) { |
| 5022 | if (auto *OpSCEV = getExistingSCEV(BO->Op)) { |
| 5023 | AddOps.push_back(OpSCEV); |
| 5024 | break; |
| 5025 | } |
Jingyue Wu | 42f1d67 | 2015-07-28 18:22:40 +0000 | [diff] [blame] | 5026 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5027 | // If a NUW or NSW flag can be applied to the SCEV for this |
| 5028 | // addition, then compute the SCEV for this addition by itself |
| 5029 | // with a separate call to getAddExpr. We need to do that |
| 5030 | // instead of pushing the operands of the addition onto AddOps, |
| 5031 | // since the flags are only known to apply to this particular |
| 5032 | // addition - they may not apply to other additions that can be |
| 5033 | // formed with operands from AddOps. |
| 5034 | const SCEV *RHS = getSCEV(BO->RHS); |
| 5035 | SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); |
| 5036 | if (Flags != SCEV::FlagAnyWrap) { |
| 5037 | const SCEV *LHS = getSCEV(BO->LHS); |
| 5038 | if (BO->Opcode == Instruction::Sub) |
| 5039 | AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); |
| 5040 | else |
| 5041 | AddOps.push_back(getAddExpr(LHS, RHS, Flags)); |
| 5042 | break; |
| 5043 | } |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 5044 | } |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5045 | |
| 5046 | if (BO->Opcode == Instruction::Sub) |
| 5047 | AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); |
| 5048 | else |
| 5049 | AddOps.push_back(getSCEV(BO->RHS)); |
| 5050 | |
Sanjoy Das | f49ca52 | 2016-05-29 00:34:42 +0000 | [diff] [blame] | 5051 | auto NewBO = MatchBinaryOp(BO->LHS, DT); |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5052 | if (!NewBO || (NewBO->Opcode != Instruction::Add && |
| 5053 | NewBO->Opcode != Instruction::Sub)) { |
| 5054 | AddOps.push_back(getSCEV(BO->LHS)); |
| 5055 | break; |
| 5056 | } |
| 5057 | BO = NewBO; |
| 5058 | } while (true); |
| 5059 | |
| 5060 | return getAddExpr(AddOps); |
| 5061 | } |
| 5062 | |
| 5063 | case Instruction::Mul: { |
| 5064 | SmallVector<const SCEV *, 4> MulOps; |
| 5065 | do { |
| 5066 | if (BO->Op) { |
| 5067 | if (auto *OpSCEV = getExistingSCEV(BO->Op)) { |
| 5068 | MulOps.push_back(OpSCEV); |
| 5069 | break; |
| 5070 | } |
| 5071 | |
| 5072 | SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); |
| 5073 | if (Flags != SCEV::FlagAnyWrap) { |
| 5074 | MulOps.push_back( |
| 5075 | getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); |
| 5076 | break; |
| 5077 | } |
| 5078 | } |
| 5079 | |
| 5080 | MulOps.push_back(getSCEV(BO->RHS)); |
Sanjoy Das | f49ca52 | 2016-05-29 00:34:42 +0000 | [diff] [blame] | 5081 | auto NewBO = MatchBinaryOp(BO->LHS, DT); |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5082 | if (!NewBO || NewBO->Opcode != Instruction::Mul) { |
| 5083 | MulOps.push_back(getSCEV(BO->LHS)); |
| 5084 | break; |
| 5085 | } |
NAKAMURA Takumi | 940cd93 | 2016-07-04 01:26:21 +0000 | [diff] [blame] | 5086 | BO = NewBO; |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5087 | } while (true); |
| 5088 | |
| 5089 | return getMulExpr(MulOps); |
| 5090 | } |
| 5091 | case Instruction::UDiv: |
| 5092 | return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); |
| 5093 | case Instruction::Sub: { |
| 5094 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; |
| 5095 | if (BO->Op) |
| 5096 | Flags = getNoWrapFlagsFromUB(BO->Op); |
| 5097 | return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); |
| 5098 | } |
| 5099 | case Instruction::And: |
| 5100 | // For an expression like x&255 that merely masks off the high bits, |
| 5101 | // use zext(trunc(x)) as the SCEV expression. |
| 5102 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { |
| 5103 | if (CI->isNullValue()) |
| 5104 | return getSCEV(BO->RHS); |
| 5105 | if (CI->isAllOnesValue()) |
| 5106 | return getSCEV(BO->LHS); |
| 5107 | const APInt &A = CI->getValue(); |
| 5108 | |
| 5109 | // Instcombine's ShrinkDemandedConstant may strip bits out of |
| 5110 | // constants, obscuring what would otherwise be a low-bits mask. |
| 5111 | // Use computeKnownBits to compute what ShrinkDemandedConstant |
| 5112 | // knew about to reconstruct a low-bits mask value. |
| 5113 | unsigned LZ = A.countLeadingZeros(); |
| 5114 | unsigned TZ = A.countTrailingZeros(); |
| 5115 | unsigned BitWidth = A.getBitWidth(); |
| 5116 | APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); |
| 5117 | computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(), |
| 5118 | 0, &AC, nullptr, &DT); |
| 5119 | |
| 5120 | APInt EffectiveMask = |
| 5121 | APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); |
| 5122 | if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) { |
| 5123 | const SCEV *MulCount = getConstant(ConstantInt::get( |
| 5124 | getContext(), APInt::getOneBitSet(BitWidth, TZ))); |
| 5125 | return getMulExpr( |
| 5126 | getZeroExtendExpr( |
| 5127 | getTruncateExpr( |
| 5128 | getUDivExactExpr(getSCEV(BO->LHS), MulCount), |
| 5129 | IntegerType::get(getContext(), BitWidth - LZ - TZ)), |
| 5130 | BO->LHS->getType()), |
| 5131 | MulCount); |
| 5132 | } |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 5133 | } |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5134 | break; |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 5135 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5136 | case Instruction::Or: |
| 5137 | // If the RHS of the Or is a constant, we may have something like: |
| 5138 | // X*4+1 which got turned into X*4|1. Handle this as an Add so loop |
| 5139 | // optimizations will transparently handle this case. |
| 5140 | // |
| 5141 | // In order for this transformation to be safe, the LHS must be of the |
| 5142 | // form X*(2^n) and the Or constant must be less than 2^n. |
| 5143 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { |
| 5144 | const SCEV *LHS = getSCEV(BO->LHS); |
| 5145 | const APInt &CIVal = CI->getValue(); |
| 5146 | if (GetMinTrailingZeros(LHS) >= |
| 5147 | (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { |
| 5148 | // Build a plain add SCEV. |
| 5149 | const SCEV *S = getAddExpr(LHS, getSCEV(CI)); |
| 5150 | // If the LHS of the add was an addrec and it has no-wrap flags, |
| 5151 | // transfer the no-wrap flags, since an or won't introduce a wrap. |
| 5152 | if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { |
| 5153 | const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); |
| 5154 | const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( |
| 5155 | OldAR->getNoWrapFlags()); |
| 5156 | } |
| 5157 | return S; |
| 5158 | } |
| 5159 | } |
| 5160 | break; |
Dan Gohman | 6350296e | 2009-05-18 16:29:04 +0000 | [diff] [blame] | 5161 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5162 | case Instruction::Xor: |
| 5163 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { |
| 5164 | // If the RHS of xor is -1, then this is a not operation. |
| 5165 | if (CI->isAllOnesValue()) |
| 5166 | return getNotSCEV(getSCEV(BO->LHS)); |
Dan Gohman | eddf771 | 2009-06-18 00:00:20 +0000 | [diff] [blame] | 5167 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5168 | // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. |
| 5169 | // This is a variant of the check for xor with -1, and it handles |
| 5170 | // the case where instcombine has trimmed non-demanded bits out |
| 5171 | // of an xor with -1. |
| 5172 | if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) |
| 5173 | if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) |
| 5174 | if (LBO->getOpcode() == Instruction::And && |
| 5175 | LCI->getValue() == CI->getValue()) |
| 5176 | if (const SCEVZeroExtendExpr *Z = |
| 5177 | dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { |
| 5178 | Type *UTy = BO->LHS->getType(); |
| 5179 | const SCEV *Z0 = Z->getOperand(); |
| 5180 | Type *Z0Ty = Z0->getType(); |
| 5181 | unsigned Z0TySize = getTypeSizeInBits(Z0Ty); |
Dan Gohman | eddf771 | 2009-06-18 00:00:20 +0000 | [diff] [blame] | 5182 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5183 | // If C is a low-bits mask, the zero extend is serving to |
| 5184 | // mask off the high bits. Complement the operand and |
| 5185 | // re-apply the zext. |
| 5186 | if (APIntOps::isMask(Z0TySize, CI->getValue())) |
| 5187 | return getZeroExtendExpr(getNotSCEV(Z0), UTy); |
| 5188 | |
| 5189 | // If C is a single bit, it may be in the sign-bit position |
| 5190 | // before the zero-extend. In this case, represent the xor |
| 5191 | // using an add, which is equivalent, and re-apply the zext. |
| 5192 | APInt Trunc = CI->getValue().trunc(Z0TySize); |
| 5193 | if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && |
| 5194 | Trunc.isSignBit()) |
| 5195 | return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), |
| 5196 | UTy); |
| 5197 | } |
| 5198 | } |
| 5199 | break; |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5200 | |
| 5201 | case Instruction::Shl: |
| 5202 | // Turn shift left of a constant amount into a multiply. |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5203 | if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { |
| 5204 | uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 5205 | |
| 5206 | // If the shift count is not less than the bitwidth, the result of |
| 5207 | // the shift is undefined. Don't try to analyze it, because the |
| 5208 | // resolution chosen here may differ from the resolution chosen in |
| 5209 | // other parts of the compiler. |
| 5210 | if (SA->getValue().uge(BitWidth)) |
| 5211 | break; |
| 5212 | |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 5213 | // It is currently not resolved how to interpret NSW for left |
| 5214 | // shift by BitWidth - 1, so we avoid applying flags in that |
| 5215 | // case. Remove this check (or this comment) once the situation |
| 5216 | // is resolved. See |
| 5217 | // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html |
| 5218 | // and http://reviews.llvm.org/D8890 . |
| 5219 | auto Flags = SCEV::FlagAnyWrap; |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5220 | if (BO->Op && SA->getValue().ult(BitWidth - 1)) |
| 5221 | Flags = getNoWrapFlagsFromUB(BO->Op); |
Bjarke Hammersholt Roune | 9791ed4 | 2015-08-14 22:45:26 +0000 | [diff] [blame] | 5222 | |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 5223 | Constant *X = ConstantInt::get(getContext(), |
Benjamin Kramer | fc3ea6f | 2013-07-11 16:05:50 +0000 | [diff] [blame] | 5224 | APInt::getOneBitSet(BitWidth, SA->getZExtValue())); |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5225 | return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5226 | } |
| 5227 | break; |
| 5228 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5229 | case Instruction::AShr: |
| 5230 | // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression. |
| 5231 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) |
| 5232 | if (Operator *L = dyn_cast<Operator>(BO->LHS)) |
| 5233 | if (L->getOpcode() == Instruction::Shl && |
| 5234 | L->getOperand(1) == BO->RHS) { |
| 5235 | uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType()); |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 5236 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5237 | // If the shift count is not less than the bitwidth, the result of |
| 5238 | // the shift is undefined. Don't try to analyze it, because the |
| 5239 | // resolution chosen here may differ from the resolution chosen in |
| 5240 | // other parts of the compiler. |
| 5241 | if (CI->getValue().uge(BitWidth)) |
| 5242 | break; |
Dan Gohman | acd700a | 2010-04-22 01:35:11 +0000 | [diff] [blame] | 5243 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5244 | uint64_t Amt = BitWidth - CI->getZExtValue(); |
| 5245 | if (Amt == BitWidth) |
| 5246 | return getSCEV(L->getOperand(0)); // shift by zero --> noop |
| 5247 | return getSignExtendExpr( |
| 5248 | getTruncateExpr(getSCEV(L->getOperand(0)), |
| 5249 | IntegerType::get(getContext(), Amt)), |
| 5250 | BO->LHS->getType()); |
| 5251 | } |
| 5252 | break; |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 5253 | } |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5254 | } |
Nick Lewycky | f5c547d | 2008-07-07 06:15:49 +0000 | [diff] [blame] | 5255 | |
Sanjoy Das | 2381fcd | 2016-03-29 16:40:44 +0000 | [diff] [blame] | 5256 | switch (U->getOpcode()) { |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5257 | case Instruction::Trunc: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5258 | return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5259 | |
| 5260 | case Instruction::ZExt: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5261 | return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5262 | |
| 5263 | case Instruction::SExt: |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5264 | return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5265 | |
| 5266 | case Instruction::BitCast: |
| 5267 | // BitCasts are no-op casts so we just eliminate the cast. |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 5268 | if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5269 | return getSCEV(U->getOperand(0)); |
| 5270 | break; |
| 5271 | |
Dan Gohman | e5e1b7b | 2010-02-01 18:27:38 +0000 | [diff] [blame] | 5272 | // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can |
| 5273 | // lead to pointer expressions which cannot safely be expanded to GEPs, |
| 5274 | // because ScalarEvolution doesn't respect the GEP aliasing rules when |
| 5275 | // simplifying integer expressions. |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 5276 | |
Dan Gohman | ee750d1 | 2009-05-08 20:26:55 +0000 | [diff] [blame] | 5277 | case Instruction::GetElementPtr: |
Dan Gohman | b256ccf | 2009-12-18 02:09:29 +0000 | [diff] [blame] | 5278 | return createNodeForGEP(cast<GEPOperator>(U)); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 5279 | |
Dan Gohman | 05e8973 | 2008-06-22 19:56:46 +0000 | [diff] [blame] | 5280 | case Instruction::PHI: |
| 5281 | return createNodeForPHI(cast<PHINode>(U)); |
| 5282 | |
| 5283 | case Instruction::Select: |
Sanjoy Das | d067134 | 2015-10-02 19:39:59 +0000 | [diff] [blame] | 5284 | // U can also be a select constant expr, which let fall through. Since |
| 5285 | // createNodeForSelect only works for a condition that is an `ICmpInst`, and |
| 5286 | // constant expressions cannot have instructions as operands, we'd have |
| 5287 | // returned getUnknown for a select constant expressions anyway. |
| 5288 | if (isa<Instruction>(U)) |
Sanjoy Das | 55015d2 | 2015-10-02 23:09:44 +0000 | [diff] [blame] | 5289 | return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), |
| 5290 | U->getOperand(1), U->getOperand(2)); |
Hal Finkel | e186deb | 2016-07-11 02:48:23 +0000 | [diff] [blame] | 5291 | break; |
| 5292 | |
| 5293 | case Instruction::Call: |
| 5294 | case Instruction::Invoke: |
| 5295 | if (Value *RV = CallSite(U).getReturnedArgOperand()) |
| 5296 | return getSCEV(RV); |
| 5297 | break; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5298 | } |
| 5299 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 5300 | return getUnknown(V); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5301 | } |
| 5302 | |
| 5303 | |
| 5304 | |
| 5305 | //===----------------------------------------------------------------------===// |
| 5306 | // Iteration Count Computation Code |
| 5307 | // |
| 5308 | |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5309 | unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) { |
| 5310 | if (BasicBlock *ExitingBB = L->getExitingBlock()) |
| 5311 | return getSmallConstantTripCount(L, ExitingBB); |
| 5312 | |
| 5313 | // No trip count information for multiple exits. |
| 5314 | return 0; |
| 5315 | } |
| 5316 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5317 | unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L, |
| 5318 | BasicBlock *ExitingBlock) { |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5319 | assert(ExitingBlock && "Must pass a non-null exiting block!"); |
| 5320 | assert(L->isLoopExiting(ExitingBlock) && |
| 5321 | "Exiting block must actually branch out of the loop!"); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5322 | const SCEVConstant *ExitCount = |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5323 | dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5324 | if (!ExitCount) |
| 5325 | return 0; |
| 5326 | |
| 5327 | ConstantInt *ExitConst = ExitCount->getValue(); |
| 5328 | |
| 5329 | // Guard against huge trip counts. |
| 5330 | if (ExitConst->getValue().getActiveBits() > 32) |
| 5331 | return 0; |
| 5332 | |
| 5333 | // In case of integer overflow, this returns 0, which is correct. |
| 5334 | return ((unsigned)ExitConst->getZExtValue()) + 1; |
| 5335 | } |
| 5336 | |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5337 | unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) { |
| 5338 | if (BasicBlock *ExitingBB = L->getExitingBlock()) |
| 5339 | return getSmallConstantTripMultiple(L, ExitingBB); |
| 5340 | |
| 5341 | // No trip multiple information for multiple exits. |
| 5342 | return 0; |
| 5343 | } |
| 5344 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5345 | /// Returns the largest constant divisor of the trip count of this loop as a |
| 5346 | /// normal unsigned value, if possible. This means that the actual trip count is |
| 5347 | /// always a multiple of the returned value (don't forget the trip count could |
| 5348 | /// very well be zero as well!). |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5349 | /// |
| 5350 | /// Returns 1 if the trip count is unknown or not guaranteed to be the |
| 5351 | /// multiple of a constant (which is also the case if the trip count is simply |
| 5352 | /// constant, use getSmallConstantTripCount for that case), Will also return 1 |
| 5353 | /// if the trip count is very large (>= 2^32). |
Andrew Trick | e81211f | 2012-01-11 06:52:55 +0000 | [diff] [blame] | 5354 | /// |
| 5355 | /// As explained in the comments for getSmallConstantTripCount, this assumes |
| 5356 | /// that control exits the loop via ExitingBlock. |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5357 | unsigned |
| 5358 | ScalarEvolution::getSmallConstantTripMultiple(Loop *L, |
| 5359 | BasicBlock *ExitingBlock) { |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 5360 | assert(ExitingBlock && "Must pass a non-null exiting block!"); |
| 5361 | assert(L->isLoopExiting(ExitingBlock) && |
| 5362 | "Exiting block must actually branch out of the loop!"); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5363 | const SCEV *ExitCount = getExitCount(L, ExitingBlock); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5364 | if (ExitCount == getCouldNotCompute()) |
| 5365 | return 1; |
| 5366 | |
| 5367 | // Get the trip count from the BE count by adding 1. |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 5368 | const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType())); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5369 | // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt |
| 5370 | // to factor simple cases. |
| 5371 | if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul)) |
| 5372 | TCMul = Mul->getOperand(0); |
| 5373 | |
| 5374 | const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul); |
| 5375 | if (!MulC) |
| 5376 | return 1; |
| 5377 | |
| 5378 | ConstantInt *Result = MulC->getValue(); |
| 5379 | |
Hal Finkel | 30bd934 | 2012-10-24 19:46:44 +0000 | [diff] [blame] | 5380 | // Guard against huge trip counts (this requires checking |
| 5381 | // for zero to handle the case where the trip count == -1 and the |
| 5382 | // addition wraps). |
| 5383 | if (!Result || Result->getValue().getActiveBits() > 32 || |
| 5384 | Result->getValue().getActiveBits() == 0) |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 5385 | return 1; |
| 5386 | |
| 5387 | return (unsigned)Result->getZExtValue(); |
| 5388 | } |
| 5389 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5390 | /// Get the expression for the number of loop iterations for which this loop is |
| 5391 | /// guaranteed not to exit via ExitingBlock. Otherwise return |
| 5392 | /// SCEVCouldNotCompute. |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5393 | const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) { |
| 5394 | return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5395 | } |
| 5396 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5397 | const SCEV * |
| 5398 | ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, |
| 5399 | SCEVUnionPredicate &Preds) { |
| 5400 | return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds); |
| 5401 | } |
| 5402 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5403 | const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5404 | return getBackedgeTakenInfo(L).getExact(this); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5405 | } |
| 5406 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5407 | /// Similar to getBackedgeTakenCount, except return the least SCEV value that is |
| 5408 | /// known never to be less than the actual backedge taken count. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5409 | const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5410 | return getBackedgeTakenInfo(L).getMax(this); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5411 | } |
| 5412 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5413 | /// 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] | 5414 | static void |
| 5415 | PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { |
| 5416 | BasicBlock *Header = L->getHeader(); |
| 5417 | |
| 5418 | // Push all Loop-header PHIs onto the Worklist stack. |
| 5419 | for (BasicBlock::iterator I = Header->begin(); |
| 5420 | PHINode *PN = dyn_cast<PHINode>(I); ++I) |
| 5421 | Worklist.push_back(PN); |
| 5422 | } |
| 5423 | |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5424 | const ScalarEvolution::BackedgeTakenInfo & |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5425 | ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { |
| 5426 | auto &BTI = getBackedgeTakenInfo(L); |
| 5427 | if (BTI.hasFullInfo()) |
| 5428 | return BTI; |
| 5429 | |
| 5430 | auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); |
| 5431 | |
| 5432 | if (!Pair.second) |
| 5433 | return Pair.first->second; |
| 5434 | |
| 5435 | BackedgeTakenInfo Result = |
| 5436 | computeBackedgeTakenCount(L, /*AllowPredicates=*/true); |
| 5437 | |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5438 | return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5439 | } |
| 5440 | |
| 5441 | const ScalarEvolution::BackedgeTakenInfo & |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5442 | ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5443 | // Initially insert an invalid entry for this loop. If the insertion |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 5444 | // succeeds, proceed to actually compute a backedge-taken count and |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 5445 | // update the value. The temporary CouldNotCompute value tells SCEV |
| 5446 | // code elsewhere that it shouldn't attempt to request a new |
| 5447 | // backedge-taken count, which could result in infinite recursion. |
Dan Gohman | 0daf687 | 2011-05-09 18:44:09 +0000 | [diff] [blame] | 5448 | std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 5449 | BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5450 | if (!Pair.second) |
| 5451 | return Pair.first->second; |
Dan Gohman | 7646637 | 2009-04-27 20:16:15 +0000 | [diff] [blame] | 5452 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5453 | // computeBackedgeTakenCount may allocate memory for its result. Inserting it |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5454 | // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result |
| 5455 | // must be cleared in this scope. |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5456 | BackedgeTakenInfo Result = computeBackedgeTakenCount(L); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5457 | |
| 5458 | if (Result.getExact(this) != getCouldNotCompute()) { |
| 5459 | assert(isLoopInvariant(Result.getExact(this), L) && |
| 5460 | isLoopInvariant(Result.getMax(this), L) && |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5461 | "Computed backedge-taken count isn't loop invariant for loop!"); |
| 5462 | ++NumTripCountsComputed; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5463 | } |
| 5464 | else if (Result.getMax(this) == getCouldNotCompute() && |
| 5465 | isa<PHINode>(L->getHeader()->begin())) { |
| 5466 | // Only count loops that have phi nodes as not being computable. |
| 5467 | ++NumTripCountsNotComputed; |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5468 | } |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 5469 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5470 | // Now that we know more about the trip count for this loop, forget any |
| 5471 | // existing SCEV values for PHI nodes in this loop since they are only |
| 5472 | // conservative estimates made without the benefit of trip count |
| 5473 | // information. This is similar to the code in forgetLoop, except that |
| 5474 | // it handles SCEVUnknown PHI nodes specially. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5475 | if (Result.hasAnyInfo()) { |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5476 | SmallVector<Instruction *, 16> Worklist; |
| 5477 | PushLoopPHIs(L, Worklist); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5478 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5479 | SmallPtrSet<Instruction *, 8> Visited; |
| 5480 | while (!Worklist.empty()) { |
| 5481 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5482 | if (!Visited.insert(I).second) |
| 5483 | continue; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5484 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5485 | ValueExprMapType::iterator It = |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 5486 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5487 | if (It != ValueExprMap.end()) { |
| 5488 | const SCEV *Old = It->second; |
Dan Gohman | 761065e | 2010-11-17 02:44:44 +0000 | [diff] [blame] | 5489 | |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5490 | // SCEVUnknown for a PHI either means that it has an unrecognized |
| 5491 | // structure, or it's a PHI that's in the progress of being computed |
| 5492 | // by createNodeForPHI. In the former case, additional loop trip |
| 5493 | // count information isn't going to change anything. In the later |
| 5494 | // case, createNodeForPHI will perform the necessary updates on its |
| 5495 | // own when it gets to that point. |
| 5496 | if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 5497 | eraseValueFromMap(It->first); |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5498 | forgetMemoizedResults(Old); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5499 | } |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5500 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5501 | ConstantEvolutionLoopExitValue.erase(PN); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5502 | } |
Chris Lattner | a337f5e | 2011-01-09 02:16:18 +0000 | [diff] [blame] | 5503 | |
| 5504 | PushDefUseChildren(I, Worklist); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5505 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5506 | } |
Dan Gohman | 6acd95b | 2011-04-25 22:48:29 +0000 | [diff] [blame] | 5507 | |
| 5508 | // Re-lookup the insert position, since the call to |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5509 | // computeBackedgeTakenCount above could result in a |
Dan Gohman | 6acd95b | 2011-04-25 22:48:29 +0000 | [diff] [blame] | 5510 | // recusive call to getBackedgeTakenInfo (on a different |
| 5511 | // loop), which would invalidate the iterator computed |
| 5512 | // earlier. |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5513 | return BackedgeTakenCounts.find(L)->second = std::move(Result); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5514 | } |
| 5515 | |
Dan Gohman | 880c92a | 2009-10-31 15:04:55 +0000 | [diff] [blame] | 5516 | void ScalarEvolution::forgetLoop(const Loop *L) { |
| 5517 | // Drop any stored trip count value. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5518 | auto RemoveLoopFromBackedgeMap = |
| 5519 | [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { |
| 5520 | auto BTCPos = Map.find(L); |
| 5521 | if (BTCPos != Map.end()) { |
| 5522 | BTCPos->second.clear(); |
| 5523 | Map.erase(BTCPos); |
| 5524 | } |
| 5525 | }; |
| 5526 | |
| 5527 | RemoveLoopFromBackedgeMap(BackedgeTakenCounts); |
| 5528 | RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts); |
Dan Gohman | f150572 | 2009-05-02 17:43:35 +0000 | [diff] [blame] | 5529 | |
Dan Gohman | 880c92a | 2009-10-31 15:04:55 +0000 | [diff] [blame] | 5530 | // Drop information about expressions based on loop-header PHIs. |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5531 | SmallVector<Instruction *, 16> Worklist; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5532 | PushLoopPHIs(L, Worklist); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5533 | |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5534 | SmallPtrSet<Instruction *, 8> Visited; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5535 | while (!Worklist.empty()) { |
| 5536 | Instruction *I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5537 | if (!Visited.insert(I).second) |
| 5538 | continue; |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5539 | |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 5540 | ValueExprMapType::iterator It = |
| 5541 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 5542 | if (It != ValueExprMap.end()) { |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 5543 | eraseValueFromMap(It->first); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 5544 | forgetMemoizedResults(It->second); |
Dan Gohman | dc19104 | 2009-07-08 19:23:34 +0000 | [diff] [blame] | 5545 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5546 | ConstantEvolutionLoopExitValue.erase(PN); |
| 5547 | } |
| 5548 | |
| 5549 | PushDefUseChildren(I, Worklist); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 5550 | } |
Dan Gohman | dcb354b | 2010-10-29 20:16:10 +0000 | [diff] [blame] | 5551 | |
| 5552 | // Forget all contained loops too, to avoid dangling entries in the |
| 5553 | // ValuesAtScopes map. |
Benjamin Kramer | aa20915 | 2016-06-26 17:27:42 +0000 | [diff] [blame] | 5554 | for (Loop *I : *L) |
| 5555 | forgetLoop(I); |
Sanjoy Das | 7e4a641 | 2016-05-29 00:32:17 +0000 | [diff] [blame] | 5556 | |
Sanjoy Das | 5603fc0 | 2016-09-26 02:44:07 +0000 | [diff] [blame] | 5557 | LoopPropertiesCache.erase(L); |
Dan Gohman | 4330034 | 2009-02-17 20:49:49 +0000 | [diff] [blame] | 5558 | } |
| 5559 | |
Eric Christopher | ef6d593 | 2010-07-29 01:25:38 +0000 | [diff] [blame] | 5560 | void ScalarEvolution::forgetValue(Value *V) { |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 5561 | Instruction *I = dyn_cast<Instruction>(V); |
| 5562 | if (!I) return; |
| 5563 | |
| 5564 | // Drop information about expressions based on loop-header PHIs. |
| 5565 | SmallVector<Instruction *, 16> Worklist; |
| 5566 | Worklist.push_back(I); |
| 5567 | |
| 5568 | SmallPtrSet<Instruction *, 8> Visited; |
| 5569 | while (!Worklist.empty()) { |
| 5570 | I = Worklist.pop_back_val(); |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 5571 | if (!Visited.insert(I).second) |
| 5572 | continue; |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 5573 | |
Benjamin Kramer | e2ef47c | 2012-06-30 22:37:15 +0000 | [diff] [blame] | 5574 | ValueExprMapType::iterator It = |
| 5575 | ValueExprMap.find_as(static_cast<Value *>(I)); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 5576 | if (It != ValueExprMap.end()) { |
Wei Mi | 785858c | 2016-08-09 20:37:50 +0000 | [diff] [blame] | 5577 | eraseValueFromMap(It->first); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 5578 | forgetMemoizedResults(It->second); |
Dale Johannesen | 1d6827a | 2010-02-19 07:14:22 +0000 | [diff] [blame] | 5579 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 5580 | ConstantEvolutionLoopExitValue.erase(PN); |
| 5581 | } |
| 5582 | |
| 5583 | PushDefUseChildren(I, Worklist); |
| 5584 | } |
| 5585 | } |
| 5586 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5587 | /// Get the exact loop backedge taken count considering all loop exits. A |
| 5588 | /// computable result can only be returned for loops with a single exit. |
| 5589 | /// Returning the minimum taken count among all exits is incorrect because one |
| 5590 | /// of the loop's exit limit's may have been skipped. howFarToZero assumes that |
| 5591 | /// the limit of each loop test is never skipped. This is a valid assumption as |
| 5592 | /// long as the loop exits via that test. For precise results, it is the |
| 5593 | /// caller's responsibility to specify the relevant loop exit using |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5594 | /// getExact(ExitingBlock, SE). |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5595 | const SCEV * |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5596 | ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE, |
| 5597 | SCEVUnionPredicate *Preds) const { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5598 | // If any exits were not computable, the loop is not computable. |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5599 | if (!isComplete() || ExitNotTaken.empty()) |
| 5600 | return SE->getCouldNotCompute(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5601 | |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5602 | const SCEV *BECount = nullptr; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5603 | for (auto &ENT : ExitNotTaken) { |
| 5604 | assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5605 | |
| 5606 | if (!BECount) |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5607 | BECount = ENT.ExactNotTaken; |
| 5608 | else if (BECount != ENT.ExactNotTaken) |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5609 | return SE->getCouldNotCompute(); |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5610 | if (Preds && !ENT.hasAlwaysTruePredicate()) |
| 5611 | Preds->add(ENT.Predicate.get()); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5612 | |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5613 | assert((Preds || ENT.hasAlwaysTruePredicate()) && |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5614 | "Predicate should be always true!"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5615 | } |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5616 | |
Andrew Trick | bbb226a | 2011-09-02 21:20:46 +0000 | [diff] [blame] | 5617 | assert(BECount && "Invalid not taken count for loop exit"); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5618 | return BECount; |
| 5619 | } |
| 5620 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5621 | /// Get the exact not taken count for this loop exit. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5622 | const SCEV * |
Andrew Trick | 77c5542 | 2011-08-02 04:23:35 +0000 | [diff] [blame] | 5623 | ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5624 | ScalarEvolution *SE) const { |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5625 | for (auto &ENT : ExitNotTaken) |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5626 | if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5627 | return ENT.ExactNotTaken; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5628 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5629 | return SE->getCouldNotCompute(); |
| 5630 | } |
| 5631 | |
| 5632 | /// getMax - Get the max backedge taken count for the loop. |
| 5633 | const SCEV * |
| 5634 | ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { |
Sanjoy Das | 7326861 | 2016-09-26 01:10:22 +0000 | [diff] [blame] | 5635 | auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { |
| 5636 | return !ENT.hasAlwaysTruePredicate(); |
| 5637 | }; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5638 | |
Sanjoy Das | 7326861 | 2016-09-26 01:10:22 +0000 | [diff] [blame] | 5639 | if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) |
| 5640 | return SE->getCouldNotCompute(); |
| 5641 | |
| 5642 | return getMax(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5643 | } |
| 5644 | |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 5645 | bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, |
| 5646 | ScalarEvolution *SE) const { |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5647 | if (getMax() && getMax() != SE->getCouldNotCompute() && |
| 5648 | SE->hasOperand(getMax(), S)) |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 5649 | return true; |
| 5650 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5651 | for (auto &ENT : ExitNotTaken) |
| 5652 | if (ENT.ExactNotTaken != SE->getCouldNotCompute() && |
| 5653 | SE->hasOperand(ENT.ExactNotTaken, S)) |
Silviu Baranga | a393baf | 2016-04-06 14:06:32 +0000 | [diff] [blame] | 5654 | return true; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5655 | |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 5656 | return false; |
| 5657 | } |
| 5658 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5659 | /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each |
| 5660 | /// computable exit into a persistent ExitNotTakenInfo array. |
| 5661 | ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( |
Sanjoy Das | 5c4869b | 2016-09-26 01:10:27 +0000 | [diff] [blame] | 5662 | SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> |
| 5663 | &&ExitCounts, |
Sanjoy Das | 6b76cdf | 2016-09-26 01:10:25 +0000 | [diff] [blame] | 5664 | bool Complete, const SCEV *MaxCount) |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5665 | : MaxAndComplete(MaxCount, Complete) { |
Sanjoy Das | 6b76cdf | 2016-09-26 01:10:25 +0000 | [diff] [blame] | 5666 | typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; |
Sanjoy Das | e935c77 | 2016-09-25 23:12:08 +0000 | [diff] [blame] | 5667 | ExitNotTaken.reserve(ExitCounts.size()); |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5668 | std::transform( |
| 5669 | ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), |
Sanjoy Das | 6b76cdf | 2016-09-26 01:10:25 +0000 | [diff] [blame] | 5670 | [&](const EdgeExitInfo &EEI) { |
Sanjoy Das | c9bbf56 | 2016-09-25 23:12:04 +0000 | [diff] [blame] | 5671 | BasicBlock *ExitBB = EEI.first; |
| 5672 | const ExitLimit &EL = EEI.second; |
| 5673 | if (EL.Predicate.isAlwaysTrue()) |
| 5674 | return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr); |
| 5675 | return ExitNotTakenInfo( |
| 5676 | ExitBB, EL.ExactNotTaken, |
| 5677 | llvm::make_unique<SCEVUnionPredicate>(std::move(EL.Predicate))); |
| 5678 | }); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5679 | } |
| 5680 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5681 | /// Invalidate this result and free the ExitNotTakenInfo array. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5682 | void ScalarEvolution::BackedgeTakenInfo::clear() { |
Sanjoy Das | d1eb62a | 2016-09-25 23:12:00 +0000 | [diff] [blame] | 5683 | ExitNotTaken.clear(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5684 | } |
| 5685 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 5686 | /// 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] | 5687 | ScalarEvolution::BackedgeTakenInfo |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5688 | ScalarEvolution::computeBackedgeTakenCount(const Loop *L, |
| 5689 | bool AllowPredicates) { |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 5690 | SmallVector<BasicBlock *, 8> ExitingBlocks; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5691 | L->getExitingBlocks(ExitingBlocks); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5692 | |
Sanjoy Das | 6b76cdf | 2016-09-26 01:10:25 +0000 | [diff] [blame] | 5693 | typedef ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo EdgeExitInfo; |
| 5694 | |
| 5695 | SmallVector<EdgeExitInfo, 4> ExitCounts; |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5696 | bool CouldComputeBECount = true; |
Andrew Trick | ee5aa7f | 2014-01-15 06:42:11 +0000 | [diff] [blame] | 5697 | BasicBlock *Latch = L->getLoopLatch(); // may be NULL. |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5698 | const SCEV *MustExitMaxBECount = nullptr; |
| 5699 | const SCEV *MayExitMaxBECount = nullptr; |
| 5700 | |
| 5701 | // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts |
| 5702 | // and compute maxBECount. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5703 | // Do a union of all the predicates here. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5704 | for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5705 | BasicBlock *ExitBB = ExitingBlocks[i]; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5706 | ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); |
| 5707 | |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5708 | assert((AllowPredicates || EL.Predicate.isAlwaysTrue()) && |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5709 | "Predicated exit limit when predicates are not allowed!"); |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5710 | |
| 5711 | // 1. For each exit that can be computed, add an entry to ExitCounts. |
| 5712 | // CouldComputeBECount is true only if all exits can be computed. |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5713 | if (EL.ExactNotTaken == getCouldNotCompute()) |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5714 | // We couldn't compute an exact value for this exit, so |
Dan Gohman | 8885b37 | 2009-06-22 21:10:22 +0000 | [diff] [blame] | 5715 | // 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] | 5716 | CouldComputeBECount = false; |
| 5717 | else |
Sanjoy Das | bdd9710 | 2016-09-25 23:11:55 +0000 | [diff] [blame] | 5718 | ExitCounts.emplace_back(ExitBB, EL); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5719 | |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5720 | // 2. Derive the loop's MaxBECount from each exit's max number of |
| 5721 | // non-exiting iterations. Partition the loop exits into two kinds: |
| 5722 | // LoopMustExits and LoopMayExits. |
| 5723 | // |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5724 | // If the exit dominates the loop latch, it is a LoopMustExit otherwise it |
| 5725 | // is a LoopMayExit. If any computable LoopMustExit is found, then |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5726 | // MaxBECount is the minimum EL.MaxNotTaken of computable |
| 5727 | // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum |
| 5728 | // EL.MaxNotTaken, where CouldNotCompute is considered greater than any |
| 5729 | // computable EL.MaxNotTaken. |
| 5730 | if (EL.MaxNotTaken != getCouldNotCompute() && Latch && |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 5731 | DT.dominates(ExitBB, Latch)) { |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5732 | if (!MustExitMaxBECount) |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5733 | MustExitMaxBECount = EL.MaxNotTaken; |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5734 | else { |
| 5735 | MustExitMaxBECount = |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5736 | getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); |
Andrew Trick | e255359 | 2014-05-22 00:37:03 +0000 | [diff] [blame] | 5737 | } |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5738 | } else if (MayExitMaxBECount != getCouldNotCompute()) { |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5739 | if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) |
| 5740 | MayExitMaxBECount = EL.MaxNotTaken; |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5741 | else { |
| 5742 | MayExitMaxBECount = |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5743 | getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5744 | } |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 5745 | } |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5746 | } |
Andrew Trick | 839e30b | 2014-05-23 19:47:13 +0000 | [diff] [blame] | 5747 | const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : |
| 5748 | (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); |
Sanjoy Das | 5c4869b | 2016-09-26 01:10:27 +0000 | [diff] [blame] | 5749 | return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, |
| 5750 | MaxBECount); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5751 | } |
| 5752 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5753 | ScalarEvolution::ExitLimit |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5754 | ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, |
| 5755 | bool AllowPredicates) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5756 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5757 | // Okay, we've chosen an exiting block. See what condition causes us to exit |
| 5758 | // 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] | 5759 | // lead to the loop header. |
| 5760 | bool MustExecuteLoopHeader = true; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 5761 | BasicBlock *Exit = nullptr; |
Sanjoy Das | 0ff0787 | 2016-01-19 20:53:46 +0000 | [diff] [blame] | 5762 | for (auto *SBB : successors(ExitingBlock)) |
| 5763 | if (!L->contains(SBB)) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5764 | if (Exit) // Multiple exit successors. |
| 5765 | return getCouldNotCompute(); |
Sanjoy Das | 0ff0787 | 2016-01-19 20:53:46 +0000 | [diff] [blame] | 5766 | Exit = SBB; |
| 5767 | } else if (SBB != L->getHeader()) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5768 | MustExecuteLoopHeader = false; |
| 5769 | } |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 5770 | |
Chris Lattner | 1895485 | 2007-01-07 02:24:26 +0000 | [diff] [blame] | 5771 | // At this point, we know we have a conditional branch that determines whether |
| 5772 | // the loop is exited. However, we don't know if the branch is executed each |
| 5773 | // time through the loop. If not, then the execution count of the branch will |
| 5774 | // not be equal to the trip count of the loop. |
| 5775 | // |
| 5776 | // Currently we check for this by checking to see if the Exit branch goes to |
| 5777 | // 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] | 5778 | // 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] | 5779 | // loop header. This is common for un-rotated loops. |
| 5780 | // |
| 5781 | // If both of those tests fail, walk up the unique predecessor chain to the |
| 5782 | // header, stopping if there is an edge that doesn't exit the loop. If the |
| 5783 | // header is reached, the execution count of the branch will be equal to the |
| 5784 | // trip count of the loop. |
| 5785 | // |
| 5786 | // More extensive analysis could be done to handle more cases here. |
| 5787 | // |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5788 | if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5789 | // The simple checks failed, try climbing the unique predecessor chain |
| 5790 | // up to the header. |
| 5791 | bool Ok = false; |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5792 | for (BasicBlock *BB = ExitingBlock; BB; ) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5793 | BasicBlock *Pred = BB->getUniquePredecessor(); |
| 5794 | if (!Pred) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5795 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5796 | TerminatorInst *PredTerm = Pred->getTerminator(); |
Pete Cooper | ebcd748 | 2015-08-06 20:22:46 +0000 | [diff] [blame] | 5797 | for (const BasicBlock *PredSucc : PredTerm->successors()) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5798 | if (PredSucc == BB) |
| 5799 | continue; |
| 5800 | // If the predecessor has a successor that isn't BB and isn't |
| 5801 | // outside the loop, assume the worst. |
| 5802 | if (L->contains(PredSucc)) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5803 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5804 | } |
| 5805 | if (Pred == L->getHeader()) { |
| 5806 | Ok = true; |
| 5807 | break; |
| 5808 | } |
| 5809 | BB = Pred; |
| 5810 | } |
| 5811 | if (!Ok) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5812 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5813 | } |
| 5814 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5815 | bool IsOnlyExit = (L->getExitingBlock() != nullptr); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5816 | TerminatorInst *Term = ExitingBlock->getTerminator(); |
| 5817 | if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { |
| 5818 | assert(BI->isConditional() && "If unconditional, it can't be in loop!"); |
| 5819 | // Proceed to the next level to examine the exit condition expression. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5820 | return computeExitLimitFromCond( |
| 5821 | L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1), |
| 5822 | /*ControlsExit=*/IsOnlyExit, AllowPredicates); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5823 | } |
| 5824 | |
| 5825 | if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5826 | return computeExitLimitFromSingleExitSwitch(L, SI, Exit, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 5827 | /*ControlsExit=*/IsOnlyExit); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 5828 | |
| 5829 | return getCouldNotCompute(); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5830 | } |
| 5831 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5832 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5833 | ScalarEvolution::computeExitLimitFromCond(const Loop *L, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5834 | Value *ExitCond, |
| 5835 | BasicBlock *TBB, |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5836 | BasicBlock *FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5837 | bool ControlsExit, |
| 5838 | bool AllowPredicates) { |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 5839 | // 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] | 5840 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { |
| 5841 | if (BO->getOpcode() == Instruction::And) { |
| 5842 | // Recurse on the operands of the and. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5843 | bool EitherMayExit = L->contains(TBB); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5844 | ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5845 | ControlsExit && !EitherMayExit, |
| 5846 | AllowPredicates); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5847 | ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5848 | ControlsExit && !EitherMayExit, |
| 5849 | AllowPredicates); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5850 | const SCEV *BECount = getCouldNotCompute(); |
| 5851 | const SCEV *MaxBECount = getCouldNotCompute(); |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5852 | if (EitherMayExit) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5853 | // Both conditions must be true for the loop to continue executing. |
| 5854 | // Choose the less conservative count. |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5855 | if (EL0.ExactNotTaken == getCouldNotCompute() || |
| 5856 | EL1.ExactNotTaken == getCouldNotCompute()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5857 | BECount = getCouldNotCompute(); |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5858 | else |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5859 | BECount = |
| 5860 | getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); |
| 5861 | if (EL0.MaxNotTaken == getCouldNotCompute()) |
| 5862 | MaxBECount = EL1.MaxNotTaken; |
| 5863 | else if (EL1.MaxNotTaken == getCouldNotCompute()) |
| 5864 | MaxBECount = EL0.MaxNotTaken; |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5865 | else |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5866 | MaxBECount = |
| 5867 | getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5868 | } else { |
Dan Gohman | f7495f2 | 2010-08-11 00:12:36 +0000 | [diff] [blame] | 5869 | // Both conditions must be true at the same time for the loop to exit. |
| 5870 | // For now, be conservative. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5871 | assert(L->contains(FBB) && "Loop block has no successor in loop!"); |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5872 | if (EL0.MaxNotTaken == EL1.MaxNotTaken) |
| 5873 | MaxBECount = EL0.MaxNotTaken; |
| 5874 | if (EL0.ExactNotTaken == EL1.ExactNotTaken) |
| 5875 | BECount = EL0.ExactNotTaken; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5876 | } |
| 5877 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5878 | SCEVUnionPredicate NP; |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5879 | NP.add(&EL0.Predicate); |
| 5880 | NP.add(&EL1.Predicate); |
Sanjoy Das | 29a4b5d | 2016-01-19 20:53:51 +0000 | [diff] [blame] | 5881 | // There are cases (e.g. PR26207) where computeExitLimitFromCond is able |
| 5882 | // to be more aggressive when computing BECount than when computing |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5883 | // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and |
| 5884 | // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken |
| 5885 | // to not. |
Sanjoy Das | 29a4b5d | 2016-01-19 20:53:51 +0000 | [diff] [blame] | 5886 | if (isa<SCEVCouldNotCompute>(MaxBECount) && |
| 5887 | !isa<SCEVCouldNotCompute>(BECount)) |
| 5888 | MaxBECount = BECount; |
| 5889 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5890 | return ExitLimit(BECount, MaxBECount, NP); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5891 | } |
| 5892 | if (BO->getOpcode() == Instruction::Or) { |
| 5893 | // Recurse on the operands of the or. |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5894 | bool EitherMayExit = L->contains(FBB); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5895 | ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5896 | ControlsExit && !EitherMayExit, |
| 5897 | AllowPredicates); |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5898 | ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5899 | ControlsExit && !EitherMayExit, |
| 5900 | AllowPredicates); |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5901 | const SCEV *BECount = getCouldNotCompute(); |
| 5902 | const SCEV *MaxBECount = getCouldNotCompute(); |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5903 | if (EitherMayExit) { |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5904 | // Both conditions must be false for the loop to continue executing. |
| 5905 | // Choose the less conservative count. |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5906 | if (EL0.ExactNotTaken == getCouldNotCompute() || |
| 5907 | EL1.ExactNotTaken == getCouldNotCompute()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 5908 | BECount = getCouldNotCompute(); |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5909 | else |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5910 | BECount = |
| 5911 | getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); |
| 5912 | if (EL0.MaxNotTaken == getCouldNotCompute()) |
| 5913 | MaxBECount = EL1.MaxNotTaken; |
| 5914 | else if (EL1.MaxNotTaken == getCouldNotCompute()) |
| 5915 | MaxBECount = EL0.MaxNotTaken; |
Dan Gohman | ed62738 | 2009-06-22 15:09:28 +0000 | [diff] [blame] | 5916 | else |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5917 | MaxBECount = |
| 5918 | getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5919 | } else { |
Dan Gohman | f7495f2 | 2010-08-11 00:12:36 +0000 | [diff] [blame] | 5920 | // Both conditions must be false at the same time for the loop to exit. |
| 5921 | // For now, be conservative. |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5922 | assert(L->contains(TBB) && "Loop block has no successor in loop!"); |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5923 | if (EL0.MaxNotTaken == EL1.MaxNotTaken) |
| 5924 | MaxBECount = EL0.MaxNotTaken; |
| 5925 | if (EL0.ExactNotTaken == EL1.ExactNotTaken) |
| 5926 | BECount = EL0.ExactNotTaken; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5927 | } |
| 5928 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5929 | SCEVUnionPredicate NP; |
Sanjoy Das | 89eea6b | 2016-09-25 23:11:57 +0000 | [diff] [blame] | 5930 | NP.add(&EL0.Predicate); |
| 5931 | NP.add(&EL1.Predicate); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5932 | return ExitLimit(BECount, MaxBECount, NP); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5933 | } |
| 5934 | } |
| 5935 | |
| 5936 | // 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] | 5937 | // Proceed to the next level to examine the icmp. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5938 | if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { |
| 5939 | ExitLimit EL = |
| 5940 | computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit); |
| 5941 | if (EL.hasFullInfo() || !AllowPredicates) |
| 5942 | return EL; |
| 5943 | |
| 5944 | // Try again, but use SCEV predicates this time. |
| 5945 | return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit, |
| 5946 | /*AllowPredicates=*/true); |
| 5947 | } |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5948 | |
Dan Gohman | 6b1e2a8 | 2010-02-19 18:12:07 +0000 | [diff] [blame] | 5949 | // Check for a constant condition. These are normally stripped out by |
| 5950 | // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to |
| 5951 | // preserve the CFG and is temporarily leaving constant conditions |
| 5952 | // in place. |
| 5953 | if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { |
| 5954 | if (L->contains(FBB) == !CI->getZExtValue()) |
| 5955 | // The backedge is always taken. |
| 5956 | return getCouldNotCompute(); |
| 5957 | else |
| 5958 | // The backedge is never taken. |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 5959 | return getZero(CI->getType()); |
Dan Gohman | 6b1e2a8 | 2010-02-19 18:12:07 +0000 | [diff] [blame] | 5960 | } |
| 5961 | |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 5962 | // 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] | 5963 | return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5964 | } |
| 5965 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5966 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5967 | ScalarEvolution::computeExitLimitFromICmp(const Loop *L, |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5968 | ICmpInst *ExitCond, |
| 5969 | BasicBlock *TBB, |
Andrew Trick | 5b245a1 | 2013-05-31 06:43:25 +0000 | [diff] [blame] | 5970 | BasicBlock *FBB, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 5971 | bool ControlsExit, |
| 5972 | bool AllowPredicates) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5973 | |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5974 | // If the condition was exit on true, convert the condition to exit on false |
| 5975 | ICmpInst::Predicate Cond; |
Dan Gohman | 96212b6 | 2009-06-22 00:31:57 +0000 | [diff] [blame] | 5976 | if (!L->contains(FBB)) |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5977 | Cond = ExitCond->getPredicate(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5978 | else |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 5979 | Cond = ExitCond->getInversePredicate(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5980 | |
| 5981 | // Handle common loops like: for (X = "string"; *X; ++X) |
| 5982 | if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) |
| 5983 | if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 5984 | ExitLimit ItCnt = |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 5985 | computeLoadConstantCompareExitLimit(LI, RHS, L, Cond); |
Dan Gohman | ba82034 | 2010-02-24 17:31:30 +0000 | [diff] [blame] | 5986 | if (ItCnt.hasAnyInfo()) |
| 5987 | return ItCnt; |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 5988 | } |
| 5989 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 5990 | const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); |
| 5991 | const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5992 | |
| 5993 | // Try to evaluate any dependencies out of the loop. |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 5994 | LHS = getSCEVAtScope(LHS, L); |
| 5995 | RHS = getSCEVAtScope(RHS, L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 5996 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 5997 | // 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] | 5998 | // loop the predicate will return true for these inputs. |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 5999 | if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { |
Dan Gohman | dc5f5cb | 2008-09-16 18:52:57 +0000 | [diff] [blame] | 6000 | // If there is a loop-invariant, force it into the RHS. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6001 | std::swap(LHS, RHS); |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6002 | Cond = ICmpInst::getSwappedPredicate(Cond); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6003 | } |
| 6004 | |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 6005 | // Simplify the operands before analyzing them. |
| 6006 | (void)SimplifyICmpOperands(Cond, LHS, RHS); |
| 6007 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6008 | // If we have a comparison of a chrec against a constant, try to use value |
| 6009 | // ranges to answer this query. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6010 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) |
| 6011 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6012 | if (AddRec->getLoop() == L) { |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 6013 | // Form the constant range. |
| 6014 | ConstantRange CompRange( |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 6015 | ICmpInst::makeConstantRange(Cond, RHSC->getAPInt())); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6016 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6017 | const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); |
Eli Friedman | ebf98b0 | 2009-05-09 12:32:42 +0000 | [diff] [blame] | 6018 | if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6019 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6020 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6021 | switch (Cond) { |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6022 | case ICmpInst::ICMP_NE: { // while (X != Y) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6023 | // Convert to: while (X-Y != 0) |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 6024 | ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 6025 | AllowPredicates); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6026 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6027 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6028 | } |
Dan Gohman | 8a8ad7d | 2009-08-20 16:42:55 +0000 | [diff] [blame] | 6029 | case ICmpInst::ICMP_EQ: { // while (X == Y) |
| 6030 | // Convert to: while (X-Y == 0) |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 6031 | ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6032 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6033 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6034 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 6035 | case ICmpInst::ICMP_SLT: |
| 6036 | case ICmpInst::ICMP_ULT: { // while (X < Y) |
| 6037 | bool IsSigned = Cond == ICmpInst::ICMP_SLT; |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 6038 | ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 6039 | AllowPredicates); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6040 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 6041 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6042 | } |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 6043 | case ICmpInst::ICMP_SGT: |
| 6044 | case ICmpInst::ICMP_UGT: { // while (X > Y) |
| 6045 | bool IsSigned = Cond == ICmpInst::ICMP_SGT; |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 6046 | ExitLimit EL = |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 6047 | howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 6048 | AllowPredicates); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6049 | if (EL.hasAnyInfo()) return EL; |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 6050 | break; |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6051 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6052 | default: |
Chris Lattner | 0defaa1 | 2004-04-03 00:43:03 +0000 | [diff] [blame] | 6053 | break; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6054 | } |
Sanjoy Das | 0da2d14 | 2016-06-30 02:47:28 +0000 | [diff] [blame] | 6055 | |
| 6056 | auto *ExhaustiveCount = |
| 6057 | computeExitCountExhaustively(L, ExitCond, !L->contains(TBB)); |
| 6058 | |
| 6059 | if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) |
| 6060 | return ExhaustiveCount; |
| 6061 | |
| 6062 | return computeShiftCompareExitLimit(ExitCond->getOperand(0), |
| 6063 | ExitCond->getOperand(1), L, Cond); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6064 | } |
| 6065 | |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 6066 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 6067 | ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 6068 | SwitchInst *Switch, |
| 6069 | BasicBlock *ExitingBlock, |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 6070 | bool ControlsExit) { |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 6071 | assert(!L->contains(ExitingBlock) && "Not an exiting block!"); |
| 6072 | |
| 6073 | // Give up if the exit is the default dest of a switch. |
| 6074 | if (Switch->getDefaultDest() == ExitingBlock) |
| 6075 | return getCouldNotCompute(); |
| 6076 | |
| 6077 | assert(L->contains(Switch->getDefaultDest()) && |
| 6078 | "Default case must not exit the loop!"); |
| 6079 | const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); |
| 6080 | const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); |
| 6081 | |
| 6082 | // while (X != Y) --> while (X-Y != 0) |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 6083 | ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); |
Benjamin Kramer | 5a18854 | 2014-02-11 15:44:32 +0000 | [diff] [blame] | 6084 | if (EL.hasAnyInfo()) |
| 6085 | return EL; |
| 6086 | |
| 6087 | return getCouldNotCompute(); |
| 6088 | } |
| 6089 | |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6090 | static ConstantInt * |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 6091 | EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, |
| 6092 | ScalarEvolution &SE) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6093 | const SCEV *InVal = SE.getConstant(C); |
| 6094 | const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6095 | assert(isa<SCEVConstant>(Val) && |
| 6096 | "Evaluation of SCEV at constant didn't fold correctly?"); |
| 6097 | return cast<SCEVConstant>(Val)->getValue(); |
| 6098 | } |
| 6099 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 6100 | /// Given an exit condition of 'icmp op load X, cst', try to see if we can |
| 6101 | /// compute the backedge execution count. |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6102 | ScalarEvolution::ExitLimit |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 6103 | ScalarEvolution::computeLoadConstantCompareExitLimit( |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 6104 | LoadInst *LI, |
| 6105 | Constant *RHS, |
| 6106 | const Loop *L, |
| 6107 | ICmpInst::Predicate predicate) { |
| 6108 | |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6109 | if (LI->isVolatile()) return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6110 | |
| 6111 | // 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] | 6112 | // TODO: Use SCEV instead of manually grubbing with GEPs. |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6113 | GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6114 | if (!GEP) return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6115 | |
| 6116 | // Make sure that it is really a constant global we are gepping, with an |
| 6117 | // initializer, and make sure the first IDX is really 0. |
| 6118 | GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); |
Dan Gohman | 5d5bc6d | 2009-08-19 18:20:44 +0000 | [diff] [blame] | 6119 | if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6120 | GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || |
| 6121 | !cast<Constant>(GEP->getOperand(1))->isNullValue()) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6122 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6123 | |
| 6124 | // Okay, we allow one non-constant index into the GEP instruction. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6125 | Value *VarIdx = nullptr; |
Chris Lattner | e166a85 | 2012-01-24 05:49:24 +0000 | [diff] [blame] | 6126 | std::vector<Constant*> Indexes; |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6127 | unsigned VarIdxNum = 0; |
| 6128 | for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) |
| 6129 | if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { |
| 6130 | Indexes.push_back(CI); |
| 6131 | } else if (!isa<ConstantInt>(GEP->getOperand(i))) { |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6132 | if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6133 | VarIdx = GEP->getOperand(i); |
| 6134 | VarIdxNum = i-2; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6135 | Indexes.push_back(nullptr); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6136 | } |
| 6137 | |
Andrew Trick | 7004e4b | 2012-03-26 22:33:59 +0000 | [diff] [blame] | 6138 | // Loop-invariant loads may be a byproduct of loop optimization. Skip them. |
| 6139 | if (!VarIdx) |
| 6140 | return getCouldNotCompute(); |
| 6141 | |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6142 | // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. |
| 6143 | // Check to see if X is a loop variant variable value now. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6144 | const SCEV *Idx = getSCEV(VarIdx); |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 6145 | Idx = getSCEVAtScope(Idx, L); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6146 | |
| 6147 | // We can only recognize very limited forms of loop index expressions, in |
| 6148 | // particular, only affine AddRec's like {C1,+,C2}. |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 6149 | const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 6150 | if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6151 | !isa<SCEVConstant>(IdxExpr->getOperand(0)) || |
| 6152 | !isa<SCEVConstant>(IdxExpr->getOperand(1))) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6153 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6154 | |
| 6155 | unsigned MaxSteps = MaxBruteForceIterations; |
| 6156 | for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 6157 | ConstantInt *ItCst = ConstantInt::get( |
Owen Anderson | b6b2530 | 2009-07-14 23:09:55 +0000 | [diff] [blame] | 6158 | cast<IntegerType>(IdxExpr->getType()), IterationNum); |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6159 | ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6160 | |
| 6161 | // Form the GEP offset. |
| 6162 | Indexes[VarIdxNum] = Val; |
| 6163 | |
Chris Lattner | e166a85 | 2012-01-24 05:49:24 +0000 | [diff] [blame] | 6164 | Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), |
| 6165 | Indexes); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6166 | if (!Result) break; // Cannot compute! |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6167 | |
| 6168 | // Evaluate the condition for this iteration. |
Reid Spencer | 266e42b | 2006-12-23 06:05:41 +0000 | [diff] [blame] | 6169 | Result = ConstantExpr::getICmp(predicate, Result, RHS); |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6170 | if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6171 | if (cast<ConstantInt>(Result)->getValue().isMinValue()) { |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6172 | ++NumArrayLenItCounts; |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6173 | return getConstant(ItCst); // Found terminating iteration! |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6174 | } |
| 6175 | } |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6176 | return getCouldNotCompute(); |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6177 | } |
| 6178 | |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 6179 | ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( |
| 6180 | Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { |
| 6181 | ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); |
| 6182 | if (!RHS) |
| 6183 | return getCouldNotCompute(); |
| 6184 | |
| 6185 | const BasicBlock *Latch = L->getLoopLatch(); |
| 6186 | if (!Latch) |
| 6187 | return getCouldNotCompute(); |
| 6188 | |
| 6189 | const BasicBlock *Predecessor = L->getLoopPredecessor(); |
| 6190 | if (!Predecessor) |
| 6191 | return getCouldNotCompute(); |
| 6192 | |
| 6193 | // Return true if V is of the form "LHS `shift_op` <positive constant>". |
| 6194 | // Return LHS in OutLHS and shift_opt in OutOpCode. |
| 6195 | auto MatchPositiveShift = |
| 6196 | [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { |
| 6197 | |
| 6198 | using namespace PatternMatch; |
| 6199 | |
| 6200 | ConstantInt *ShiftAmt; |
| 6201 | if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) |
| 6202 | OutOpCode = Instruction::LShr; |
| 6203 | else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) |
| 6204 | OutOpCode = Instruction::AShr; |
| 6205 | else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) |
| 6206 | OutOpCode = Instruction::Shl; |
| 6207 | else |
| 6208 | return false; |
| 6209 | |
| 6210 | return ShiftAmt->getValue().isStrictlyPositive(); |
| 6211 | }; |
| 6212 | |
| 6213 | // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in |
| 6214 | // |
| 6215 | // loop: |
| 6216 | // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] |
| 6217 | // %iv.shifted = lshr i32 %iv, <positive constant> |
| 6218 | // |
| 6219 | // Return true on a succesful match. Return the corresponding PHI node (%iv |
| 6220 | // above) in PNOut and the opcode of the shift operation in OpCodeOut. |
| 6221 | auto MatchShiftRecurrence = |
| 6222 | [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { |
| 6223 | Optional<Instruction::BinaryOps> PostShiftOpCode; |
| 6224 | |
| 6225 | { |
| 6226 | Instruction::BinaryOps OpC; |
| 6227 | Value *V; |
| 6228 | |
| 6229 | // If we encounter a shift instruction, "peel off" the shift operation, |
| 6230 | // and remember that we did so. Later when we inspect %iv's backedge |
| 6231 | // value, we will make sure that the backedge value uses the same |
| 6232 | // operation. |
| 6233 | // |
| 6234 | // Note: the peeled shift operation does not have to be the same |
| 6235 | // instruction as the one feeding into the PHI's backedge value. We only |
| 6236 | // really care about it being the same *kind* of shift instruction -- |
| 6237 | // that's all that is required for our later inferences to hold. |
| 6238 | if (MatchPositiveShift(LHS, V, OpC)) { |
| 6239 | PostShiftOpCode = OpC; |
| 6240 | LHS = V; |
| 6241 | } |
| 6242 | } |
| 6243 | |
| 6244 | PNOut = dyn_cast<PHINode>(LHS); |
| 6245 | if (!PNOut || PNOut->getParent() != L->getHeader()) |
| 6246 | return false; |
| 6247 | |
| 6248 | Value *BEValue = PNOut->getIncomingValueForBlock(Latch); |
| 6249 | Value *OpLHS; |
| 6250 | |
| 6251 | return |
| 6252 | // The backedge value for the PHI node must be a shift by a positive |
| 6253 | // amount |
| 6254 | MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && |
| 6255 | |
| 6256 | // of the PHI node itself |
| 6257 | OpLHS == PNOut && |
| 6258 | |
| 6259 | // and the kind of shift should be match the kind of shift we peeled |
| 6260 | // off, if any. |
| 6261 | (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); |
| 6262 | }; |
| 6263 | |
| 6264 | PHINode *PN; |
| 6265 | Instruction::BinaryOps OpCode; |
| 6266 | if (!MatchShiftRecurrence(LHS, PN, OpCode)) |
| 6267 | return getCouldNotCompute(); |
| 6268 | |
| 6269 | const DataLayout &DL = getDataLayout(); |
| 6270 | |
| 6271 | // The key rationale for this optimization is that for some kinds of shift |
| 6272 | // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 |
| 6273 | // within a finite number of iterations. If the condition guarding the |
| 6274 | // backedge (in the sense that the backedge is taken if the condition is true) |
| 6275 | // is false for the value the shift recurrence stabilizes to, then we know |
| 6276 | // that the backedge is taken only a finite number of times. |
| 6277 | |
| 6278 | ConstantInt *StableValue = nullptr; |
| 6279 | switch (OpCode) { |
| 6280 | default: |
| 6281 | llvm_unreachable("Impossible case!"); |
| 6282 | |
| 6283 | case Instruction::AShr: { |
| 6284 | // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most |
| 6285 | // bitwidth(K) iterations. |
| 6286 | Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); |
| 6287 | bool KnownZero, KnownOne; |
| 6288 | ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr, |
| 6289 | Predecessor->getTerminator(), &DT); |
| 6290 | auto *Ty = cast<IntegerType>(RHS->getType()); |
| 6291 | if (KnownZero) |
| 6292 | StableValue = ConstantInt::get(Ty, 0); |
| 6293 | else if (KnownOne) |
| 6294 | StableValue = ConstantInt::get(Ty, -1, true); |
| 6295 | else |
| 6296 | return getCouldNotCompute(); |
| 6297 | |
| 6298 | break; |
| 6299 | } |
| 6300 | case Instruction::LShr: |
| 6301 | case Instruction::Shl: |
| 6302 | // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} |
| 6303 | // stabilize to 0 in at most bitwidth(K) iterations. |
| 6304 | StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); |
| 6305 | break; |
| 6306 | } |
| 6307 | |
| 6308 | auto *Result = |
| 6309 | ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); |
| 6310 | assert(Result->getType()->isIntegerTy(1) && |
| 6311 | "Otherwise cannot be an operand to a branch instruction"); |
| 6312 | |
| 6313 | if (Result->isZeroValue()) { |
| 6314 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
| 6315 | const SCEV *UpperBound = |
| 6316 | getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 6317 | SCEVUnionPredicate P; |
| 6318 | return ExitLimit(getCouldNotCompute(), UpperBound, P); |
Sanjoy Das | c88f5d3 | 2015-10-28 21:27:14 +0000 | [diff] [blame] | 6319 | } |
| 6320 | |
| 6321 | return getCouldNotCompute(); |
| 6322 | } |
Chris Lattner | ec901cc | 2004-10-12 01:49:27 +0000 | [diff] [blame] | 6323 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 6324 | /// Return true if we can constant fold an instruction of the specified type, |
| 6325 | /// assuming that all operands were constants. |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6326 | static bool CanConstantFold(const Instruction *I) { |
Reid Spencer | 2341c22 | 2007-02-02 02:16:23 +0000 | [diff] [blame] | 6327 | if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6328 | isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || |
| 6329 | isa<LoadInst>(I)) |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6330 | return true; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6331 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6332 | if (const CallInst *CI = dyn_cast<CallInst>(I)) |
| 6333 | if (const Function *F = CI->getCalledFunction()) |
Dan Gohman | a65951f | 2008-01-31 01:05:10 +0000 | [diff] [blame] | 6334 | return canConstantFoldCallTo(F); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6335 | return false; |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6336 | } |
| 6337 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6338 | /// Determine whether this instruction can constant evolve within this loop |
| 6339 | /// assuming its operands can all constant evolve. |
| 6340 | static bool canConstantEvolve(Instruction *I, const Loop *L) { |
| 6341 | // An instruction outside of the loop can't be derived from a loop PHI. |
| 6342 | if (!L->contains(I)) return false; |
| 6343 | |
| 6344 | if (isa<PHINode>(I)) { |
David Blaikie | 19ef0d3 | 2015-03-24 16:33:19 +0000 | [diff] [blame] | 6345 | // We don't currently keep track of the control flow needed to evaluate |
| 6346 | // PHIs, so we cannot handle PHIs inside of loops. |
| 6347 | return L->getHeader() == I->getParent(); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6348 | } |
| 6349 | |
| 6350 | // If we won't be able to constant fold this expression even if the operands |
| 6351 | // are constants, bail early. |
| 6352 | return CanConstantFold(I); |
| 6353 | } |
| 6354 | |
| 6355 | /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by |
| 6356 | /// recursing through each instruction operand until reaching a loop header phi. |
| 6357 | static PHINode * |
| 6358 | getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6359 | DenseMap<Instruction *, PHINode *> &PHIMap) { |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6360 | |
| 6361 | // Otherwise, we can evaluate this instruction if all of its operands are |
| 6362 | // constant or derived from a PHI node themselves. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6363 | PHINode *PHI = nullptr; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 6364 | for (Value *Op : UseInst->operands()) { |
| 6365 | if (isa<Constant>(Op)) continue; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6366 | |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 6367 | Instruction *OpInst = dyn_cast<Instruction>(Op); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6368 | if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6369 | |
| 6370 | PHINode *P = dyn_cast<PHINode>(OpInst); |
Andrew Trick | 3e8a576 | 2011-10-05 22:06:53 +0000 | [diff] [blame] | 6371 | if (!P) |
| 6372 | // If this operand is already visited, reuse the prior result. |
| 6373 | // We may have P != PHI if this is the deepest point at which the |
| 6374 | // inconsistent paths meet. |
| 6375 | P = PHIMap.lookup(OpInst); |
| 6376 | if (!P) { |
| 6377 | // Recurse and memoize the results, whether a phi is found or not. |
| 6378 | // This recursive call invalidates pointers into PHIMap. |
| 6379 | P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap); |
| 6380 | PHIMap[OpInst] = P; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6381 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6382 | if (!P) |
| 6383 | return nullptr; // Not evolving from PHI |
| 6384 | if (PHI && PHI != P) |
| 6385 | return nullptr; // Evolving from multiple different PHIs. |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6386 | PHI = P; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6387 | } |
| 6388 | // This is a expression evolving from a constant PHI! |
| 6389 | return PHI; |
| 6390 | } |
| 6391 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6392 | /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node |
| 6393 | /// in the loop that V is derived from. We allow arbitrary operations along the |
| 6394 | /// way, but the operands of an operation must either be constants or a value |
| 6395 | /// derived from a constant PHI. If this expression does not fit with these |
| 6396 | /// constraints, return null. |
| 6397 | static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6398 | Instruction *I = dyn_cast<Instruction>(V); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6399 | if (!I || !canConstantEvolve(I, L)) return nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6400 | |
Sanjoy Das | d295f2c | 2015-10-18 00:29:27 +0000 | [diff] [blame] | 6401 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6402 | return PN; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6403 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6404 | // Record non-constant instructions contained by the loop. |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6405 | DenseMap<Instruction *, PHINode *> PHIMap; |
| 6406 | return getConstantEvolvingPHIOperands(I, L, PHIMap); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6407 | } |
| 6408 | |
| 6409 | /// EvaluateExpression - Given an expression that passes the |
| 6410 | /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node |
| 6411 | /// in the loop has the value PHIVal. If we can't fold this expression for some |
| 6412 | /// reason, return null. |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6413 | static Constant *EvaluateExpression(Value *V, const Loop *L, |
| 6414 | DenseMap<Instruction *, Constant *> &Vals, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 6415 | const DataLayout &DL, |
Chad Rosier | e6de63d | 2011-12-01 21:29:16 +0000 | [diff] [blame] | 6416 | const TargetLibraryInfo *TLI) { |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6417 | // Convenient constant check, but redundant for recursive calls. |
Reid Spencer | 30d69a5 | 2004-07-18 00:18:30 +0000 | [diff] [blame] | 6418 | if (Constant *C = dyn_cast<Constant>(V)) return C; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +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) return nullptr; |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6421 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6422 | if (Constant *C = Vals.lookup(I)) return C; |
| 6423 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6424 | // An instruction inside the loop depends on a value outside the loop that we |
| 6425 | // 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] | 6426 | if (!canConstantEvolve(I, L)) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6427 | |
| 6428 | // An unmapped PHI can be due to a branch or another loop inside this loop, |
| 6429 | // or due to this not being the initial iteration through a loop where we |
| 6430 | // couldn't compute the evolution of this particular PHI last time. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6431 | if (isa<PHINode>(I)) return nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6432 | |
Dan Gohman | f820bd3 | 2010-06-22 13:15:46 +0000 | [diff] [blame] | 6433 | std::vector<Constant*> Operands(I->getNumOperands()); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6434 | |
| 6435 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6436 | Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); |
| 6437 | if (!Operand) { |
Nick Lewycky | a447e0f3 | 2011-10-14 09:38:46 +0000 | [diff] [blame] | 6438 | Operands[i] = dyn_cast<Constant>(I->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6439 | if (!Operands[i]) return nullptr; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6440 | continue; |
| 6441 | } |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 6442 | Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6443 | Vals[Operand] = C; |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6444 | if (!C) return nullptr; |
Andrew Trick | e9162f1 | 2011-10-05 05:58:49 +0000 | [diff] [blame] | 6445 | Operands[i] = C; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6446 | } |
| 6447 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6448 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Chris Lattner | cdfb80d | 2009-11-09 23:06:58 +0000 | [diff] [blame] | 6449 | return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], |
Rafael Espindola | 7c68beb | 2014-02-18 15:33:12 +0000 | [diff] [blame] | 6450 | Operands[1], DL, TLI); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6451 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
| 6452 | if (!LI->isVolatile()) |
Eduard Burtescu | 1423921 | 2016-01-22 01:17:26 +0000 | [diff] [blame] | 6453 | return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6454 | } |
Manuel Jacob | e902459 | 2016-01-21 06:33:22 +0000 | [diff] [blame] | 6455 | return ConstantFoldInstOperands(I, Operands, DL, TLI); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6456 | } |
| 6457 | |
Sanjoy Das | 52bfa0f | 2015-11-02 02:06:01 +0000 | [diff] [blame] | 6458 | |
| 6459 | // If every incoming value to PN except the one for BB is a specific Constant, |
| 6460 | // return that, else return nullptr. |
| 6461 | static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { |
| 6462 | Constant *IncomingVal = nullptr; |
| 6463 | |
| 6464 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 6465 | if (PN->getIncomingBlock(i) == BB) |
| 6466 | continue; |
| 6467 | |
| 6468 | auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); |
| 6469 | if (!CurrentVal) |
| 6470 | return nullptr; |
| 6471 | |
| 6472 | if (IncomingVal != CurrentVal) { |
| 6473 | if (IncomingVal) |
| 6474 | return nullptr; |
| 6475 | IncomingVal = CurrentVal; |
| 6476 | } |
| 6477 | } |
| 6478 | |
| 6479 | return IncomingVal; |
| 6480 | } |
| 6481 | |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6482 | /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is |
| 6483 | /// in the header of its containing loop, we know the loop executes a |
| 6484 | /// constant number of times, and the PHI node is just a recurrence |
| 6485 | /// involving constants, fold it. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6486 | Constant * |
| 6487 | ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 6488 | const APInt &BEs, |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6489 | const Loop *L) { |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6490 | auto I = ConstantEvolutionLoopExitValue.find(PN); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6491 | if (I != ConstantEvolutionLoopExitValue.end()) |
| 6492 | return I->second; |
| 6493 | |
Dan Gohman | 4ce1fb1 | 2010-04-08 23:03:40 +0000 | [diff] [blame] | 6494 | if (BEs.ugt(MaxBruteForceIterations)) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6495 | return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6496 | |
| 6497 | Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; |
| 6498 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6499 | DenseMap<Instruction *, Constant *> CurrentIterVals; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6500 | BasicBlock *Header = L->getHeader(); |
| 6501 | assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6502 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6503 | BasicBlock *Latch = L->getLoopLatch(); |
| 6504 | if (!Latch) |
| 6505 | return nullptr; |
| 6506 | |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6507 | for (auto &I : *Header) { |
| 6508 | PHINode *PHI = dyn_cast<PHINode>(&I); |
| 6509 | if (!PHI) break; |
Sanjoy Das | 52bfa0f | 2015-11-02 02:06:01 +0000 | [diff] [blame] | 6510 | auto *StartCST = getOtherIncomingValue(PHI, Latch); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6511 | if (!StartCST) continue; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6512 | CurrentIterVals[PHI] = StartCST; |
| 6513 | } |
| 6514 | if (!CurrentIterVals.count(PN)) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6515 | return RetVal = nullptr; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6516 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6517 | Value *BEValue = PN->getIncomingValueForBlock(Latch); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6518 | |
| 6519 | // Execute the loop symbolically to determine the exit value. |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6520 | if (BEs.getActiveBits() >= 32) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6521 | return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it! |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6522 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6523 | unsigned NumIterations = BEs.getZExtValue(); // must be in range |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6524 | unsigned IterationNum = 0; |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 6525 | const DataLayout &DL = getDataLayout(); |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6526 | for (; ; ++IterationNum) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6527 | if (IterationNum == NumIterations) |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6528 | return RetVal = CurrentIterVals[PN]; // Got exit value! |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6529 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6530 | // Compute the value of the PHIs for the next iteration. |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6531 | // EvaluateExpression adds non-phi values to the CurrentIterVals map. |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6532 | DenseMap<Instruction *, Constant *> NextIterVals; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 6533 | Constant *NextPHI = |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6534 | EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6535 | if (!NextPHI) |
| 6536 | return nullptr; // Couldn't evaluate! |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6537 | NextIterVals[PN] = NextPHI; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6538 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6539 | bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; |
| 6540 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6541 | // Also evaluate the other PHI nodes. However, we don't get to stop if we |
| 6542 | // cease to be able to evaluate one of them or if they stop evolving, |
| 6543 | // because that doesn't necessarily prevent us from computing PN. |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6544 | SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6545 | for (const auto &I : CurrentIterVals) { |
| 6546 | PHINode *PHI = dyn_cast<PHINode>(I.first); |
Nick Lewycky | 8e904de | 2011-10-24 05:51:01 +0000 | [diff] [blame] | 6547 | if (!PHI || PHI == PN || PHI->getParent() != Header) continue; |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6548 | PHIsToCompute.emplace_back(PHI, I.second); |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6549 | } |
| 6550 | // We use two distinct loops because EvaluateExpression may invalidate any |
| 6551 | // iterators into CurrentIterVals. |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6552 | for (const auto &I : PHIsToCompute) { |
| 6553 | PHINode *PHI = I.first; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6554 | Constant *&NextPHI = NextIterVals[PHI]; |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6555 | if (!NextPHI) { // Not already computed. |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6556 | Value *BEValue = PHI->getIncomingValueForBlock(Latch); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6557 | NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6558 | } |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6559 | if (NextPHI != I.second) |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6560 | StoppedEvolving = false; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6561 | } |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6562 | |
| 6563 | // If all entries in CurrentIterVals == NextIterVals then we can stop |
| 6564 | // iterating, the loop can't continue to change. |
| 6565 | if (StoppedEvolving) |
| 6566 | return RetVal = CurrentIterVals[PN]; |
| 6567 | |
Andrew Trick | 3a86ba7 | 2011-10-05 03:25:31 +0000 | [diff] [blame] | 6568 | CurrentIterVals.swap(NextIterVals); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6569 | } |
| 6570 | } |
| 6571 | |
Sanjoy Das | 413dbbb | 2015-10-08 18:46:59 +0000 | [diff] [blame] | 6572 | const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6573 | Value *Cond, |
| 6574 | bool ExitWhen) { |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6575 | PHINode *PN = getConstantEvolvingPHI(Cond, L); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6576 | if (!PN) return getCouldNotCompute(); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6577 | |
Dan Gohman | 866971e | 2010-06-19 14:17:24 +0000 | [diff] [blame] | 6578 | // If the loop is canonicalized, the PHI will have exactly two entries. |
| 6579 | // That's the only form we support here. |
| 6580 | if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); |
| 6581 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6582 | DenseMap<Instruction *, Constant *> CurrentIterVals; |
| 6583 | BasicBlock *Header = L->getHeader(); |
| 6584 | assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); |
| 6585 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6586 | BasicBlock *Latch = L->getLoopLatch(); |
| 6587 | assert(Latch && "Should follow from NumIncomingValues == 2!"); |
| 6588 | |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6589 | for (auto &I : *Header) { |
| 6590 | PHINode *PHI = dyn_cast<PHINode>(&I); |
| 6591 | if (!PHI) |
| 6592 | break; |
Sanjoy Das | 52bfa0f | 2015-11-02 02:06:01 +0000 | [diff] [blame] | 6593 | auto *StartCST = getOtherIncomingValue(PHI, Latch); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6594 | if (!StartCST) continue; |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6595 | CurrentIterVals[PHI] = StartCST; |
| 6596 | } |
| 6597 | if (!CurrentIterVals.count(PN)) |
| 6598 | return getCouldNotCompute(); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6599 | |
| 6600 | // Okay, we find a PHI node that defines the trip count of this loop. Execute |
| 6601 | // the loop symbolically to determine when the condition gets a value of |
| 6602 | // "ExitWhen". |
Andrew Trick | 90c7a10 | 2011-11-16 00:52:40 +0000 | [diff] [blame] | 6603 | unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 6604 | const DataLayout &DL = getDataLayout(); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6605 | for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6606 | auto *CondVal = dyn_cast_or_null<ConstantInt>( |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6607 | EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6608 | |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6609 | // Couldn't symbolically evaluate. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6610 | if (!CondVal) return getCouldNotCompute(); |
Zhou Sheng | 75b871f | 2007-01-11 12:24:14 +0000 | [diff] [blame] | 6611 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 6612 | if (CondVal->getValue() == uint64_t(ExitWhen)) { |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6613 | ++NumBruteForceTripCountsComputed; |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 6614 | return getConstant(Type::getInt32Ty(getContext()), IterationNum); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6615 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6616 | |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6617 | // Update all the PHI nodes for the next iteration. |
| 6618 | DenseMap<Instruction *, Constant *> NextIterVals; |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6619 | |
| 6620 | // Create a list of which PHIs we need to compute. We want to do this before |
| 6621 | // calling EvaluateExpression on them because that may invalidate iterators |
| 6622 | // into CurrentIterVals. |
| 6623 | SmallVector<PHINode *, 8> PHIsToCompute; |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6624 | for (const auto &I : CurrentIterVals) { |
| 6625 | PHINode *PHI = dyn_cast<PHINode>(I.first); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6626 | if (!PHI || PHI->getParent() != Header) continue; |
Nick Lewycky | d48ab84 | 2011-11-12 03:09:12 +0000 | [diff] [blame] | 6627 | PHIsToCompute.push_back(PHI); |
| 6628 | } |
Sanjoy Das | 4493b40 | 2015-10-07 17:38:25 +0000 | [diff] [blame] | 6629 | for (PHINode *PHI : PHIsToCompute) { |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6630 | Constant *&NextPHI = NextIterVals[PHI]; |
| 6631 | if (NextPHI) continue; // Already computed! |
| 6632 | |
Sanjoy Das | dd70996 | 2015-10-08 18:28:36 +0000 | [diff] [blame] | 6633 | Value *BEValue = PHI->getIncomingValueForBlock(Latch); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6634 | NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); |
Duncan Sands | a370f3e | 2011-10-25 12:28:52 +0000 | [diff] [blame] | 6635 | } |
| 6636 | CurrentIterVals.swap(NextIterVals); |
Chris Lattner | 4021d1a | 2004-04-17 18:36:24 +0000 | [diff] [blame] | 6637 | } |
| 6638 | |
| 6639 | // Too many iterations were needed to evaluate. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6640 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6641 | } |
| 6642 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6643 | const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 6644 | SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = |
| 6645 | ValuesAtScopes[V]; |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6646 | // 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] | 6647 | for (auto &LS : Values) |
| 6648 | if (LS.first == L) |
| 6649 | return LS.second ? LS.second : V; |
| 6650 | |
| 6651 | Values.emplace_back(L, nullptr); |
| 6652 | |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6653 | // Otherwise compute it. |
| 6654 | const SCEV *C = computeSCEVAtScope(V, L); |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 6655 | for (auto &LS : reverse(ValuesAtScopes[V])) |
| 6656 | if (LS.first == L) { |
| 6657 | LS.second = C; |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 6658 | break; |
| 6659 | } |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6660 | return C; |
| 6661 | } |
| 6662 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6663 | /// This builds up a Constant using the ConstantExpr interface. That way, we |
| 6664 | /// will return Constants for objects which aren't represented by a |
| 6665 | /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. |
| 6666 | /// Returns NULL if the SCEV isn't representable as a Constant. |
| 6667 | static Constant *BuildConstantFromSCEV(const SCEV *V) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 6668 | switch (static_cast<SCEVTypes>(V->getSCEVType())) { |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6669 | case scCouldNotCompute: |
| 6670 | case scAddRecExpr: |
| 6671 | break; |
| 6672 | case scConstant: |
| 6673 | return cast<SCEVConstant>(V)->getValue(); |
| 6674 | case scUnknown: |
| 6675 | return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); |
| 6676 | case scSignExtend: { |
| 6677 | const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); |
| 6678 | if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) |
| 6679 | return ConstantExpr::getSExt(CastOp, SS->getType()); |
| 6680 | break; |
| 6681 | } |
| 6682 | case scZeroExtend: { |
| 6683 | const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); |
| 6684 | if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) |
| 6685 | return ConstantExpr::getZExt(CastOp, SZ->getType()); |
| 6686 | break; |
| 6687 | } |
| 6688 | case scTruncate: { |
| 6689 | const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); |
| 6690 | if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) |
| 6691 | return ConstantExpr::getTrunc(CastOp, ST->getType()); |
| 6692 | break; |
| 6693 | } |
| 6694 | case scAddExpr: { |
| 6695 | const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); |
| 6696 | if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6697 | if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { |
| 6698 | unsigned AS = PTy->getAddressSpace(); |
| 6699 | Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); |
| 6700 | C = ConstantExpr::getBitCast(C, DestPtrTy); |
| 6701 | } |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6702 | for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { |
| 6703 | Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6704 | if (!C2) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6705 | |
| 6706 | // First pointer! |
| 6707 | if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6708 | unsigned AS = C2->getType()->getPointerAddressSpace(); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6709 | std::swap(C, C2); |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6710 | Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6711 | // The offsets have been converted to bytes. We can add bytes to an |
| 6712 | // i8* by GEP with the byte count in the first index. |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6713 | C = ConstantExpr::getBitCast(C, DestPtrTy); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6714 | } |
| 6715 | |
| 6716 | // Don't bother trying to sum two pointers. We probably can't |
| 6717 | // statically compute a load that results from it anyway. |
| 6718 | if (C2->getType()->isPointerTy()) |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6719 | return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6720 | |
Matt Arsenault | be18b8a | 2013-10-21 18:41:10 +0000 | [diff] [blame] | 6721 | if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { |
| 6722 | if (PTy->getElementType()->isStructTy()) |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6723 | C2 = ConstantExpr::getIntegerCast( |
| 6724 | C2, Type::getInt32Ty(C->getContext()), true); |
David Blaikie | 4a2e73b | 2015-04-02 18:55:32 +0000 | [diff] [blame] | 6725 | C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6726 | } else |
| 6727 | C = ConstantExpr::getAdd(C, C2); |
| 6728 | } |
| 6729 | return C; |
| 6730 | } |
| 6731 | break; |
| 6732 | } |
| 6733 | case scMulExpr: { |
| 6734 | const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); |
| 6735 | if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { |
| 6736 | // Don't bother with pointers at all. |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6737 | if (C->getType()->isPointerTy()) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6738 | for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { |
| 6739 | Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6740 | if (!C2 || C2->getType()->isPointerTy()) return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6741 | C = ConstantExpr::getMul(C, C2); |
| 6742 | } |
| 6743 | return C; |
| 6744 | } |
| 6745 | break; |
| 6746 | } |
| 6747 | case scUDivExpr: { |
| 6748 | const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); |
| 6749 | if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) |
| 6750 | if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) |
| 6751 | if (LHS->getType() == RHS->getType()) |
| 6752 | return ConstantExpr::getUDiv(LHS, RHS); |
| 6753 | break; |
| 6754 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 6755 | case scSMaxExpr: |
| 6756 | case scUMaxExpr: |
| 6757 | break; // TODO: smax, umax. |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6758 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6759 | return nullptr; |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6760 | } |
| 6761 | |
Dan Gohman | cc2f1eb | 2009-08-31 21:15:23 +0000 | [diff] [blame] | 6762 | const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6763 | if (isa<SCEVConstant>(V)) return V; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6764 | |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 6765 | // If this instruction is evolved from a constant-evolving PHI, compute the |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6766 | // exit value from the loop without using SCEVs. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6767 | if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6768 | if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6769 | const Loop *LI = this->LI[I->getParent()]; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6770 | if (LI && LI->getParentLoop() == L) // Looking for loop exit value. |
| 6771 | if (PHINode *PN = dyn_cast<PHINode>(I)) |
| 6772 | if (PN->getParent() == LI->getHeader()) { |
| 6773 | // Okay, there is no closed form solution for the PHI node. Check |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6774 | // to see if the loop that contains it has a known backedge-taken |
| 6775 | // count. If so, we may be able to force computation of the exit |
| 6776 | // value. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6777 | const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6778 | if (const SCEVConstant *BTCC = |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 6779 | dyn_cast<SCEVConstant>(BackedgeTakenCount)) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6780 | // Okay, we know how many times the containing loop executes. If |
| 6781 | // this is a constant evolving PHI node, get the final value at |
| 6782 | // the specified iteration number. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 6783 | Constant *RV = |
| 6784 | getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); |
Dan Gohman | 9d203c6 | 2009-06-29 21:31:18 +0000 | [diff] [blame] | 6785 | if (RV) return getSCEV(RV); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6786 | } |
| 6787 | } |
| 6788 | |
Reid Spencer | e6328ca | 2006-12-04 21:33:23 +0000 | [diff] [blame] | 6789 | // Okay, this is an expression that we cannot symbolically evaluate |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6790 | // 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] | 6791 | // the arguments into constants, and if so, try to constant propagate the |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6792 | // result. This is particularly useful for computing loop exit values. |
| 6793 | if (CanConstantFold(I)) { |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6794 | SmallVector<Constant *, 4> Operands; |
| 6795 | bool MadeImprovement = false; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 6796 | for (Value *Op : I->operands()) { |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6797 | if (Constant *C = dyn_cast<Constant>(Op)) { |
| 6798 | Operands.push_back(C); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6799 | continue; |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6800 | } |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6801 | |
| 6802 | // If any of the operands is non-constant and if they are |
| 6803 | // non-integer and non-pointer, don't even try to analyze them |
| 6804 | // with scev techniques. |
| 6805 | if (!isSCEVable(Op->getType())) |
| 6806 | return V; |
| 6807 | |
| 6808 | const SCEV *OrigV = getSCEV(Op); |
| 6809 | const SCEV *OpV = getSCEVAtScope(OrigV, L); |
| 6810 | MadeImprovement |= OrigV != OpV; |
| 6811 | |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6812 | Constant *C = BuildConstantFromSCEV(OpV); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6813 | if (!C) return V; |
| 6814 | if (C->getType() != Op->getType()) |
| 6815 | C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, |
| 6816 | Op->getType(), |
| 6817 | false), |
| 6818 | C, Op->getType()); |
| 6819 | Operands.push_back(C); |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6820 | } |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6821 | |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6822 | // Check to see if getSCEVAtScope actually made an improvement. |
| 6823 | if (MadeImprovement) { |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 6824 | Constant *C = nullptr; |
Sanjoy Das | 49edd3b | 2015-10-27 00:52:09 +0000 | [diff] [blame] | 6825 | const DataLayout &DL = getDataLayout(); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6826 | if (const CmpInst *CI = dyn_cast<CmpInst>(I)) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 6827 | C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 6828 | Operands[1], DL, &TLI); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6829 | else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { |
| 6830 | if (!LI->isVolatile()) |
Eduard Burtescu | 1423921 | 2016-01-22 01:17:26 +0000 | [diff] [blame] | 6831 | C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); |
Nick Lewycky | a6674c7 | 2011-10-22 19:58:20 +0000 | [diff] [blame] | 6832 | } else |
Manuel Jacob | e902459 | 2016-01-21 06:33:22 +0000 | [diff] [blame] | 6833 | C = ConstantFoldInstOperands(I, Operands, DL, &TLI); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6834 | if (!C) return V; |
Dan Gohman | 4aad750 | 2010-02-24 19:31:47 +0000 | [diff] [blame] | 6835 | return getSCEV(C); |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6836 | } |
Chris Lattner | dd73047 | 2004-04-17 22:58:41 +0000 | [diff] [blame] | 6837 | } |
| 6838 | } |
| 6839 | |
| 6840 | // This is some other type of SCEVUnknown, just return it. |
| 6841 | return V; |
| 6842 | } |
| 6843 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6844 | if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6845 | // Avoid performing the look-up in the common case where the specified |
| 6846 | // expression has no loop-variant portions. |
| 6847 | for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6848 | const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6849 | if (OpAtScope != Comm->getOperand(i)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6850 | // Okay, at least one of these operands is loop variant but might be |
| 6851 | // foldable. Build a new instance of the folded commutative expression. |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 6852 | SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), |
| 6853 | Comm->op_begin()+i); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6854 | NewOps.push_back(OpAtScope); |
| 6855 | |
| 6856 | for (++i; i != e; ++i) { |
| 6857 | OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6858 | NewOps.push_back(OpAtScope); |
| 6859 | } |
| 6860 | if (isa<SCEVAddExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6861 | return getAddExpr(NewOps); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 6862 | if (isa<SCEVMulExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6863 | return getMulExpr(NewOps); |
Nick Lewycky | cdb7e54 | 2007-11-25 22:41:31 +0000 | [diff] [blame] | 6864 | if (isa<SCEVSMaxExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6865 | return getSMaxExpr(NewOps); |
Nick Lewycky | 1c44ebc | 2008-02-20 06:48:22 +0000 | [diff] [blame] | 6866 | if (isa<SCEVUMaxExpr>(Comm)) |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6867 | return getUMaxExpr(NewOps); |
Torok Edwin | fbcc663 | 2009-07-14 16:55:14 +0000 | [diff] [blame] | 6868 | llvm_unreachable("Unknown commutative SCEV type!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6869 | } |
| 6870 | } |
| 6871 | // If we got here, all operands are loop invariant. |
| 6872 | return Comm; |
| 6873 | } |
| 6874 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6875 | if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6876 | const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); |
| 6877 | const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); |
Nick Lewycky | 5234830 | 2009-01-13 09:18:58 +0000 | [diff] [blame] | 6878 | if (LHS == Div->getLHS() && RHS == Div->getRHS()) |
| 6879 | return Div; // must be loop invariant |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6880 | return getUDivExpr(LHS, RHS); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6881 | } |
| 6882 | |
| 6883 | // If this is a loop recurrence for a loop that does not contain L, then we |
| 6884 | // are dealing with the final value computed by the loop. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6885 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6886 | // First, attempt to evaluate each operand. |
| 6887 | // Avoid performing the look-up in the common case where the specified |
| 6888 | // expression has no loop-variant portions. |
| 6889 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { |
| 6890 | const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); |
| 6891 | if (OpAtScope == AddRec->getOperand(i)) |
| 6892 | continue; |
| 6893 | |
| 6894 | // Okay, at least one of these operands is loop variant but might be |
| 6895 | // foldable. Build a new instance of the folded commutative expression. |
| 6896 | SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), |
| 6897 | AddRec->op_begin()+i); |
| 6898 | NewOps.push_back(OpAtScope); |
| 6899 | for (++i; i != e; ++i) |
| 6900 | NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); |
| 6901 | |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6902 | const SCEV *FoldedRec = |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 6903 | getAddRecExpr(NewOps, AddRec->getLoop(), |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6904 | AddRec->getNoWrapFlags(SCEV::FlagNW)); |
| 6905 | AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); |
Andrew Trick | 01eff82 | 2011-04-27 05:42:17 +0000 | [diff] [blame] | 6906 | // The addrec may be folded to a nonrecurrence, for example, if the |
| 6907 | // induction variable is multiplied by zero after constant folding. Go |
| 6908 | // ahead and return the folded value. |
Andrew Trick | 759ba08 | 2011-04-27 01:21:25 +0000 | [diff] [blame] | 6909 | if (!AddRec) |
| 6910 | return FoldedRec; |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6911 | break; |
| 6912 | } |
| 6913 | |
| 6914 | // If the scope is outside the addrec's loop, evaluate it by using the |
| 6915 | // loop exit value of the addrec. |
| 6916 | if (!AddRec->getLoop()->contains(L)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6917 | // To evaluate this recurrence, we need to know how many times the AddRec |
| 6918 | // loop iterates. Compute this now. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6919 | const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 6920 | if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 6921 | |
Eli Friedman | 61f6762 | 2008-08-04 23:49:06 +0000 | [diff] [blame] | 6922 | // Then, evaluate the AddRec. |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6923 | return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6924 | } |
Dan Gohman | ae36b1e | 2010-06-29 23:43:06 +0000 | [diff] [blame] | 6925 | |
Dan Gohman | 8ca0885 | 2009-05-24 23:25:42 +0000 | [diff] [blame] | 6926 | return AddRec; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6927 | } |
| 6928 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6929 | if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6930 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 6931 | if (Op == Cast->getOperand()) |
| 6932 | return Cast; // must be loop invariant |
| 6933 | return getZeroExtendExpr(Op, Cast->getType()); |
| 6934 | } |
| 6935 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6936 | if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6937 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 6938 | if (Op == Cast->getOperand()) |
| 6939 | return Cast; // must be loop invariant |
| 6940 | return getSignExtendExpr(Op, Cast->getType()); |
| 6941 | } |
| 6942 | |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 6943 | if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6944 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); |
Dan Gohman | 0098d01 | 2009-04-29 22:29:01 +0000 | [diff] [blame] | 6945 | if (Op == Cast->getOperand()) |
| 6946 | return Cast; // must be loop invariant |
| 6947 | return getTruncateExpr(Op, Cast->getType()); |
| 6948 | } |
| 6949 | |
Torok Edwin | fbcc663 | 2009-07-14 16:55:14 +0000 | [diff] [blame] | 6950 | llvm_unreachable("Unknown SCEV type!"); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 6951 | } |
| 6952 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6953 | const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 6954 | return getSCEVAtScope(getSCEV(V), L); |
| 6955 | } |
| 6956 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 6957 | /// Finds the minimum unsigned root of the following equation: |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6958 | /// |
| 6959 | /// A * X = B (mod N) |
| 6960 | /// |
| 6961 | /// where N = 2^BW and BW is the common bit width of A and B. The signedness of |
| 6962 | /// A and B isn't important. |
| 6963 | /// |
| 6964 | /// If the equation does not have a solution, SCEVCouldNotCompute is returned. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 6965 | static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B, |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6966 | ScalarEvolution &SE) { |
| 6967 | uint32_t BW = A.getBitWidth(); |
| 6968 | assert(BW == B.getBitWidth() && "Bit widths must be the same."); |
| 6969 | assert(A != 0 && "A must be non-zero."); |
| 6970 | |
| 6971 | // 1. D = gcd(A, N) |
| 6972 | // |
| 6973 | // The gcd of A and N may have only one prime factor: 2. The number of |
| 6974 | // trailing zeros in A is its multiplicity |
| 6975 | uint32_t Mult2 = A.countTrailingZeros(); |
| 6976 | // D = 2^Mult2 |
| 6977 | |
| 6978 | // 2. Check if B is divisible by D. |
| 6979 | // |
| 6980 | // B is divisible by D if and only if the multiplicity of prime factor 2 for B |
| 6981 | // is not less than multiplicity of this prime factor for D. |
| 6982 | if (B.countTrailingZeros() < Mult2) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 6983 | return SE.getCouldNotCompute(); |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6984 | |
| 6985 | // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic |
| 6986 | // modulo (N / D). |
| 6987 | // |
| 6988 | // (N / D) may need BW+1 bits in its representation. Hence, we'll use this |
| 6989 | // bit width during computations. |
| 6990 | APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D |
| 6991 | APInt Mod(BW + 1, 0); |
Jay Foad | 25a5e4c | 2010-12-01 08:53:58 +0000 | [diff] [blame] | 6992 | Mod.setBit(BW - Mult2); // Mod = N / D |
Wojciech Matyjewicz | f0d21cd | 2008-07-20 15:55:14 +0000 | [diff] [blame] | 6993 | APInt I = AD.multiplicativeInverse(Mod); |
| 6994 | |
| 6995 | // 4. Compute the minimum unsigned root of the equation: |
| 6996 | // I * (B / D) mod (N / D) |
| 6997 | APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod); |
| 6998 | |
| 6999 | // The result is guaranteed to be less than 2^BW so we may truncate it to BW |
| 7000 | // bits. |
| 7001 | return SE.getConstant(Result.trunc(BW)); |
| 7002 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7003 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 7004 | /// Find the roots of the quadratic equation for the given quadratic chrec |
| 7005 | /// {L,+,M,+,N}. This returns either the two roots (which might be the same) or |
| 7006 | /// two SCEVCouldNotCompute objects. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7007 | /// |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 7008 | static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>> |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 7009 | SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7010 | assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 7011 | const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); |
| 7012 | const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); |
| 7013 | const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7014 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7015 | // We currently can only solve this if the coefficients are constants. |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 7016 | if (!LC || !MC || !NC) |
| 7017 | return None; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7018 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7019 | uint32_t BitWidth = LC->getAPInt().getBitWidth(); |
| 7020 | const APInt &L = LC->getAPInt(); |
| 7021 | const APInt &M = MC->getAPInt(); |
| 7022 | const APInt &N = NC->getAPInt(); |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7023 | APInt Two(BitWidth, 2); |
| 7024 | APInt Four(BitWidth, 4); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7025 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 7026 | { |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7027 | using namespace APIntOps; |
Zhou Sheng | 2852d99 | 2007-04-07 17:48:27 +0000 | [diff] [blame] | 7028 | const APInt& C = L; |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7029 | // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C |
| 7030 | // The B coefficient is M-N/2 |
| 7031 | APInt B(M); |
| 7032 | B -= sdiv(N,Two); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7033 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7034 | // The A coefficient is N/2 |
Zhou Sheng | 2852d99 | 2007-04-07 17:48:27 +0000 | [diff] [blame] | 7035 | APInt A(N.sdiv(Two)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7036 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7037 | // Compute the B^2-4ac term. |
| 7038 | APInt SqrtTerm(B); |
| 7039 | SqrtTerm *= B; |
| 7040 | SqrtTerm -= Four * (A * C); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7041 | |
Nick Lewycky | fb78083 | 2012-08-01 09:14:36 +0000 | [diff] [blame] | 7042 | if (SqrtTerm.isNegative()) { |
| 7043 | // The loop is provably infinite. |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 7044 | return None; |
Nick Lewycky | fb78083 | 2012-08-01 09:14:36 +0000 | [diff] [blame] | 7045 | } |
| 7046 | |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7047 | // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest |
| 7048 | // integer value or else APInt::sqrt() will assert. |
| 7049 | APInt SqrtVal(SqrtTerm.sqrt()); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7050 | |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 7051 | // Compute the two solutions for the quadratic formula. |
Reid Spencer | 983e3b3 | 2007-03-01 07:25:48 +0000 | [diff] [blame] | 7052 | // The divisions must be performed as signed divisions. |
| 7053 | APInt NegB(-B); |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 7054 | APInt TwoA(A << 1); |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 7055 | if (TwoA.isMinValue()) |
| 7056 | return None; |
Nick Lewycky | 7b14e20 | 2008-11-03 02:43:49 +0000 | [diff] [blame] | 7057 | |
Owen Anderson | 47db941 | 2009-07-22 00:24:57 +0000 | [diff] [blame] | 7058 | LLVMContext &Context = SE.getContext(); |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 7059 | |
| 7060 | ConstantInt *Solution1 = |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 7061 | ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA)); |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 7062 | ConstantInt *Solution2 = |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 7063 | ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA)); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7064 | |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 7065 | return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)), |
| 7066 | cast<SCEVConstant>(SE.getConstant(Solution2))); |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 7067 | } // end APIntOps namespace |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7068 | } |
| 7069 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 7070 | ScalarEvolution::ExitLimit |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 7071 | ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7072 | bool AllowPredicates) { |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 7073 | |
| 7074 | // This is only used for loops with a "x != y" exit test. The exit condition |
| 7075 | // is now expressed as a single expression, V = x-y. So the exit test is |
| 7076 | // effectively V != 0. We know and take advantage of the fact that this |
| 7077 | // expression only being used in a comparison by zero context. |
| 7078 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7079 | SCEVUnionPredicate P; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7080 | // If the value is a constant |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 7081 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7082 | // If the value is already zero, the branch will execute zero times. |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 7083 | if (C->getValue()->isZero()) return C; |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7084 | return getCouldNotCompute(); // Otherwise it will loop infinitely. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7085 | } |
| 7086 | |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 7087 | const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7088 | if (!AddRec && AllowPredicates) |
| 7089 | // Try to make this an AddRec using runtime tests, in the first X |
| 7090 | // iterations of this loop, where X is the SCEV expression found by the |
| 7091 | // algorithm below. |
| 7092 | AddRec = convertSCEVToAddRecWithPredicates(V, L, P); |
| 7093 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7094 | if (!AddRec || AddRec->getLoop() != L) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7095 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7096 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7097 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of |
| 7098 | // the quadratic equation to solve it. |
| 7099 | if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 7100 | if (auto Roots = SolveQuadraticEquation(AddRec, *this)) { |
| 7101 | const SCEVConstant *R1 = Roots->first; |
| 7102 | const SCEVConstant *R2 = Roots->second; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7103 | // Pick the smallest positive root value. |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 7104 | if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( |
| 7105 | CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 7106 | if (!CB->getZExtValue()) |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 7107 | std::swap(R1, R2); // R1 is the minimum root now. |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 7108 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7109 | // We can only use this value if the chrec ends up with an exact zero |
| 7110 | // value at this index. When solving for "X*X != 5", for example, we |
| 7111 | // should not accept a root of 2. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 7112 | const SCEV *Val = AddRec->evaluateAtIteration(R1, *this); |
Dan Gohman | be928e3 | 2008-06-18 16:23:07 +0000 | [diff] [blame] | 7113 | if (Val->isZero()) |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7114 | return ExitLimit(R1, R1, P); // We found a quadratic root! |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7115 | } |
| 7116 | } |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7117 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7118 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7119 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7120 | // Otherwise we can only handle this if it is affine. |
| 7121 | if (!AddRec->isAffine()) |
| 7122 | return getCouldNotCompute(); |
| 7123 | |
| 7124 | // If this is an affine expression, the execution count of this branch is |
| 7125 | // the minimum unsigned root of the following equation: |
| 7126 | // |
| 7127 | // Start + Step*N = 0 (mod 2^BW) |
| 7128 | // |
| 7129 | // equivalent to: |
| 7130 | // |
| 7131 | // Step*N = -Start (mod 2^BW) |
| 7132 | // |
| 7133 | // where BW is the common bit width of Start and Step. |
| 7134 | |
| 7135 | // Get the initial value for the loop. |
| 7136 | const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); |
| 7137 | const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); |
| 7138 | |
| 7139 | // For now we handle only constant steps. |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7140 | // |
| 7141 | // TODO: Handle a nonconstant Step given AddRec<NUW>. If the |
| 7142 | // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap |
| 7143 | // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. |
| 7144 | // We have not yet seen any such cases. |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7145 | const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 7146 | if (!StepC || StepC->getValue()->equalsInt(0)) |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7147 | return getCouldNotCompute(); |
| 7148 | |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7149 | // For positive steps (counting up until unsigned overflow): |
| 7150 | // N = -Start/Step (as unsigned) |
| 7151 | // For negative steps (counting down to zero): |
| 7152 | // N = Start/-Step |
| 7153 | // First compute the unsigned distance from zero in the direction of Step. |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7154 | bool CountDown = StepC->getAPInt().isNegative(); |
Andrew Trick | f1781db | 2011-03-14 17:28:02 +0000 | [diff] [blame] | 7155 | const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7156 | |
| 7157 | // Handle unitary steps, which cannot wraparound. |
Andrew Trick | f1781db | 2011-03-14 17:28:02 +0000 | [diff] [blame] | 7158 | // 1*N = -Start; -1*N = Start (mod 2^BW), so: |
| 7159 | // N = Distance (as unsigned) |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 7160 | if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) { |
| 7161 | ConstantRange CR = getUnsignedRange(Start); |
| 7162 | const SCEV *MaxBECount; |
| 7163 | if (!CountDown && CR.getUnsignedMin().isMinValue()) |
| 7164 | // When counting up, the worst starting value is 1, not 0. |
| 7165 | MaxBECount = CR.getUnsignedMax().isMinValue() |
| 7166 | ? getConstant(APInt::getMinValue(CR.getBitWidth())) |
| 7167 | : getConstant(APInt::getMaxValue(CR.getBitWidth())); |
| 7168 | else |
| 7169 | MaxBECount = getConstant(CountDown ? CR.getUnsignedMax() |
| 7170 | : -CR.getUnsignedMin()); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7171 | return ExitLimit(Distance, MaxBECount, P); |
Nick Lewycky | 3155552 | 2011-10-03 07:10:45 +0000 | [diff] [blame] | 7172 | } |
Andrew Trick | 2a3b716 | 2011-03-09 17:23:39 +0000 | [diff] [blame] | 7173 | |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 7174 | // As a special case, handle the instance where Step is a positive power of |
| 7175 | // two. In this case, determining whether Step divides Distance evenly can be |
| 7176 | // done by counting and comparing the number of trailing zeros of Step and |
| 7177 | // Distance. |
| 7178 | if (!CountDown) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7179 | const APInt &StepV = StepC->getAPInt(); |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 7180 | // StepV.isPowerOf2() returns true if StepV is an positive power of two. It |
| 7181 | // also returns true if StepV is maximally negative (eg, INT_MIN), but that |
| 7182 | // case is not handled as this code is guarded by !CountDown. |
| 7183 | if (StepV.isPowerOf2() && |
Sanjoy Das | f3132d3 | 2015-09-10 05:27:38 +0000 | [diff] [blame] | 7184 | GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) { |
| 7185 | // Here we've constrained the equation to be of the form |
| 7186 | // |
| 7187 | // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0) |
| 7188 | // |
| 7189 | // where we're operating on a W bit wide integer domain and k is |
| 7190 | // non-negative. The smallest unsigned solution for X is the trip count. |
| 7191 | // |
| 7192 | // (0) is equivalent to: |
| 7193 | // |
| 7194 | // 2^(N + k) * Distance' - 2^N * X = L * 2^W |
| 7195 | // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N |
| 7196 | // <=> 2^k * Distance' - X = L * 2^(W - N) |
| 7197 | // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1) |
| 7198 | // |
| 7199 | // The smallest X satisfying (1) is unsigned remainder of dividing the LHS |
| 7200 | // by 2^(W - N). |
| 7201 | // |
| 7202 | // <=> X = 2^k * Distance' URem 2^(W - N) ... (2) |
| 7203 | // |
| 7204 | // E.g. say we're solving |
| 7205 | // |
| 7206 | // 2 * Val = 2 * X (in i8) ... (3) |
| 7207 | // |
| 7208 | // then from (2), we get X = Val URem i8 128 (k = 0 in this case). |
| 7209 | // |
| 7210 | // Note: It is tempting to solve (3) by setting X = Val, but Val is not |
| 7211 | // necessarily the smallest unsigned value of X that satisfies (3). |
| 7212 | // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3) |
| 7213 | // is i8 1, not i8 -127 |
| 7214 | |
| 7215 | const auto *ModuloResult = getUDivExactExpr(Distance, Step); |
| 7216 | |
| 7217 | // Since SCEV does not have a URem node, we construct one using a truncate |
| 7218 | // and a zero extend. |
| 7219 | |
| 7220 | unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros(); |
| 7221 | auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth); |
| 7222 | auto *WideTy = Distance->getType(); |
| 7223 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7224 | const SCEV *Limit = |
| 7225 | getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy); |
| 7226 | return ExitLimit(Limit, Limit, P); |
Sanjoy Das | f3132d3 | 2015-09-10 05:27:38 +0000 | [diff] [blame] | 7227 | } |
Mark Heffernan | acbed5e | 2014-12-15 21:19:53 +0000 | [diff] [blame] | 7228 | } |
Benjamin Kramer | e75eaca | 2014-03-25 16:25:12 +0000 | [diff] [blame] | 7229 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7230 | // If the condition controls loop exit (the loop exits only if the expression |
| 7231 | // is true) and the addition is no-wrap we can use unsigned divide to |
| 7232 | // compute the backedge count. In this case, the step may not divide the |
| 7233 | // distance, but we don't care because if the condition is "missed" the loop |
| 7234 | // will have undefined behavior due to wrapping. |
Sanjoy Das | c7f69b9 | 2016-06-09 01:13:59 +0000 | [diff] [blame] | 7235 | if (ControlsExit && AddRec->hasNoSelfWrap() && |
| 7236 | loopHasNoAbnormalExits(AddRec->getLoop())) { |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7237 | const SCEV *Exact = |
| 7238 | getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7239 | return ExitLimit(Exact, Exact, P); |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 7240 | } |
Benjamin Kramer | e75eaca | 2014-03-25 16:25:12 +0000 | [diff] [blame] | 7241 | |
Chris Lattner | dff679f | 2011-01-09 22:39:48 +0000 | [diff] [blame] | 7242 | // Then, try to solve the above equation provided that Start is constant. |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 7243 | if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) { |
| 7244 | const SCEV *E = SolveLinEquationWithOverflow( |
| 7245 | StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this); |
| 7246 | return ExitLimit(E, E, P); |
| 7247 | } |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7248 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7249 | } |
| 7250 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 7251 | ScalarEvolution::ExitLimit |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 7252 | ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7253 | // Loops that look like: while (X == 0) are very strange indeed. We don't |
| 7254 | // handle them yet except for the trivial case. This could be expanded in the |
| 7255 | // future as needed. |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7256 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7257 | // If the value is a constant, check to see if it is known to be non-zero |
| 7258 | // already. If so, the backedge will execute zero times. |
Dan Gohman | a30370b | 2009-05-04 22:02:23 +0000 | [diff] [blame] | 7259 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { |
Nick Lewycky | 5a3db14 | 2008-02-21 09:14:53 +0000 | [diff] [blame] | 7260 | if (!C->getValue()->isNullValue()) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 7261 | return getZero(C->getType()); |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7262 | return getCouldNotCompute(); // Otherwise it will loop infinitely. |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7263 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 7264 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7265 | // We could implement others, but I really doubt anyone writes loops like |
| 7266 | // this, and if they did, they would already be constant folded. |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 7267 | return getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 7268 | } |
| 7269 | |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 7270 | std::pair<BasicBlock *, BasicBlock *> |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 7271 | ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { |
Dan Gohman | fa066ef | 2009-04-30 20:48:53 +0000 | [diff] [blame] | 7272 | // If the block has a unique predecessor, then there is no path from the |
| 7273 | // predecessor to the block that does not go through the direct edge |
| 7274 | // from the predecessor to the block. |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7275 | if (BasicBlock *Pred = BB->getSinglePredecessor()) |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 7276 | return {Pred, BB}; |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7277 | |
| 7278 | // 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] | 7279 | // If the header has a unique predecessor outside the loop, it must be |
| 7280 | // a block that has exactly one successor that can reach the loop. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7281 | if (Loop *L = LI.getLoopFor(BB)) |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 7282 | return {L->getLoopPredecessor(), L->getHeader()}; |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7283 | |
Sanjoy Das | c42f7cc | 2016-02-20 01:35:56 +0000 | [diff] [blame] | 7284 | return {nullptr, nullptr}; |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 7285 | } |
| 7286 | |
Sanjoy Das | f857081 | 2016-05-29 00:38:22 +0000 | [diff] [blame] | 7287 | /// SCEV structural equivalence is usually sufficient for testing whether two |
| 7288 | /// expressions are equal, however for the purposes of looking for a condition |
| 7289 | /// guarding a loop, it can be useful to be a little more general, since a |
| 7290 | /// front-end may have replicated the controlling expression. |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7291 | /// |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 7292 | static bool HasSameValue(const SCEV *A, const SCEV *B) { |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7293 | // Quick check to see if they are the same SCEV. |
| 7294 | if (A == B) return true; |
| 7295 | |
Sanjoy Das | f1090b6 | 2015-09-27 21:09:48 +0000 | [diff] [blame] | 7296 | auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { |
| 7297 | // Not all instructions that are "identical" compute the same value. For |
| 7298 | // instance, two distinct alloca instructions allocating the same type are |
| 7299 | // identical and do not read memory; but compute distinct values. |
| 7300 | return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); |
| 7301 | }; |
| 7302 | |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7303 | // Otherwise, if they're both SCEVUnknown, it's possible that they hold |
| 7304 | // two different instructions with the same value. Check for this case. |
| 7305 | if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) |
| 7306 | if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) |
| 7307 | if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) |
| 7308 | if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) |
Sanjoy Das | f1090b6 | 2015-09-27 21:09:48 +0000 | [diff] [blame] | 7309 | if (ComputesEqualValues(AI, BI)) |
Dan Gohman | 450f4e0 | 2009-06-20 00:35:32 +0000 | [diff] [blame] | 7310 | return true; |
| 7311 | |
| 7312 | // Otherwise assume they may have a different value. |
| 7313 | return false; |
| 7314 | } |
| 7315 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7316 | bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7317 | const SCEV *&LHS, const SCEV *&RHS, |
| 7318 | unsigned Depth) { |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7319 | bool Changed = false; |
| 7320 | |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7321 | // If we hit the max recursion limit bail out. |
| 7322 | if (Depth >= 3) |
| 7323 | return false; |
| 7324 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7325 | // Canonicalize a constant to the right side. |
| 7326 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { |
| 7327 | // Check for both operands constant. |
| 7328 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { |
| 7329 | if (ConstantExpr::getICmp(Pred, |
| 7330 | LHSC->getValue(), |
| 7331 | RHSC->getValue())->isNullValue()) |
| 7332 | goto trivially_false; |
| 7333 | else |
| 7334 | goto trivially_true; |
| 7335 | } |
| 7336 | // Otherwise swap the operands to put the constant on the right. |
| 7337 | std::swap(LHS, RHS); |
| 7338 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7339 | Changed = true; |
| 7340 | } |
| 7341 | |
| 7342 | // 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] | 7343 | // addrec's loop, put the addrec on the left. Also make a dominance check, |
| 7344 | // as both operands could be addrecs loop-invariant in each other's loop. |
| 7345 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { |
| 7346 | const Loop *L = AR->getLoop(); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 7347 | if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7348 | std::swap(LHS, RHS); |
| 7349 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7350 | Changed = true; |
| 7351 | } |
Dan Gohman | df564ca | 2010-05-03 17:00:11 +0000 | [diff] [blame] | 7352 | } |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7353 | |
| 7354 | // If there's a constant operand, canonicalize comparisons with boundary |
| 7355 | // cases, and canonicalize *-or-equal comparisons to regular comparisons. |
| 7356 | if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7357 | const APInt &RA = RC->getAPInt(); |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7358 | switch (Pred) { |
| 7359 | default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); |
| 7360 | case ICmpInst::ICMP_EQ: |
| 7361 | case ICmpInst::ICMP_NE: |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7362 | // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. |
| 7363 | if (!RA) |
| 7364 | if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) |
| 7365 | if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0))) |
Benjamin Kramer | 406a2db | 2012-05-30 18:42:43 +0000 | [diff] [blame] | 7366 | if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && |
| 7367 | ME->getOperand(0)->isAllOnesValue()) { |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7368 | RHS = AE->getOperand(1); |
| 7369 | LHS = ME->getOperand(1); |
| 7370 | Changed = true; |
| 7371 | } |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7372 | break; |
| 7373 | case ICmpInst::ICMP_UGE: |
| 7374 | if ((RA - 1).isMinValue()) { |
| 7375 | Pred = ICmpInst::ICMP_NE; |
| 7376 | RHS = getConstant(RA - 1); |
| 7377 | Changed = true; |
| 7378 | break; |
| 7379 | } |
| 7380 | if (RA.isMaxValue()) { |
| 7381 | Pred = ICmpInst::ICMP_EQ; |
| 7382 | Changed = true; |
| 7383 | break; |
| 7384 | } |
| 7385 | if (RA.isMinValue()) goto trivially_true; |
| 7386 | |
| 7387 | Pred = ICmpInst::ICMP_UGT; |
| 7388 | RHS = getConstant(RA - 1); |
| 7389 | Changed = true; |
| 7390 | break; |
| 7391 | case ICmpInst::ICMP_ULE: |
| 7392 | if ((RA + 1).isMaxValue()) { |
| 7393 | Pred = ICmpInst::ICMP_NE; |
| 7394 | RHS = getConstant(RA + 1); |
| 7395 | Changed = true; |
| 7396 | break; |
| 7397 | } |
| 7398 | if (RA.isMinValue()) { |
| 7399 | Pred = ICmpInst::ICMP_EQ; |
| 7400 | Changed = true; |
| 7401 | break; |
| 7402 | } |
| 7403 | if (RA.isMaxValue()) goto trivially_true; |
| 7404 | |
| 7405 | Pred = ICmpInst::ICMP_ULT; |
| 7406 | RHS = getConstant(RA + 1); |
| 7407 | Changed = true; |
| 7408 | break; |
| 7409 | case ICmpInst::ICMP_SGE: |
| 7410 | if ((RA - 1).isMinSignedValue()) { |
| 7411 | Pred = ICmpInst::ICMP_NE; |
| 7412 | RHS = getConstant(RA - 1); |
| 7413 | Changed = true; |
| 7414 | break; |
| 7415 | } |
| 7416 | if (RA.isMaxSignedValue()) { |
| 7417 | Pred = ICmpInst::ICMP_EQ; |
| 7418 | Changed = true; |
| 7419 | break; |
| 7420 | } |
| 7421 | if (RA.isMinSignedValue()) goto trivially_true; |
| 7422 | |
| 7423 | Pred = ICmpInst::ICMP_SGT; |
| 7424 | RHS = getConstant(RA - 1); |
| 7425 | Changed = true; |
| 7426 | break; |
| 7427 | case ICmpInst::ICMP_SLE: |
| 7428 | if ((RA + 1).isMaxSignedValue()) { |
| 7429 | Pred = ICmpInst::ICMP_NE; |
| 7430 | RHS = getConstant(RA + 1); |
| 7431 | Changed = true; |
| 7432 | break; |
| 7433 | } |
| 7434 | if (RA.isMinSignedValue()) { |
| 7435 | Pred = ICmpInst::ICMP_EQ; |
| 7436 | Changed = true; |
| 7437 | break; |
| 7438 | } |
| 7439 | if (RA.isMaxSignedValue()) goto trivially_true; |
| 7440 | |
| 7441 | Pred = ICmpInst::ICMP_SLT; |
| 7442 | RHS = getConstant(RA + 1); |
| 7443 | Changed = true; |
| 7444 | break; |
| 7445 | case ICmpInst::ICMP_UGT: |
| 7446 | if (RA.isMinValue()) { |
| 7447 | Pred = ICmpInst::ICMP_NE; |
| 7448 | Changed = true; |
| 7449 | break; |
| 7450 | } |
| 7451 | if ((RA + 1).isMaxValue()) { |
| 7452 | Pred = ICmpInst::ICMP_EQ; |
| 7453 | RHS = getConstant(RA + 1); |
| 7454 | Changed = true; |
| 7455 | break; |
| 7456 | } |
| 7457 | if (RA.isMaxValue()) goto trivially_false; |
| 7458 | break; |
| 7459 | case ICmpInst::ICMP_ULT: |
| 7460 | if (RA.isMaxValue()) { |
| 7461 | Pred = ICmpInst::ICMP_NE; |
| 7462 | Changed = true; |
| 7463 | break; |
| 7464 | } |
| 7465 | if ((RA - 1).isMinValue()) { |
| 7466 | Pred = ICmpInst::ICMP_EQ; |
| 7467 | RHS = getConstant(RA - 1); |
| 7468 | Changed = true; |
| 7469 | break; |
| 7470 | } |
| 7471 | if (RA.isMinValue()) goto trivially_false; |
| 7472 | break; |
| 7473 | case ICmpInst::ICMP_SGT: |
| 7474 | if (RA.isMinSignedValue()) { |
| 7475 | Pred = ICmpInst::ICMP_NE; |
| 7476 | Changed = true; |
| 7477 | break; |
| 7478 | } |
| 7479 | if ((RA + 1).isMaxSignedValue()) { |
| 7480 | Pred = ICmpInst::ICMP_EQ; |
| 7481 | RHS = getConstant(RA + 1); |
| 7482 | Changed = true; |
| 7483 | break; |
| 7484 | } |
| 7485 | if (RA.isMaxSignedValue()) goto trivially_false; |
| 7486 | break; |
| 7487 | case ICmpInst::ICMP_SLT: |
| 7488 | if (RA.isMaxSignedValue()) { |
| 7489 | Pred = ICmpInst::ICMP_NE; |
| 7490 | Changed = true; |
| 7491 | break; |
| 7492 | } |
| 7493 | if ((RA - 1).isMinSignedValue()) { |
| 7494 | Pred = ICmpInst::ICMP_EQ; |
| 7495 | RHS = getConstant(RA - 1); |
| 7496 | Changed = true; |
| 7497 | break; |
| 7498 | } |
| 7499 | if (RA.isMinSignedValue()) goto trivially_false; |
| 7500 | break; |
| 7501 | } |
| 7502 | } |
| 7503 | |
| 7504 | // Check for obvious equality. |
| 7505 | if (HasSameValue(LHS, RHS)) { |
| 7506 | if (ICmpInst::isTrueWhenEqual(Pred)) |
| 7507 | goto trivially_true; |
| 7508 | if (ICmpInst::isFalseWhenEqual(Pred)) |
| 7509 | goto trivially_false; |
| 7510 | } |
| 7511 | |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7512 | // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by |
| 7513 | // adding or subtracting 1 from one of the operands. |
| 7514 | switch (Pred) { |
| 7515 | case ICmpInst::ICMP_SLE: |
| 7516 | if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) { |
| 7517 | RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7518 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7519 | Pred = ICmpInst::ICMP_SLT; |
| 7520 | Changed = true; |
| 7521 | } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7522 | LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7523 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7524 | Pred = ICmpInst::ICMP_SLT; |
| 7525 | Changed = true; |
| 7526 | } |
| 7527 | break; |
| 7528 | case ICmpInst::ICMP_SGE: |
| 7529 | if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7530 | RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7531 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7532 | Pred = ICmpInst::ICMP_SGT; |
| 7533 | Changed = true; |
| 7534 | } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) { |
| 7535 | LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7536 | SCEV::FlagNSW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7537 | Pred = ICmpInst::ICMP_SGT; |
| 7538 | Changed = true; |
| 7539 | } |
| 7540 | break; |
| 7541 | case ICmpInst::ICMP_ULE: |
| 7542 | if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7543 | RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7544 | SCEV::FlagNUW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7545 | Pred = ICmpInst::ICMP_ULT; |
| 7546 | Changed = true; |
| 7547 | } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) { |
Peter Collingbourne | c85f4ce | 2015-11-20 01:26:13 +0000 | [diff] [blame] | 7548 | LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7549 | Pred = ICmpInst::ICMP_ULT; |
| 7550 | Changed = true; |
| 7551 | } |
| 7552 | break; |
| 7553 | case ICmpInst::ICMP_UGE: |
| 7554 | if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) { |
Peter Collingbourne | c85f4ce | 2015-11-20 01:26:13 +0000 | [diff] [blame] | 7555 | RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7556 | Pred = ICmpInst::ICMP_UGT; |
| 7557 | Changed = true; |
| 7558 | } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) { |
Dan Gohman | 267700c | 2010-05-03 20:23:47 +0000 | [diff] [blame] | 7559 | LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 7560 | SCEV::FlagNUW); |
Dan Gohman | 81585c1 | 2010-05-03 16:35:17 +0000 | [diff] [blame] | 7561 | Pred = ICmpInst::ICMP_UGT; |
| 7562 | Changed = true; |
| 7563 | } |
| 7564 | break; |
| 7565 | default: |
| 7566 | break; |
| 7567 | } |
| 7568 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7569 | // TODO: More simplifications are possible here. |
| 7570 | |
Benjamin Kramer | 50b26eb | 2012-05-30 18:32:23 +0000 | [diff] [blame] | 7571 | // Recursively simplify until we either hit a recursion limit or nothing |
| 7572 | // changes. |
| 7573 | if (Changed) |
| 7574 | return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); |
| 7575 | |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7576 | return Changed; |
| 7577 | |
| 7578 | trivially_true: |
| 7579 | // Return 0 == 0. |
Benjamin Kramer | ddd1b7b | 2010-11-20 18:43:35 +0000 | [diff] [blame] | 7580 | LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7581 | Pred = ICmpInst::ICMP_EQ; |
| 7582 | return true; |
| 7583 | |
| 7584 | trivially_false: |
| 7585 | // Return 0 != 0. |
Benjamin Kramer | ddd1b7b | 2010-11-20 18:43:35 +0000 | [diff] [blame] | 7586 | LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); |
Dan Gohman | 48ff3cf | 2010-04-24 01:28:42 +0000 | [diff] [blame] | 7587 | Pred = ICmpInst::ICMP_NE; |
| 7588 | return true; |
| 7589 | } |
| 7590 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7591 | bool ScalarEvolution::isKnownNegative(const SCEV *S) { |
| 7592 | return getSignedRange(S).getSignedMax().isNegative(); |
| 7593 | } |
| 7594 | |
| 7595 | bool ScalarEvolution::isKnownPositive(const SCEV *S) { |
| 7596 | return getSignedRange(S).getSignedMin().isStrictlyPositive(); |
| 7597 | } |
| 7598 | |
| 7599 | bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { |
| 7600 | return !getSignedRange(S).getSignedMin().isNegative(); |
| 7601 | } |
| 7602 | |
| 7603 | bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { |
| 7604 | return !getSignedRange(S).getSignedMax().isStrictlyPositive(); |
| 7605 | } |
| 7606 | |
| 7607 | bool ScalarEvolution::isKnownNonZero(const SCEV *S) { |
| 7608 | return isKnownNegative(S) || isKnownPositive(S); |
| 7609 | } |
| 7610 | |
| 7611 | bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, |
| 7612 | const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | 36cce7e | 2010-04-24 01:38:36 +0000 | [diff] [blame] | 7613 | // Canonicalize the inputs first. |
| 7614 | (void)SimplifyICmpOperands(Pred, LHS, RHS); |
| 7615 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7616 | // If LHS or RHS is an addrec, check to see if the condition is true in |
| 7617 | // every iteration of the loop. |
Justin Bogner | cbb8438 | 2014-05-23 00:06:56 +0000 | [diff] [blame] | 7618 | // If LHS and RHS are both addrec, both conditions must be true in |
| 7619 | // every iteration of the loop. |
| 7620 | const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); |
| 7621 | const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); |
| 7622 | bool LeftGuarded = false; |
| 7623 | bool RightGuarded = false; |
| 7624 | if (LAR) { |
| 7625 | const Loop *L = LAR->getLoop(); |
| 7626 | if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) && |
| 7627 | isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) { |
| 7628 | if (!RAR) return true; |
| 7629 | LeftGuarded = true; |
| 7630 | } |
| 7631 | } |
| 7632 | if (RAR) { |
| 7633 | const Loop *L = RAR->getLoop(); |
| 7634 | if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) && |
| 7635 | isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) { |
| 7636 | if (!LAR) return true; |
| 7637 | RightGuarded = true; |
| 7638 | } |
| 7639 | } |
| 7640 | if (LeftGuarded && RightGuarded) |
| 7641 | return true; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7642 | |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7643 | if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) |
| 7644 | return true; |
| 7645 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7646 | // Otherwise see what can be done with known constant ranges. |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7647 | return isKnownPredicateViaConstantRanges(Pred, LHS, RHS); |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7648 | } |
| 7649 | |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7650 | bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, |
| 7651 | ICmpInst::Predicate Pred, |
| 7652 | bool &Increasing) { |
| 7653 | bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); |
| 7654 | |
| 7655 | #ifndef NDEBUG |
| 7656 | // Verify an invariant: inverting the predicate should turn a monotonically |
| 7657 | // increasing change to a monotonically decreasing one, and vice versa. |
| 7658 | bool IncreasingSwapped; |
| 7659 | bool ResultSwapped = isMonotonicPredicateImpl( |
| 7660 | LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); |
| 7661 | |
| 7662 | assert(Result == ResultSwapped && "should be able to analyze both!"); |
| 7663 | if (ResultSwapped) |
| 7664 | assert(Increasing == !IncreasingSwapped && |
| 7665 | "monotonicity should flip as we flip the predicate"); |
| 7666 | #endif |
| 7667 | |
| 7668 | return Result; |
| 7669 | } |
| 7670 | |
| 7671 | bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, |
| 7672 | ICmpInst::Predicate Pred, |
| 7673 | bool &Increasing) { |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7674 | |
| 7675 | // A zero step value for LHS means the induction variable is essentially a |
| 7676 | // loop invariant value. We don't really depend on the predicate actually |
| 7677 | // flipping from false to true (for increasing predicates, and the other way |
| 7678 | // around for decreasing predicates), all we care about is that *if* the |
| 7679 | // predicate changes then it only changes from false to true. |
| 7680 | // |
| 7681 | // A zero step value in itself is not very useful, but there may be places |
| 7682 | // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be |
| 7683 | // as general as possible. |
| 7684 | |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7685 | switch (Pred) { |
| 7686 | default: |
| 7687 | return false; // Conservative answer |
| 7688 | |
| 7689 | case ICmpInst::ICMP_UGT: |
| 7690 | case ICmpInst::ICMP_UGE: |
| 7691 | case ICmpInst::ICMP_ULT: |
| 7692 | case ICmpInst::ICMP_ULE: |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 7693 | if (!LHS->hasNoUnsignedWrap()) |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7694 | return false; |
| 7695 | |
| 7696 | Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7697 | return true; |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7698 | |
| 7699 | case ICmpInst::ICMP_SGT: |
| 7700 | case ICmpInst::ICMP_SGE: |
| 7701 | case ICmpInst::ICMP_SLT: |
| 7702 | case ICmpInst::ICMP_SLE: { |
Sanjoy Das | 76c48e0 | 2016-02-04 18:21:54 +0000 | [diff] [blame] | 7703 | if (!LHS->hasNoSignedWrap()) |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7704 | return false; |
| 7705 | |
| 7706 | const SCEV *Step = LHS->getStepRecurrence(*this); |
| 7707 | |
| 7708 | if (isKnownNonNegative(Step)) { |
| 7709 | Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; |
| 7710 | return true; |
| 7711 | } |
| 7712 | |
| 7713 | if (isKnownNonPositive(Step)) { |
| 7714 | Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; |
| 7715 | return true; |
| 7716 | } |
| 7717 | |
| 7718 | return false; |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7719 | } |
| 7720 | |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7721 | } |
| 7722 | |
Sanjoy Das | 366acc1 | 2015-08-06 20:43:41 +0000 | [diff] [blame] | 7723 | llvm_unreachable("switch has default clause!"); |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 7724 | } |
| 7725 | |
| 7726 | bool ScalarEvolution::isLoopInvariantPredicate( |
| 7727 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, |
| 7728 | ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, |
| 7729 | const SCEV *&InvariantRHS) { |
| 7730 | |
| 7731 | // If there is a loop-invariant, force it into the RHS, otherwise bail out. |
| 7732 | if (!isLoopInvariant(RHS, L)) { |
| 7733 | if (!isLoopInvariant(LHS, L)) |
| 7734 | return false; |
| 7735 | |
| 7736 | std::swap(LHS, RHS); |
| 7737 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 7738 | } |
| 7739 | |
| 7740 | const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); |
| 7741 | if (!ArLHS || ArLHS->getLoop() != L) |
| 7742 | return false; |
| 7743 | |
| 7744 | bool Increasing; |
| 7745 | if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) |
| 7746 | return false; |
| 7747 | |
| 7748 | // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to |
| 7749 | // true as the loop iterates, and the backedge is control dependent on |
| 7750 | // "ArLHS `Pred` RHS" == true then we can reason as follows: |
| 7751 | // |
| 7752 | // * if the predicate was false in the first iteration then the predicate |
| 7753 | // is never evaluated again, since the loop exits without taking the |
| 7754 | // backedge. |
| 7755 | // * if the predicate was true in the first iteration then it will |
| 7756 | // continue to be true for all future iterations since it is |
| 7757 | // monotonically increasing. |
| 7758 | // |
| 7759 | // For both the above possibilities, we can replace the loop varying |
| 7760 | // predicate with its value on the first iteration of the loop (which is |
| 7761 | // loop invariant). |
| 7762 | // |
| 7763 | // A similar reasoning applies for a monotonically decreasing predicate, by |
| 7764 | // replacing true with false and false with true in the above two bullets. |
| 7765 | |
| 7766 | auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); |
| 7767 | |
| 7768 | if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) |
| 7769 | return false; |
| 7770 | |
| 7771 | InvariantPred = Pred; |
| 7772 | InvariantLHS = ArLHS->getStart(); |
| 7773 | InvariantRHS = RHS; |
| 7774 | return true; |
| 7775 | } |
| 7776 | |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7777 | bool ScalarEvolution::isKnownPredicateViaConstantRanges( |
| 7778 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7779 | if (HasSameValue(LHS, RHS)) |
| 7780 | return ICmpInst::isTrueWhenEqual(Pred); |
| 7781 | |
Dan Gohman | 0759169 | 2010-04-11 22:16:48 +0000 | [diff] [blame] | 7782 | // This code is split out from isKnownPredicate because it is called from |
| 7783 | // within isLoopEntryGuardedByCond. |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7784 | |
Sanjoy Das | 4c7b6d7 | 2016-02-01 20:48:14 +0000 | [diff] [blame] | 7785 | auto CheckRanges = |
| 7786 | [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { |
| 7787 | return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) |
| 7788 | .contains(RangeLHS); |
| 7789 | }; |
| 7790 | |
| 7791 | // The check at the top of the function catches the case where the values are |
| 7792 | // known to be equal. |
| 7793 | if (Pred == CmpInst::ICMP_EQ) |
| 7794 | return false; |
| 7795 | |
| 7796 | if (Pred == CmpInst::ICMP_NE) |
| 7797 | return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || |
| 7798 | CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || |
| 7799 | isKnownNonZero(getMinusSCEV(LHS, RHS)); |
| 7800 | |
| 7801 | if (CmpInst::isSigned(Pred)) |
| 7802 | return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); |
| 7803 | |
| 7804 | return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7805 | } |
| 7806 | |
Sanjoy Das | c1a2977 | 2015-11-05 23:45:38 +0000 | [diff] [blame] | 7807 | bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, |
| 7808 | const SCEV *LHS, |
| 7809 | const SCEV *RHS) { |
| 7810 | |
| 7811 | // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. |
| 7812 | // Return Y via OutY. |
| 7813 | auto MatchBinaryAddToConst = |
| 7814 | [this](const SCEV *Result, const SCEV *X, APInt &OutY, |
| 7815 | SCEV::NoWrapFlags ExpectedFlags) { |
| 7816 | const SCEV *NonConstOp, *ConstOp; |
| 7817 | SCEV::NoWrapFlags FlagsPresent; |
| 7818 | |
| 7819 | if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || |
| 7820 | !isa<SCEVConstant>(ConstOp) || NonConstOp != X) |
| 7821 | return false; |
| 7822 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 7823 | OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); |
Sanjoy Das | c1a2977 | 2015-11-05 23:45:38 +0000 | [diff] [blame] | 7824 | return (FlagsPresent & ExpectedFlags) == ExpectedFlags; |
| 7825 | }; |
| 7826 | |
| 7827 | APInt C; |
| 7828 | |
| 7829 | switch (Pred) { |
| 7830 | default: |
| 7831 | break; |
| 7832 | |
| 7833 | case ICmpInst::ICMP_SGE: |
| 7834 | std::swap(LHS, RHS); |
| 7835 | case ICmpInst::ICMP_SLE: |
| 7836 | // X s<= (X + C)<nsw> if C >= 0 |
| 7837 | if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) |
| 7838 | return true; |
| 7839 | |
| 7840 | // (X + C)<nsw> s<= X if C <= 0 |
| 7841 | if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && |
| 7842 | !C.isStrictlyPositive()) |
| 7843 | return true; |
| 7844 | break; |
| 7845 | |
| 7846 | case ICmpInst::ICMP_SGT: |
| 7847 | std::swap(LHS, RHS); |
| 7848 | case ICmpInst::ICMP_SLT: |
| 7849 | // X s< (X + C)<nsw> if C > 0 |
| 7850 | if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && |
| 7851 | C.isStrictlyPositive()) |
| 7852 | return true; |
| 7853 | |
| 7854 | // (X + C)<nsw> s< X if C < 0 |
| 7855 | if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) |
| 7856 | return true; |
| 7857 | break; |
| 7858 | } |
| 7859 | |
| 7860 | return false; |
| 7861 | } |
| 7862 | |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7863 | bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, |
| 7864 | const SCEV *LHS, |
| 7865 | const SCEV *RHS) { |
Sanjoy Das | 10dffcb | 2015-10-08 03:46:00 +0000 | [diff] [blame] | 7866 | if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7867 | return false; |
| 7868 | |
| 7869 | // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on |
| 7870 | // the stack can result in exponential time complexity. |
| 7871 | SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); |
| 7872 | |
| 7873 | // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L |
| 7874 | // |
| 7875 | // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use |
| 7876 | // isKnownPredicate. isKnownPredicate is more powerful, but also more |
| 7877 | // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the |
| 7878 | // interesting cases seen in practice. We can consider "upgrading" L >= 0 to |
| 7879 | // use isKnownPredicate later if needed. |
Alexander Kornienko | 484e48e3 | 2015-11-05 21:07:12 +0000 | [diff] [blame] | 7880 | return isKnownNonNegative(RHS) && |
| 7881 | isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && |
| 7882 | isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 7883 | } |
| 7884 | |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 7885 | bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, |
| 7886 | ICmpInst::Predicate Pred, |
| 7887 | const SCEV *LHS, const SCEV *RHS) { |
| 7888 | // No need to even try if we know the module has no guards. |
| 7889 | if (!HasGuards) |
| 7890 | return false; |
| 7891 | |
| 7892 | return any_of(*BB, [&](Instruction &I) { |
| 7893 | using namespace llvm::PatternMatch; |
| 7894 | |
| 7895 | Value *Condition; |
| 7896 | return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( |
| 7897 | m_Value(Condition))) && |
| 7898 | isImpliedCond(Pred, LHS, RHS, Condition, false); |
| 7899 | }); |
| 7900 | } |
| 7901 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7902 | /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is |
| 7903 | /// protected by a conditional between LHS and RHS. This is used to |
| 7904 | /// to eliminate casts. |
| 7905 | bool |
| 7906 | ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, |
| 7907 | ICmpInst::Predicate Pred, |
| 7908 | const SCEV *LHS, const SCEV *RHS) { |
| 7909 | // Interpret a null as meaning no loop, where there is obviously no guard |
| 7910 | // (interprocedural conditions notwithstanding). |
| 7911 | if (!L) return true; |
| 7912 | |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 7913 | if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) |
| 7914 | return true; |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 7915 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7916 | BasicBlock *Latch = L->getLoopLatch(); |
| 7917 | if (!Latch) |
| 7918 | return false; |
| 7919 | |
| 7920 | BranchInst *LoopContinuePredicate = |
| 7921 | dyn_cast<BranchInst>(Latch->getTerminator()); |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 7922 | if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && |
| 7923 | isImpliedCond(Pred, LHS, RHS, |
| 7924 | LoopContinuePredicate->getCondition(), |
| 7925 | LoopContinuePredicate->getSuccessor(0) != L->getHeader())) |
| 7926 | return true; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 7927 | |
Piotr Padlewski | 0dde00d2 | 2015-09-09 20:47:30 +0000 | [diff] [blame] | 7928 | // 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] | 7929 | // -- that can lead to O(n!) time complexity. |
| 7930 | if (WalkingBEDominatingConds) |
| 7931 | return false; |
| 7932 | |
Sanjoy Das | 5d9a8cb | 2015-09-22 00:10:57 +0000 | [diff] [blame] | 7933 | SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7934 | |
Sanjoy Das | b174f9a | 2015-09-25 23:53:50 +0000 | [diff] [blame] | 7935 | // See if we can exploit a trip count to prove the predicate. |
| 7936 | const auto &BETakenInfo = getBackedgeTakenInfo(L); |
| 7937 | const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); |
| 7938 | if (LatchBECount != getCouldNotCompute()) { |
| 7939 | // We know that Latch branches back to the loop header exactly |
| 7940 | // LatchBECount times. This means the backdege condition at Latch is |
| 7941 | // equivalent to "{0,+,1} u< LatchBECount". |
| 7942 | Type *Ty = LatchBECount->getType(); |
| 7943 | auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); |
| 7944 | const SCEV *LoopCounter = |
| 7945 | getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); |
| 7946 | if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, |
| 7947 | LatchBECount)) |
| 7948 | return true; |
| 7949 | } |
| 7950 | |
Piotr Padlewski | 0dde00d2 | 2015-09-09 20:47:30 +0000 | [diff] [blame] | 7951 | // Check conditions due to any @llvm.assume intrinsics. |
| 7952 | for (auto &AssumeVH : AC.assumptions()) { |
| 7953 | if (!AssumeVH) |
| 7954 | continue; |
| 7955 | auto *CI = cast<CallInst>(AssumeVH); |
| 7956 | if (!DT.dominates(CI, Latch->getTerminator())) |
| 7957 | continue; |
| 7958 | |
| 7959 | if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) |
| 7960 | return true; |
| 7961 | } |
| 7962 | |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7963 | // If the loop is not reachable from the entry block, we risk running into an |
| 7964 | // infinite loop as we walk up into the dom tree. These loops do not matter |
| 7965 | // anyway, so we just return a conservative answer when we see them. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7966 | if (!DT.isReachableFromEntry(L->getHeader())) |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7967 | return false; |
| 7968 | |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 7969 | if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) |
| 7970 | return true; |
| 7971 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 7972 | for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; |
| 7973 | DTN != HeaderDTN; DTN = DTN->getIDom()) { |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7974 | |
| 7975 | assert(DTN && "should reach the loop header before reaching the root!"); |
| 7976 | |
| 7977 | BasicBlock *BB = DTN->getBlock(); |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 7978 | if (isImpliedViaGuard(BB, Pred, LHS, RHS)) |
| 7979 | return true; |
| 7980 | |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 7981 | BasicBlock *PBB = BB->getSinglePredecessor(); |
| 7982 | if (!PBB) |
| 7983 | continue; |
| 7984 | |
| 7985 | BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); |
| 7986 | if (!ContinuePredicate || !ContinuePredicate->isConditional()) |
| 7987 | continue; |
| 7988 | |
| 7989 | Value *Condition = ContinuePredicate->getCondition(); |
| 7990 | |
| 7991 | // If we have an edge `E` within the loop body that dominates the only |
| 7992 | // latch, the condition guarding `E` also guards the backedge. This |
| 7993 | // reasoning works only for loops with a single latch. |
| 7994 | |
| 7995 | BasicBlockEdge DominatingEdge(PBB, BB); |
| 7996 | if (DominatingEdge.isSingleEdge()) { |
| 7997 | // We're constructively (and conservatively) enumerating edges within the |
| 7998 | // loop body that dominate the latch. The dominator tree better agree |
| 7999 | // with us on this: |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8000 | assert(DT.dominates(DominatingEdge, Latch) && "should be!"); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 8001 | |
| 8002 | if (isImpliedCond(Pred, LHS, RHS, Condition, |
| 8003 | BB != ContinuePredicate->getSuccessor(0))) |
| 8004 | return true; |
| 8005 | } |
| 8006 | } |
| 8007 | |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 8008 | return false; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8009 | } |
| 8010 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8011 | bool |
Dan Gohman | b50349a | 2010-04-11 19:27:13 +0000 | [diff] [blame] | 8012 | ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, |
| 8013 | ICmpInst::Predicate Pred, |
| 8014 | const SCEV *LHS, const SCEV *RHS) { |
Dan Gohman | 9cf09f8 | 2009-05-18 16:03:58 +0000 | [diff] [blame] | 8015 | // Interpret a null as meaning no loop, where there is obviously no guard |
| 8016 | // (interprocedural conditions notwithstanding). |
| 8017 | if (!L) return false; |
| 8018 | |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 8019 | if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS)) |
| 8020 | return true; |
Sanjoy Das | 1f05c51 | 2014-10-10 21:22:34 +0000 | [diff] [blame] | 8021 | |
Dan Gohman | 8c77f1a | 2009-05-18 15:36:09 +0000 | [diff] [blame] | 8022 | // Starting at the loop predecessor, climb up the predecessor chain, as long |
| 8023 | // as there are predecessors that can be found that have unique successors |
Dan Gohman | f9081a2 | 2008-09-15 22:18:04 +0000 | [diff] [blame] | 8024 | // leading to the original header. |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 8025 | for (std::pair<BasicBlock *, BasicBlock *> |
Dan Gohman | 75c6b0b | 2010-06-22 23:43:28 +0000 | [diff] [blame] | 8026 | Pair(L->getLoopPredecessor(), L->getHeader()); |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 8027 | Pair.first; |
| 8028 | Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 8029 | |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 8030 | if (isImpliedViaGuard(Pair.first, Pred, LHS, RHS)) |
| 8031 | return true; |
| 8032 | |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 8033 | BranchInst *LoopEntryPredicate = |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 8034 | dyn_cast<BranchInst>(Pair.first->getTerminator()); |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 8035 | if (!LoopEntryPredicate || |
| 8036 | LoopEntryPredicate->isUnconditional()) |
| 8037 | continue; |
| 8038 | |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8039 | if (isImpliedCond(Pred, LHS, RHS, |
| 8040 | LoopEntryPredicate->getCondition(), |
Dan Gohman | 4e3c113 | 2010-04-15 16:19:08 +0000 | [diff] [blame] | 8041 | LoopEntryPredicate->getSuccessor(0) != Pair.second)) |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 8042 | return true; |
Nick Lewycky | b5688cc | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 8043 | } |
| 8044 | |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 8045 | // Check conditions due to any @llvm.assume intrinsics. |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8046 | for (auto &AssumeVH : AC.assumptions()) { |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 8047 | if (!AssumeVH) |
| 8048 | continue; |
| 8049 | auto *CI = cast<CallInst>(AssumeVH); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 8050 | if (!DT.dominates(CI, L->getHeader())) |
Hal Finkel | cebf0cc | 2014-09-07 21:37:59 +0000 | [diff] [blame] | 8051 | continue; |
| 8052 | |
| 8053 | if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) |
| 8054 | return true; |
| 8055 | } |
| 8056 | |
Dan Gohman | 2a62fd9 | 2008-08-12 20:17:31 +0000 | [diff] [blame] | 8057 | return false; |
Nick Lewycky | b5688cc | 2008-07-12 07:41:32 +0000 | [diff] [blame] | 8058 | } |
| 8059 | |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8060 | bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8061 | const SCEV *LHS, const SCEV *RHS, |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8062 | Value *FoundCondValue, |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8063 | bool Inverse) { |
Sanjoy Das | c46bceb | 2016-09-27 18:01:42 +0000 | [diff] [blame] | 8064 | if (!PendingLoopPredicates.insert(FoundCondValue).second) |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 8065 | return false; |
| 8066 | |
Sanjoy Das | c46bceb | 2016-09-27 18:01:42 +0000 | [diff] [blame] | 8067 | auto ClearOnExit = |
| 8068 | make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); |
| 8069 | |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 8070 | // Recursively handle And and Or conditions. |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8071 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8072 | if (BO->getOpcode() == Instruction::And) { |
| 8073 | if (!Inverse) |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8074 | return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || |
| 8075 | isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8076 | } else if (BO->getOpcode() == Instruction::Or) { |
| 8077 | if (Inverse) |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8078 | return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || |
| 8079 | isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8080 | } |
| 8081 | } |
| 8082 | |
Dan Gohman | e18c2d6 | 2010-08-10 23:46:30 +0000 | [diff] [blame] | 8083 | ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8084 | if (!ICI) return false; |
| 8085 | |
Andrew Trick | fa59403 | 2012-11-29 18:35:13 +0000 | [diff] [blame] | 8086 | // Now that we found a conditional branch that dominates the loop or controls |
| 8087 | // 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] | 8088 | ICmpInst::Predicate FoundPred; |
| 8089 | if (Inverse) |
| 8090 | FoundPred = ICI->getInversePredicate(); |
| 8091 | else |
| 8092 | FoundPred = ICI->getPredicate(); |
| 8093 | |
| 8094 | const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); |
| 8095 | const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8096 | |
Sanjoy Das | df1635d | 2015-09-25 19:59:52 +0000 | [diff] [blame] | 8097 | return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); |
| 8098 | } |
| 8099 | |
| 8100 | bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, |
| 8101 | const SCEV *RHS, |
| 8102 | ICmpInst::Predicate FoundPred, |
| 8103 | const SCEV *FoundLHS, |
| 8104 | const SCEV *FoundRHS) { |
Sanjoy Das | 1459883 | 2015-03-26 17:28:26 +0000 | [diff] [blame] | 8105 | // Balance the types. |
| 8106 | if (getTypeSizeInBits(LHS->getType()) < |
| 8107 | getTypeSizeInBits(FoundLHS->getType())) { |
| 8108 | if (CmpInst::isSigned(Pred)) { |
| 8109 | LHS = getSignExtendExpr(LHS, FoundLHS->getType()); |
| 8110 | RHS = getSignExtendExpr(RHS, FoundLHS->getType()); |
| 8111 | } else { |
| 8112 | LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); |
| 8113 | RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); |
| 8114 | } |
| 8115 | } else if (getTypeSizeInBits(LHS->getType()) > |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8116 | getTypeSizeInBits(FoundLHS->getType())) { |
Stepan Dyatkovskiy | 431993b | 2014-01-09 12:26:12 +0000 | [diff] [blame] | 8117 | if (CmpInst::isSigned(FoundPred)) { |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8118 | FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); |
| 8119 | FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); |
| 8120 | } else { |
| 8121 | FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); |
| 8122 | FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); |
| 8123 | } |
| 8124 | } |
| 8125 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8126 | // Canonicalize the query to match the way instcombine will have |
| 8127 | // canonicalized the comparison. |
Dan Gohman | 3673aa1 | 2010-04-24 01:34:53 +0000 | [diff] [blame] | 8128 | if (SimplifyICmpOperands(Pred, LHS, RHS)) |
| 8129 | if (LHS == RHS) |
Dan Gohman | b5025c7 | 2010-05-03 18:00:24 +0000 | [diff] [blame] | 8130 | return CmpInst::isTrueWhenEqual(Pred); |
Benjamin Kramer | ba11a98 | 2012-11-29 19:07:57 +0000 | [diff] [blame] | 8131 | if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) |
| 8132 | if (FoundLHS == FoundRHS) |
| 8133 | return CmpInst::isFalseWhenEqual(FoundPred); |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8134 | |
| 8135 | // Check to see if we can make the LHS or RHS match. |
| 8136 | if (LHS == FoundRHS || RHS == FoundLHS) { |
| 8137 | if (isa<SCEVConstant>(RHS)) { |
| 8138 | std::swap(FoundLHS, FoundRHS); |
| 8139 | FoundPred = ICmpInst::getSwappedPredicate(FoundPred); |
| 8140 | } else { |
| 8141 | std::swap(LHS, RHS); |
| 8142 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 8143 | } |
| 8144 | } |
| 8145 | |
| 8146 | // Check whether the found predicate is the same as the desired predicate. |
| 8147 | if (FoundPred == Pred) |
| 8148 | return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); |
| 8149 | |
| 8150 | // Check whether swapping the found predicate makes it the same as the |
| 8151 | // desired predicate. |
| 8152 | if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { |
| 8153 | if (isa<SCEVConstant>(RHS)) |
| 8154 | return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); |
| 8155 | else |
| 8156 | return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), |
| 8157 | RHS, LHS, FoundLHS, FoundRHS); |
| 8158 | } |
| 8159 | |
Sanjoy Das | 6e78b17 | 2015-10-22 19:57:34 +0000 | [diff] [blame] | 8160 | // Unsigned comparison is the same as signed comparison when both the operands |
| 8161 | // are non-negative. |
| 8162 | if (CmpInst::isUnsigned(FoundPred) && |
| 8163 | CmpInst::getSignedPredicate(FoundPred) == Pred && |
| 8164 | isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) |
| 8165 | return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); |
| 8166 | |
Sanjoy Das | c5676df | 2014-11-13 00:00:58 +0000 | [diff] [blame] | 8167 | // Check if we can make progress by sharpening ranges. |
| 8168 | if (FoundPred == ICmpInst::ICMP_NE && |
| 8169 | (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { |
| 8170 | |
| 8171 | const SCEVConstant *C = nullptr; |
| 8172 | const SCEV *V = nullptr; |
| 8173 | |
| 8174 | if (isa<SCEVConstant>(FoundLHS)) { |
| 8175 | C = cast<SCEVConstant>(FoundLHS); |
| 8176 | V = FoundRHS; |
| 8177 | } else { |
| 8178 | C = cast<SCEVConstant>(FoundRHS); |
| 8179 | V = FoundLHS; |
| 8180 | } |
| 8181 | |
| 8182 | // The guarding predicate tells us that C != V. If the known range |
| 8183 | // of V is [C, t), we can sharpen the range to [C + 1, t). The |
| 8184 | // range we consider has to correspond to same signedness as the |
| 8185 | // predicate we're interested in folding. |
| 8186 | |
| 8187 | APInt Min = ICmpInst::isSigned(Pred) ? |
| 8188 | getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin(); |
| 8189 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8190 | if (Min == C->getAPInt()) { |
Sanjoy Das | c5676df | 2014-11-13 00:00:58 +0000 | [diff] [blame] | 8191 | // Given (V >= Min && V != Min) we conclude V >= (Min + 1). |
| 8192 | // This is true even if (Min + 1) wraps around -- in case of |
| 8193 | // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). |
| 8194 | |
| 8195 | APInt SharperMin = Min + 1; |
| 8196 | |
| 8197 | switch (Pred) { |
| 8198 | case ICmpInst::ICMP_SGE: |
| 8199 | case ICmpInst::ICMP_UGE: |
| 8200 | // We know V `Pred` SharperMin. If this implies LHS `Pred` |
| 8201 | // RHS, we're done. |
| 8202 | if (isImpliedCondOperands(Pred, LHS, RHS, V, |
| 8203 | getConstant(SharperMin))) |
| 8204 | return true; |
| 8205 | |
| 8206 | case ICmpInst::ICMP_SGT: |
| 8207 | case ICmpInst::ICMP_UGT: |
| 8208 | // We know from the range information that (V `Pred` Min || |
| 8209 | // V == Min). We know from the guarding condition that !(V |
| 8210 | // == Min). This gives us |
| 8211 | // |
| 8212 | // V `Pred` Min || V == Min && !(V == Min) |
| 8213 | // => V `Pred` Min |
| 8214 | // |
| 8215 | // If V `Pred` Min implies LHS `Pred` RHS, we're done. |
| 8216 | |
| 8217 | if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) |
| 8218 | return true; |
| 8219 | |
| 8220 | default: |
| 8221 | // No change |
| 8222 | break; |
| 8223 | } |
| 8224 | } |
| 8225 | } |
| 8226 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8227 | // Check whether the actual condition is beyond sufficient. |
| 8228 | if (FoundPred == ICmpInst::ICMP_EQ) |
| 8229 | if (ICmpInst::isTrueWhenEqual(Pred)) |
| 8230 | if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8231 | return true; |
| 8232 | if (Pred == ICmpInst::ICMP_NE) |
| 8233 | if (!ICmpInst::isTrueWhenEqual(FoundPred)) |
| 8234 | if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8235 | return true; |
| 8236 | |
| 8237 | // Otherwise assume the worst. |
| 8238 | return false; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8239 | } |
| 8240 | |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8241 | bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, |
| 8242 | const SCEV *&L, const SCEV *&R, |
| 8243 | SCEV::NoWrapFlags &Flags) { |
| 8244 | const auto *AE = dyn_cast<SCEVAddExpr>(Expr); |
| 8245 | if (!AE || AE->getNumOperands() != 2) |
| 8246 | return false; |
| 8247 | |
| 8248 | L = AE->getOperand(0); |
| 8249 | R = AE->getOperand(1); |
| 8250 | Flags = AE->getNoWrapFlags(); |
| 8251 | return true; |
| 8252 | } |
| 8253 | |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8254 | Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, |
| 8255 | const SCEV *Less) { |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8256 | // We avoid subtracting expressions here because this function is usually |
| 8257 | // fairly deep in the call stack (i.e. is called many times). |
| 8258 | |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8259 | if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { |
| 8260 | const auto *LAR = cast<SCEVAddRecExpr>(Less); |
| 8261 | const auto *MAR = cast<SCEVAddRecExpr>(More); |
| 8262 | |
| 8263 | if (LAR->getLoop() != MAR->getLoop()) |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8264 | return None; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8265 | |
| 8266 | // We look at affine expressions only; not for correctness but to keep |
| 8267 | // getStepRecurrence cheap. |
| 8268 | if (!LAR->isAffine() || !MAR->isAffine()) |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8269 | return None; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8270 | |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8271 | if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8272 | return None; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8273 | |
| 8274 | Less = LAR->getStart(); |
| 8275 | More = MAR->getStart(); |
| 8276 | |
| 8277 | // fall through |
| 8278 | } |
| 8279 | |
| 8280 | if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8281 | const auto &M = cast<SCEVConstant>(More)->getAPInt(); |
| 8282 | const auto &L = cast<SCEVConstant>(Less)->getAPInt(); |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8283 | return M - L; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8284 | } |
| 8285 | |
| 8286 | const SCEV *L, *R; |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8287 | SCEV::NoWrapFlags Flags; |
| 8288 | if (splitBinaryAdd(Less, L, R, Flags)) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8289 | if (const auto *LC = dyn_cast<SCEVConstant>(L)) |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8290 | if (R == More) |
| 8291 | return -(LC->getAPInt()); |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8292 | |
Sanjoy Das | 1ed6910 | 2015-10-13 02:53:27 +0000 | [diff] [blame] | 8293 | if (splitBinaryAdd(More, L, R, Flags)) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8294 | if (const auto *LC = dyn_cast<SCEVConstant>(L)) |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8295 | if (R == Less) |
| 8296 | return LC->getAPInt(); |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8297 | |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8298 | return None; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8299 | } |
| 8300 | |
| 8301 | bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( |
| 8302 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, |
| 8303 | const SCEV *FoundLHS, const SCEV *FoundRHS) { |
| 8304 | if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) |
| 8305 | return false; |
| 8306 | |
| 8307 | const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); |
| 8308 | if (!AddRecLHS) |
| 8309 | return false; |
| 8310 | |
| 8311 | const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); |
| 8312 | if (!AddRecFoundLHS) |
| 8313 | return false; |
| 8314 | |
| 8315 | // We'd like to let SCEV reason about control dependencies, so we constrain |
| 8316 | // both the inequalities to be about add recurrences on the same loop. This |
| 8317 | // way we can use isLoopEntryGuardedByCond later. |
| 8318 | |
| 8319 | const Loop *L = AddRecFoundLHS->getLoop(); |
| 8320 | if (L != AddRecLHS->getLoop()) |
| 8321 | return false; |
| 8322 | |
| 8323 | // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) |
| 8324 | // |
| 8325 | // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) |
| 8326 | // ... (2) |
| 8327 | // |
| 8328 | // Informal proof for (2), assuming (1) [*]: |
| 8329 | // |
| 8330 | // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] |
| 8331 | // |
| 8332 | // Then |
| 8333 | // |
| 8334 | // FoundLHS s< FoundRHS s< INT_MIN - C |
| 8335 | // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] |
| 8336 | // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] |
| 8337 | // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< |
| 8338 | // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] |
| 8339 | // <=> FoundLHS + C s< FoundRHS + C |
| 8340 | // |
| 8341 | // [*]: (1) can be proved by ruling out overflow. |
| 8342 | // |
| 8343 | // [**]: This can be proved by analyzing all the four possibilities: |
| 8344 | // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and |
| 8345 | // (A s>= 0, B s>= 0). |
| 8346 | // |
| 8347 | // Note: |
| 8348 | // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" |
| 8349 | // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS |
| 8350 | // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS |
| 8351 | // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is |
| 8352 | // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + |
| 8353 | // C)". |
| 8354 | |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8355 | Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); |
| 8356 | Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); |
| 8357 | if (!LDiff || !RDiff || *LDiff != *RDiff) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8358 | return false; |
| 8359 | |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8360 | if (LDiff->isMinValue()) |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8361 | return true; |
| 8362 | |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8363 | APInt FoundRHSLimit; |
| 8364 | |
| 8365 | if (Pred == CmpInst::ICMP_ULT) { |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8366 | FoundRHSLimit = -(*RDiff); |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8367 | } else { |
| 8368 | assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); |
Sanjoy Das | 0b1af85 | 2016-07-23 00:28:56 +0000 | [diff] [blame] | 8369 | FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8370 | } |
| 8371 | |
| 8372 | // Try to prove (1) or (2), as needed. |
| 8373 | return isLoopEntryGuardedByCond(L, Pred, FoundRHS, |
| 8374 | getConstant(FoundRHSLimit)); |
| 8375 | } |
| 8376 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8377 | bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, |
| 8378 | const SCEV *LHS, const SCEV *RHS, |
| 8379 | const SCEV *FoundLHS, |
| 8380 | const SCEV *FoundRHS) { |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8381 | if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8382 | return true; |
| 8383 | |
Sanjoy Das | 96709c4 | 2015-09-25 23:53:45 +0000 | [diff] [blame] | 8384 | if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) |
| 8385 | return true; |
| 8386 | |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8387 | return isImpliedCondOperandsHelper(Pred, LHS, RHS, |
| 8388 | FoundLHS, FoundRHS) || |
| 8389 | // ~x < ~y --> x > y |
| 8390 | isImpliedCondOperandsHelper(Pred, LHS, RHS, |
| 8391 | getNotSCEV(FoundRHS), |
| 8392 | getNotSCEV(FoundLHS)); |
| 8393 | } |
| 8394 | |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8395 | |
| 8396 | /// If Expr computes ~A, return A else return nullptr |
| 8397 | static const SCEV *MatchNotExpr(const SCEV *Expr) { |
| 8398 | const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); |
Sanjoy Das | 16e7ff1 | 2015-10-13 23:28:31 +0000 | [diff] [blame] | 8399 | if (!Add || Add->getNumOperands() != 2 || |
| 8400 | !Add->getOperand(0)->isAllOnesValue()) |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8401 | return nullptr; |
| 8402 | |
| 8403 | const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); |
Sanjoy Das | 16e7ff1 | 2015-10-13 23:28:31 +0000 | [diff] [blame] | 8404 | if (!AddRHS || AddRHS->getNumOperands() != 2 || |
| 8405 | !AddRHS->getOperand(0)->isAllOnesValue()) |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8406 | return nullptr; |
| 8407 | |
| 8408 | return AddRHS->getOperand(1); |
| 8409 | } |
| 8410 | |
| 8411 | |
| 8412 | /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values? |
| 8413 | template<typename MaxExprType> |
| 8414 | static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr, |
| 8415 | const SCEV *Candidate) { |
| 8416 | const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr); |
| 8417 | if (!MaxExpr) return false; |
| 8418 | |
Sanjoy Das | 347d272 | 2015-12-01 07:49:27 +0000 | [diff] [blame] | 8419 | return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end(); |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8420 | } |
| 8421 | |
| 8422 | |
| 8423 | /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values? |
| 8424 | template<typename MaxExprType> |
| 8425 | static bool IsMinConsistingOf(ScalarEvolution &SE, |
| 8426 | const SCEV *MaybeMinExpr, |
| 8427 | const SCEV *Candidate) { |
| 8428 | const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr); |
| 8429 | if (!MaybeMaxExpr) |
| 8430 | return false; |
| 8431 | |
| 8432 | return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate)); |
| 8433 | } |
| 8434 | |
Hal Finkel | a8d205f | 2015-08-19 01:51:51 +0000 | [diff] [blame] | 8435 | static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, |
| 8436 | ICmpInst::Predicate Pred, |
| 8437 | const SCEV *LHS, const SCEV *RHS) { |
| 8438 | |
| 8439 | // If both sides are affine addrecs for the same loop, with equal |
| 8440 | // steps, and we know the recurrences don't wrap, then we only |
| 8441 | // need to check the predicate on the starting values. |
| 8442 | |
| 8443 | if (!ICmpInst::isRelational(Pred)) |
| 8444 | return false; |
| 8445 | |
| 8446 | const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); |
| 8447 | if (!LAR) |
| 8448 | return false; |
| 8449 | const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); |
| 8450 | if (!RAR) |
| 8451 | return false; |
| 8452 | if (LAR->getLoop() != RAR->getLoop()) |
| 8453 | return false; |
| 8454 | if (!LAR->isAffine() || !RAR->isAffine()) |
| 8455 | return false; |
| 8456 | |
| 8457 | if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) |
| 8458 | return false; |
| 8459 | |
Hal Finkel | ff08a2e | 2015-08-19 17:26:07 +0000 | [diff] [blame] | 8460 | SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? |
| 8461 | SCEV::FlagNSW : SCEV::FlagNUW; |
| 8462 | if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) |
Hal Finkel | a8d205f | 2015-08-19 01:51:51 +0000 | [diff] [blame] | 8463 | return false; |
| 8464 | |
| 8465 | return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); |
| 8466 | } |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8467 | |
| 8468 | /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max |
| 8469 | /// expression? |
| 8470 | static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, |
| 8471 | ICmpInst::Predicate Pred, |
| 8472 | const SCEV *LHS, const SCEV *RHS) { |
| 8473 | switch (Pred) { |
| 8474 | default: |
| 8475 | return false; |
| 8476 | |
| 8477 | case ICmpInst::ICMP_SGE: |
| 8478 | std::swap(LHS, RHS); |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 8479 | LLVM_FALLTHROUGH; |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8480 | case ICmpInst::ICMP_SLE: |
| 8481 | return |
| 8482 | // min(A, ...) <= A |
| 8483 | IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) || |
| 8484 | // A <= max(A, ...) |
| 8485 | IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); |
| 8486 | |
| 8487 | case ICmpInst::ICMP_UGE: |
| 8488 | std::swap(LHS, RHS); |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 8489 | LLVM_FALLTHROUGH; |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8490 | case ICmpInst::ICMP_ULE: |
| 8491 | return |
| 8492 | // min(A, ...) <= A |
| 8493 | IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) || |
| 8494 | // A <= max(A, ...) |
| 8495 | IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); |
| 8496 | } |
| 8497 | |
| 8498 | llvm_unreachable("covered switch fell through?!"); |
| 8499 | } |
| 8500 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8501 | bool |
Dan Gohman | 430f0cc | 2009-07-21 23:03:19 +0000 | [diff] [blame] | 8502 | ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, |
| 8503 | const SCEV *LHS, const SCEV *RHS, |
| 8504 | const SCEV *FoundLHS, |
| 8505 | const SCEV *FoundRHS) { |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8506 | auto IsKnownPredicateFull = |
| 8507 | [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { |
Sanjoy Das | 401e631 | 2016-02-01 20:48:10 +0000 | [diff] [blame] | 8508 | return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || |
Sanjoy Das | 1123148 | 2015-10-22 19:57:29 +0000 | [diff] [blame] | 8509 | IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || |
Sanjoy Das | c1a2977 | 2015-11-05 23:45:38 +0000 | [diff] [blame] | 8510 | IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || |
| 8511 | isKnownPredicateViaNoOverflow(Pred, LHS, RHS); |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8512 | }; |
| 8513 | |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8514 | switch (Pred) { |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8515 | default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); |
| 8516 | case ICmpInst::ICMP_EQ: |
| 8517 | case ICmpInst::ICMP_NE: |
| 8518 | if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) |
| 8519 | return true; |
| 8520 | break; |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8521 | case ICmpInst::ICMP_SLT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8522 | case ICmpInst::ICMP_SLE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8523 | if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) && |
| 8524 | IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8525 | return true; |
| 8526 | break; |
| 8527 | case ICmpInst::ICMP_SGT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8528 | case ICmpInst::ICMP_SGE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8529 | if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) && |
| 8530 | IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8531 | return true; |
| 8532 | break; |
| 8533 | case ICmpInst::ICMP_ULT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8534 | case ICmpInst::ICMP_ULE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8535 | if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) && |
| 8536 | IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8537 | return true; |
| 8538 | break; |
| 8539 | case ICmpInst::ICMP_UGT: |
Dan Gohman | 8c129d7 | 2009-07-16 17:34:36 +0000 | [diff] [blame] | 8540 | case ICmpInst::ICMP_UGE: |
Sanjoy Das | 4555b6d | 2014-12-15 22:50:15 +0000 | [diff] [blame] | 8541 | if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) && |
| 8542 | IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS)) |
Dan Gohman | e65c917 | 2009-07-13 21:35:55 +0000 | [diff] [blame] | 8543 | return true; |
| 8544 | break; |
| 8545 | } |
| 8546 | |
| 8547 | return false; |
Dan Gohman | f19aeec | 2009-06-24 01:18:18 +0000 | [diff] [blame] | 8548 | } |
| 8549 | |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8550 | bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, |
| 8551 | const SCEV *LHS, |
| 8552 | const SCEV *RHS, |
| 8553 | const SCEV *FoundLHS, |
| 8554 | const SCEV *FoundRHS) { |
| 8555 | if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) |
| 8556 | // The restriction on `FoundRHS` be lifted easily -- it exists only to |
| 8557 | // reduce the compile time impact of this optimization. |
| 8558 | return false; |
| 8559 | |
Sanjoy Das | a7d9ec8 | 2016-07-23 00:54:36 +0000 | [diff] [blame] | 8560 | Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); |
Sanjoy Das | 095f5b2 | 2016-07-22 20:47:55 +0000 | [diff] [blame] | 8561 | if (!Addend) |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8562 | return false; |
| 8563 | |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8564 | APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8565 | |
| 8566 | // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the |
| 8567 | // antecedent "`FoundLHS` `Pred` `FoundRHS`". |
| 8568 | ConstantRange FoundLHSRange = |
| 8569 | ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); |
| 8570 | |
Sanjoy Das | 095f5b2 | 2016-07-22 20:47:55 +0000 | [diff] [blame] | 8571 | // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: |
| 8572 | ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8573 | |
| 8574 | // We can also compute the range of values for `LHS` that satisfy the |
| 8575 | // consequent, "`LHS` `Pred` `RHS`": |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8576 | APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); |
Sanjoy Das | cb8bca1 | 2015-03-18 00:41:29 +0000 | [diff] [blame] | 8577 | ConstantRange SatisfyingLHSRange = |
| 8578 | ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); |
| 8579 | |
| 8580 | // The antecedent implies the consequent if every value of `LHS` that |
| 8581 | // satisfies the antecedent also satisfies the consequent. |
| 8582 | return SatisfyingLHSRange.contains(LHSRange); |
| 8583 | } |
| 8584 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8585 | bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, |
| 8586 | bool IsSigned, bool NoWrap) { |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8587 | assert(isKnownPositive(Stride) && "Positive stride expected!"); |
| 8588 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8589 | if (NoWrap) return false; |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 8590 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8591 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8592 | const SCEV *One = getOne(Stride->getType()); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 8593 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8594 | if (IsSigned) { |
| 8595 | APInt MaxRHS = getSignedRange(RHS).getSignedMax(); |
| 8596 | APInt MaxValue = APInt::getSignedMaxValue(BitWidth); |
| 8597 | APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) |
| 8598 | .getSignedMax(); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 8599 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8600 | // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! |
| 8601 | return (MaxValue - MaxStrideMinusOne).slt(MaxRHS); |
Dan Gohman | 36bad00 | 2009-09-17 18:05:20 +0000 | [diff] [blame] | 8602 | } |
Dan Gohman | 0104842 | 2009-06-21 23:46:38 +0000 | [diff] [blame] | 8603 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8604 | APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax(); |
| 8605 | APInt MaxValue = APInt::getMaxValue(BitWidth); |
| 8606 | APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) |
| 8607 | .getUnsignedMax(); |
| 8608 | |
| 8609 | // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! |
| 8610 | return (MaxValue - MaxStrideMinusOne).ult(MaxRHS); |
| 8611 | } |
| 8612 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8613 | bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, |
| 8614 | bool IsSigned, bool NoWrap) { |
| 8615 | if (NoWrap) return false; |
| 8616 | |
| 8617 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8618 | const SCEV *One = getOne(Stride->getType()); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8619 | |
| 8620 | if (IsSigned) { |
| 8621 | APInt MinRHS = getSignedRange(RHS).getSignedMin(); |
| 8622 | APInt MinValue = APInt::getSignedMinValue(BitWidth); |
| 8623 | APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One)) |
| 8624 | .getSignedMax(); |
| 8625 | |
| 8626 | // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! |
| 8627 | return (MinValue + MaxStrideMinusOne).sgt(MinRHS); |
| 8628 | } |
| 8629 | |
| 8630 | APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin(); |
| 8631 | APInt MinValue = APInt::getMinValue(BitWidth); |
| 8632 | APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One)) |
| 8633 | .getUnsignedMax(); |
| 8634 | |
| 8635 | // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! |
| 8636 | return (MinValue + MaxStrideMinusOne).ugt(MinRHS); |
| 8637 | } |
| 8638 | |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8639 | const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8640 | bool Equality) { |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8641 | const SCEV *One = getOne(Step->getType()); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8642 | Delta = Equality ? getAddExpr(Delta, Step) |
| 8643 | : getAddExpr(Delta, getMinusSCEV(Step, One)); |
| 8644 | return getUDivExpr(Delta, Step); |
Dan Gohman | 0104842 | 2009-06-21 23:46:38 +0000 | [diff] [blame] | 8645 | } |
| 8646 | |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 8647 | ScalarEvolution::ExitLimit |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 8648 | ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8649 | const Loop *L, bool IsSigned, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8650 | bool ControlsExit, bool AllowPredicates) { |
| 8651 | SCEVUnionPredicate P; |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8652 | // We handle only IV < Invariant |
| 8653 | if (!isLoopInvariant(RHS, L)) |
Dan Gohman | c5c85c0 | 2009-06-27 21:21:31 +0000 | [diff] [blame] | 8654 | return getCouldNotCompute(); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8655 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8656 | const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8657 | bool PredicatedIV = false; |
| 8658 | |
| 8659 | if (!IV && AllowPredicates) { |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8660 | // Try to make this an AddRec using runtime tests, in the first X |
| 8661 | // iterations of this loop, where X is the SCEV expression found by the |
| 8662 | // algorithm below. |
| 8663 | IV = convertSCEVToAddRecWithPredicates(LHS, L, P); |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8664 | PredicatedIV = true; |
| 8665 | } |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8666 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8667 | // Avoid weird loops |
| 8668 | if (!IV || IV->getLoop() != L || !IV->isAffine()) |
| 8669 | return getCouldNotCompute(); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8670 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8671 | bool NoWrap = ControlsExit && |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8672 | IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); |
Wojciech Matyjewicz | 35545fd | 2008-02-13 11:51:34 +0000 | [diff] [blame] | 8673 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8674 | const SCEV *Stride = IV->getStepRecurrence(*this); |
Wojciech Matyjewicz | 35545fd | 2008-02-13 11:51:34 +0000 | [diff] [blame] | 8675 | |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8676 | bool PositiveStride = isKnownPositive(Stride); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8677 | |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8678 | // Avoid negative or zero stride values. |
| 8679 | if (!PositiveStride) { |
| 8680 | // We can compute the correct backedge taken count for loops with unknown |
| 8681 | // strides if we can prove that the loop is not an infinite loop with side |
| 8682 | // effects. Here's the loop structure we are trying to handle - |
| 8683 | // |
| 8684 | // i = start |
| 8685 | // do { |
| 8686 | // A[i] = i; |
| 8687 | // i += s; |
| 8688 | // } while (i < end); |
| 8689 | // |
| 8690 | // The backedge taken count for such loops is evaluated as - |
| 8691 | // (max(end, start + stride) - start - 1) /u stride |
| 8692 | // |
| 8693 | // The additional preconditions that we need to check to prove correctness |
| 8694 | // of the above formula is as follows - |
| 8695 | // |
| 8696 | // a) IV is either nuw or nsw depending upon signedness (indicated by the |
| 8697 | // NoWrap flag). |
| 8698 | // b) loop is single exit with no side effects. |
| 8699 | // |
| 8700 | // |
| 8701 | // Precondition a) implies that if the stride is negative, this is a single |
| 8702 | // trip loop. The backedge taken count formula reduces to zero in this case. |
| 8703 | // |
| 8704 | // Precondition b) implies that the unknown stride cannot be zero otherwise |
| 8705 | // we have UB. |
| 8706 | // |
| 8707 | // The positive stride case is the same as isKnownPositive(Stride) returning |
| 8708 | // true (original behavior of the function). |
| 8709 | // |
| 8710 | // We want to make sure that the stride is truly unknown as there are edge |
| 8711 | // cases where ScalarEvolution propagates no wrap flags to the |
| 8712 | // post-increment/decrement IV even though the increment/decrement operation |
| 8713 | // itself is wrapping. The computed backedge taken count may be wrong in |
| 8714 | // such cases. This is prevented by checking that the stride is not known to |
| 8715 | // be either positive or non-positive. For example, no wrap flags are |
| 8716 | // propagated to the post-increment IV of this loop with a trip count of 2 - |
| 8717 | // |
| 8718 | // unsigned char i; |
| 8719 | // for(i=127; i<128; i+=129) |
| 8720 | // A[i] = i; |
| 8721 | // |
| 8722 | if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || |
| 8723 | !loopHasNoSideEffects(L)) |
| 8724 | return getCouldNotCompute(); |
| 8725 | |
| 8726 | } else if (!Stride->isOne() && |
| 8727 | doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) |
| 8728 | // Avoid proven overflow cases: this will ensure that the backedge taken |
| 8729 | // count will not generate any unsigned overflow. Relaxed no-overflow |
| 8730 | // conditions exploit NoWrapFlags, allowing to optimize in presence of |
| 8731 | // undefined behaviors like the case of C language. |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8732 | return getCouldNotCompute(); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8733 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8734 | ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT |
| 8735 | : ICmpInst::ICMP_ULT; |
| 8736 | const SCEV *Start = IV->getStart(); |
| 8737 | const SCEV *End = RHS; |
Sanjoy Das | e8fd956 | 2016-06-18 04:38:31 +0000 | [diff] [blame] | 8738 | if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) |
| 8739 | End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); |
Dan Gohman | 51aaf02 | 2010-01-26 04:40:18 +0000 | [diff] [blame] | 8740 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8741 | const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); |
Dan Gohman | 2b8da35 | 2009-04-30 20:47:05 +0000 | [diff] [blame] | 8742 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8743 | APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin() |
| 8744 | : getUnsignedRange(Start).getUnsignedMin(); |
Andrew Trick | 2afa325 | 2011-03-09 17:29:58 +0000 | [diff] [blame] | 8745 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8746 | unsigned BitWidth = getTypeSizeInBits(LHS->getType()); |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8747 | |
| 8748 | APInt StrideForMaxBECount; |
| 8749 | |
| 8750 | if (PositiveStride) |
| 8751 | StrideForMaxBECount = IsSigned ? getSignedRange(Stride).getSignedMin() |
| 8752 | : getUnsignedRange(Stride).getUnsignedMin(); |
| 8753 | else |
| 8754 | // Using a stride of 1 is safe when computing max backedge taken count for |
| 8755 | // a loop with unknown stride. |
| 8756 | StrideForMaxBECount = APInt(BitWidth, 1, IsSigned); |
| 8757 | |
| 8758 | APInt Limit = |
| 8759 | IsSigned ? APInt::getSignedMaxValue(BitWidth) - (StrideForMaxBECount - 1) |
| 8760 | : APInt::getMaxValue(BitWidth) - (StrideForMaxBECount - 1); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8761 | |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8762 | // Although End can be a MAX expression we estimate MaxEnd considering only |
| 8763 | // the case End = RHS. This is safe because in the other case (End - Start) |
| 8764 | // is zero, leading to a zero maximum backedge taken count. |
| 8765 | APInt MaxEnd = |
| 8766 | IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit) |
| 8767 | : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit); |
| 8768 | |
Arnaud A. de Grandmaison | 75c9e6d | 2014-03-15 22:13:15 +0000 | [diff] [blame] | 8769 | const SCEV *MaxBECount; |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8770 | if (isa<SCEVConstant>(BECount)) |
| 8771 | MaxBECount = BECount; |
| 8772 | else |
| 8773 | MaxBECount = computeBECount(getConstant(MaxEnd - MinStart), |
David L Kreitzer | 8bbabee | 2016-09-16 14:38:13 +0000 | [diff] [blame] | 8774 | getConstant(StrideForMaxBECount), false); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8775 | |
| 8776 | if (isa<SCEVCouldNotCompute>(MaxBECount)) |
| 8777 | MaxBECount = BECount; |
| 8778 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8779 | return ExitLimit(BECount, MaxBECount, P); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8780 | } |
| 8781 | |
| 8782 | ScalarEvolution::ExitLimit |
Sanjoy Das | 108fcf2 | 2016-05-29 00:38:00 +0000 | [diff] [blame] | 8783 | ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8784 | const Loop *L, bool IsSigned, |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8785 | bool ControlsExit, bool AllowPredicates) { |
| 8786 | SCEVUnionPredicate P; |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8787 | // We handle only IV > Invariant |
| 8788 | if (!isLoopInvariant(RHS, L)) |
| 8789 | return getCouldNotCompute(); |
| 8790 | |
| 8791 | const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8792 | if (!IV && AllowPredicates) |
| 8793 | // Try to make this an AddRec using runtime tests, in the first X |
| 8794 | // iterations of this loop, where X is the SCEV expression found by the |
| 8795 | // algorithm below. |
| 8796 | IV = convertSCEVToAddRecWithPredicates(LHS, L, P); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8797 | |
| 8798 | // Avoid weird loops |
| 8799 | if (!IV || IV->getLoop() != L || !IV->isAffine()) |
| 8800 | return getCouldNotCompute(); |
| 8801 | |
Mark Heffernan | 2beab5f | 2014-10-10 17:39:11 +0000 | [diff] [blame] | 8802 | bool NoWrap = ControlsExit && |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8803 | IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); |
| 8804 | |
| 8805 | const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); |
| 8806 | |
| 8807 | // Avoid negative or zero stride values |
| 8808 | if (!isKnownPositive(Stride)) |
| 8809 | return getCouldNotCompute(); |
| 8810 | |
| 8811 | // Avoid proven overflow cases: this will ensure that the backedge taken count |
| 8812 | // will not generate any unsigned overflow. Relaxed no-overflow conditions |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8813 | // exploit NoWrapFlags, allowing to optimize in presence of undefined |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8814 | // behaviors like the case of C language. |
| 8815 | if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) |
| 8816 | return getCouldNotCompute(); |
| 8817 | |
| 8818 | ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT |
| 8819 | : ICmpInst::ICMP_UGT; |
| 8820 | |
| 8821 | const SCEV *Start = IV->getStart(); |
| 8822 | const SCEV *End = RHS; |
Sanjoy Das | e8fd956 | 2016-06-18 04:38:31 +0000 | [diff] [blame] | 8823 | if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) |
| 8824 | End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8825 | |
| 8826 | const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); |
| 8827 | |
| 8828 | APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax() |
| 8829 | : getUnsignedRange(Start).getUnsignedMax(); |
| 8830 | |
| 8831 | APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin() |
| 8832 | : getUnsignedRange(Stride).getUnsignedMin(); |
| 8833 | |
| 8834 | unsigned BitWidth = getTypeSizeInBits(LHS->getType()); |
| 8835 | APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) |
| 8836 | : APInt::getMinValue(BitWidth) + (MinStride - 1); |
| 8837 | |
| 8838 | // Although End can be a MIN expression we estimate MinEnd considering only |
| 8839 | // the case End = RHS. This is safe because in the other case (Start - End) |
| 8840 | // is zero, leading to a zero maximum backedge taken count. |
| 8841 | APInt MinEnd = |
| 8842 | IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit) |
| 8843 | : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit); |
| 8844 | |
| 8845 | |
| 8846 | const SCEV *MaxBECount = getCouldNotCompute(); |
| 8847 | if (isa<SCEVConstant>(BECount)) |
| 8848 | MaxBECount = BECount; |
| 8849 | else |
Johannes Doerfert | 2683e56 | 2015-02-09 12:34:23 +0000 | [diff] [blame] | 8850 | MaxBECount = computeBECount(getConstant(MaxStart - MinEnd), |
Andrew Trick | 34e2f0c | 2013-11-06 02:08:26 +0000 | [diff] [blame] | 8851 | getConstant(MinStride), false); |
| 8852 | |
| 8853 | if (isa<SCEVCouldNotCompute>(MaxBECount)) |
| 8854 | MaxBECount = BECount; |
| 8855 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 8856 | return ExitLimit(BECount, MaxBECount, P); |
Chris Lattner | 587a75b | 2005-08-15 23:33:51 +0000 | [diff] [blame] | 8857 | } |
| 8858 | |
Benjamin Kramer | c321e53 | 2016-06-08 19:09:22 +0000 | [diff] [blame] | 8859 | const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 8860 | ScalarEvolution &SE) const { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8861 | if (Range.isFullSet()) // Infinite loop. |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8862 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8863 | |
| 8864 | // 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] | 8865 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) |
Reid Spencer | 2e54a15 | 2007-03-02 00:28:52 +0000 | [diff] [blame] | 8866 | if (!SC->getValue()->isZero()) { |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 8867 | SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8868 | Operands[0] = SE.getZero(SC->getType()); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 8869 | const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), |
Andrew Trick | f6b01ff | 2011-03-15 00:37:00 +0000 | [diff] [blame] | 8870 | getNoWrapFlags(FlagNW)); |
Sanjoy Das | 6391459 | 2015-10-18 00:29:20 +0000 | [diff] [blame] | 8871 | if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8872 | return ShiftedAddRec->getNumIterationsInRange( |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8873 | Range.subtract(SC->getAPInt()), SE); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8874 | // This is strange and shouldn't happen. |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8875 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8876 | } |
| 8877 | |
| 8878 | // The only time we can solve this is when we have all constant indices. |
| 8879 | // Otherwise, we cannot determine the overflow conditions. |
Sanjoy Das | ff3b8b4 | 2015-12-01 07:49:23 +0000 | [diff] [blame] | 8880 | if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) |
Sanjoy Das | f07d2a7 | 2015-10-18 00:29:23 +0000 | [diff] [blame] | 8881 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8882 | |
| 8883 | // Okay at this point we know that all elements of the chrec are constants and |
| 8884 | // that the start element is zero. |
| 8885 | |
| 8886 | // First check to see if the range contains zero. If not, the first |
| 8887 | // iteration exits. |
Dan Gohman | b397e1a | 2009-04-21 01:07:12 +0000 | [diff] [blame] | 8888 | unsigned BitWidth = SE.getTypeSizeInBits(getType()); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 8889 | if (!Range.contains(APInt(BitWidth, 0))) |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 8890 | return SE.getZero(getType()); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8891 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8892 | if (isAffine()) { |
| 8893 | // If this is an affine expression then we have this situation: |
| 8894 | // Solve {0,+,A} in Range === Ax in Range |
| 8895 | |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 8896 | // We know that zero is in the range. If A is positive then we know that |
| 8897 | // the upper value of the range must be the first possible exit value. |
| 8898 | // If A is negative then the lower of the range is the last possible loop |
| 8899 | // value. Also note that we already checked for a full range. |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 8900 | APInt One(BitWidth,1); |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8901 | APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 8902 | APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8903 | |
Nick Lewycky | 5246026 | 2007-07-16 02:08:00 +0000 | [diff] [blame] | 8904 | // The exit value should be (End+A)/A. |
Nick Lewycky | 3934961 | 2007-09-27 14:12:54 +0000 | [diff] [blame] | 8905 | APInt ExitVal = (End + A).udiv(A); |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 8906 | ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8907 | |
| 8908 | // Evaluate at the exit value. If we really did fall out of the valid |
| 8909 | // range, then we computed our trip count, otherwise wrap around or other |
| 8910 | // things must have happened. |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8911 | ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8912 | if (Range.contains(Val->getValue())) |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8913 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8914 | |
| 8915 | // 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] | 8916 | assert(Range.contains( |
Dan Gohman | ce973df | 2009-06-24 04:48:43 +0000 | [diff] [blame] | 8917 | EvaluateConstantChrecAtConstant(this, |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 8918 | ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) && |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8919 | "Linear scev computation is off in a bad way!"); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8920 | return SE.getConstant(ExitValue); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8921 | } else if (isQuadratic()) { |
| 8922 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the |
| 8923 | // quadratic equation to solve it. To do this, we must frame our problem in |
| 8924 | // terms of figuring out when zero is crossed, instead of when |
| 8925 | // Range.getUpper() is crossed. |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 8926 | SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end()); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8927 | NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper())); |
Andrew Trick | 8b55b73 | 2011-03-14 16:50:06 +0000 | [diff] [blame] | 8928 | const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(), |
| 8929 | // getNoWrapFlags(FlagNW) |
| 8930 | FlagAnyWrap); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8931 | |
| 8932 | // Next, solve the constructed addrec |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 8933 | if (auto Roots = |
| 8934 | SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE)) { |
Sanjoy Das | 5a3d893 | 2016-06-15 04:37:47 +0000 | [diff] [blame] | 8935 | const SCEVConstant *R1 = Roots->first; |
| 8936 | const SCEVConstant *R2 = Roots->second; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8937 | // Pick the smallest positive root value. |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 8938 | if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp( |
| 8939 | ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 8940 | if (!CB->getZExtValue()) |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 8941 | std::swap(R1, R2); // R1 is the minimum root now. |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8942 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8943 | // Make sure the root is not off by one. The returned iteration should |
| 8944 | // not be in the range, but the previous one should be. When solving |
| 8945 | // 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] | 8946 | ConstantInt *R1Val = |
| 8947 | EvaluateConstantChrecAtConstant(this, R1->getValue(), SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8948 | if (Range.contains(R1Val->getValue())) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8949 | // The next iteration must be out of the range... |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 8950 | ConstantInt *NextVal = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8951 | ConstantInt::get(SE.getContext(), R1->getAPInt() + 1); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8952 | |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8953 | R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8954 | if (!Range.contains(R1Val->getValue())) |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8955 | return SE.getConstant(NextVal); |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 8956 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8957 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 8958 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8959 | // If R1 was not in the range, then it is a good return value. Make |
| 8960 | // sure that R1-1 WAS in the range though, just in case. |
Owen Anderson | f1f1743 | 2009-07-06 22:37:39 +0000 | [diff] [blame] | 8961 | ConstantInt *NextVal = |
Sanjoy Das | 0de2fec | 2015-12-17 20:28:46 +0000 | [diff] [blame] | 8962 | ConstantInt::get(SE.getContext(), R1->getAPInt() - 1); |
Dan Gohman | a37eaf2 | 2007-10-22 18:31:58 +0000 | [diff] [blame] | 8963 | R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE); |
Reid Spencer | 6a44033 | 2007-03-01 07:54:15 +0000 | [diff] [blame] | 8964 | if (Range.contains(R1Val->getValue())) |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8965 | return R1; |
Sanjoy Das | 0e392d5 | 2016-06-15 04:37:50 +0000 | [diff] [blame] | 8966 | return SE.getCouldNotCompute(); // Something strange happened |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8967 | } |
| 8968 | } |
| 8969 | } |
| 8970 | |
Dan Gohman | 31efa30 | 2009-04-18 17:58:19 +0000 | [diff] [blame] | 8971 | return SE.getCouldNotCompute(); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 8972 | } |
| 8973 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 8974 | namespace { |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 8975 | struct FindUndefs { |
| 8976 | bool Found; |
| 8977 | FindUndefs() : Found(false) {} |
| 8978 | |
| 8979 | bool follow(const SCEV *S) { |
| 8980 | if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) { |
| 8981 | if (isa<UndefValue>(C->getValue())) |
| 8982 | Found = true; |
| 8983 | } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { |
| 8984 | if (isa<UndefValue>(C->getValue())) |
| 8985 | Found = true; |
| 8986 | } |
| 8987 | |
| 8988 | // Keep looking if we haven't found it yet. |
| 8989 | return !Found; |
| 8990 | } |
| 8991 | bool isDone() const { |
| 8992 | // Stop recursion if we have found an undef. |
| 8993 | return Found; |
| 8994 | } |
| 8995 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 8996 | } |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 8997 | |
| 8998 | // Return true when S contains at least an undef value. |
| 8999 | static inline bool |
| 9000 | containsUndefs(const SCEV *S) { |
| 9001 | FindUndefs F; |
| 9002 | SCEVTraversal<FindUndefs> ST(F); |
| 9003 | ST.visitAll(S); |
| 9004 | |
| 9005 | return F.Found; |
| 9006 | } |
| 9007 | |
| 9008 | namespace { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9009 | // Collect all steps of SCEV expressions. |
| 9010 | struct SCEVCollectStrides { |
| 9011 | ScalarEvolution &SE; |
| 9012 | SmallVectorImpl<const SCEV *> &Strides; |
| 9013 | |
| 9014 | SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) |
| 9015 | : SE(SE), Strides(S) {} |
| 9016 | |
| 9017 | bool follow(const SCEV *S) { |
| 9018 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) |
| 9019 | Strides.push_back(AR->getStepRecurrence(SE)); |
| 9020 | return true; |
| 9021 | } |
| 9022 | bool isDone() const { return false; } |
| 9023 | }; |
| 9024 | |
| 9025 | // Collect all SCEVUnknown and SCEVMulExpr expressions. |
| 9026 | struct SCEVCollectTerms { |
| 9027 | SmallVectorImpl<const SCEV *> &Terms; |
| 9028 | |
| 9029 | SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) |
| 9030 | : Terms(T) {} |
| 9031 | |
| 9032 | bool follow(const SCEV *S) { |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9033 | if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) { |
Sebastian Pop | a7d3d6a | 2014-05-07 19:00:32 +0000 | [diff] [blame] | 9034 | if (!containsUndefs(S)) |
| 9035 | Terms.push_back(S); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9036 | |
| 9037 | // Stop recursion: once we collected a term, do not walk its operands. |
| 9038 | return false; |
| 9039 | } |
| 9040 | |
| 9041 | // Keep looking. |
| 9042 | return true; |
| 9043 | } |
| 9044 | bool isDone() const { return false; } |
| 9045 | }; |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9046 | |
| 9047 | // Check if a SCEV contains an AddRecExpr. |
| 9048 | struct SCEVHasAddRec { |
| 9049 | bool &ContainsAddRec; |
| 9050 | |
| 9051 | SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { |
| 9052 | ContainsAddRec = false; |
| 9053 | } |
| 9054 | |
| 9055 | bool follow(const SCEV *S) { |
| 9056 | if (isa<SCEVAddRecExpr>(S)) { |
| 9057 | ContainsAddRec = true; |
| 9058 | |
| 9059 | // Stop recursion: once we collected a term, do not walk its operands. |
| 9060 | return false; |
| 9061 | } |
| 9062 | |
| 9063 | // Keep looking. |
| 9064 | return true; |
| 9065 | } |
| 9066 | bool isDone() const { return false; } |
| 9067 | }; |
| 9068 | |
| 9069 | // Find factors that are multiplied with an expression that (possibly as a |
| 9070 | // subexpression) contains an AddRecExpr. In the expression: |
| 9071 | // |
| 9072 | // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) |
| 9073 | // |
| 9074 | // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" |
| 9075 | // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size |
| 9076 | // parameters as they form a product with an induction variable. |
| 9077 | // |
| 9078 | // This collector expects all array size parameters to be in the same MulExpr. |
| 9079 | // It might be necessary to later add support for collecting parameters that are |
| 9080 | // spread over different nested MulExpr. |
| 9081 | struct SCEVCollectAddRecMultiplies { |
| 9082 | SmallVectorImpl<const SCEV *> &Terms; |
| 9083 | ScalarEvolution &SE; |
| 9084 | |
| 9085 | SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) |
| 9086 | : Terms(T), SE(SE) {} |
| 9087 | |
| 9088 | bool follow(const SCEV *S) { |
| 9089 | if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { |
| 9090 | bool HasAddRec = false; |
| 9091 | SmallVector<const SCEV *, 0> Operands; |
| 9092 | for (auto Op : Mul->operands()) { |
| 9093 | if (isa<SCEVUnknown>(Op)) { |
| 9094 | Operands.push_back(Op); |
| 9095 | } else { |
| 9096 | bool ContainsAddRec; |
| 9097 | SCEVHasAddRec ContiansAddRec(ContainsAddRec); |
| 9098 | visitAll(Op, ContiansAddRec); |
| 9099 | HasAddRec |= ContainsAddRec; |
| 9100 | } |
| 9101 | } |
| 9102 | if (Operands.size() == 0) |
| 9103 | return true; |
| 9104 | |
| 9105 | if (!HasAddRec) |
| 9106 | return false; |
| 9107 | |
| 9108 | Terms.push_back(SE.getMulExpr(Operands)); |
| 9109 | // Stop recursion: once we collected a term, do not walk its operands. |
| 9110 | return false; |
| 9111 | } |
| 9112 | |
| 9113 | // Keep looking. |
| 9114 | return true; |
| 9115 | } |
| 9116 | bool isDone() const { return false; } |
| 9117 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 9118 | } |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9119 | |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9120 | /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in |
| 9121 | /// two places: |
| 9122 | /// 1) The strides of AddRec expressions. |
| 9123 | /// 2) Unknowns that are multiplied with AddRec expressions. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9124 | void ScalarEvolution::collectParametricTerms(const SCEV *Expr, |
| 9125 | SmallVectorImpl<const SCEV *> &Terms) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9126 | SmallVector<const SCEV *, 4> Strides; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9127 | SCEVCollectStrides StrideCollector(*this, Strides); |
| 9128 | visitAll(Expr, StrideCollector); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9129 | |
| 9130 | DEBUG({ |
| 9131 | dbgs() << "Strides:\n"; |
| 9132 | for (const SCEV *S : Strides) |
| 9133 | dbgs() << *S << "\n"; |
| 9134 | }); |
| 9135 | |
| 9136 | for (const SCEV *S : Strides) { |
| 9137 | SCEVCollectTerms TermCollector(Terms); |
| 9138 | visitAll(S, TermCollector); |
| 9139 | } |
| 9140 | |
| 9141 | DEBUG({ |
| 9142 | dbgs() << "Terms:\n"; |
| 9143 | for (const SCEV *T : Terms) |
| 9144 | dbgs() << *T << "\n"; |
| 9145 | }); |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9146 | |
| 9147 | SCEVCollectAddRecMultiplies MulCollector(Terms, *this); |
| 9148 | visitAll(Expr, MulCollector); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9149 | } |
| 9150 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9151 | static bool findArrayDimensionsRec(ScalarEvolution &SE, |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9152 | SmallVectorImpl<const SCEV *> &Terms, |
Sebastian Pop | 47fe7de | 2014-05-09 22:45:07 +0000 | [diff] [blame] | 9153 | SmallVectorImpl<const SCEV *> &Sizes) { |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9154 | int Last = Terms.size() - 1; |
| 9155 | const SCEV *Step = Terms[Last]; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9156 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9157 | // End of recursion. |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9158 | if (Last == 0) { |
| 9159 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9160 | SmallVector<const SCEV *, 2> Qs; |
| 9161 | for (const SCEV *Op : M->operands()) |
| 9162 | if (!isa<SCEVConstant>(Op)) |
| 9163 | Qs.push_back(Op); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9164 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9165 | Step = SE.getMulExpr(Qs); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9166 | } |
| 9167 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9168 | Sizes.push_back(Step); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9169 | return true; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9170 | } |
| 9171 | |
Benjamin Kramer | 8cff45a | 2014-05-10 17:47:18 +0000 | [diff] [blame] | 9172 | for (const SCEV *&Term : Terms) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9173 | // Normalize the terms before the next call to findArrayDimensionsRec. |
| 9174 | const SCEV *Q, *R; |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 9175 | SCEVDivision::divide(SE, Term, Step, &Q, &R); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9176 | |
| 9177 | // Bail out when GCD does not evenly divide one of the terms. |
| 9178 | if (!R->isZero()) |
| 9179 | return false; |
| 9180 | |
Benjamin Kramer | 8cff45a | 2014-05-10 17:47:18 +0000 | [diff] [blame] | 9181 | Term = Q; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9182 | } |
| 9183 | |
Tobias Grosser | 3080cf1 | 2014-05-08 07:55:34 +0000 | [diff] [blame] | 9184 | // Remove all SCEVConstants. |
David Majnemer | c700490 | 2016-08-12 04:32:37 +0000 | [diff] [blame] | 9185 | Terms.erase( |
| 9186 | remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), |
| 9187 | Terms.end()); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9188 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9189 | if (Terms.size() > 0) |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9190 | if (!findArrayDimensionsRec(SE, Terms, Sizes)) |
| 9191 | return false; |
| 9192 | |
Sebastian Pop | e30bd35 | 2014-05-27 22:41:56 +0000 | [diff] [blame] | 9193 | Sizes.push_back(Step); |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9194 | return true; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9195 | } |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9196 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9197 | // Returns true when S contains at least a SCEVUnknown parameter. |
| 9198 | static inline bool |
| 9199 | containsParameters(const SCEV *S) { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 9200 | struct FindParameter { |
| 9201 | bool FoundParameter; |
| 9202 | FindParameter() : FoundParameter(false) {} |
| 9203 | |
| 9204 | bool follow(const SCEV *S) { |
| 9205 | if (isa<SCEVUnknown>(S)) { |
| 9206 | FoundParameter = true; |
| 9207 | // Stop recursion: we found a parameter. |
| 9208 | return false; |
| 9209 | } |
| 9210 | // Keep looking. |
| 9211 | return true; |
| 9212 | } |
| 9213 | bool isDone() const { |
| 9214 | // Stop recursion if we have found a parameter. |
| 9215 | return FoundParameter; |
| 9216 | } |
| 9217 | }; |
| 9218 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9219 | FindParameter F; |
| 9220 | SCEVTraversal<FindParameter> ST(F); |
| 9221 | ST.visitAll(S); |
| 9222 | |
| 9223 | return F.FoundParameter; |
| 9224 | } |
| 9225 | |
| 9226 | // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. |
| 9227 | static inline bool |
| 9228 | containsParameters(SmallVectorImpl<const SCEV *> &Terms) { |
| 9229 | for (const SCEV *T : Terms) |
| 9230 | if (containsParameters(T)) |
| 9231 | return true; |
| 9232 | return false; |
| 9233 | } |
| 9234 | |
| 9235 | // Return the number of product terms in S. |
| 9236 | static inline int numberOfTerms(const SCEV *S) { |
| 9237 | if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) |
| 9238 | return Expr->getNumOperands(); |
| 9239 | return 1; |
| 9240 | } |
| 9241 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9242 | static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { |
| 9243 | if (isa<SCEVConstant>(T)) |
| 9244 | return nullptr; |
| 9245 | |
| 9246 | if (isa<SCEVUnknown>(T)) |
| 9247 | return T; |
| 9248 | |
| 9249 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { |
| 9250 | SmallVector<const SCEV *, 2> Factors; |
| 9251 | for (const SCEV *Op : M->operands()) |
| 9252 | if (!isa<SCEVConstant>(Op)) |
| 9253 | Factors.push_back(Op); |
| 9254 | |
| 9255 | return SE.getMulExpr(Factors); |
| 9256 | } |
| 9257 | |
| 9258 | return T; |
| 9259 | } |
| 9260 | |
| 9261 | /// Return the size of an element read or written by Inst. |
| 9262 | const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { |
| 9263 | Type *Ty; |
| 9264 | if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) |
| 9265 | Ty = Store->getValueOperand()->getType(); |
| 9266 | else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) |
Tobias Grosser | 40ac100 | 2014-06-08 19:21:20 +0000 | [diff] [blame] | 9267 | Ty = Load->getType(); |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9268 | else |
| 9269 | return nullptr; |
| 9270 | |
| 9271 | Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); |
| 9272 | return getSizeOfExpr(ETy, Ty); |
| 9273 | } |
| 9274 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9275 | void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, |
| 9276 | SmallVectorImpl<const SCEV *> &Sizes, |
| 9277 | const SCEV *ElementSize) const { |
Sebastian Pop | 5352408 | 2014-05-29 19:44:05 +0000 | [diff] [blame] | 9278 | if (Terms.size() < 1 || !ElementSize) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9279 | return; |
| 9280 | |
| 9281 | // Early return when Terms do not contain parameters: we do not delinearize |
| 9282 | // non parametric SCEVs. |
| 9283 | if (!containsParameters(Terms)) |
| 9284 | return; |
| 9285 | |
| 9286 | DEBUG({ |
| 9287 | dbgs() << "Terms:\n"; |
| 9288 | for (const SCEV *T : Terms) |
| 9289 | dbgs() << *T << "\n"; |
| 9290 | }); |
| 9291 | |
| 9292 | // Remove duplicates. |
| 9293 | std::sort(Terms.begin(), Terms.end()); |
| 9294 | Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); |
| 9295 | |
| 9296 | // Put larger terms first. |
| 9297 | std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) { |
| 9298 | return numberOfTerms(LHS) > numberOfTerms(RHS); |
| 9299 | }); |
| 9300 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9301 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
| 9302 | |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9303 | // Try to divide all terms by the element size. If term is not divisible by |
| 9304 | // element size, proceed with the original term. |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9305 | for (const SCEV *&Term : Terms) { |
| 9306 | const SCEV *Q, *R; |
David Majnemer | 4e87936 | 2014-12-14 09:12:33 +0000 | [diff] [blame] | 9307 | SCEVDivision::divide(SE, Term, ElementSize, &Q, &R); |
Tobias Grosser | 374bce0 | 2015-10-12 08:02:00 +0000 | [diff] [blame] | 9308 | if (!Q->isZero()) |
| 9309 | Term = Q; |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9310 | } |
| 9311 | |
| 9312 | SmallVector<const SCEV *, 4> NewTerms; |
| 9313 | |
| 9314 | // Remove constant factors. |
| 9315 | for (const SCEV *T : Terms) |
| 9316 | if (const SCEV *NewT = removeConstantFactors(SE, T)) |
| 9317 | NewTerms.push_back(NewT); |
| 9318 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9319 | DEBUG({ |
| 9320 | dbgs() << "Terms after sorting:\n"; |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9321 | for (const SCEV *T : NewTerms) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9322 | dbgs() << *T << "\n"; |
| 9323 | }); |
| 9324 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9325 | if (NewTerms.empty() || |
| 9326 | !findArrayDimensionsRec(SE, NewTerms, Sizes)) { |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9327 | Sizes.clear(); |
| 9328 | return; |
| 9329 | } |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9330 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9331 | // The last element to be pushed into Sizes is the size of an element. |
| 9332 | Sizes.push_back(ElementSize); |
| 9333 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9334 | DEBUG({ |
| 9335 | dbgs() << "Sizes:\n"; |
| 9336 | for (const SCEV *S : Sizes) |
| 9337 | dbgs() << *S << "\n"; |
| 9338 | }); |
| 9339 | } |
| 9340 | |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9341 | void ScalarEvolution::computeAccessFunctions( |
| 9342 | const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, |
| 9343 | SmallVectorImpl<const SCEV *> &Sizes) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9344 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9345 | // Early exit in case this SCEV is not an affine multivariate function. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9346 | if (Sizes.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9347 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9348 | |
Sanjoy Das | 1195dbe | 2015-10-08 03:45:58 +0000 | [diff] [blame] | 9349 | if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9350 | if (!AR->isAffine()) |
| 9351 | return; |
| 9352 | |
| 9353 | const SCEV *Res = Expr; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9354 | int Last = Sizes.size() - 1; |
| 9355 | for (int i = Last; i >= 0; i--) { |
| 9356 | const SCEV *Q, *R; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9357 | SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9358 | |
| 9359 | DEBUG({ |
| 9360 | dbgs() << "Res: " << *Res << "\n"; |
| 9361 | dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; |
| 9362 | dbgs() << "Res divided by Sizes[i]:\n"; |
| 9363 | dbgs() << "Quotient: " << *Q << "\n"; |
| 9364 | dbgs() << "Remainder: " << *R << "\n"; |
| 9365 | }); |
| 9366 | |
| 9367 | Res = Q; |
| 9368 | |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9369 | // Do not record the last subscript corresponding to the size of elements in |
| 9370 | // the array. |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9371 | if (i == Last) { |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9372 | |
| 9373 | // Bail out if the remainder is too complex. |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9374 | if (isa<SCEVAddRecExpr>(R)) { |
| 9375 | Subscripts.clear(); |
| 9376 | Sizes.clear(); |
| 9377 | return; |
| 9378 | } |
Sebastian Pop | a6e5860 | 2014-05-27 22:41:45 +0000 | [diff] [blame] | 9379 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9380 | continue; |
| 9381 | } |
| 9382 | |
| 9383 | // Record the access function for the current subscript. |
| 9384 | Subscripts.push_back(R); |
| 9385 | } |
| 9386 | |
| 9387 | // Also push in last position the remainder of the last division: it will be |
| 9388 | // the access function of the innermost dimension. |
| 9389 | Subscripts.push_back(Res); |
| 9390 | |
| 9391 | std::reverse(Subscripts.begin(), Subscripts.end()); |
| 9392 | |
| 9393 | DEBUG({ |
| 9394 | dbgs() << "Subscripts:\n"; |
| 9395 | for (const SCEV *S : Subscripts) |
| 9396 | dbgs() << *S << "\n"; |
| 9397 | }); |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9398 | } |
| 9399 | |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9400 | /// Splits the SCEV into two vectors of SCEVs representing the subscripts and |
| 9401 | /// sizes of an array access. Returns the remainder of the delinearization that |
Sebastian Pop | 7ee1472 | 2013-11-13 22:37:58 +0000 | [diff] [blame] | 9402 | /// is the offset start of the array. The SCEV->delinearize algorithm computes |
| 9403 | /// the multiples of SCEV coefficients: that is a pattern matching of sub |
| 9404 | /// expressions in the stride and base of a SCEV corresponding to the |
| 9405 | /// computation of a GCD (greatest common divisor) of base and stride. When |
| 9406 | /// SCEV->delinearize fails, it returns the SCEV unchanged. |
| 9407 | /// |
| 9408 | /// For example: when analyzing the memory access A[i][j][k] in this loop nest |
| 9409 | /// |
| 9410 | /// void foo(long n, long m, long o, double A[n][m][o]) { |
| 9411 | /// |
| 9412 | /// for (long i = 0; i < n; i++) |
| 9413 | /// for (long j = 0; j < m; j++) |
| 9414 | /// for (long k = 0; k < o; k++) |
| 9415 | /// A[i][j][k] = 1.0; |
| 9416 | /// } |
| 9417 | /// |
| 9418 | /// the delinearization input is the following AddRec SCEV: |
| 9419 | /// |
| 9420 | /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> |
| 9421 | /// |
| 9422 | /// From this SCEV, we are able to say that the base offset of the access is %A |
| 9423 | /// because it appears as an offset that does not divide any of the strides in |
| 9424 | /// the loops: |
| 9425 | /// |
| 9426 | /// CHECK: Base offset: %A |
| 9427 | /// |
| 9428 | /// and then SCEV->delinearize determines the size of some of the dimensions of |
| 9429 | /// the array as these are the multiples by which the strides are happening: |
| 9430 | /// |
| 9431 | /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. |
| 9432 | /// |
| 9433 | /// Note that the outermost dimension remains of UnknownSize because there are |
| 9434 | /// no strides that would help identifying the size of the last dimension: when |
| 9435 | /// the array has been statically allocated, one could compute the size of that |
| 9436 | /// dimension by dividing the overall size of the array by the size of the known |
| 9437 | /// dimensions: %m * %o * 8. |
| 9438 | /// |
| 9439 | /// Finally delinearize provides the access functions for the array reference |
| 9440 | /// that does correspond to A[i][j][k] of the above C testcase: |
| 9441 | /// |
| 9442 | /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] |
| 9443 | /// |
| 9444 | /// The testcases are checking the output of a function pass: |
| 9445 | /// DelinearizationPass that walks through all loads and stores of a function |
| 9446 | /// asking for the SCEV of the memory access with respect to all enclosing |
| 9447 | /// loops, calling SCEV->delinearize on that and printing the results. |
| 9448 | |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9449 | void ScalarEvolution::delinearize(const SCEV *Expr, |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9450 | SmallVectorImpl<const SCEV *> &Subscripts, |
| 9451 | SmallVectorImpl<const SCEV *> &Sizes, |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9452 | const SCEV *ElementSize) { |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9453 | // First step: collect parametric terms. |
| 9454 | SmallVector<const SCEV *, 4> Terms; |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9455 | collectParametricTerms(Expr, Terms); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9456 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9457 | if (Terms.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9458 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9459 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9460 | // Second step: find subscript sizes. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9461 | findArrayDimensions(Terms, Sizes, ElementSize); |
Sebastian Pop | 7ee1472 | 2013-11-13 22:37:58 +0000 | [diff] [blame] | 9462 | |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9463 | if (Sizes.empty()) |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9464 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9465 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9466 | // Third step: compute the access functions for each subscript. |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9467 | computeAccessFunctions(Expr, Subscripts, Sizes); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9468 | |
Sebastian Pop | 28e6b97 | 2014-05-27 22:41:51 +0000 | [diff] [blame] | 9469 | if (Subscripts.empty()) |
| 9470 | return; |
Sebastian Pop | b1a548f | 2014-05-12 19:01:53 +0000 | [diff] [blame] | 9471 | |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9472 | DEBUG({ |
Tobias Grosser | 3cdc37c | 2015-06-29 14:42:48 +0000 | [diff] [blame] | 9473 | dbgs() << "succeeded to delinearize " << *Expr << "\n"; |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9474 | dbgs() << "ArrayDecl[UnknownSize]"; |
| 9475 | for (const SCEV *S : Sizes) |
| 9476 | dbgs() << "[" << *S << "]"; |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9477 | |
Sebastian Pop | 444621a | 2014-05-09 22:45:02 +0000 | [diff] [blame] | 9478 | dbgs() << "\nArrayRef"; |
| 9479 | for (const SCEV *S : Subscripts) |
Sebastian Pop | 448712b | 2014-05-07 18:01:20 +0000 | [diff] [blame] | 9480 | dbgs() << "[" << *S << "]"; |
| 9481 | dbgs() << "\n"; |
| 9482 | }); |
Sebastian Pop | c62c679 | 2013-11-12 22:47:20 +0000 | [diff] [blame] | 9483 | } |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9484 | |
| 9485 | //===----------------------------------------------------------------------===// |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9486 | // SCEVCallbackVH Class Implementation |
| 9487 | //===----------------------------------------------------------------------===// |
| 9488 | |
Dan Gohman | d33a090 | 2009-05-19 19:22:47 +0000 | [diff] [blame] | 9489 | void ScalarEvolution::SCEVCallbackVH::deleted() { |
Dan Gohman | dd707af | 2009-07-13 22:20:53 +0000 | [diff] [blame] | 9490 | assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9491 | if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) |
| 9492 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9493 | SE->eraseValueFromMap(getValPtr()); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9494 | // this now dangles! |
| 9495 | } |
| 9496 | |
Dan Gohman | 7a06672 | 2010-07-28 01:09:07 +0000 | [diff] [blame] | 9497 | void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { |
Dan Gohman | dd707af | 2009-07-13 22:20:53 +0000 | [diff] [blame] | 9498 | assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); |
Eric Christopher | ef6d593 | 2010-07-29 01:25:38 +0000 | [diff] [blame] | 9499 | |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9500 | // Forget all the expressions associated with users of the old value, |
| 9501 | // so that future queries will recompute the expressions using the new |
| 9502 | // value. |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 9503 | Value *Old = getValPtr(); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 9504 | SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); |
Dan Gohman | f34f863 | 2009-07-14 14:34:04 +0000 | [diff] [blame] | 9505 | SmallPtrSet<User *, 8> Visited; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9506 | while (!Worklist.empty()) { |
| 9507 | User *U = Worklist.pop_back_val(); |
| 9508 | // Deleting the Old value will cause this to dangle. Postpone |
| 9509 | // that until everything else is done. |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 9510 | if (U == Old) |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9511 | continue; |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 9512 | if (!Visited.insert(U).second) |
Dan Gohman | f34f863 | 2009-07-14 14:34:04 +0000 | [diff] [blame] | 9513 | continue; |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9514 | if (PHINode *PN = dyn_cast<PHINode>(U)) |
| 9515 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9516 | SE->eraseValueFromMap(U); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 9517 | Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9518 | } |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 9519 | // Delete the Old value. |
| 9520 | if (PHINode *PN = dyn_cast<PHINode>(Old)) |
| 9521 | SE->ConstantEvolutionLoopExitValue.erase(PN); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9522 | SE->eraseValueFromMap(Old); |
Dan Gohman | 8aeb0fb | 2010-07-28 00:28:25 +0000 | [diff] [blame] | 9523 | // this now dangles! |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9524 | } |
| 9525 | |
Dan Gohman | d33a090 | 2009-05-19 19:22:47 +0000 | [diff] [blame] | 9526 | ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) |
Dan Gohman | 48f8222 | 2009-05-04 22:30:44 +0000 | [diff] [blame] | 9527 | : CallbackVH(V), SE(se) {} |
| 9528 | |
| 9529 | //===----------------------------------------------------------------------===// |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9530 | // ScalarEvolution Class Implementation |
| 9531 | //===----------------------------------------------------------------------===// |
| 9532 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9533 | ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, |
| 9534 | AssumptionCache &AC, DominatorTree &DT, |
| 9535 | LoopInfo &LI) |
| 9536 | : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), |
| 9537 | CouldNotCompute(new SCEVCouldNotCompute()), |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 9538 | WalkingBEDominatingConds(false), ProvingSplitPredicate(false), |
| 9539 | ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 9540 | FirstUnknown(nullptr) { |
| 9541 | |
| 9542 | // To use guards for proving predicates, we need to scan every instruction in |
| 9543 | // relevant basic blocks, and not just terminators. Doing this is a waste of |
| 9544 | // time if the IR does not actually contain any calls to |
| 9545 | // @llvm.experimental.guard, so do a quick check and remember this beforehand. |
| 9546 | // |
| 9547 | // This pessimizes the case where a pass that preserves ScalarEvolution wants |
| 9548 | // to _add_ guards to the module when there weren't any before, and wants |
| 9549 | // ScalarEvolution to optimize based on those guards. For now we prefer to be |
| 9550 | // efficient in lieu of being smart in that rather obscure case. |
| 9551 | |
| 9552 | auto *GuardDecl = F.getParent()->getFunction( |
| 9553 | Intrinsic::getName(Intrinsic::experimental_guard)); |
| 9554 | HasGuards = GuardDecl && !GuardDecl->use_empty(); |
| 9555 | } |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9556 | |
| 9557 | ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) |
Sanjoy Das | 2512d0c | 2016-05-10 00:31:49 +0000 | [diff] [blame] | 9558 | : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), |
| 9559 | LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9560 | ValueExprMap(std::move(Arg.ValueExprMap)), |
Sanjoy Das | db93375 | 2016-09-27 18:01:38 +0000 | [diff] [blame] | 9561 | PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 9562 | WalkingBEDominatingConds(false), ProvingSplitPredicate(false), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9563 | BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 9564 | PredicatedBackedgeTakenCounts( |
| 9565 | std::move(Arg.PredicatedBackedgeTakenCounts)), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9566 | ConstantEvolutionLoopExitValue( |
| 9567 | std::move(Arg.ConstantEvolutionLoopExitValue)), |
| 9568 | ValuesAtScopes(std::move(Arg.ValuesAtScopes)), |
| 9569 | LoopDispositions(std::move(Arg.LoopDispositions)), |
Sanjoy Das | 5cb11b6 | 2016-09-26 02:44:10 +0000 | [diff] [blame] | 9570 | LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), |
Chandler Carruth | 68abda5 | 2016-09-26 04:49:58 +0000 | [diff] [blame] | 9571 | BlockDispositions(std::move(Arg.BlockDispositions)), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9572 | UnsignedRanges(std::move(Arg.UnsignedRanges)), |
| 9573 | SignedRanges(std::move(Arg.SignedRanges)), |
| 9574 | UniqueSCEVs(std::move(Arg.UniqueSCEVs)), |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 9575 | UniquePreds(std::move(Arg.UniquePreds)), |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9576 | SCEVAllocator(std::move(Arg.SCEVAllocator)), |
| 9577 | FirstUnknown(Arg.FirstUnknown) { |
| 9578 | Arg.FirstUnknown = nullptr; |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9579 | } |
| 9580 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9581 | ScalarEvolution::~ScalarEvolution() { |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 9582 | // Iterate through all the SCEVUnknown instances and call their |
| 9583 | // destructors, so that they release their references to their values. |
Naomi Musgrave | f90c1be | 2015-09-16 23:46:40 +0000 | [diff] [blame] | 9584 | for (SCEVUnknown *U = FirstUnknown; U;) { |
| 9585 | SCEVUnknown *Tmp = U; |
| 9586 | U = U->Next; |
| 9587 | Tmp->~SCEVUnknown(); |
| 9588 | } |
Craig Topper | 9f00886 | 2014-04-15 04:59:12 +0000 | [diff] [blame] | 9589 | FirstUnknown = nullptr; |
Dan Gohman | 7cac957 | 2010-08-02 23:49:30 +0000 | [diff] [blame] | 9590 | |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9591 | ExprValueMap.clear(); |
Dan Gohman | 9bad2fb | 2010-08-27 18:55:03 +0000 | [diff] [blame] | 9592 | ValueExprMap.clear(); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9593 | HasRecMap.clear(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 9594 | |
| 9595 | // Free any extra memory created for ExitNotTakenInfo in the unlikely event |
| 9596 | // that a loop had multiple computable exits. |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9597 | for (auto &BTCI : BackedgeTakenCounts) |
| 9598 | BTCI.second.clear(); |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 9599 | for (auto &BTCI : PredicatedBackedgeTakenCounts) |
| 9600 | BTCI.second.clear(); |
Andrew Trick | 3ca3f98 | 2011-07-26 17:19:55 +0000 | [diff] [blame] | 9601 | |
Andrew Trick | 7fa4e0f | 2012-05-19 00:48:25 +0000 | [diff] [blame] | 9602 | assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); |
Sanjoy Das | b864c1f | 2015-04-01 18:24:06 +0000 | [diff] [blame] | 9603 | assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); |
Sanjoy Das | 7d910f2 | 2015-10-02 18:50:30 +0000 | [diff] [blame] | 9604 | assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); |
Dan Gohman | 0a40ad9 | 2009-04-16 03:18:22 +0000 | [diff] [blame] | 9605 | } |
| 9606 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9607 | bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 9608 | return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9609 | } |
| 9610 | |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9611 | static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9612 | const Loop *L) { |
| 9613 | // Print all inner loops first |
Benjamin Kramer | aa20915 | 2016-06-26 17:27:42 +0000 | [diff] [blame] | 9614 | for (Loop *I : *L) |
| 9615 | PrintLoopInfo(OS, SE, I); |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 9616 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9617 | OS << "Loop "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 9618 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9619 | OS << ": "; |
Chris Lattner | d72c3eb | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 9620 | |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 9621 | SmallVector<BasicBlock *, 8> ExitBlocks; |
Chris Lattner | d72c3eb | 2004-04-18 22:14:10 +0000 | [diff] [blame] | 9622 | L->getExitBlocks(ExitBlocks); |
| 9623 | if (ExitBlocks.size() != 1) |
Nick Lewycky | d1200b0 | 2008-01-02 02:49:20 +0000 | [diff] [blame] | 9624 | OS << "<multiple exits> "; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9625 | |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 9626 | if (SE->hasLoopInvariantBackedgeTakenCount(L)) { |
| 9627 | OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9628 | } else { |
Dan Gohman | 0bddac1 | 2009-02-24 18:55:53 +0000 | [diff] [blame] | 9629 | OS << "Unpredictable backedge-taken count. "; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9630 | } |
| 9631 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9632 | OS << "\n" |
| 9633 | "Loop "; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 9634 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9635 | OS << ": "; |
Dan Gohman | 6994293 | 2009-06-24 00:33:16 +0000 | [diff] [blame] | 9636 | |
| 9637 | if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) { |
| 9638 | OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L); |
| 9639 | } else { |
| 9640 | OS << "Unpredictable max backedge-taken count. "; |
| 9641 | } |
| 9642 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 9643 | OS << "\n" |
| 9644 | "Loop "; |
| 9645 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
| 9646 | OS << ": "; |
| 9647 | |
| 9648 | SCEVUnionPredicate Pred; |
| 9649 | auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); |
| 9650 | if (!isa<SCEVCouldNotCompute>(PBT)) { |
| 9651 | OS << "Predicated backedge-taken count is " << *PBT << "\n"; |
| 9652 | OS << " Predicates:\n"; |
| 9653 | Pred.print(OS, 4); |
| 9654 | } else { |
| 9655 | OS << "Unpredictable predicated backedge-taken count. "; |
| 9656 | } |
Dan Gohman | 6994293 | 2009-06-24 00:33:16 +0000 | [diff] [blame] | 9657 | OS << "\n"; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9658 | } |
| 9659 | |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9660 | static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { |
| 9661 | switch (LD) { |
| 9662 | case ScalarEvolution::LoopVariant: |
| 9663 | return "Variant"; |
| 9664 | case ScalarEvolution::LoopInvariant: |
| 9665 | return "Invariant"; |
| 9666 | case ScalarEvolution::LoopComputable: |
| 9667 | return "Computable"; |
| 9668 | } |
Simon Pilgrim | 33ae13d | 2016-05-01 15:52:31 +0000 | [diff] [blame] | 9669 | llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9670 | } |
| 9671 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9672 | void ScalarEvolution::print(raw_ostream &OS) const { |
Dan Gohman | 8b0a419 | 2010-03-01 17:49:51 +0000 | [diff] [blame] | 9673 | // ScalarEvolution's implementation of the print method is to print |
Dan Gohman | c8e2362 | 2009-04-21 23:15:49 +0000 | [diff] [blame] | 9674 | // out SCEV values of all instructions that are interesting. Doing |
| 9675 | // this potentially causes it to create new SCEV objects though, |
| 9676 | // which technically conflicts with the const qualifier. This isn't |
Dan Gohman | 028e615 | 2009-07-10 20:25:29 +0000 | [diff] [blame] | 9677 | // observable from outside the class though, so casting away the |
| 9678 | // const isn't dangerous. |
Dan Gohman | cb0efec | 2009-12-18 01:14:11 +0000 | [diff] [blame] | 9679 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9680 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9681 | OS << "Classifying expressions for: "; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9682 | F.printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9683 | OS << "\n"; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9684 | for (Instruction &I : instructions(F)) |
| 9685 | if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { |
| 9686 | OS << I << '\n'; |
Dan Gohman | 81313fd | 2008-09-14 17:21:12 +0000 | [diff] [blame] | 9687 | OS << " --> "; |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9688 | const SCEV *SV = SE.getSCEV(&I); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9689 | SV->print(OS); |
Sanjoy Das | f257452 | 2015-03-09 21:43:39 +0000 | [diff] [blame] | 9690 | if (!isa<SCEVCouldNotCompute>(SV)) { |
| 9691 | OS << " U: "; |
| 9692 | SE.getUnsignedRange(SV).print(OS); |
| 9693 | OS << " S: "; |
| 9694 | SE.getSignedRange(SV).print(OS); |
| 9695 | } |
Misha Brukman | 01808ca | 2005-04-21 21:13:18 +0000 | [diff] [blame] | 9696 | |
Sanjoy Das | d9f6d33 | 2015-10-18 00:29:16 +0000 | [diff] [blame] | 9697 | const Loop *L = LI.getLoopFor(I.getParent()); |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 9698 | |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 9699 | const SCEV *AtUse = SE.getSCEVAtScope(SV, L); |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 9700 | if (AtUse != SV) { |
| 9701 | OS << " --> "; |
| 9702 | AtUse->print(OS); |
Sanjoy Das | f257452 | 2015-03-09 21:43:39 +0000 | [diff] [blame] | 9703 | if (!isa<SCEVCouldNotCompute>(AtUse)) { |
| 9704 | OS << " U: "; |
| 9705 | SE.getUnsignedRange(AtUse).print(OS); |
| 9706 | OS << " S: "; |
| 9707 | SE.getSignedRange(AtUse).print(OS); |
| 9708 | } |
Dan Gohman | b9063a8 | 2009-06-19 17:49:54 +0000 | [diff] [blame] | 9709 | } |
| 9710 | |
| 9711 | if (L) { |
Dan Gohman | 94c468f | 2009-06-18 00:37:45 +0000 | [diff] [blame] | 9712 | OS << "\t\t" "Exits: "; |
Dan Gohman | af75234 | 2009-07-07 17:06:11 +0000 | [diff] [blame] | 9713 | const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9714 | if (!SE.isLoopInvariant(ExitValue, L)) { |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9715 | OS << "<<Unknown>>"; |
| 9716 | } else { |
| 9717 | OS << *ExitValue; |
| 9718 | } |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9719 | |
| 9720 | bool First = true; |
| 9721 | for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { |
| 9722 | if (First) { |
Sanjoy Das | 013a4ac | 2016-05-03 17:49:57 +0000 | [diff] [blame] | 9723 | OS << "\t\t" "LoopDispositions: { "; |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9724 | First = false; |
| 9725 | } else { |
| 9726 | OS << ", "; |
| 9727 | } |
| 9728 | |
Sanjoy Das | 013a4ac | 2016-05-03 17:49:57 +0000 | [diff] [blame] | 9729 | Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
| 9730 | OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); |
Sanjoy Das | f2f00fb1 | 2016-05-01 04:51:05 +0000 | [diff] [blame] | 9731 | } |
| 9732 | |
Sanjoy Das | 013a4ac | 2016-05-03 17:49:57 +0000 | [diff] [blame] | 9733 | for (auto *InnerL : depth_first(L)) { |
| 9734 | if (InnerL == L) |
| 9735 | continue; |
| 9736 | if (First) { |
| 9737 | OS << "\t\t" "LoopDispositions: { "; |
| 9738 | First = false; |
| 9739 | } else { |
| 9740 | OS << ", "; |
| 9741 | } |
| 9742 | |
| 9743 | InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); |
| 9744 | OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); |
| 9745 | } |
| 9746 | |
| 9747 | OS << " }"; |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9748 | } |
| 9749 | |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9750 | OS << "\n"; |
| 9751 | } |
| 9752 | |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9753 | OS << "Determining loop execution counts for: "; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9754 | F.printAsOperand(OS, /*PrintType=*/false); |
Dan Gohman | bc69491 | 2010-01-09 18:17:45 +0000 | [diff] [blame] | 9755 | OS << "\n"; |
Benjamin Kramer | aa20915 | 2016-06-26 17:27:42 +0000 | [diff] [blame] | 9756 | for (Loop *I : LI) |
| 9757 | PrintLoopInfo(OS, &SE, I); |
Chris Lattner | d934c70 | 2004-04-02 20:23:17 +0000 | [diff] [blame] | 9758 | } |
Dan Gohman | e20f824 | 2009-04-21 00:47:46 +0000 | [diff] [blame] | 9759 | |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9760 | ScalarEvolution::LoopDisposition |
| 9761 | ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9762 | auto &Values = LoopDispositions[S]; |
| 9763 | for (auto &V : Values) { |
| 9764 | if (V.getPointer() == L) |
| 9765 | return V.getInt(); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9766 | } |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9767 | Values.emplace_back(L, LoopVariant); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9768 | LoopDisposition D = computeLoopDisposition(S, L); |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9769 | auto &Values2 = LoopDispositions[S]; |
| 9770 | for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { |
| 9771 | if (V.getPointer() == L) { |
| 9772 | V.setInt(D); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9773 | break; |
| 9774 | } |
| 9775 | } |
| 9776 | return D; |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9777 | } |
| 9778 | |
| 9779 | ScalarEvolution::LoopDisposition |
| 9780 | ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9781 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9782 | case scConstant: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9783 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9784 | case scTruncate: |
| 9785 | case scZeroExtend: |
| 9786 | case scSignExtend: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9787 | return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9788 | case scAddRecExpr: { |
| 9789 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); |
| 9790 | |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9791 | // If L is the addrec's loop, it's computable. |
| 9792 | if (AR->getLoop() == L) |
| 9793 | return LoopComputable; |
| 9794 | |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9795 | // Add recurrences are never invariant in the function-body (null loop). |
| 9796 | if (!L) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9797 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9798 | |
| 9799 | // This recurrence is variant w.r.t. L if L contains AR's loop. |
| 9800 | if (L->contains(AR->getLoop())) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9801 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9802 | |
| 9803 | // This recurrence is invariant w.r.t. L if AR's loop contains L. |
| 9804 | if (AR->getLoop()->contains(L)) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9805 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9806 | |
| 9807 | // This recurrence is variant w.r.t. L if any of its operands |
| 9808 | // are variant. |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 9809 | for (auto *Op : AR->operands()) |
| 9810 | if (!isLoopInvariant(Op, L)) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9811 | return LoopVariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9812 | |
| 9813 | // Otherwise it's loop-invariant. |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9814 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9815 | } |
| 9816 | case scAddExpr: |
| 9817 | case scMulExpr: |
| 9818 | case scUMaxExpr: |
| 9819 | case scSMaxExpr: { |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9820 | bool HasVarying = false; |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 9821 | for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { |
| 9822 | LoopDisposition D = getLoopDisposition(Op, L); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9823 | if (D == LoopVariant) |
| 9824 | return LoopVariant; |
| 9825 | if (D == LoopComputable) |
| 9826 | HasVarying = true; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9827 | } |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9828 | return HasVarying ? LoopComputable : LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9829 | } |
| 9830 | case scUDivExpr: { |
| 9831 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9832 | LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); |
| 9833 | if (LD == LoopVariant) |
| 9834 | return LoopVariant; |
| 9835 | LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); |
| 9836 | if (RD == LoopVariant) |
| 9837 | return LoopVariant; |
| 9838 | return (LD == LoopInvariant && RD == LoopInvariant) ? |
| 9839 | LoopInvariant : LoopComputable; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9840 | } |
| 9841 | case scUnknown: |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9842 | // All non-instruction values are loop invariant. All instructions are loop |
| 9843 | // invariant if they are not contained in the specified loop. |
| 9844 | // Instructions are never considered invariant in the function body |
| 9845 | // (null loop) because they are defined within the "loop". |
Sanjoy Das | 0194743 | 2015-11-22 21:20:13 +0000 | [diff] [blame] | 9846 | if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9847 | return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; |
| 9848 | return LoopInvariant; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9849 | case scCouldNotCompute: |
| 9850 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9851 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9852 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 7ee1bbb | 2010-11-17 23:21:44 +0000 | [diff] [blame] | 9853 | } |
| 9854 | |
| 9855 | bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { |
| 9856 | return getLoopDisposition(S, L) == LoopInvariant; |
| 9857 | } |
| 9858 | |
| 9859 | bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { |
| 9860 | return getLoopDisposition(S, L) == LoopComputable; |
Dan Gohman | afd6db9 | 2010-11-17 21:23:15 +0000 | [diff] [blame] | 9861 | } |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9862 | |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9863 | ScalarEvolution::BlockDisposition |
| 9864 | ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9865 | auto &Values = BlockDispositions[S]; |
| 9866 | for (auto &V : Values) { |
| 9867 | if (V.getPointer() == BB) |
| 9868 | return V.getInt(); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9869 | } |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9870 | Values.emplace_back(BB, DoesNotDominateBlock); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9871 | BlockDisposition D = computeBlockDisposition(S, BB); |
Benjamin Kramer | d7e331e | 2015-02-07 16:41:12 +0000 | [diff] [blame] | 9872 | auto &Values2 = BlockDispositions[S]; |
| 9873 | for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { |
| 9874 | if (V.getPointer() == BB) { |
| 9875 | V.setInt(D); |
Wan Xiaofei | b2c8cdc | 2013-11-12 09:40:41 +0000 | [diff] [blame] | 9876 | break; |
| 9877 | } |
| 9878 | } |
| 9879 | return D; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9880 | } |
| 9881 | |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9882 | ScalarEvolution::BlockDisposition |
| 9883 | ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9884 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9885 | case scConstant: |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9886 | return ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9887 | case scTruncate: |
| 9888 | case scZeroExtend: |
| 9889 | case scSignExtend: |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9890 | return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9891 | case scAddRecExpr: { |
| 9892 | // This uses a "dominates" query instead of "properly dominates" query |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9893 | // to test for proper dominance too, because the instruction which |
| 9894 | // produces the addrec's value is a PHI, and a PHI effectively properly |
| 9895 | // dominates its entire containing block. |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9896 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9897 | if (!DT.dominates(AR->getLoop()->getHeader(), BB)) |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9898 | return DoesNotDominateBlock; |
Justin Bogner | cd1d5aa | 2016-08-17 20:30:52 +0000 | [diff] [blame] | 9899 | |
| 9900 | // Fall through into SCEVNAryExpr handling. |
| 9901 | LLVM_FALLTHROUGH; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9902 | } |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9903 | case scAddExpr: |
| 9904 | case scMulExpr: |
| 9905 | case scUMaxExpr: |
| 9906 | case scSMaxExpr: { |
| 9907 | const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9908 | bool Proper = true; |
Sanjoy Das | d87e435 | 2015-12-08 22:53:36 +0000 | [diff] [blame] | 9909 | for (const SCEV *NAryOp : NAry->operands()) { |
| 9910 | BlockDisposition D = getBlockDisposition(NAryOp, BB); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9911 | if (D == DoesNotDominateBlock) |
| 9912 | return DoesNotDominateBlock; |
| 9913 | if (D == DominatesBlock) |
| 9914 | Proper = false; |
| 9915 | } |
| 9916 | return Proper ? ProperlyDominatesBlock : DominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9917 | } |
| 9918 | case scUDivExpr: { |
| 9919 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9920 | const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); |
| 9921 | BlockDisposition LD = getBlockDisposition(LHS, BB); |
| 9922 | if (LD == DoesNotDominateBlock) |
| 9923 | return DoesNotDominateBlock; |
| 9924 | BlockDisposition RD = getBlockDisposition(RHS, BB); |
| 9925 | if (RD == DoesNotDominateBlock) |
| 9926 | return DoesNotDominateBlock; |
| 9927 | return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? |
| 9928 | ProperlyDominatesBlock : DominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9929 | } |
| 9930 | case scUnknown: |
| 9931 | if (Instruction *I = |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9932 | dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { |
| 9933 | if (I->getParent() == BB) |
| 9934 | return DominatesBlock; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 9935 | if (DT.properlyDominates(I->getParent(), BB)) |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9936 | return ProperlyDominatesBlock; |
| 9937 | return DoesNotDominateBlock; |
| 9938 | } |
| 9939 | return ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9940 | case scCouldNotCompute: |
| 9941 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9942 | } |
Benjamin Kramer | 987b850 | 2014-02-11 19:02:55 +0000 | [diff] [blame] | 9943 | llvm_unreachable("Unknown SCEV kind!"); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9944 | } |
| 9945 | |
| 9946 | bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { |
| 9947 | return getBlockDisposition(S, BB) >= DominatesBlock; |
| 9948 | } |
| 9949 | |
| 9950 | bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { |
| 9951 | return getBlockDisposition(S, BB) == ProperlyDominatesBlock; |
Dan Gohman | 20d9ce2 | 2010-11-17 21:41:58 +0000 | [diff] [blame] | 9952 | } |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 9953 | |
| 9954 | bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { |
Sanjoy Das | 7d75267 | 2015-12-08 04:32:54 +0000 | [diff] [blame] | 9955 | // Search for a SCEV expression node within an expression tree. |
| 9956 | // Implements SCEVTraversal::Visitor. |
| 9957 | struct SCEVSearch { |
| 9958 | const SCEV *Node; |
| 9959 | bool IsFound; |
| 9960 | |
| 9961 | SCEVSearch(const SCEV *N): Node(N), IsFound(false) {} |
| 9962 | |
| 9963 | bool follow(const SCEV *S) { |
| 9964 | IsFound |= (S == Node); |
| 9965 | return !IsFound; |
| 9966 | } |
| 9967 | bool isDone() const { return IsFound; } |
| 9968 | }; |
| 9969 | |
Andrew Trick | 365e31c | 2012-07-13 23:33:03 +0000 | [diff] [blame] | 9970 | SCEVSearch Search(Op); |
| 9971 | visitAll(S, Search); |
| 9972 | return Search.IsFound; |
Dan Gohman | 534749b | 2010-11-17 22:27:42 +0000 | [diff] [blame] | 9973 | } |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 9974 | |
| 9975 | void ScalarEvolution::forgetMemoizedResults(const SCEV *S) { |
| 9976 | ValuesAtScopes.erase(S); |
| 9977 | LoopDispositions.erase(S); |
Dan Gohman | 8ea83d8 | 2010-11-18 00:34:22 +0000 | [diff] [blame] | 9978 | BlockDispositions.erase(S); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 9979 | UnsignedRanges.erase(S); |
| 9980 | SignedRanges.erase(S); |
Wei Mi | a49559b | 2016-02-04 01:27:38 +0000 | [diff] [blame] | 9981 | ExprValueMap.erase(S); |
| 9982 | HasRecMap.erase(S); |
Andrew Trick | 9093e15 | 2013-03-26 03:14:53 +0000 | [diff] [blame] | 9983 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 9984 | auto RemoveSCEVFromBackedgeMap = |
| 9985 | [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { |
| 9986 | for (auto I = Map.begin(), E = Map.end(); I != E;) { |
| 9987 | BackedgeTakenInfo &BEInfo = I->second; |
| 9988 | if (BEInfo.hasOperand(S, this)) { |
| 9989 | BEInfo.clear(); |
| 9990 | Map.erase(I++); |
| 9991 | } else |
| 9992 | ++I; |
| 9993 | } |
| 9994 | }; |
| 9995 | |
| 9996 | RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); |
| 9997 | RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); |
Dan Gohman | 7e6b393 | 2010-11-17 23:28:48 +0000 | [diff] [blame] | 9998 | } |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 9999 | |
| 10000 | typedef DenseMap<const Loop *, std::string> VerifyMap; |
Benjamin Kramer | 24d270d | 2012-10-27 10:45:01 +0000 | [diff] [blame] | 10001 | |
Alp Toker | cb40291 | 2014-01-24 17:20:08 +0000 | [diff] [blame] | 10002 | /// replaceSubString - Replaces all occurrences of From in Str with To. |
Benjamin Kramer | 24d270d | 2012-10-27 10:45:01 +0000 | [diff] [blame] | 10003 | static void replaceSubString(std::string &Str, StringRef From, StringRef To) { |
| 10004 | size_t Pos = 0; |
| 10005 | while ((Pos = Str.find(From, Pos)) != std::string::npos) { |
| 10006 | Str.replace(Pos, From.size(), To.data(), To.size()); |
| 10007 | Pos += To.size(); |
| 10008 | } |
| 10009 | } |
| 10010 | |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10011 | /// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis. |
| 10012 | static void |
| 10013 | getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) { |
Sanjoy Das | 2fbfb25 | 2015-12-23 17:48:14 +0000 | [diff] [blame] | 10014 | std::string &S = Map[L]; |
| 10015 | if (S.empty()) { |
| 10016 | raw_string_ostream OS(S); |
| 10017 | SE.getBackedgeTakenCount(L)->print(OS); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10018 | |
Sanjoy Das | 2fbfb25 | 2015-12-23 17:48:14 +0000 | [diff] [blame] | 10019 | // false and 0 are semantically equivalent. This can happen in dead loops. |
| 10020 | replaceSubString(OS.str(), "false", "0"); |
| 10021 | // Remove wrap flags, their use in SCEV is highly fragile. |
| 10022 | // FIXME: Remove this when SCEV gets smarter about them. |
| 10023 | replaceSubString(OS.str(), "<nw>", ""); |
| 10024 | replaceSubString(OS.str(), "<nsw>", ""); |
| 10025 | replaceSubString(OS.str(), "<nuw>", ""); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10026 | } |
Sanjoy Das | 2fbfb25 | 2015-12-23 17:48:14 +0000 | [diff] [blame] | 10027 | |
JF Bastien | 61ad8b3 | 2015-12-23 18:18:53 +0000 | [diff] [blame] | 10028 | for (auto *R : reverse(*L)) |
| 10029 | getLoopBackedgeTakenCounts(R, Map, SE); // recurse. |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10030 | } |
| 10031 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10032 | void ScalarEvolution::verify() const { |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10033 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); |
| 10034 | |
| 10035 | // Gather stringified backedge taken counts for all loops using SCEV's caches. |
| 10036 | // FIXME: It would be much better to store actual values instead of strings, |
| 10037 | // but SCEV pointers will change if we drop the caches. |
| 10038 | VerifyMap BackedgeDumpsOld, BackedgeDumpsNew; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10039 | 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] | 10040 | getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE); |
| 10041 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10042 | // Gather stringified backedge taken counts for all loops using a fresh |
| 10043 | // ScalarEvolution object. |
| 10044 | ScalarEvolution SE2(F, TLI, AC, DT, LI); |
| 10045 | for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I) |
| 10046 | getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2); |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10047 | |
| 10048 | // Now compare whether they're the same with and without caches. This allows |
| 10049 | // verifying that no pass changed the cache. |
| 10050 | assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() && |
| 10051 | "New loops suddenly appeared!"); |
| 10052 | |
| 10053 | for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(), |
| 10054 | OldE = BackedgeDumpsOld.end(), |
| 10055 | NewI = BackedgeDumpsNew.begin(); |
| 10056 | OldI != OldE; ++OldI, ++NewI) { |
| 10057 | assert(OldI->first == NewI->first && "Loop order changed!"); |
| 10058 | |
| 10059 | // Compare the stringified SCEVs. We don't care if undef backedgetaken count |
| 10060 | // changes. |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 10061 | // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10062 | // means that a pass is buggy or SCEV has to learn a new pattern but is |
| 10063 | // usually not harmful. |
| 10064 | if (OldI->second != NewI->second && |
| 10065 | OldI->second.find("undef") == std::string::npos && |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 10066 | NewI->second.find("undef") == std::string::npos && |
| 10067 | OldI->second != "***COULDNOTCOMPUTE***" && |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10068 | NewI->second != "***COULDNOTCOMPUTE***") { |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 10069 | dbgs() << "SCEVValidator: SCEV for loop '" |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10070 | << OldI->first->getHeader()->getName() |
Benjamin Kramer | 5bc077a | 2012-10-27 11:36:07 +0000 | [diff] [blame] | 10071 | << "' changed from '" << OldI->second |
| 10072 | << "' to '" << NewI->second << "'!\n"; |
Benjamin Kramer | 214935e | 2012-10-26 17:31:32 +0000 | [diff] [blame] | 10073 | std::abort(); |
| 10074 | } |
| 10075 | } |
| 10076 | |
| 10077 | // TODO: Verify more things. |
| 10078 | } |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10079 | |
Chandler Carruth | b4faf13 | 2016-03-11 10:22:49 +0000 | [diff] [blame] | 10080 | char ScalarEvolutionAnalysis::PassID; |
NAKAMURA Takumi | df0cd72 | 2016-02-28 17:17:00 +0000 | [diff] [blame] | 10081 | |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10082 | ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, |
Sean Silva | 36e0d01 | 2016-08-09 00:28:15 +0000 | [diff] [blame] | 10083 | FunctionAnalysisManager &AM) { |
Chandler Carruth | b47f801 | 2016-03-11 11:05:24 +0000 | [diff] [blame] | 10084 | return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), |
| 10085 | AM.getResult<AssumptionAnalysis>(F), |
| 10086 | AM.getResult<DominatorTreeAnalysis>(F), |
| 10087 | AM.getResult<LoopAnalysis>(F)); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10088 | } |
| 10089 | |
| 10090 | PreservedAnalyses |
Sean Silva | 36e0d01 | 2016-08-09 00:28:15 +0000 | [diff] [blame] | 10091 | ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { |
Chandler Carruth | b47f801 | 2016-03-11 11:05:24 +0000 | [diff] [blame] | 10092 | AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 10093 | return PreservedAnalyses::all(); |
| 10094 | } |
| 10095 | |
| 10096 | INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", |
| 10097 | "Scalar Evolution Analysis", false, true) |
| 10098 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) |
| 10099 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
| 10100 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 10101 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
| 10102 | INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", |
| 10103 | "Scalar Evolution Analysis", false, true) |
| 10104 | char ScalarEvolutionWrapperPass::ID = 0; |
| 10105 | |
| 10106 | ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { |
| 10107 | initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); |
| 10108 | } |
| 10109 | |
| 10110 | bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { |
| 10111 | SE.reset(new ScalarEvolution( |
| 10112 | F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(), |
| 10113 | getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), |
| 10114 | getAnalysis<DominatorTreeWrapperPass>().getDomTree(), |
| 10115 | getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); |
| 10116 | return false; |
| 10117 | } |
| 10118 | |
| 10119 | void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } |
| 10120 | |
| 10121 | void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { |
| 10122 | SE->print(OS); |
| 10123 | } |
| 10124 | |
| 10125 | void ScalarEvolutionWrapperPass::verifyAnalysis() const { |
| 10126 | if (!VerifySCEV) |
| 10127 | return; |
| 10128 | |
| 10129 | SE->verify(); |
| 10130 | } |
| 10131 | |
| 10132 | void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { |
| 10133 | AU.setPreservesAll(); |
| 10134 | AU.addRequiredTransitive<AssumptionCacheTracker>(); |
| 10135 | AU.addRequiredTransitive<LoopInfoWrapperPass>(); |
| 10136 | AU.addRequiredTransitive<DominatorTreeWrapperPass>(); |
| 10137 | AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); |
| 10138 | } |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10139 | |
| 10140 | const SCEVPredicate * |
| 10141 | ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS, |
| 10142 | const SCEVConstant *RHS) { |
| 10143 | FoldingSetNodeID ID; |
| 10144 | // Unique this node based on the arguments |
| 10145 | ID.AddInteger(SCEVPredicate::P_Equal); |
| 10146 | ID.AddPointer(LHS); |
| 10147 | ID.AddPointer(RHS); |
| 10148 | void *IP = nullptr; |
| 10149 | if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) |
| 10150 | return S; |
| 10151 | SCEVEqualPredicate *Eq = new (SCEVAllocator) |
| 10152 | SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); |
| 10153 | UniquePreds.InsertNode(Eq, IP); |
| 10154 | return Eq; |
| 10155 | } |
| 10156 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10157 | const SCEVPredicate *ScalarEvolution::getWrapPredicate( |
| 10158 | const SCEVAddRecExpr *AR, |
| 10159 | SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { |
| 10160 | FoldingSetNodeID ID; |
| 10161 | // Unique this node based on the arguments |
| 10162 | ID.AddInteger(SCEVPredicate::P_Wrap); |
| 10163 | ID.AddPointer(AR); |
| 10164 | ID.AddInteger(AddedFlags); |
| 10165 | void *IP = nullptr; |
| 10166 | if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) |
| 10167 | return S; |
| 10168 | auto *OF = new (SCEVAllocator) |
| 10169 | SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); |
| 10170 | UniquePreds.InsertNode(OF, IP); |
| 10171 | return OF; |
| 10172 | } |
| 10173 | |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 10174 | namespace { |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10175 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10176 | class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { |
| 10177 | public: |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 10178 | // Rewrites \p S in the context of a loop L and the predicate A. |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10179 | // If Assume is true, rewrite is free to add further predicates to A |
| 10180 | // such that the result will be an AddRecExpr. |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 10181 | static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, |
| 10182 | SCEVUnionPredicate &A, bool Assume) { |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10183 | SCEVPredicateRewriter Rewriter(L, SE, A, Assume); |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 10184 | return Rewriter.visit(S); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10185 | } |
| 10186 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10187 | SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, |
| 10188 | SCEVUnionPredicate &P, bool Assume) |
| 10189 | : SCEVRewriteVisitor(SE), P(P), L(L), Assume(Assume) {} |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10190 | |
| 10191 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { |
| 10192 | auto ExprPreds = P.getPredicatesForExpr(Expr); |
| 10193 | for (auto *Pred : ExprPreds) |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 10194 | if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10195 | if (IPred->getLHS() == Expr) |
| 10196 | return IPred->getRHS(); |
| 10197 | |
| 10198 | return Expr; |
| 10199 | } |
| 10200 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10201 | const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { |
| 10202 | const SCEV *Operand = visit(Expr->getOperand()); |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 10203 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10204 | if (AR && AR->getLoop() == L && AR->isAffine()) { |
| 10205 | // This couldn't be folded because the operand didn't have the nuw |
| 10206 | // flag. Add the nusw flag as an assumption that we could make. |
| 10207 | const SCEV *Step = AR->getStepRecurrence(SE); |
| 10208 | Type *Ty = Expr->getType(); |
| 10209 | if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) |
| 10210 | return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), |
| 10211 | SE.getSignExtendExpr(Step, Ty), L, |
| 10212 | AR->getNoWrapFlags()); |
| 10213 | } |
| 10214 | return SE.getZeroExtendExpr(Operand, Expr->getType()); |
| 10215 | } |
| 10216 | |
| 10217 | const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { |
| 10218 | const SCEV *Operand = visit(Expr->getOperand()); |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 10219 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10220 | if (AR && AR->getLoop() == L && AR->isAffine()) { |
| 10221 | // This couldn't be folded because the operand didn't have the nsw |
| 10222 | // flag. Add the nssw flag as an assumption that we could make. |
| 10223 | const SCEV *Step = AR->getStepRecurrence(SE); |
| 10224 | Type *Ty = Expr->getType(); |
| 10225 | if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) |
| 10226 | return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), |
| 10227 | SE.getSignExtendExpr(Step, Ty), L, |
| 10228 | AR->getNoWrapFlags()); |
| 10229 | } |
| 10230 | return SE.getSignExtendExpr(Operand, Expr->getType()); |
| 10231 | } |
| 10232 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10233 | private: |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10234 | bool addOverflowAssumption(const SCEVAddRecExpr *AR, |
| 10235 | SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { |
| 10236 | auto *A = SE.getWrapPredicate(AR, AddedFlags); |
| 10237 | if (!Assume) { |
| 10238 | // Check if we've already made this assumption. |
| 10239 | if (P.implies(A)) |
| 10240 | return true; |
| 10241 | return false; |
| 10242 | } |
| 10243 | P.add(A); |
| 10244 | return true; |
| 10245 | } |
| 10246 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10247 | SCEVUnionPredicate &P; |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10248 | const Loop *L; |
| 10249 | bool Assume; |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10250 | }; |
Benjamin Kramer | 83709b1 | 2015-11-16 09:01:28 +0000 | [diff] [blame] | 10251 | } // end anonymous namespace |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10252 | |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 10253 | const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10254 | SCEVUnionPredicate &Preds) { |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 10255 | return SCEVPredicateRewriter::rewrite(S, L, *this, Preds, false); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10256 | } |
| 10257 | |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 10258 | const SCEVAddRecExpr * |
Sanjoy Das | 807d33d | 2016-02-20 01:44:10 +0000 | [diff] [blame] | 10259 | ScalarEvolution::convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, |
| 10260 | SCEVUnionPredicate &Preds) { |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 10261 | SCEVUnionPredicate TransformPreds; |
| 10262 | S = SCEVPredicateRewriter::rewrite(S, L, *this, TransformPreds, true); |
| 10263 | auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); |
| 10264 | |
| 10265 | if (!AddRec) |
| 10266 | return nullptr; |
| 10267 | |
| 10268 | // Since the transformation was successful, we can now transfer the SCEV |
| 10269 | // predicates. |
| 10270 | Preds.add(&TransformPreds); |
| 10271 | return AddRec; |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10272 | } |
| 10273 | |
| 10274 | /// SCEV predicates |
| 10275 | SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, |
| 10276 | SCEVPredicateKind Kind) |
| 10277 | : FastID(ID), Kind(Kind) {} |
| 10278 | |
| 10279 | SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, |
| 10280 | const SCEVUnknown *LHS, |
| 10281 | const SCEVConstant *RHS) |
| 10282 | : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {} |
| 10283 | |
| 10284 | bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 10285 | const auto *Op = dyn_cast<SCEVEqualPredicate>(N); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10286 | |
| 10287 | if (!Op) |
| 10288 | return false; |
| 10289 | |
| 10290 | return Op->LHS == LHS && Op->RHS == RHS; |
| 10291 | } |
| 10292 | |
| 10293 | bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } |
| 10294 | |
| 10295 | const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } |
| 10296 | |
| 10297 | void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { |
| 10298 | OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; |
| 10299 | } |
| 10300 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10301 | SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, |
| 10302 | const SCEVAddRecExpr *AR, |
| 10303 | IncrementWrapFlags Flags) |
| 10304 | : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} |
| 10305 | |
| 10306 | const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } |
| 10307 | |
| 10308 | bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { |
| 10309 | const auto *Op = dyn_cast<SCEVWrapPredicate>(N); |
| 10310 | |
| 10311 | return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; |
| 10312 | } |
| 10313 | |
| 10314 | bool SCEVWrapPredicate::isAlwaysTrue() const { |
| 10315 | SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); |
| 10316 | IncrementWrapFlags IFlags = Flags; |
| 10317 | |
| 10318 | if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) |
| 10319 | IFlags = clearFlags(IFlags, IncrementNSSW); |
| 10320 | |
| 10321 | return IFlags == IncrementAnyWrap; |
| 10322 | } |
| 10323 | |
| 10324 | void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { |
| 10325 | OS.indent(Depth) << *getExpr() << " Added Flags: "; |
| 10326 | if (SCEVWrapPredicate::IncrementNUSW & getFlags()) |
| 10327 | OS << "<nusw>"; |
| 10328 | if (SCEVWrapPredicate::IncrementNSSW & getFlags()) |
| 10329 | OS << "<nssw>"; |
| 10330 | OS << "\n"; |
| 10331 | } |
| 10332 | |
| 10333 | SCEVWrapPredicate::IncrementWrapFlags |
| 10334 | SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, |
| 10335 | ScalarEvolution &SE) { |
| 10336 | IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; |
| 10337 | SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); |
| 10338 | |
| 10339 | // We can safely transfer the NSW flag as NSSW. |
| 10340 | if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) |
| 10341 | ImpliedFlags = IncrementNSSW; |
| 10342 | |
| 10343 | if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { |
| 10344 | // If the increment is positive, the SCEV NUW flag will also imply the |
| 10345 | // WrapPredicate NUSW flag. |
| 10346 | if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) |
| 10347 | if (Step->getValue()->getValue().isNonNegative()) |
| 10348 | ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); |
| 10349 | } |
| 10350 | |
| 10351 | return ImpliedFlags; |
| 10352 | } |
| 10353 | |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10354 | /// Union predicates don't get cached so create a dummy set ID for it. |
| 10355 | SCEVUnionPredicate::SCEVUnionPredicate() |
| 10356 | : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} |
| 10357 | |
| 10358 | bool SCEVUnionPredicate::isAlwaysTrue() const { |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 10359 | return all_of(Preds, |
| 10360 | [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10361 | } |
| 10362 | |
| 10363 | ArrayRef<const SCEVPredicate *> |
| 10364 | SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { |
| 10365 | auto I = SCEVToPreds.find(Expr); |
| 10366 | if (I == SCEVToPreds.end()) |
| 10367 | return ArrayRef<const SCEVPredicate *>(); |
| 10368 | return I->second; |
| 10369 | } |
| 10370 | |
| 10371 | bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 10372 | if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) |
Sanjoy Das | 3b827c7 | 2015-11-29 23:40:53 +0000 | [diff] [blame] | 10373 | return all_of(Set->Preds, |
| 10374 | [this](const SCEVPredicate *I) { return this->implies(I); }); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10375 | |
| 10376 | auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); |
| 10377 | if (ScevPredsIt == SCEVToPreds.end()) |
| 10378 | return false; |
| 10379 | auto &SCEVPreds = ScevPredsIt->second; |
| 10380 | |
Sanjoy Das | ff3b8b4 | 2015-12-01 07:49:23 +0000 | [diff] [blame] | 10381 | return any_of(SCEVPreds, |
| 10382 | [N](const SCEVPredicate *I) { return I->implies(N); }); |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10383 | } |
| 10384 | |
| 10385 | const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } |
| 10386 | |
| 10387 | void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { |
| 10388 | for (auto Pred : Preds) |
| 10389 | Pred->print(OS, Depth); |
| 10390 | } |
| 10391 | |
| 10392 | void SCEVUnionPredicate::add(const SCEVPredicate *N) { |
Sanjoy Das | b277a42 | 2016-06-15 06:53:55 +0000 | [diff] [blame] | 10393 | if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { |
Silviu Baranga | e3c0534 | 2015-11-02 14:41:02 +0000 | [diff] [blame] | 10394 | for (auto Pred : Set->Preds) |
| 10395 | add(Pred); |
| 10396 | return; |
| 10397 | } |
| 10398 | |
| 10399 | if (implies(N)) |
| 10400 | return; |
| 10401 | |
| 10402 | const SCEV *Key = N->getExpr(); |
| 10403 | assert(Key && "Only SCEVUnionPredicate doesn't have an " |
| 10404 | " associated expression!"); |
| 10405 | |
| 10406 | SCEVToPreds[Key].push_back(N); |
| 10407 | Preds.push_back(N); |
| 10408 | } |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10409 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10410 | PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, |
| 10411 | Loop &L) |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 10412 | : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {} |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10413 | |
| 10414 | const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { |
| 10415 | const SCEV *Expr = SE.getSCEV(V); |
| 10416 | RewriteEntry &Entry = RewriteMap[Expr]; |
| 10417 | |
| 10418 | // If we already have an entry and the version matches, return it. |
| 10419 | if (Entry.second && Generation == Entry.first) |
| 10420 | return Entry.second; |
| 10421 | |
| 10422 | // We found an entry but it's stale. Rewrite the stale entry |
| 10423 | // acording to the current predicate. |
| 10424 | if (Entry.second) |
| 10425 | Expr = Entry.second; |
| 10426 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10427 | const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10428 | Entry = {Generation, NewSCEV}; |
| 10429 | |
| 10430 | return NewSCEV; |
| 10431 | } |
| 10432 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 10433 | const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { |
| 10434 | if (!BackedgeCount) { |
| 10435 | SCEVUnionPredicate BackedgePred; |
| 10436 | BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); |
| 10437 | addPredicate(BackedgePred); |
| 10438 | } |
| 10439 | return BackedgeCount; |
| 10440 | } |
| 10441 | |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10442 | void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { |
| 10443 | if (Preds.implies(&Pred)) |
| 10444 | return; |
| 10445 | Preds.add(&Pred); |
| 10446 | updateGeneration(); |
| 10447 | } |
| 10448 | |
| 10449 | const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { |
| 10450 | return Preds; |
| 10451 | } |
| 10452 | |
| 10453 | void PredicatedScalarEvolution::updateGeneration() { |
| 10454 | // If the generation number wrapped recompute everything. |
| 10455 | if (++Generation == 0) { |
| 10456 | for (auto &II : RewriteMap) { |
| 10457 | const SCEV *Rewritten = II.second.second; |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10458 | II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; |
Silviu Baranga | 9cd9a7e | 2015-12-09 16:06:28 +0000 | [diff] [blame] | 10459 | } |
| 10460 | } |
| 10461 | } |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10462 | |
| 10463 | void PredicatedScalarEvolution::setNoOverflow( |
| 10464 | Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { |
| 10465 | const SCEV *Expr = getSCEV(V); |
| 10466 | const auto *AR = cast<SCEVAddRecExpr>(Expr); |
| 10467 | |
| 10468 | auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); |
| 10469 | |
| 10470 | // Clear the statically implied flags. |
| 10471 | Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); |
| 10472 | addPredicate(*SE.getWrapPredicate(AR, Flags)); |
| 10473 | |
| 10474 | auto II = FlagsMap.insert({V, Flags}); |
| 10475 | if (!II.second) |
| 10476 | II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); |
| 10477 | } |
| 10478 | |
| 10479 | bool PredicatedScalarEvolution::hasNoOverflow( |
| 10480 | Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { |
| 10481 | const SCEV *Expr = getSCEV(V); |
| 10482 | const auto *AR = cast<SCEVAddRecExpr>(Expr); |
| 10483 | |
| 10484 | Flags = SCEVWrapPredicate::clearFlags( |
| 10485 | Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); |
| 10486 | |
| 10487 | auto II = FlagsMap.find(V); |
| 10488 | |
| 10489 | if (II != FlagsMap.end()) |
| 10490 | Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); |
| 10491 | |
| 10492 | return Flags == SCEVWrapPredicate::IncrementAnyWrap; |
| 10493 | } |
| 10494 | |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 10495 | const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10496 | const SCEV *Expr = this->getSCEV(V); |
Silviu Baranga | d68ed85 | 2016-03-23 15:29:30 +0000 | [diff] [blame] | 10497 | auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, Preds); |
| 10498 | |
| 10499 | if (!New) |
| 10500 | return nullptr; |
| 10501 | |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10502 | updateGeneration(); |
| 10503 | RewriteMap[SE.getSCEV(V)] = {Generation, New}; |
| 10504 | return New; |
| 10505 | } |
| 10506 | |
Silviu Baranga | 6f444df | 2016-04-08 14:29:09 +0000 | [diff] [blame] | 10507 | PredicatedScalarEvolution::PredicatedScalarEvolution( |
| 10508 | const PredicatedScalarEvolution &Init) |
| 10509 | : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), |
| 10510 | Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { |
Benjamin Kramer | aa20915 | 2016-06-26 17:27:42 +0000 | [diff] [blame] | 10511 | for (const auto &I : Init.FlagsMap) |
| 10512 | FlagsMap.insert(I); |
Silviu Baranga | ea63a7f | 2016-02-08 17:02:45 +0000 | [diff] [blame] | 10513 | } |
Silviu Baranga | b77365b | 2016-04-14 16:08:45 +0000 | [diff] [blame] | 10514 | |
| 10515 | void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { |
| 10516 | // For each block. |
| 10517 | for (auto *BB : L.getBlocks()) |
| 10518 | for (auto &I : *BB) { |
| 10519 | if (!SE.isSCEVable(I.getType())) |
| 10520 | continue; |
| 10521 | |
| 10522 | auto *Expr = SE.getSCEV(&I); |
| 10523 | auto II = RewriteMap.find(Expr); |
| 10524 | |
| 10525 | if (II == RewriteMap.end()) |
| 10526 | continue; |
| 10527 | |
| 10528 | // Don't print things that are not interesting. |
| 10529 | if (II->second.second == Expr) |
| 10530 | continue; |
| 10531 | |
| 10532 | OS.indent(Depth) << "[PSE]" << I << ":\n"; |
| 10533 | OS.indent(Depth + 2) << *Expr << "\n"; |
| 10534 | OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; |
| 10535 | } |
| 10536 | } |