Bug Summary

File:lib/Analysis/ScalarEvolution.cpp
Warning:line 4046, column 3
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ScalarEvolution.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/lib/Analysis -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp -faddrsig
1//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
17// can handle. We only create one SCEV of a particular shape, so
18// pointer-comparisons for equality are legal.
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.
30//
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//
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
61#include "llvm/Analysis/ScalarEvolution.h"
62#include "llvm/ADT/APInt.h"
63#include "llvm/ADT/ArrayRef.h"
64#include "llvm/ADT/DenseMap.h"
65#include "llvm/ADT/DepthFirstIterator.h"
66#include "llvm/ADT/EquivalenceClasses.h"
67#include "llvm/ADT/FoldingSet.h"
68#include "llvm/ADT/None.h"
69#include "llvm/ADT/Optional.h"
70#include "llvm/ADT/STLExtras.h"
71#include "llvm/ADT/ScopeExit.h"
72#include "llvm/ADT/Sequence.h"
73#include "llvm/ADT/SetVector.h"
74#include "llvm/ADT/SmallPtrSet.h"
75#include "llvm/ADT/SmallSet.h"
76#include "llvm/ADT/SmallVector.h"
77#include "llvm/ADT/Statistic.h"
78#include "llvm/ADT/StringRef.h"
79#include "llvm/Analysis/AssumptionCache.h"
80#include "llvm/Analysis/ConstantFolding.h"
81#include "llvm/Analysis/InstructionSimplify.h"
82#include "llvm/Analysis/LoopInfo.h"
83#include "llvm/Analysis/ScalarEvolutionExpressions.h"
84#include "llvm/Analysis/TargetLibraryInfo.h"
85#include "llvm/Analysis/ValueTracking.h"
86#include "llvm/Config/llvm-config.h"
87#include "llvm/IR/Argument.h"
88#include "llvm/IR/BasicBlock.h"
89#include "llvm/IR/CFG.h"
90#include "llvm/IR/CallSite.h"
91#include "llvm/IR/Constant.h"
92#include "llvm/IR/ConstantRange.h"
93#include "llvm/IR/Constants.h"
94#include "llvm/IR/DataLayout.h"
95#include "llvm/IR/DerivedTypes.h"
96#include "llvm/IR/Dominators.h"
97#include "llvm/IR/Function.h"
98#include "llvm/IR/GlobalAlias.h"
99#include "llvm/IR/GlobalValue.h"
100#include "llvm/IR/GlobalVariable.h"
101#include "llvm/IR/InstIterator.h"
102#include "llvm/IR/InstrTypes.h"
103#include "llvm/IR/Instruction.h"
104#include "llvm/IR/Instructions.h"
105#include "llvm/IR/IntrinsicInst.h"
106#include "llvm/IR/Intrinsics.h"
107#include "llvm/IR/LLVMContext.h"
108#include "llvm/IR/Metadata.h"
109#include "llvm/IR/Operator.h"
110#include "llvm/IR/PatternMatch.h"
111#include "llvm/IR/Type.h"
112#include "llvm/IR/Use.h"
113#include "llvm/IR/User.h"
114#include "llvm/IR/Value.h"
115#include "llvm/Pass.h"
116#include "llvm/Support/Casting.h"
117#include "llvm/Support/CommandLine.h"
118#include "llvm/Support/Compiler.h"
119#include "llvm/Support/Debug.h"
120#include "llvm/Support/ErrorHandling.h"
121#include "llvm/Support/KnownBits.h"
122#include "llvm/Support/SaveAndRestore.h"
123#include "llvm/Support/raw_ostream.h"
124#include <algorithm>
125#include <cassert>
126#include <climits>
127#include <cstddef>
128#include <cstdint>
129#include <cstdlib>
130#include <map>
131#include <memory>
132#include <tuple>
133#include <utility>
134#include <vector>
135
136using namespace llvm;
137
138#define DEBUG_TYPE"scalar-evolution" "scalar-evolution"
139
140STATISTIC(NumArrayLenItCounts,static llvm::Statistic NumArrayLenItCounts = {"scalar-evolution"
, "NumArrayLenItCounts", "Number of trip counts computed with array length"
, {0}, {false}}
141 "Number of trip counts computed with array length")static llvm::Statistic NumArrayLenItCounts = {"scalar-evolution"
, "NumArrayLenItCounts", "Number of trip counts computed with array length"
, {0}, {false}}
;
142STATISTIC(NumTripCountsComputed,static llvm::Statistic NumTripCountsComputed = {"scalar-evolution"
, "NumTripCountsComputed", "Number of loops with predictable loop counts"
, {0}, {false}}
143 "Number of loops with predictable loop counts")static llvm::Statistic NumTripCountsComputed = {"scalar-evolution"
, "NumTripCountsComputed", "Number of loops with predictable loop counts"
, {0}, {false}}
;
144STATISTIC(NumTripCountsNotComputed,static llvm::Statistic NumTripCountsNotComputed = {"scalar-evolution"
, "NumTripCountsNotComputed", "Number of loops without predictable loop counts"
, {0}, {false}}
145 "Number of loops without predictable loop counts")static llvm::Statistic NumTripCountsNotComputed = {"scalar-evolution"
, "NumTripCountsNotComputed", "Number of loops without predictable loop counts"
, {0}, {false}}
;
146STATISTIC(NumBruteForceTripCountsComputed,static llvm::Statistic NumBruteForceTripCountsComputed = {"scalar-evolution"
, "NumBruteForceTripCountsComputed", "Number of loops with trip counts computed by force"
, {0}, {false}}
147 "Number of loops with trip counts computed by force")static llvm::Statistic NumBruteForceTripCountsComputed = {"scalar-evolution"
, "NumBruteForceTripCountsComputed", "Number of loops with trip counts computed by force"
, {0}, {false}}
;
148
149static cl::opt<unsigned>
150MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
151 cl::desc("Maximum number of iterations SCEV will "
152 "symbolically execute a constant "
153 "derived loop"),
154 cl::init(100));
155
156// FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
157static cl::opt<bool> VerifySCEV(
158 "verify-scev", cl::Hidden,
159 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
160static cl::opt<bool>
161 VerifySCEVMap("verify-scev-maps", cl::Hidden,
162 cl::desc("Verify no dangling value in ScalarEvolution's "
163 "ExprValueMap (slow)"));
164
165static cl::opt<unsigned> MulOpsInlineThreshold(
166 "scev-mulops-inline-threshold", cl::Hidden,
167 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
168 cl::init(32));
169
170static cl::opt<unsigned> AddOpsInlineThreshold(
171 "scev-addops-inline-threshold", cl::Hidden,
172 cl::desc("Threshold for inlining addition operands into a SCEV"),
173 cl::init(500));
174
175static cl::opt<unsigned> MaxSCEVCompareDepth(
176 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
177 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
178 cl::init(32));
179
180static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
181 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
182 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
183 cl::init(2));
184
185static cl::opt<unsigned> MaxValueCompareDepth(
186 "scalar-evolution-max-value-compare-depth", cl::Hidden,
187 cl::desc("Maximum depth of recursive value complexity comparisons"),
188 cl::init(2));
189
190static cl::opt<unsigned>
191 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
192 cl::desc("Maximum depth of recursive arithmetics"),
193 cl::init(32));
194
195static cl::opt<unsigned> MaxConstantEvolvingDepth(
196 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
197 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
198
199static cl::opt<unsigned>
200 MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden,
201 cl::desc("Maximum depth of recursive SExt/ZExt"),
202 cl::init(8));
203
204static cl::opt<unsigned>
205 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
206 cl::desc("Max coefficients in AddRec during evolving"),
207 cl::init(8));
208
209//===----------------------------------------------------------------------===//
210// SCEV class definitions
211//===----------------------------------------------------------------------===//
212
213//===----------------------------------------------------------------------===//
214// Implementation of the SCEV class.
215//
216
217#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
218LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void SCEV::dump() const {
219 print(dbgs());
220 dbgs() << '\n';
221}
222#endif
223
224void SCEV::print(raw_ostream &OS) const {
225 switch (static_cast<SCEVTypes>(getSCEVType())) {
226 case scConstant:
227 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
228 return;
229 case scTruncate: {
230 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
231 const SCEV *Op = Trunc->getOperand();
232 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
233 << *Trunc->getType() << ")";
234 return;
235 }
236 case scZeroExtend: {
237 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
238 const SCEV *Op = ZExt->getOperand();
239 OS << "(zext " << *Op->getType() << " " << *Op << " to "
240 << *ZExt->getType() << ")";
241 return;
242 }
243 case scSignExtend: {
244 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
245 const SCEV *Op = SExt->getOperand();
246 OS << "(sext " << *Op->getType() << " " << *Op << " to "
247 << *SExt->getType() << ")";
248 return;
249 }
250 case scAddRecExpr: {
251 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
252 OS << "{" << *AR->getOperand(0);
253 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
254 OS << ",+," << *AR->getOperand(i);
255 OS << "}<";
256 if (AR->hasNoUnsignedWrap())
257 OS << "nuw><";
258 if (AR->hasNoSignedWrap())
259 OS << "nsw><";
260 if (AR->hasNoSelfWrap() &&
261 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
262 OS << "nw><";
263 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
264 OS << ">";
265 return;
266 }
267 case scAddExpr:
268 case scMulExpr:
269 case scUMaxExpr:
270 case scSMaxExpr: {
271 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
272 const char *OpStr = nullptr;
273 switch (NAry->getSCEVType()) {
274 case scAddExpr: OpStr = " + "; break;
275 case scMulExpr: OpStr = " * "; break;
276 case scUMaxExpr: OpStr = " umax "; break;
277 case scSMaxExpr: OpStr = " smax "; break;
278 }
279 OS << "(";
280 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
281 I != E; ++I) {
282 OS << **I;
283 if (std::next(I) != E)
284 OS << OpStr;
285 }
286 OS << ")";
287 switch (NAry->getSCEVType()) {
288 case scAddExpr:
289 case scMulExpr:
290 if (NAry->hasNoUnsignedWrap())
291 OS << "<nuw>";
292 if (NAry->hasNoSignedWrap())
293 OS << "<nsw>";
294 }
295 return;
296 }
297 case scUDivExpr: {
298 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
299 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
300 return;
301 }
302 case scUnknown: {
303 const SCEVUnknown *U = cast<SCEVUnknown>(this);
304 Type *AllocTy;
305 if (U->isSizeOf(AllocTy)) {
306 OS << "sizeof(" << *AllocTy << ")";
307 return;
308 }
309 if (U->isAlignOf(AllocTy)) {
310 OS << "alignof(" << *AllocTy << ")";
311 return;
312 }
313
314 Type *CTy;
315 Constant *FieldNo;
316 if (U->isOffsetOf(CTy, FieldNo)) {
317 OS << "offsetof(" << *CTy << ", ";
318 FieldNo->printAsOperand(OS, false);
319 OS << ")";
320 return;
321 }
322
323 // Otherwise just print it normally.
324 U->getValue()->printAsOperand(OS, false);
325 return;
326 }
327 case scCouldNotCompute:
328 OS << "***COULDNOTCOMPUTE***";
329 return;
330 }
331 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 331)
;
332}
333
334Type *SCEV::getType() const {
335 switch (static_cast<SCEVTypes>(getSCEVType())) {
336 case scConstant:
337 return cast<SCEVConstant>(this)->getType();
338 case scTruncate:
339 case scZeroExtend:
340 case scSignExtend:
341 return cast<SCEVCastExpr>(this)->getType();
342 case scAddRecExpr:
343 case scMulExpr:
344 case scUMaxExpr:
345 case scSMaxExpr:
346 return cast<SCEVNAryExpr>(this)->getType();
347 case scAddExpr:
348 return cast<SCEVAddExpr>(this)->getType();
349 case scUDivExpr:
350 return cast<SCEVUDivExpr>(this)->getType();
351 case scUnknown:
352 return cast<SCEVUnknown>(this)->getType();
353 case scCouldNotCompute:
354 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 354)
;
355 }
356 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 356)
;
357}
358
359bool SCEV::isZero() const {
360 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
361 return SC->getValue()->isZero();
362 return false;
363}
364
365bool SCEV::isOne() const {
366 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
367 return SC->getValue()->isOne();
368 return false;
369}
370
371bool SCEV::isAllOnesValue() const {
372 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
373 return SC->getValue()->isMinusOne();
374 return false;
375}
376
377bool SCEV::isNonConstantNegative() const {
378 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
379 if (!Mul) return false;
380
381 // If there is a constant factor, it will be first.
382 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
383 if (!SC) return false;
384
385 // Return true if the value is negative, this matches things like (-42 * V).
386 return SC->getAPInt().isNegative();
387}
388
389SCEVCouldNotCompute::SCEVCouldNotCompute() :
390 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
391
392bool SCEVCouldNotCompute::classof(const SCEV *S) {
393 return S->getSCEVType() == scCouldNotCompute;
394}
395
396const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
397 FoldingSetNodeID ID;
398 ID.AddInteger(scConstant);
399 ID.AddPointer(V);
400 void *IP = nullptr;
401 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
402 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
403 UniqueSCEVs.InsertNode(S, IP);
404 return S;
405}
406
407const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
408 return getConstant(ConstantInt::get(getContext(), Val));
409}
410
411const SCEV *
412ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
413 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
414 return getConstant(ConstantInt::get(ITy, V, isSigned));
415}
416
417SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
418 unsigned SCEVTy, const SCEV *op, Type *ty)
419 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
420
421SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
422 const SCEV *op, Type *ty)
423 : SCEVCastExpr(ID, scTruncate, op, ty) {
424 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy
() && "Cannot truncate non-integer value!") ? static_cast
<void> (0) : __assert_fail ("Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate non-integer value!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 425, __PRETTY_FUNCTION__))
425 "Cannot truncate non-integer value!")((Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy
() && "Cannot truncate non-integer value!") ? static_cast
<void> (0) : __assert_fail ("Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate non-integer value!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 425, __PRETTY_FUNCTION__))
;
426}
427
428SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
429 const SCEV *op, Type *ty)
430 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
431 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy
() && "Cannot zero extend non-integer value!") ? static_cast
<void> (0) : __assert_fail ("Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot zero extend non-integer value!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 432, __PRETTY_FUNCTION__))
432 "Cannot zero extend non-integer value!")((Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy
() && "Cannot zero extend non-integer value!") ? static_cast
<void> (0) : __assert_fail ("Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot zero extend non-integer value!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 432, __PRETTY_FUNCTION__))
;
433}
434
435SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
436 const SCEV *op, Type *ty)
437 : SCEVCastExpr(ID, scSignExtend, op, ty) {
438 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy
() && "Cannot sign extend non-integer value!") ? static_cast
<void> (0) : __assert_fail ("Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot sign extend non-integer value!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 439, __PRETTY_FUNCTION__))
439 "Cannot sign extend non-integer value!")((Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy
() && "Cannot sign extend non-integer value!") ? static_cast
<void> (0) : __assert_fail ("Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot sign extend non-integer value!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 439, __PRETTY_FUNCTION__))
;
440}
441
442void SCEVUnknown::deleted() {
443 // Clear this SCEVUnknown from various maps.
444 SE->forgetMemoizedResults(this);
445
446 // Remove this SCEVUnknown from the uniquing map.
447 SE->UniqueSCEVs.RemoveNode(this);
448
449 // Release the value.
450 setValPtr(nullptr);
451}
452
453void SCEVUnknown::allUsesReplacedWith(Value *New) {
454 // Remove this SCEVUnknown from the uniquing map.
455 SE->UniqueSCEVs.RemoveNode(this);
456
457 // Update this SCEVUnknown to point to the new value. This is needed
458 // because there may still be outstanding SCEVs which still point to
459 // this SCEVUnknown.
460 setValPtr(New);
461}
462
463bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
464 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
465 if (VCE->getOpcode() == Instruction::PtrToInt)
466 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
467 if (CE->getOpcode() == Instruction::GetElementPtr &&
468 CE->getOperand(0)->isNullValue() &&
469 CE->getNumOperands() == 2)
470 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
471 if (CI->isOne()) {
472 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
473 ->getElementType();
474 return true;
475 }
476
477 return false;
478}
479
480bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
481 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
482 if (VCE->getOpcode() == Instruction::PtrToInt)
483 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
484 if (CE->getOpcode() == Instruction::GetElementPtr &&
485 CE->getOperand(0)->isNullValue()) {
486 Type *Ty =
487 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
488 if (StructType *STy = dyn_cast<StructType>(Ty))
489 if (!STy->isPacked() &&
490 CE->getNumOperands() == 3 &&
491 CE->getOperand(1)->isNullValue()) {
492 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
493 if (CI->isOne() &&
494 STy->getNumElements() == 2 &&
495 STy->getElementType(0)->isIntegerTy(1)) {
496 AllocTy = STy->getElementType(1);
497 return true;
498 }
499 }
500 }
501
502 return false;
503}
504
505bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
506 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
507 if (VCE->getOpcode() == Instruction::PtrToInt)
508 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
509 if (CE->getOpcode() == Instruction::GetElementPtr &&
510 CE->getNumOperands() == 3 &&
511 CE->getOperand(0)->isNullValue() &&
512 CE->getOperand(1)->isNullValue()) {
513 Type *Ty =
514 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
515 // Ignore vector types here so that ScalarEvolutionExpander doesn't
516 // emit getelementptrs that index into vectors.
517 if (Ty->isStructTy() || Ty->isArrayTy()) {
518 CTy = Ty;
519 FieldNo = CE->getOperand(2);
520 return true;
521 }
522 }
523
524 return false;
525}
526
527//===----------------------------------------------------------------------===//
528// SCEV Utilities
529//===----------------------------------------------------------------------===//
530
531/// Compare the two values \p LV and \p RV in terms of their "complexity" where
532/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
533/// operands in SCEV expressions. \p EqCache is a set of pairs of values that
534/// have been previously deemed to be "equally complex" by this routine. It is
535/// intended to avoid exponential time complexity in cases like:
536///
537/// %a = f(%x, %y)
538/// %b = f(%a, %a)
539/// %c = f(%b, %b)
540///
541/// %d = f(%x, %y)
542/// %e = f(%d, %d)
543/// %f = f(%e, %e)
544///
545/// CompareValueComplexity(%f, %c)
546///
547/// Since we do not continue running this routine on expression trees once we
548/// have seen unequal values, there is no need to track them in the cache.
549static int
550CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
551 const LoopInfo *const LI, Value *LV, Value *RV,
552 unsigned Depth) {
553 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
554 return 0;
555
556 // Order pointer values after integer values. This helps SCEVExpander form
557 // GEPs.
558 bool LIsPointer = LV->getType()->isPointerTy(),
559 RIsPointer = RV->getType()->isPointerTy();
560 if (LIsPointer != RIsPointer)
561 return (int)LIsPointer - (int)RIsPointer;
562
563 // Compare getValueID values.
564 unsigned LID = LV->getValueID(), RID = RV->getValueID();
565 if (LID != RID)
566 return (int)LID - (int)RID;
567
568 // Sort arguments by their position.
569 if (const auto *LA = dyn_cast<Argument>(LV)) {
570 const auto *RA = cast<Argument>(RV);
571 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
572 return (int)LArgNo - (int)RArgNo;
573 }
574
575 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
576 const auto *RGV = cast<GlobalValue>(RV);
577
578 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
579 auto LT = GV->getLinkage();
580 return !(GlobalValue::isPrivateLinkage(LT) ||
581 GlobalValue::isInternalLinkage(LT));
582 };
583
584 // Use the names to distinguish the two values, but only if the
585 // names are semantically important.
586 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
587 return LGV->getName().compare(RGV->getName());
588 }
589
590 // For instructions, compare their loop depth, and their operand count. This
591 // is pretty loose.
592 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
593 const auto *RInst = cast<Instruction>(RV);
594
595 // Compare loop depths.
596 const BasicBlock *LParent = LInst->getParent(),
597 *RParent = RInst->getParent();
598 if (LParent != RParent) {
599 unsigned LDepth = LI->getLoopDepth(LParent),
600 RDepth = LI->getLoopDepth(RParent);
601 if (LDepth != RDepth)
602 return (int)LDepth - (int)RDepth;
603 }
604
605 // Compare the number of operands.
606 unsigned LNumOps = LInst->getNumOperands(),
607 RNumOps = RInst->getNumOperands();
608 if (LNumOps != RNumOps)
609 return (int)LNumOps - (int)RNumOps;
610
611 for (unsigned Idx : seq(0u, LNumOps)) {
612 int Result =
613 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
614 RInst->getOperand(Idx), Depth + 1);
615 if (Result != 0)
616 return Result;
617 }
618 }
619
620 EqCacheValue.unionSets(LV, RV);
621 return 0;
622}
623
624// Return negative, zero, or positive, if LHS is less than, equal to, or greater
625// than RHS, respectively. A three-way result allows recursive comparisons to be
626// more efficient.
627static int CompareSCEVComplexity(
628 EquivalenceClasses<const SCEV *> &EqCacheSCEV,
629 EquivalenceClasses<const Value *> &EqCacheValue,
630 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
631 DominatorTree &DT, unsigned Depth = 0) {
632 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
633 if (LHS == RHS)
634 return 0;
635
636 // Primarily, sort the SCEVs by their getSCEVType().
637 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
638 if (LType != RType)
639 return (int)LType - (int)RType;
640
641 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
642 return 0;
643 // Aside from the getSCEVType() ordering, the particular ordering
644 // isn't very important except that it's beneficial to be consistent,
645 // so that (a + b) and (b + a) don't end up as different expressions.
646 switch (static_cast<SCEVTypes>(LType)) {
647 case scUnknown: {
648 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
649 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
650
651 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
652 RU->getValue(), Depth + 1);
653 if (X == 0)
654 EqCacheSCEV.unionSets(LHS, RHS);
655 return X;
656 }
657
658 case scConstant: {
659 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
660 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
661
662 // Compare constant values.
663 const APInt &LA = LC->getAPInt();
664 const APInt &RA = RC->getAPInt();
665 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
666 if (LBitWidth != RBitWidth)
667 return (int)LBitWidth - (int)RBitWidth;
668 return LA.ult(RA) ? -1 : 1;
669 }
670
671 case scAddRecExpr: {
672 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
673 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
674
675 // There is always a dominance between two recs that are used by one SCEV,
676 // so we can safely sort recs by loop header dominance. We require such
677 // order in getAddExpr.
678 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
679 if (LLoop != RLoop) {
680 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
681 assert(LHead != RHead && "Two loops share the same header?")((LHead != RHead && "Two loops share the same header?"
) ? static_cast<void> (0) : __assert_fail ("LHead != RHead && \"Two loops share the same header?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 681, __PRETTY_FUNCTION__))
;
682 if (DT.dominates(LHead, RHead))
683 return 1;
684 else
685 assert(DT.dominates(RHead, LHead) &&((DT.dominates(RHead, LHead) && "No dominance between recurrences used by one SCEV?"
) ? static_cast<void> (0) : __assert_fail ("DT.dominates(RHead, LHead) && \"No dominance between recurrences used by one SCEV?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 686, __PRETTY_FUNCTION__))
686 "No dominance between recurrences used by one SCEV?")((DT.dominates(RHead, LHead) && "No dominance between recurrences used by one SCEV?"
) ? static_cast<void> (0) : __assert_fail ("DT.dominates(RHead, LHead) && \"No dominance between recurrences used by one SCEV?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 686, __PRETTY_FUNCTION__))
;
687 return -1;
688 }
689
690 // Addrec complexity grows with operand count.
691 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
692 if (LNumOps != RNumOps)
693 return (int)LNumOps - (int)RNumOps;
694
695 // Lexicographically compare.
696 for (unsigned i = 0; i != LNumOps; ++i) {
697 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
698 LA->getOperand(i), RA->getOperand(i), DT,
699 Depth + 1);
700 if (X != 0)
701 return X;
702 }
703 EqCacheSCEV.unionSets(LHS, RHS);
704 return 0;
705 }
706
707 case scAddExpr:
708 case scMulExpr:
709 case scSMaxExpr:
710 case scUMaxExpr: {
711 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
712 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
713
714 // Lexicographically compare n-ary expressions.
715 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
716 if (LNumOps != RNumOps)
717 return (int)LNumOps - (int)RNumOps;
718
719 for (unsigned i = 0; i != LNumOps; ++i) {
720 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
721 LC->getOperand(i), RC->getOperand(i), DT,
722 Depth + 1);
723 if (X != 0)
724 return X;
725 }
726 EqCacheSCEV.unionSets(LHS, RHS);
727 return 0;
728 }
729
730 case scUDivExpr: {
731 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
732 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
733
734 // Lexicographically compare udiv expressions.
735 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
736 RC->getLHS(), DT, Depth + 1);
737 if (X != 0)
738 return X;
739 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
740 RC->getRHS(), DT, Depth + 1);
741 if (X == 0)
742 EqCacheSCEV.unionSets(LHS, RHS);
743 return X;
744 }
745
746 case scTruncate:
747 case scZeroExtend:
748 case scSignExtend: {
749 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
750 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
751
752 // Compare cast expressions by operand.
753 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
754 LC->getOperand(), RC->getOperand(), DT,
755 Depth + 1);
756 if (X == 0)
757 EqCacheSCEV.unionSets(LHS, RHS);
758 return X;
759 }
760
761 case scCouldNotCompute:
762 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 762)
;
763 }
764 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 764)
;
765}
766
767/// Given a list of SCEV objects, order them by their complexity, and group
768/// objects of the same complexity together by value. When this routine is
769/// finished, we know that any duplicates in the vector are consecutive and that
770/// complexity is monotonically increasing.
771///
772/// Note that we go take special precautions to ensure that we get deterministic
773/// results from this routine. In other words, we don't want the results of
774/// this to depend on where the addresses of various SCEV objects happened to
775/// land in memory.
776static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
777 LoopInfo *LI, DominatorTree &DT) {
778 if (Ops.size() < 2) return; // Noop
779
780 EquivalenceClasses<const SCEV *> EqCacheSCEV;
781 EquivalenceClasses<const Value *> EqCacheValue;
782 if (Ops.size() == 2) {
783 // This is the common case, which also happens to be trivially simple.
784 // Special case it.
785 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
786 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
787 std::swap(LHS, RHS);
788 return;
789 }
790
791 // Do the rough sort by complexity.
792 std::stable_sort(Ops.begin(), Ops.end(),
793 [&](const SCEV *LHS, const SCEV *RHS) {
794 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
795 LHS, RHS, DT) < 0;
796 });
797
798 // Now that we are sorted by complexity, group elements of the same
799 // complexity. Note that this is, at worst, N^2, but the vector is likely to
800 // be extremely short in practice. Note that we take this approach because we
801 // do not want to depend on the addresses of the objects we are grouping.
802 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
803 const SCEV *S = Ops[i];
804 unsigned Complexity = S->getSCEVType();
805
806 // If there are any objects of the same complexity and same value as this
807 // one, group them.
808 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
809 if (Ops[j] == S) { // Found a duplicate.
810 // Move it to immediately after i'th element.
811 std::swap(Ops[i+1], Ops[j]);
812 ++i; // no need to rescan it.
813 if (i == e-2) return; // Done!
814 }
815 }
816 }
817}
818
819// Returns the size of the SCEV S.
820static inline int sizeOfSCEV(const SCEV *S) {
821 struct FindSCEVSize {
822 int Size = 0;
823
824 FindSCEVSize() = default;
825
826 bool follow(const SCEV *S) {
827 ++Size;
828 // Keep looking at all operands of S.
829 return true;
830 }
831
832 bool isDone() const {
833 return false;
834 }
835 };
836
837 FindSCEVSize F;
838 SCEVTraversal<FindSCEVSize> ST(F);
839 ST.visitAll(S);
840 return F.Size;
841}
842
843namespace {
844
845struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
846public:
847 // Computes the Quotient and Remainder of the division of Numerator by
848 // Denominator.
849 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
850 const SCEV *Denominator, const SCEV **Quotient,
851 const SCEV **Remainder) {
852 assert(Numerator && Denominator && "Uninitialized SCEV")((Numerator && Denominator && "Uninitialized SCEV"
) ? static_cast<void> (0) : __assert_fail ("Numerator && Denominator && \"Uninitialized SCEV\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 852, __PRETTY_FUNCTION__))
;
853
854 SCEVDivision D(SE, Numerator, Denominator);
855
856 // Check for the trivial case here to avoid having to check for it in the
857 // rest of the code.
858 if (Numerator == Denominator) {
859 *Quotient = D.One;
860 *Remainder = D.Zero;
861 return;
862 }
863
864 if (Numerator->isZero()) {
865 *Quotient = D.Zero;
866 *Remainder = D.Zero;
867 return;
868 }
869
870 // A simple case when N/1. The quotient is N.
871 if (Denominator->isOne()) {
872 *Quotient = Numerator;
873 *Remainder = D.Zero;
874 return;
875 }
876
877 // Split the Denominator when it is a product.
878 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
879 const SCEV *Q, *R;
880 *Quotient = Numerator;
881 for (const SCEV *Op : T->operands()) {
882 divide(SE, *Quotient, Op, &Q, &R);
883 *Quotient = Q;
884
885 // Bail out when the Numerator is not divisible by one of the terms of
886 // the Denominator.
887 if (!R->isZero()) {
888 *Quotient = D.Zero;
889 *Remainder = Numerator;
890 return;
891 }
892 }
893 *Remainder = D.Zero;
894 return;
895 }
896
897 D.visit(Numerator);
898 *Quotient = D.Quotient;
899 *Remainder = D.Remainder;
900 }
901
902 // Except in the trivial case described above, we do not know how to divide
903 // Expr by Denominator for the following functions with empty implementation.
904 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
905 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
906 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
907 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
908 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
909 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
910 void visitUnknown(const SCEVUnknown *Numerator) {}
911 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
912
913 void visitConstant(const SCEVConstant *Numerator) {
914 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
915 APInt NumeratorVal = Numerator->getAPInt();
916 APInt DenominatorVal = D->getAPInt();
917 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
918 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
919
920 if (NumeratorBW > DenominatorBW)
921 DenominatorVal = DenominatorVal.sext(NumeratorBW);
922 else if (NumeratorBW < DenominatorBW)
923 NumeratorVal = NumeratorVal.sext(DenominatorBW);
924
925 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
926 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
927 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
928 Quotient = SE.getConstant(QuotientVal);
929 Remainder = SE.getConstant(RemainderVal);
930 return;
931 }
932 }
933
934 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
935 const SCEV *StartQ, *StartR, *StepQ, *StepR;
936 if (!Numerator->isAffine())
937 return cannotDivide(Numerator);
938 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
939 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
940 // Bail out if the types do not match.
941 Type *Ty = Denominator->getType();
942 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
943 Ty != StepQ->getType() || Ty != StepR->getType())
944 return cannotDivide(Numerator);
945 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
946 Numerator->getNoWrapFlags());
947 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
948 Numerator->getNoWrapFlags());
949 }
950
951 void visitAddExpr(const SCEVAddExpr *Numerator) {
952 SmallVector<const SCEV *, 2> Qs, Rs;
953 Type *Ty = Denominator->getType();
954
955 for (const SCEV *Op : Numerator->operands()) {
956 const SCEV *Q, *R;
957 divide(SE, Op, Denominator, &Q, &R);
958
959 // Bail out if types do not match.
960 if (Ty != Q->getType() || Ty != R->getType())
961 return cannotDivide(Numerator);
962
963 Qs.push_back(Q);
964 Rs.push_back(R);
965 }
966
967 if (Qs.size() == 1) {
968 Quotient = Qs[0];
969 Remainder = Rs[0];
970 return;
971 }
972
973 Quotient = SE.getAddExpr(Qs);
974 Remainder = SE.getAddExpr(Rs);
975 }
976
977 void visitMulExpr(const SCEVMulExpr *Numerator) {
978 SmallVector<const SCEV *, 2> Qs;
979 Type *Ty = Denominator->getType();
980
981 bool FoundDenominatorTerm = false;
982 for (const SCEV *Op : Numerator->operands()) {
983 // Bail out if types do not match.
984 if (Ty != Op->getType())
985 return cannotDivide(Numerator);
986
987 if (FoundDenominatorTerm) {
988 Qs.push_back(Op);
989 continue;
990 }
991
992 // Check whether Denominator divides one of the product operands.
993 const SCEV *Q, *R;
994 divide(SE, Op, Denominator, &Q, &R);
995 if (!R->isZero()) {
996 Qs.push_back(Op);
997 continue;
998 }
999
1000 // Bail out if types do not match.
1001 if (Ty != Q->getType())
1002 return cannotDivide(Numerator);
1003
1004 FoundDenominatorTerm = true;
1005 Qs.push_back(Q);
1006 }
1007
1008 if (FoundDenominatorTerm) {
1009 Remainder = Zero;
1010 if (Qs.size() == 1)
1011 Quotient = Qs[0];
1012 else
1013 Quotient = SE.getMulExpr(Qs);
1014 return;
1015 }
1016
1017 if (!isa<SCEVUnknown>(Denominator))
1018 return cannotDivide(Numerator);
1019
1020 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1021 ValueToValueMap RewriteMap;
1022 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1023 cast<SCEVConstant>(Zero)->getValue();
1024 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1025
1026 if (Remainder->isZero()) {
1027 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1028 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1029 cast<SCEVConstant>(One)->getValue();
1030 Quotient =
1031 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1032 return;
1033 }
1034
1035 // Quotient is (Numerator - Remainder) divided by Denominator.
1036 const SCEV *Q, *R;
1037 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1038 // This SCEV does not seem to simplify: fail the division here.
1039 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1040 return cannotDivide(Numerator);
1041 divide(SE, Diff, Denominator, &Q, &R);
1042 if (R != Zero)
1043 return cannotDivide(Numerator);
1044 Quotient = Q;
1045 }
1046
1047private:
1048 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1049 const SCEV *Denominator)
1050 : SE(S), Denominator(Denominator) {
1051 Zero = SE.getZero(Denominator->getType());
1052 One = SE.getOne(Denominator->getType());
1053
1054 // We generally do not know how to divide Expr by Denominator. We
1055 // initialize the division to a "cannot divide" state to simplify the rest
1056 // of the code.
1057 cannotDivide(Numerator);
1058 }
1059
1060 // Convenience function for giving up on the division. We set the quotient to
1061 // be equal to zero and the remainder to be equal to the numerator.
1062 void cannotDivide(const SCEV *Numerator) {
1063 Quotient = Zero;
1064 Remainder = Numerator;
1065 }
1066
1067 ScalarEvolution &SE;
1068 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1069};
1070
1071} // end anonymous namespace
1072
1073//===----------------------------------------------------------------------===//
1074// Simple SCEV method implementations
1075//===----------------------------------------------------------------------===//
1076
1077/// Compute BC(It, K). The result has width W. Assume, K > 0.
1078static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1079 ScalarEvolution &SE,
1080 Type *ResultTy) {
1081 // Handle the simplest case efficiently.
1082 if (K == 1)
1083 return SE.getTruncateOrZeroExtend(It, ResultTy);
1084
1085 // We are using the following formula for BC(It, K):
1086 //
1087 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1088 //
1089 // Suppose, W is the bitwidth of the return value. We must be prepared for
1090 // overflow. Hence, we must assure that the result of our computation is
1091 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1092 // safe in modular arithmetic.
1093 //
1094 // However, this code doesn't use exactly that formula; the formula it uses
1095 // is something like the following, where T is the number of factors of 2 in
1096 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1097 // exponentiation:
1098 //
1099 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1100 //
1101 // This formula is trivially equivalent to the previous formula. However,
1102 // this formula can be implemented much more efficiently. The trick is that
1103 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1104 // arithmetic. To do exact division in modular arithmetic, all we have
1105 // to do is multiply by the inverse. Therefore, this step can be done at
1106 // width W.
1107 //
1108 // The next issue is how to safely do the division by 2^T. The way this
1109 // is done is by doing the multiplication step at a width of at least W + T
1110 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1111 // when we perform the division by 2^T (which is equivalent to a right shift
1112 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1113 // truncated out after the division by 2^T.
1114 //
1115 // In comparison to just directly using the first formula, this technique
1116 // is much more efficient; using the first formula requires W * K bits,
1117 // but this formula less than W + K bits. Also, the first formula requires
1118 // a division step, whereas this formula only requires multiplies and shifts.
1119 //
1120 // It doesn't matter whether the subtraction step is done in the calculation
1121 // width or the input iteration count's width; if the subtraction overflows,
1122 // the result must be zero anyway. We prefer here to do it in the width of
1123 // the induction variable because it helps a lot for certain cases; CodeGen
1124 // isn't smart enough to ignore the overflow, which leads to much less
1125 // efficient code if the width of the subtraction is wider than the native
1126 // register width.
1127 //
1128 // (It's possible to not widen at all by pulling out factors of 2 before
1129 // the multiplication; for example, K=2 can be calculated as
1130 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1131 // extra arithmetic, so it's not an obvious win, and it gets
1132 // much more complicated for K > 3.)
1133
1134 // Protection from insane SCEVs; this bound is conservative,
1135 // but it probably doesn't matter.
1136 if (K > 1000)
1137 return SE.getCouldNotCompute();
1138
1139 unsigned W = SE.getTypeSizeInBits(ResultTy);
1140
1141 // Calculate K! / 2^T and T; we divide out the factors of two before
1142 // multiplying for calculating K! / 2^T to avoid overflow.
1143 // Other overflow doesn't matter because we only care about the bottom
1144 // W bits of the result.
1145 APInt OddFactorial(W, 1);
1146 unsigned T = 1;
1147 for (unsigned i = 3; i <= K; ++i) {
1148 APInt Mult(W, i);
1149 unsigned TwoFactors = Mult.countTrailingZeros();
1150 T += TwoFactors;
1151 Mult.lshrInPlace(TwoFactors);
1152 OddFactorial *= Mult;
1153 }
1154
1155 // We need at least W + T bits for the multiplication step
1156 unsigned CalculationBits = W + T;
1157
1158 // Calculate 2^T, at width T+W.
1159 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1160
1161 // Calculate the multiplicative inverse of K! / 2^T;
1162 // this multiplication factor will perform the exact division by
1163 // K! / 2^T.
1164 APInt Mod = APInt::getSignedMinValue(W+1);
1165 APInt MultiplyFactor = OddFactorial.zext(W+1);
1166 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1167 MultiplyFactor = MultiplyFactor.trunc(W);
1168
1169 // Calculate the product, at width T+W
1170 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1171 CalculationBits);
1172 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1173 for (unsigned i = 1; i != K; ++i) {
1174 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1175 Dividend = SE.getMulExpr(Dividend,
1176 SE.getTruncateOrZeroExtend(S, CalculationTy));
1177 }
1178
1179 // Divide by 2^T
1180 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1181
1182 // Truncate the result, and divide by K! / 2^T.
1183
1184 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1185 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1186}
1187
1188/// Return the value of this chain of recurrences at the specified iteration
1189/// number. We can evaluate this recurrence by multiplying each element in the
1190/// chain by the binomial coefficient corresponding to it. In other words, we
1191/// can evaluate {A,+,B,+,C,+,D} as:
1192///
1193/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1194///
1195/// where BC(It, k) stands for binomial coefficient.
1196const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1197 ScalarEvolution &SE) const {
1198 const SCEV *Result = getStart();
1199 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1200 // The computation is correct in the face of overflow provided that the
1201 // multiplication is performed _after_ the evaluation of the binomial
1202 // coefficient.
1203 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1204 if (isa<SCEVCouldNotCompute>(Coeff))
1205 return Coeff;
1206
1207 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1208 }
1209 return Result;
1210}
1211
1212//===----------------------------------------------------------------------===//
1213// SCEV Expression folder implementations
1214//===----------------------------------------------------------------------===//
1215
1216const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1217 Type *Ty) {
1218 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&((getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(
Ty) && "This is not a truncating conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && \"This is not a truncating conversion!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 1219, __PRETTY_FUNCTION__))
1219 "This is not a truncating conversion!")((getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(
Ty) && "This is not a truncating conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && \"This is not a truncating conversion!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 1219, __PRETTY_FUNCTION__))
;
1220 assert(isSCEVable(Ty) &&((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 1221, __PRETTY_FUNCTION__))
1221 "This is not a conversion to a SCEVable type!")((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 1221, __PRETTY_FUNCTION__))
;
1222 Ty = getEffectiveSCEVType(Ty);
1223
1224 FoldingSetNodeID ID;
1225 ID.AddInteger(scTruncate);
1226 ID.AddPointer(Op);
1227 ID.AddPointer(Ty);
1228 void *IP = nullptr;
1229 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1230
1231 // Fold if the operand is constant.
1232 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1233 return getConstant(
1234 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1235
1236 // trunc(trunc(x)) --> trunc(x)
1237 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1238 return getTruncateExpr(ST->getOperand(), Ty);
1239
1240 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1241 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1242 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1243
1244 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1245 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1246 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1247
1248 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1249 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1250 // if after transforming we have at most one truncate, not counting truncates
1251 // that replace other casts.
1252 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1253 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1254 SmallVector<const SCEV *, 4> Operands;
1255 unsigned numTruncs = 0;
1256 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1257 ++i) {
1258 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty);
1259 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S))
1260 numTruncs++;
1261 Operands.push_back(S);
1262 }
1263 if (numTruncs < 2) {
1264 if (isa<SCEVAddExpr>(Op))
1265 return getAddExpr(Operands);
1266 else if (isa<SCEVMulExpr>(Op))
1267 return getMulExpr(Operands);
1268 else
1269 llvm_unreachable("Unexpected SCEV type for Op.")::llvm::llvm_unreachable_internal("Unexpected SCEV type for Op."
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 1269)
;
1270 }
1271 // Although we checked in the beginning that ID is not in the cache, it is
1272 // possible that during recursion and different modification ID was inserted
1273 // into the cache. So if we find it, just return it.
1274 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1275 return S;
1276 }
1277
1278 // If the input value is a chrec scev, truncate the chrec's operands.
1279 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1280 SmallVector<const SCEV *, 4> Operands;
1281 for (const SCEV *Op : AddRec->operands())
1282 Operands.push_back(getTruncateExpr(Op, Ty));
1283 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1284 }
1285
1286 // The cast wasn't folded; create an explicit cast node. We can reuse
1287 // the existing insert position since if we get here, we won't have
1288 // made any changes which would invalidate it.
1289 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1290 Op, Ty);
1291 UniqueSCEVs.InsertNode(S, IP);
1292 addToLoopUseLists(S);
1293 return S;
1294}
1295
1296// Get the limit of a recurrence such that incrementing by Step cannot cause
1297// signed overflow as long as the value of the recurrence within the
1298// loop does not exceed this limit before incrementing.
1299static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1300 ICmpInst::Predicate *Pred,
1301 ScalarEvolution *SE) {
1302 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1303 if (SE->isKnownPositive(Step)) {
1304 *Pred = ICmpInst::ICMP_SLT;
1305 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1306 SE->getSignedRangeMax(Step));
1307 }
1308 if (SE->isKnownNegative(Step)) {
1309 *Pred = ICmpInst::ICMP_SGT;
1310 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1311 SE->getSignedRangeMin(Step));
1312 }
1313 return nullptr;
1314}
1315
1316// Get the limit of a recurrence such that incrementing by Step cannot cause
1317// unsigned overflow as long as the value of the recurrence within the loop does
1318// not exceed this limit before incrementing.
1319static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1320 ICmpInst::Predicate *Pred,
1321 ScalarEvolution *SE) {
1322 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1323 *Pred = ICmpInst::ICMP_ULT;
1324
1325 return SE->getConstant(APInt::getMinValue(BitWidth) -
1326 SE->getUnsignedRangeMax(Step));
1327}
1328
1329namespace {
1330
1331struct ExtendOpTraitsBase {
1332 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1333 unsigned);
1334};
1335
1336// Used to make code generic over signed and unsigned overflow.
1337template <typename ExtendOp> struct ExtendOpTraits {
1338 // Members present:
1339 //
1340 // static const SCEV::NoWrapFlags WrapType;
1341 //
1342 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1343 //
1344 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1345 // ICmpInst::Predicate *Pred,
1346 // ScalarEvolution *SE);
1347};
1348
1349template <>
1350struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1351 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1352
1353 static const GetExtendExprTy GetExtendExpr;
1354
1355 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1356 ICmpInst::Predicate *Pred,
1357 ScalarEvolution *SE) {
1358 return getSignedOverflowLimitForStep(Step, Pred, SE);
1359 }
1360};
1361
1362const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1363 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1364
1365template <>
1366struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1367 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1368
1369 static const GetExtendExprTy GetExtendExpr;
1370
1371 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1372 ICmpInst::Predicate *Pred,
1373 ScalarEvolution *SE) {
1374 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1375 }
1376};
1377
1378const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1379 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1380
1381} // end anonymous namespace
1382
1383// The recurrence AR has been shown to have no signed/unsigned wrap or something
1384// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1385// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1386// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1387// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1388// expression "Step + sext/zext(PreIncAR)" is congruent with
1389// "sext/zext(PostIncAR)"
1390template <typename ExtendOpTy>
1391static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1392 ScalarEvolution *SE, unsigned Depth) {
1393 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1394 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1395
1396 const Loop *L = AR->getLoop();
1397 const SCEV *Start = AR->getStart();
1398 const SCEV *Step = AR->getStepRecurrence(*SE);
1399
1400 // Check for a simple looking step prior to loop entry.
1401 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1402 if (!SA)
1403 return nullptr;
1404
1405 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1406 // subtraction is expensive. For this purpose, perform a quick and dirty
1407 // difference, by checking for Step in the operand list.
1408 SmallVector<const SCEV *, 4> DiffOps;
1409 for (const SCEV *Op : SA->operands())
1410 if (Op != Step)
1411 DiffOps.push_back(Op);
1412
1413 if (DiffOps.size() == SA->getNumOperands())
1414 return nullptr;
1415
1416 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1417 // `Step`:
1418
1419 // 1. NSW/NUW flags on the step increment.
1420 auto PreStartFlags =
1421 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1422 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1423 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1424 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1425
1426 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1427 // "S+X does not sign/unsign-overflow".
1428 //
1429
1430 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1431 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1432 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1433 return PreStart;
1434
1435 // 2. Direct overflow check on the step operation's expression.
1436 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1437 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1438 const SCEV *OperandExtendedStart =
1439 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1440 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1441 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1442 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1443 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1444 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1445 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1446 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1447 }
1448 return PreStart;
1449 }
1450
1451 // 3. Loop precondition.
1452 ICmpInst::Predicate Pred;
1453 const SCEV *OverflowLimit =
1454 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1455
1456 if (OverflowLimit &&
1457 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1458 return PreStart;
1459
1460 return nullptr;
1461}
1462
1463// Get the normalized zero or sign extended expression for this AddRec's Start.
1464template <typename ExtendOpTy>
1465static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1466 ScalarEvolution *SE,
1467 unsigned Depth) {
1468 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1469
1470 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1471 if (!PreStart)
1472 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1473
1474 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1475 Depth),
1476 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1477}
1478
1479// Try to prove away overflow by looking at "nearby" add recurrences. A
1480// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1481// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1482//
1483// Formally:
1484//
1485// {S,+,X} == {S-T,+,X} + T
1486// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1487//
1488// If ({S-T,+,X} + T) does not overflow ... (1)
1489//
1490// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1491//
1492// If {S-T,+,X} does not overflow ... (2)
1493//
1494// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1495// == {Ext(S-T)+Ext(T),+,Ext(X)}
1496//
1497// If (S-T)+T does not overflow ... (3)
1498//
1499// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1500// == {Ext(S),+,Ext(X)} == LHS
1501//
1502// Thus, if (1), (2) and (3) are true for some T, then
1503// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1504//
1505// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1506// does not overflow" restricted to the 0th iteration. Therefore we only need
1507// to check for (1) and (2).
1508//
1509// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1510// is `Delta` (defined below).
1511template <typename ExtendOpTy>
1512bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1513 const SCEV *Step,
1514 const Loop *L) {
1515 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1516
1517 // We restrict `Start` to a constant to prevent SCEV from spending too much
1518 // time here. It is correct (but more expensive) to continue with a
1519 // non-constant `Start` and do a general SCEV subtraction to compute
1520 // `PreStart` below.
1521 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1522 if (!StartC)
1523 return false;
1524
1525 APInt StartAI = StartC->getAPInt();
1526
1527 for (unsigned Delta : {-2, -1, 1, 2}) {
1528 const SCEV *PreStart = getConstant(StartAI - Delta);
1529
1530 FoldingSetNodeID ID;
1531 ID.AddInteger(scAddRecExpr);
1532 ID.AddPointer(PreStart);
1533 ID.AddPointer(Step);
1534 ID.AddPointer(L);
1535 void *IP = nullptr;
1536 const auto *PreAR =
1537 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1538
1539 // Give up if we don't already have the add recurrence we need because
1540 // actually constructing an add recurrence is relatively expensive.
1541 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1542 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1543 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1544 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1545 DeltaS, &Pred, this);
1546 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1547 return true;
1548 }
1549 }
1550
1551 return false;
1552}
1553
1554// Finds an integer D for an expression (C + x + y + ...) such that the top
1555// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1556// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1557// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1558// the (C + x + y + ...) expression is \p WholeAddExpr.
1559static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1560 const SCEVConstant *ConstantTerm,
1561 const SCEVAddExpr *WholeAddExpr) {
1562 const APInt C = ConstantTerm->getAPInt();
1563 const unsigned BitWidth = C.getBitWidth();
1564 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1565 uint32_t TZ = BitWidth;
1566 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1567 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1568 if (TZ) {
1569 // Set D to be as many least significant bits of C as possible while still
1570 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1571 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1572 }
1573 return APInt(BitWidth, 0);
1574}
1575
1576// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1577// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1578// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1579// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1580static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1581 const APInt &ConstantStart,
1582 const SCEV *Step) {
1583 const unsigned BitWidth = ConstantStart.getBitWidth();
1584 const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1585 if (TZ)
1586 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1587 : ConstantStart;
1588 return APInt(BitWidth, 0);
1589}
1590
1591const SCEV *
1592ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1593 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&((getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(
Ty) && "This is not an extending conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 1594, __PRETTY_FUNCTION__))
1594 "This is not an extending conversion!")((getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(
Ty) && "This is not an extending conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 1594, __PRETTY_FUNCTION__))
;
1595 assert(isSCEVable(Ty) &&((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 1596, __PRETTY_FUNCTION__))
1596 "This is not a conversion to a SCEVable type!")((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 1596, __PRETTY_FUNCTION__))
;
1597 Ty = getEffectiveSCEVType(Ty);
1598
1599 // Fold if the operand is constant.
1600 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1601 return getConstant(
1602 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1603
1604 // zext(zext(x)) --> zext(x)
1605 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1606 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1607
1608 // Before doing any expensive analysis, check to see if we've already
1609 // computed a SCEV for this Op and Ty.
1610 FoldingSetNodeID ID;
1611 ID.AddInteger(scZeroExtend);
1612 ID.AddPointer(Op);
1613 ID.AddPointer(Ty);
1614 void *IP = nullptr;
1615 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1616 if (Depth > MaxExtDepth) {
1617 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1618 Op, Ty);
1619 UniqueSCEVs.InsertNode(S, IP);
1620 addToLoopUseLists(S);
1621 return S;
1622 }
1623
1624 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1625 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1626 // It's possible the bits taken off by the truncate were all zero bits. If
1627 // so, we should be able to simplify this further.
1628 const SCEV *X = ST->getOperand();
1629 ConstantRange CR = getUnsignedRange(X);
1630 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1631 unsigned NewBits = getTypeSizeInBits(Ty);
1632 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1633 CR.zextOrTrunc(NewBits)))
1634 return getTruncateOrZeroExtend(X, Ty);
1635 }
1636
1637 // If the input value is a chrec scev, and we can prove that the value
1638 // did not overflow the old, smaller, value, we can zero extend all of the
1639 // operands (often constants). This allows analysis of something like
1640 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1641 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1642 if (AR->isAffine()) {
1643 const SCEV *Start = AR->getStart();
1644 const SCEV *Step = AR->getStepRecurrence(*this);
1645 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1646 const Loop *L = AR->getLoop();
1647
1648 if (!AR->hasNoUnsignedWrap()) {
1649 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1650 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1651 }
1652
1653 // If we have special knowledge that this addrec won't overflow,
1654 // we don't need to do any further analysis.
1655 if (AR->hasNoUnsignedWrap())
1656 return getAddRecExpr(
1657 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1658 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1659
1660 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1661 // Note that this serves two purposes: It filters out loops that are
1662 // simply not analyzable, and it covers the case where this code is
1663 // being called from within backedge-taken count analysis, such that
1664 // attempting to ask for the backedge-taken count would likely result
1665 // in infinite recursion. In the later case, the analysis code will
1666 // cope with a conservative value, and it will take care to purge
1667 // that value once it has finished.
1668 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1669 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1670 // Manually compute the final value for AR, checking for
1671 // overflow.
1672
1673 // Check whether the backedge-taken count can be losslessly casted to
1674 // the addrec's type. The count is always unsigned.
1675 const SCEV *CastedMaxBECount =
1676 getTruncateOrZeroExtend(MaxBECount, Start->getType());
1677 const SCEV *RecastedMaxBECount =
1678 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1679 if (MaxBECount == RecastedMaxBECount) {
1680 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1681 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1682 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1683 SCEV::FlagAnyWrap, Depth + 1);
1684 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1685 SCEV::FlagAnyWrap,
1686 Depth + 1),
1687 WideTy, Depth + 1);
1688 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1689 const SCEV *WideMaxBECount =
1690 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1691 const SCEV *OperandExtendedAdd =
1692 getAddExpr(WideStart,
1693 getMulExpr(WideMaxBECount,
1694 getZeroExtendExpr(Step, WideTy, Depth + 1),
1695 SCEV::FlagAnyWrap, Depth + 1),
1696 SCEV::FlagAnyWrap, Depth + 1);
1697 if (ZAdd == OperandExtendedAdd) {
1698 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1699 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1700 // Return the expression with the addrec on the outside.
1701 return getAddRecExpr(
1702 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1703 Depth + 1),
1704 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1705 AR->getNoWrapFlags());
1706 }
1707 // Similar to above, only this time treat the step value as signed.
1708 // This covers loops that count down.
1709 OperandExtendedAdd =
1710 getAddExpr(WideStart,
1711 getMulExpr(WideMaxBECount,
1712 getSignExtendExpr(Step, WideTy, Depth + 1),
1713 SCEV::FlagAnyWrap, Depth + 1),
1714 SCEV::FlagAnyWrap, Depth + 1);
1715 if (ZAdd == OperandExtendedAdd) {
1716 // Cache knowledge of AR NW, which is propagated to this AddRec.
1717 // Negative step causes unsigned wrap, but it still can't self-wrap.
1718 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1719 // Return the expression with the addrec on the outside.
1720 return getAddRecExpr(
1721 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1722 Depth + 1),
1723 getSignExtendExpr(Step, Ty, Depth + 1), L,
1724 AR->getNoWrapFlags());
1725 }
1726 }
1727 }
1728
1729 // Normally, in the cases we can prove no-overflow via a
1730 // backedge guarding condition, we can also compute a backedge
1731 // taken count for the loop. The exceptions are assumptions and
1732 // guards present in the loop -- SCEV is not great at exploiting
1733 // these to compute max backedge taken counts, but can still use
1734 // these to prove lack of overflow. Use this fact to avoid
1735 // doing extra work that may not pay off.
1736 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1737 !AC.assumptions().empty()) {
1738 // If the backedge is guarded by a comparison with the pre-inc
1739 // value the addrec is safe. Also, if the entry is guarded by
1740 // a comparison with the start value and the backedge is
1741 // guarded by a comparison with the post-inc value, the addrec
1742 // is safe.
1743 if (isKnownPositive(Step)) {
1744 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1745 getUnsignedRangeMax(Step));
1746 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1747 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
1748 // Cache knowledge of AR NUW, which is propagated to this
1749 // AddRec.
1750 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1751 // Return the expression with the addrec on the outside.
1752 return getAddRecExpr(
1753 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1754 Depth + 1),
1755 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1756 AR->getNoWrapFlags());
1757 }
1758 } else if (isKnownNegative(Step)) {
1759 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1760 getSignedRangeMin(Step));
1761 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1762 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1763 // Cache knowledge of AR NW, which is propagated to this
1764 // AddRec. Negative step causes unsigned wrap, but it
1765 // still can't self-wrap.
1766 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1767 // Return the expression with the addrec on the outside.
1768 return getAddRecExpr(
1769 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1770 Depth + 1),
1771 getSignExtendExpr(Step, Ty, Depth + 1), L,
1772 AR->getNoWrapFlags());
1773 }
1774 }
1775 }
1776
1777 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1778 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1779 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1780 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1781 const APInt &C = SC->getAPInt();
1782 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1783 if (D != 0) {
1784 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1785 const SCEV *SResidual =
1786 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1787 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1788 return getAddExpr(SZExtD, SZExtR,
1789 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1790 Depth + 1);
1791 }
1792 }
1793
1794 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1795 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1796 return getAddRecExpr(
1797 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1798 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1799 }
1800 }
1801
1802 // zext(A % B) --> zext(A) % zext(B)
1803 {
1804 const SCEV *LHS;
1805 const SCEV *RHS;
1806 if (matchURem(Op, LHS, RHS))
1807 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1808 getZeroExtendExpr(RHS, Ty, Depth + 1));
1809 }
1810
1811 // zext(A / B) --> zext(A) / zext(B).
1812 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1813 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1814 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1815
1816 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1817 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1818 if (SA->hasNoUnsignedWrap()) {
1819 // If the addition does not unsign overflow then we can, by definition,
1820 // commute the zero extension with the addition operation.
1821 SmallVector<const SCEV *, 4> Ops;
1822 for (const auto *Op : SA->operands())
1823 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1824 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1825 }
1826
1827 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1828 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1829 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1830 //
1831 // Often address arithmetics contain expressions like
1832 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1833 // This transformation is useful while proving that such expressions are
1834 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1835 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1836 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1837 if (D != 0) {
1838 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1839 const SCEV *SResidual =
1840 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1841 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1842 return getAddExpr(SZExtD, SZExtR,
1843 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1844 Depth + 1);
1845 }
1846 }
1847 }
1848
1849 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1850 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1851 if (SM->hasNoUnsignedWrap()) {
1852 // If the multiply does not unsign overflow then we can, by definition,
1853 // commute the zero extension with the multiply operation.
1854 SmallVector<const SCEV *, 4> Ops;
1855 for (const auto *Op : SM->operands())
1856 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1857 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1858 }
1859
1860 // zext(2^K * (trunc X to iN)) to iM ->
1861 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1862 //
1863 // Proof:
1864 //
1865 // zext(2^K * (trunc X to iN)) to iM
1866 // = zext((trunc X to iN) << K) to iM
1867 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1868 // (because shl removes the top K bits)
1869 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1870 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1871 //
1872 if (SM->getNumOperands() == 2)
1873 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1874 if (MulLHS->getAPInt().isPowerOf2())
1875 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1876 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1877 MulLHS->getAPInt().logBase2();
1878 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1879 return getMulExpr(
1880 getZeroExtendExpr(MulLHS, Ty),
1881 getZeroExtendExpr(
1882 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1883 SCEV::FlagNUW, Depth + 1);
1884 }
1885 }
1886
1887 // The cast wasn't folded; create an explicit cast node.
1888 // Recompute the insert position, as it may have been invalidated.
1889 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1890 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1891 Op, Ty);
1892 UniqueSCEVs.InsertNode(S, IP);
1893 addToLoopUseLists(S);
1894 return S;
1895}
1896
1897const SCEV *
1898ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1899 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&((getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(
Ty) && "This is not an extending conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 1900, __PRETTY_FUNCTION__))
1900 "This is not an extending conversion!")((getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(
Ty) && "This is not an extending conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 1900, __PRETTY_FUNCTION__))
;
1901 assert(isSCEVable(Ty) &&((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 1902, __PRETTY_FUNCTION__))
1902 "This is not a conversion to a SCEVable type!")((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 1902, __PRETTY_FUNCTION__))
;
1903 Ty = getEffectiveSCEVType(Ty);
1904
1905 // Fold if the operand is constant.
1906 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1907 return getConstant(
1908 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1909
1910 // sext(sext(x)) --> sext(x)
1911 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1912 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1913
1914 // sext(zext(x)) --> zext(x)
1915 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1916 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1917
1918 // Before doing any expensive analysis, check to see if we've already
1919 // computed a SCEV for this Op and Ty.
1920 FoldingSetNodeID ID;
1921 ID.AddInteger(scSignExtend);
1922 ID.AddPointer(Op);
1923 ID.AddPointer(Ty);
1924 void *IP = nullptr;
1925 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1926 // Limit recursion depth.
1927 if (Depth > MaxExtDepth) {
1928 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1929 Op, Ty);
1930 UniqueSCEVs.InsertNode(S, IP);
1931 addToLoopUseLists(S);
1932 return S;
1933 }
1934
1935 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1936 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1937 // It's possible the bits taken off by the truncate were all sign bits. If
1938 // so, we should be able to simplify this further.
1939 const SCEV *X = ST->getOperand();
1940 ConstantRange CR = getSignedRange(X);
1941 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1942 unsigned NewBits = getTypeSizeInBits(Ty);
1943 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1944 CR.sextOrTrunc(NewBits)))
1945 return getTruncateOrSignExtend(X, Ty);
1946 }
1947
1948 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1949 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1950 if (SA->hasNoSignedWrap()) {
1951 // If the addition does not sign overflow then we can, by definition,
1952 // commute the sign extension with the addition operation.
1953 SmallVector<const SCEV *, 4> Ops;
1954 for (const auto *Op : SA->operands())
1955 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1956 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1957 }
1958
1959 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1960 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1961 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1962 //
1963 // For instance, this will bring two seemingly different expressions:
1964 // 1 + sext(5 + 20 * %x + 24 * %y) and
1965 // sext(6 + 20 * %x + 24 * %y)
1966 // to the same form:
1967 // 2 + sext(4 + 20 * %x + 24 * %y)
1968 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1969 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1970 if (D != 0) {
1971 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1972 const SCEV *SResidual =
1973 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1974 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1975 return getAddExpr(SSExtD, SSExtR,
1976 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1977 Depth + 1);
1978 }
1979 }
1980 }
1981 // If the input value is a chrec scev, and we can prove that the value
1982 // did not overflow the old, smaller, value, we can sign extend all of the
1983 // operands (often constants). This allows analysis of something like
1984 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1985 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1986 if (AR->isAffine()) {
1987 const SCEV *Start = AR->getStart();
1988 const SCEV *Step = AR->getStepRecurrence(*this);
1989 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1990 const Loop *L = AR->getLoop();
1991
1992 if (!AR->hasNoSignedWrap()) {
1993 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1994 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1995 }
1996
1997 // If we have special knowledge that this addrec won't overflow,
1998 // we don't need to do any further analysis.
1999 if (AR->hasNoSignedWrap())
2000 return getAddRecExpr(
2001 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2002 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
2003
2004 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2005 // Note that this serves two purposes: It filters out loops that are
2006 // simply not analyzable, and it covers the case where this code is
2007 // being called from within backedge-taken count analysis, such that
2008 // attempting to ask for the backedge-taken count would likely result
2009 // in infinite recursion. In the later case, the analysis code will
2010 // cope with a conservative value, and it will take care to purge
2011 // that value once it has finished.
2012 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
2013 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2014 // Manually compute the final value for AR, checking for
2015 // overflow.
2016
2017 // Check whether the backedge-taken count can be losslessly casted to
2018 // the addrec's type. The count is always unsigned.
2019 const SCEV *CastedMaxBECount =
2020 getTruncateOrZeroExtend(MaxBECount, Start->getType());
2021 const SCEV *RecastedMaxBECount =
2022 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
2023 if (MaxBECount == RecastedMaxBECount) {
2024 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2025 // Check whether Start+Step*MaxBECount has no signed overflow.
2026 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2027 SCEV::FlagAnyWrap, Depth + 1);
2028 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2029 SCEV::FlagAnyWrap,
2030 Depth + 1),
2031 WideTy, Depth + 1);
2032 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2033 const SCEV *WideMaxBECount =
2034 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2035 const SCEV *OperandExtendedAdd =
2036 getAddExpr(WideStart,
2037 getMulExpr(WideMaxBECount,
2038 getSignExtendExpr(Step, WideTy, Depth + 1),
2039 SCEV::FlagAnyWrap, Depth + 1),
2040 SCEV::FlagAnyWrap, Depth + 1);
2041 if (SAdd == OperandExtendedAdd) {
2042 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2043 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2044 // Return the expression with the addrec on the outside.
2045 return getAddRecExpr(
2046 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2047 Depth + 1),
2048 getSignExtendExpr(Step, Ty, Depth + 1), L,
2049 AR->getNoWrapFlags());
2050 }
2051 // Similar to above, only this time treat the step value as unsigned.
2052 // This covers loops that count up with an unsigned step.
2053 OperandExtendedAdd =
2054 getAddExpr(WideStart,
2055 getMulExpr(WideMaxBECount,
2056 getZeroExtendExpr(Step, WideTy, Depth + 1),
2057 SCEV::FlagAnyWrap, Depth + 1),
2058 SCEV::FlagAnyWrap, Depth + 1);
2059 if (SAdd == OperandExtendedAdd) {
2060 // If AR wraps around then
2061 //
2062 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2063 // => SAdd != OperandExtendedAdd
2064 //
2065 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2066 // (SAdd == OperandExtendedAdd => AR is NW)
2067
2068 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
2069
2070 // Return the expression with the addrec on the outside.
2071 return getAddRecExpr(
2072 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2073 Depth + 1),
2074 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2075 AR->getNoWrapFlags());
2076 }
2077 }
2078 }
2079
2080 // Normally, in the cases we can prove no-overflow via a
2081 // backedge guarding condition, we can also compute a backedge
2082 // taken count for the loop. The exceptions are assumptions and
2083 // guards present in the loop -- SCEV is not great at exploiting
2084 // these to compute max backedge taken counts, but can still use
2085 // these to prove lack of overflow. Use this fact to avoid
2086 // doing extra work that may not pay off.
2087
2088 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
2089 !AC.assumptions().empty()) {
2090 // If the backedge is guarded by a comparison with the pre-inc
2091 // value the addrec is safe. Also, if the entry is guarded by
2092 // a comparison with the start value and the backedge is
2093 // guarded by a comparison with the post-inc value, the addrec
2094 // is safe.
2095 ICmpInst::Predicate Pred;
2096 const SCEV *OverflowLimit =
2097 getSignedOverflowLimitForStep(Step, &Pred, this);
2098 if (OverflowLimit &&
2099 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
2100 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
2101 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
2102 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2103 return getAddRecExpr(
2104 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2105 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2106 }
2107 }
2108
2109 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2110 // if D + (C - D + Step * n) could be proven to not signed wrap
2111 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2112 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2113 const APInt &C = SC->getAPInt();
2114 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2115 if (D != 0) {
2116 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2117 const SCEV *SResidual =
2118 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2119 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2120 return getAddExpr(SSExtD, SSExtR,
2121 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2122 Depth + 1);
2123 }
2124 }
2125
2126 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2127 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2128 return getAddRecExpr(
2129 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2130 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2131 }
2132 }
2133
2134 // If the input value is provably positive and we could not simplify
2135 // away the sext build a zext instead.
2136 if (isKnownNonNegative(Op))
2137 return getZeroExtendExpr(Op, Ty, Depth + 1);
2138
2139 // The cast wasn't folded; create an explicit cast node.
2140 // Recompute the insert position, as it may have been invalidated.
2141 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2142 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2143 Op, Ty);
2144 UniqueSCEVs.InsertNode(S, IP);
2145 addToLoopUseLists(S);
2146 return S;
2147}
2148
2149/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2150/// unspecified bits out to the given type.
2151const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2152 Type *Ty) {
2153 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&((getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(
Ty) && "This is not an extending conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2154, __PRETTY_FUNCTION__))
2154 "This is not an extending conversion!")((getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(
Ty) && "This is not an extending conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2154, __PRETTY_FUNCTION__))
;
2155 assert(isSCEVable(Ty) &&((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2156, __PRETTY_FUNCTION__))
2156 "This is not a conversion to a SCEVable type!")((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2156, __PRETTY_FUNCTION__))
;
2157 Ty = getEffectiveSCEVType(Ty);
2158
2159 // Sign-extend negative constants.
2160 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2161 if (SC->getAPInt().isNegative())
2162 return getSignExtendExpr(Op, Ty);
2163
2164 // Peel off a truncate cast.
2165 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2166 const SCEV *NewOp = T->getOperand();
2167 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2168 return getAnyExtendExpr(NewOp, Ty);
2169 return getTruncateOrNoop(NewOp, Ty);
2170 }
2171
2172 // Next try a zext cast. If the cast is folded, use it.
2173 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2174 if (!isa<SCEVZeroExtendExpr>(ZExt))
2175 return ZExt;
2176
2177 // Next try a sext cast. If the cast is folded, use it.
2178 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2179 if (!isa<SCEVSignExtendExpr>(SExt))
2180 return SExt;
2181
2182 // Force the cast to be folded into the operands of an addrec.
2183 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2184 SmallVector<const SCEV *, 4> Ops;
2185 for (const SCEV *Op : AR->operands())
2186 Ops.push_back(getAnyExtendExpr(Op, Ty));
2187 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2188 }
2189
2190 // If the expression is obviously signed, use the sext cast value.
2191 if (isa<SCEVSMaxExpr>(Op))
2192 return SExt;
2193
2194 // Absent any other information, use the zext cast value.
2195 return ZExt;
2196}
2197
2198/// Process the given Ops list, which is a list of operands to be added under
2199/// the given scale, update the given map. This is a helper function for
2200/// getAddRecExpr. As an example of what it does, given a sequence of operands
2201/// that would form an add expression like this:
2202///
2203/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2204///
2205/// where A and B are constants, update the map with these values:
2206///
2207/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2208///
2209/// and add 13 + A*B*29 to AccumulatedConstant.
2210/// This will allow getAddRecExpr to produce this:
2211///
2212/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2213///
2214/// This form often exposes folding opportunities that are hidden in
2215/// the original operand list.
2216///
2217/// Return true iff it appears that any interesting folding opportunities
2218/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2219/// the common case where no interesting opportunities are present, and
2220/// is also used as a check to avoid infinite recursion.
2221static bool
2222CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2223 SmallVectorImpl<const SCEV *> &NewOps,
2224 APInt &AccumulatedConstant,
2225 const SCEV *const *Ops, size_t NumOperands,
2226 const APInt &Scale,
2227 ScalarEvolution &SE) {
2228 bool Interesting = false;
2229
2230 // Iterate over the add operands. They are sorted, with constants first.
2231 unsigned i = 0;
2232 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2233 ++i;
2234 // Pull a buried constant out to the outside.
2235 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2236 Interesting = true;
2237 AccumulatedConstant += Scale * C->getAPInt();
2238 }
2239
2240 // Next comes everything else. We're especially interested in multiplies
2241 // here, but they're in the middle, so just visit the rest with one loop.
2242 for (; i != NumOperands; ++i) {
2243 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2244 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2245 APInt NewScale =
2246 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2247 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2248 // A multiplication of a constant with another add; recurse.
2249 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2250 Interesting |=
2251 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2252 Add->op_begin(), Add->getNumOperands(),
2253 NewScale, SE);
2254 } else {
2255 // A multiplication of a constant with some other value. Update
2256 // the map.
2257 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2258 const SCEV *Key = SE.getMulExpr(MulOps);
2259 auto Pair = M.insert({Key, NewScale});
2260 if (Pair.second) {
2261 NewOps.push_back(Pair.first->first);
2262 } else {
2263 Pair.first->second += NewScale;
2264 // The map already had an entry for this value, which may indicate
2265 // a folding opportunity.
2266 Interesting = true;
2267 }
2268 }
2269 } else {
2270 // An ordinary operand. Update the map.
2271 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2272 M.insert({Ops[i], Scale});
2273 if (Pair.second) {
2274 NewOps.push_back(Pair.first->first);
2275 } else {
2276 Pair.first->second += Scale;
2277 // The map already had an entry for this value, which may indicate
2278 // a folding opportunity.
2279 Interesting = true;
2280 }
2281 }
2282 }
2283
2284 return Interesting;
2285}
2286
2287// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2288// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2289// can't-overflow flags for the operation if possible.
2290static SCEV::NoWrapFlags
2291StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2292 const SmallVectorImpl<const SCEV *> &Ops,
2293 SCEV::NoWrapFlags Flags) {
2294 using namespace std::placeholders;
2295
2296 using OBO = OverflowingBinaryOperator;
2297
2298 bool CanAnalyze =
2299 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2300 (void)CanAnalyze;
2301 assert(CanAnalyze && "don't call from other places!")((CanAnalyze && "don't call from other places!") ? static_cast
<void> (0) : __assert_fail ("CanAnalyze && \"don't call from other places!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2301, __PRETTY_FUNCTION__))
;
2302
2303 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2304 SCEV::NoWrapFlags SignOrUnsignWrap =
2305 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2306
2307 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2308 auto IsKnownNonNegative = [&](const SCEV *S) {
2309 return SE->isKnownNonNegative(S);
2310 };
2311
2312 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2313 Flags =
2314 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2315
2316 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2317
2318 if (SignOrUnsignWrap != SignOrUnsignMask &&
2319 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2320 isa<SCEVConstant>(Ops[0])) {
2321
2322 auto Opcode = [&] {
2323 switch (Type) {
2324 case scAddExpr:
2325 return Instruction::Add;
2326 case scMulExpr:
2327 return Instruction::Mul;
2328 default:
2329 llvm_unreachable("Unexpected SCEV op.")::llvm::llvm_unreachable_internal("Unexpected SCEV op.", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2329)
;
2330 }
2331 }();
2332
2333 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2334
2335 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2336 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2337 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2338 Opcode, C, OBO::NoSignedWrap);
2339 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2340 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2341 }
2342
2343 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2344 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2345 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2346 Opcode, C, OBO::NoUnsignedWrap);
2347 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2348 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2349 }
2350 }
2351
2352 return Flags;
2353}
2354
2355bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2356 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2357}
2358
2359/// Get a canonical add expression, or something simpler if possible.
2360const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2361 SCEV::NoWrapFlags Flags,
2362 unsigned Depth) {
2363 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&((!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && "only nuw or nsw allowed"
) ? static_cast<void> (0) : __assert_fail ("!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && \"only nuw or nsw allowed\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2364, __PRETTY_FUNCTION__))
2364 "only nuw or nsw allowed")((!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && "only nuw or nsw allowed"
) ? static_cast<void> (0) : __assert_fail ("!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && \"only nuw or nsw allowed\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2364, __PRETTY_FUNCTION__))
;
2365 assert(!Ops.empty() && "Cannot get empty add!")((!Ops.empty() && "Cannot get empty add!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty add!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2365, __PRETTY_FUNCTION__))
;
2366 if (Ops.size() == 1) return Ops[0];
2367#ifndef NDEBUG
2368 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2369 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2370 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVAddExpr operand types don't match!") ? static_cast<void
> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVAddExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2371, __PRETTY_FUNCTION__))
2371 "SCEVAddExpr operand types don't match!")((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVAddExpr operand types don't match!") ? static_cast<void
> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVAddExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2371, __PRETTY_FUNCTION__))
;
2372#endif
2373
2374 // Sort by complexity, this groups all similar expression types together.
2375 GroupByComplexity(Ops, &LI, DT);
2376
2377 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2378
2379 // If there are any constants, fold them together.
2380 unsigned Idx = 0;
2381 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2382 ++Idx;
2383 assert(Idx < Ops.size())((Idx < Ops.size()) ? static_cast<void> (0) : __assert_fail
("Idx < Ops.size()", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2383, __PRETTY_FUNCTION__))
;
2384 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2385 // We found two constants, fold them together!
2386 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2387 if (Ops.size() == 2) return Ops[0];
2388 Ops.erase(Ops.begin()+1); // Erase the folded element
2389 LHSC = cast<SCEVConstant>(Ops[0]);
2390 }
2391
2392 // If we are left with a constant zero being added, strip it off.
2393 if (LHSC->getValue()->isZero()) {
2394 Ops.erase(Ops.begin());
2395 --Idx;
2396 }
2397
2398 if (Ops.size() == 1) return Ops[0];
2399 }
2400
2401 // Limit recursion calls depth.
2402 if (Depth > MaxArithDepth)
2403 return getOrCreateAddExpr(Ops, Flags);
2404
2405 // Okay, check to see if the same value occurs in the operand list more than
2406 // once. If so, merge them together into an multiply expression. Since we
2407 // sorted the list, these values are required to be adjacent.
2408 Type *Ty = Ops[0]->getType();
2409 bool FoundMatch = false;
2410 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2411 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2412 // Scan ahead to count how many equal operands there are.
2413 unsigned Count = 2;
2414 while (i+Count != e && Ops[i+Count] == Ops[i])
2415 ++Count;
2416 // Merge the values into a multiply.
2417 const SCEV *Scale = getConstant(Ty, Count);
2418 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2419 if (Ops.size() == Count)
2420 return Mul;
2421 Ops[i] = Mul;
2422 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2423 --i; e -= Count - 1;
2424 FoundMatch = true;
2425 }
2426 if (FoundMatch)
2427 return getAddExpr(Ops, Flags, Depth + 1);
2428
2429 // Check for truncates. If all the operands are truncated from the same
2430 // type, see if factoring out the truncate would permit the result to be
2431 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2432 // if the contents of the resulting outer trunc fold to something simple.
2433 auto FindTruncSrcType = [&]() -> Type * {
2434 // We're ultimately looking to fold an addrec of truncs and muls of only
2435 // constants and truncs, so if we find any other types of SCEV
2436 // as operands of the addrec then we bail and return nullptr here.
2437 // Otherwise, we return the type of the operand of a trunc that we find.
2438 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2439 return T->getOperand()->getType();
2440 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2441 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2442 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2443 return T->getOperand()->getType();
2444 }
2445 return nullptr;
2446 };
2447 if (auto *SrcType = FindTruncSrcType()) {
2448 SmallVector<const SCEV *, 8> LargeOps;
2449 bool Ok = true;
2450 // Check all the operands to see if they can be represented in the
2451 // source type of the truncate.
2452 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2453 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2454 if (T->getOperand()->getType() != SrcType) {
2455 Ok = false;
2456 break;
2457 }
2458 LargeOps.push_back(T->getOperand());
2459 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2460 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2461 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2462 SmallVector<const SCEV *, 8> LargeMulOps;
2463 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2464 if (const SCEVTruncateExpr *T =
2465 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2466 if (T->getOperand()->getType() != SrcType) {
2467 Ok = false;
2468 break;
2469 }
2470 LargeMulOps.push_back(T->getOperand());
2471 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2472 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2473 } else {
2474 Ok = false;
2475 break;
2476 }
2477 }
2478 if (Ok)
2479 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2480 } else {
2481 Ok = false;
2482 break;
2483 }
2484 }
2485 if (Ok) {
2486 // Evaluate the expression in the larger type.
2487 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2488 // If it folds to something simple, use it. Otherwise, don't.
2489 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2490 return getTruncateExpr(Fold, Ty);
2491 }
2492 }
2493
2494 // Skip past any other cast SCEVs.
2495 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2496 ++Idx;
2497
2498 // If there are add operands they would be next.
2499 if (Idx < Ops.size()) {
2500 bool DeletedAdd = false;
2501 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2502 if (Ops.size() > AddOpsInlineThreshold ||
2503 Add->getNumOperands() > AddOpsInlineThreshold)
2504 break;
2505 // If we have an add, expand the add operands onto the end of the operands
2506 // list.
2507 Ops.erase(Ops.begin()+Idx);
2508 Ops.append(Add->op_begin(), Add->op_end());
2509 DeletedAdd = true;
2510 }
2511
2512 // If we deleted at least one add, we added operands to the end of the list,
2513 // and they are not necessarily sorted. Recurse to resort and resimplify
2514 // any operands we just acquired.
2515 if (DeletedAdd)
2516 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2517 }
2518
2519 // Skip over the add expression until we get to a multiply.
2520 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2521 ++Idx;
2522
2523 // Check to see if there are any folding opportunities present with
2524 // operands multiplied by constant values.
2525 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2526 uint64_t BitWidth = getTypeSizeInBits(Ty);
2527 DenseMap<const SCEV *, APInt> M;
2528 SmallVector<const SCEV *, 8> NewOps;
2529 APInt AccumulatedConstant(BitWidth, 0);
2530 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2531 Ops.data(), Ops.size(),
2532 APInt(BitWidth, 1), *this)) {
2533 struct APIntCompare {
2534 bool operator()(const APInt &LHS, const APInt &RHS) const {
2535 return LHS.ult(RHS);
2536 }
2537 };
2538
2539 // Some interesting folding opportunity is present, so its worthwhile to
2540 // re-generate the operands list. Group the operands by constant scale,
2541 // to avoid multiplying by the same constant scale multiple times.
2542 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2543 for (const SCEV *NewOp : NewOps)
2544 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2545 // Re-generate the operands list.
2546 Ops.clear();
2547 if (AccumulatedConstant != 0)
2548 Ops.push_back(getConstant(AccumulatedConstant));
2549 for (auto &MulOp : MulOpLists)
2550 if (MulOp.first != 0)
2551 Ops.push_back(getMulExpr(
2552 getConstant(MulOp.first),
2553 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2554 SCEV::FlagAnyWrap, Depth + 1));
2555 if (Ops.empty())
2556 return getZero(Ty);
2557 if (Ops.size() == 1)
2558 return Ops[0];
2559 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2560 }
2561 }
2562
2563 // If we are adding something to a multiply expression, make sure the
2564 // something is not already an operand of the multiply. If so, merge it into
2565 // the multiply.
2566 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2567 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2568 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2569 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2570 if (isa<SCEVConstant>(MulOpSCEV))
2571 continue;
2572 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2573 if (MulOpSCEV == Ops[AddOp]) {
2574 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2575 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2576 if (Mul->getNumOperands() != 2) {
2577 // If the multiply has more than two operands, we must get the
2578 // Y*Z term.
2579 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2580 Mul->op_begin()+MulOp);
2581 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2582 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2583 }
2584 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2585 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2586 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2587 SCEV::FlagAnyWrap, Depth + 1);
2588 if (Ops.size() == 2) return OuterMul;
2589 if (AddOp < Idx) {
2590 Ops.erase(Ops.begin()+AddOp);
2591 Ops.erase(Ops.begin()+Idx-1);
2592 } else {
2593 Ops.erase(Ops.begin()+Idx);
2594 Ops.erase(Ops.begin()+AddOp-1);
2595 }
2596 Ops.push_back(OuterMul);
2597 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2598 }
2599
2600 // Check this multiply against other multiplies being added together.
2601 for (unsigned OtherMulIdx = Idx+1;
2602 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2603 ++OtherMulIdx) {
2604 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2605 // If MulOp occurs in OtherMul, we can fold the two multiplies
2606 // together.
2607 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2608 OMulOp != e; ++OMulOp)
2609 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2610 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2611 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2612 if (Mul->getNumOperands() != 2) {
2613 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2614 Mul->op_begin()+MulOp);
2615 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2616 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2617 }
2618 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2619 if (OtherMul->getNumOperands() != 2) {
2620 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2621 OtherMul->op_begin()+OMulOp);
2622 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2623 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2624 }
2625 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2626 const SCEV *InnerMulSum =
2627 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2628 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2629 SCEV::FlagAnyWrap, Depth + 1);
2630 if (Ops.size() == 2) return OuterMul;
2631 Ops.erase(Ops.begin()+Idx);
2632 Ops.erase(Ops.begin()+OtherMulIdx-1);
2633 Ops.push_back(OuterMul);
2634 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2635 }
2636 }
2637 }
2638 }
2639
2640 // If there are any add recurrences in the operands list, see if any other
2641 // added values are loop invariant. If so, we can fold them into the
2642 // recurrence.
2643 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2644 ++Idx;
2645
2646 // Scan over all recurrences, trying to fold loop invariants into them.
2647 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2648 // Scan all of the other operands to this add and add them to the vector if
2649 // they are loop invariant w.r.t. the recurrence.
2650 SmallVector<const SCEV *, 8> LIOps;
2651 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2652 const Loop *AddRecLoop = AddRec->getLoop();
2653 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2654 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2655 LIOps.push_back(Ops[i]);
2656 Ops.erase(Ops.begin()+i);
2657 --i; --e;
2658 }
2659
2660 // If we found some loop invariants, fold them into the recurrence.
2661 if (!LIOps.empty()) {
2662 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2663 LIOps.push_back(AddRec->getStart());
2664
2665 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2666 AddRec->op_end());
2667 // This follows from the fact that the no-wrap flags on the outer add
2668 // expression are applicable on the 0th iteration, when the add recurrence
2669 // will be equal to its start value.
2670 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2671
2672 // Build the new addrec. Propagate the NUW and NSW flags if both the
2673 // outer add and the inner addrec are guaranteed to have no overflow.
2674 // Always propagate NW.
2675 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2676 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2677
2678 // If all of the other operands were loop invariant, we are done.
2679 if (Ops.size() == 1) return NewRec;
2680
2681 // Otherwise, add the folded AddRec by the non-invariant parts.
2682 for (unsigned i = 0;; ++i)
2683 if (Ops[i] == AddRec) {
2684 Ops[i] = NewRec;
2685 break;
2686 }
2687 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2688 }
2689
2690 // Okay, if there weren't any loop invariants to be folded, check to see if
2691 // there are multiple AddRec's with the same loop induction variable being
2692 // added together. If so, we can fold them.
2693 for (unsigned OtherIdx = Idx+1;
2694 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2695 ++OtherIdx) {
2696 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2697 // so that the 1st found AddRecExpr is dominated by all others.
2698 assert(DT.dominates(((DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->
getLoop()->getHeader(), AddRec->getLoop()->getHeader
()) && "AddRecExprs are not sorted in reverse dominance order?"
) ? static_cast<void> (0) : __assert_fail ("DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->getLoop()->getHeader()) && \"AddRecExprs are not sorted in reverse dominance order?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2701, __PRETTY_FUNCTION__))
2699 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),((DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->
getLoop()->getHeader(), AddRec->getLoop()->getHeader
()) && "AddRecExprs are not sorted in reverse dominance order?"
) ? static_cast<void> (0) : __assert_fail ("DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->getLoop()->getHeader()) && \"AddRecExprs are not sorted in reverse dominance order?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2701, __PRETTY_FUNCTION__))
2700 AddRec->getLoop()->getHeader()) &&((DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->
getLoop()->getHeader(), AddRec->getLoop()->getHeader
()) && "AddRecExprs are not sorted in reverse dominance order?"
) ? static_cast<void> (0) : __assert_fail ("DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->getLoop()->getHeader()) && \"AddRecExprs are not sorted in reverse dominance order?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2701, __PRETTY_FUNCTION__))
2701 "AddRecExprs are not sorted in reverse dominance order?")((DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->
getLoop()->getHeader(), AddRec->getLoop()->getHeader
()) && "AddRecExprs are not sorted in reverse dominance order?"
) ? static_cast<void> (0) : __assert_fail ("DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->getLoop()->getHeader()) && \"AddRecExprs are not sorted in reverse dominance order?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2701, __PRETTY_FUNCTION__))
;
2702 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2703 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2704 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2705 AddRec->op_end());
2706 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2707 ++OtherIdx) {
2708 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2709 if (OtherAddRec->getLoop() == AddRecLoop) {
2710 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2711 i != e; ++i) {
2712 if (i >= AddRecOps.size()) {
2713 AddRecOps.append(OtherAddRec->op_begin()+i,
2714 OtherAddRec->op_end());
2715 break;
2716 }
2717 SmallVector<const SCEV *, 2> TwoOps = {
2718 AddRecOps[i], OtherAddRec->getOperand(i)};
2719 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2720 }
2721 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2722 }
2723 }
2724 // Step size has changed, so we cannot guarantee no self-wraparound.
2725 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2726 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2727 }
2728 }
2729
2730 // Otherwise couldn't fold anything into this recurrence. Move onto the
2731 // next one.
2732 }
2733
2734 // Okay, it looks like we really DO need an add expr. Check to see if we
2735 // already have one, otherwise create a new one.
2736 return getOrCreateAddExpr(Ops, Flags);
2737}
2738
2739const SCEV *
2740ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2741 SCEV::NoWrapFlags Flags) {
2742 FoldingSetNodeID ID;
2743 ID.AddInteger(scAddExpr);
2744 for (const SCEV *Op : Ops)
2745 ID.AddPointer(Op);
2746 void *IP = nullptr;
2747 SCEVAddExpr *S =
2748 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2749 if (!S) {
2750 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2751 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2752 S = new (SCEVAllocator)
2753 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2754 UniqueSCEVs.InsertNode(S, IP);
2755 addToLoopUseLists(S);
2756 }
2757 S->setNoWrapFlags(Flags);
2758 return S;
2759}
2760
2761const SCEV *
2762ScalarEvolution::getOrCreateAddRecExpr(SmallVectorImpl<const SCEV *> &Ops,
2763 const Loop *L, SCEV::NoWrapFlags Flags) {
2764 FoldingSetNodeID ID;
2765 ID.AddInteger(scAddRecExpr);
2766 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2767 ID.AddPointer(Ops[i]);
2768 ID.AddPointer(L);
2769 void *IP = nullptr;
2770 SCEVAddRecExpr *S =
2771 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2772 if (!S) {
2773 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2774 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2775 S = new (SCEVAllocator)
2776 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2777 UniqueSCEVs.InsertNode(S, IP);
2778 addToLoopUseLists(S);
2779 }
2780 S->setNoWrapFlags(Flags);
2781 return S;
2782}
2783
2784const SCEV *
2785ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2786 SCEV::NoWrapFlags Flags) {
2787 FoldingSetNodeID ID;
2788 ID.AddInteger(scMulExpr);
2789 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2790 ID.AddPointer(Ops[i]);
2791 void *IP = nullptr;
2792 SCEVMulExpr *S =
2793 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2794 if (!S) {
2795 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2796 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2797 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2798 O, Ops.size());
2799 UniqueSCEVs.InsertNode(S, IP);
2800 addToLoopUseLists(S);
2801 }
2802 S->setNoWrapFlags(Flags);
2803 return S;
2804}
2805
2806static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2807 uint64_t k = i*j;
2808 if (j > 1 && k / j != i) Overflow = true;
2809 return k;
2810}
2811
2812/// Compute the result of "n choose k", the binomial coefficient. If an
2813/// intermediate computation overflows, Overflow will be set and the return will
2814/// be garbage. Overflow is not cleared on absence of overflow.
2815static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2816 // We use the multiplicative formula:
2817 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2818 // At each iteration, we take the n-th term of the numeral and divide by the
2819 // (k-n)th term of the denominator. This division will always produce an
2820 // integral result, and helps reduce the chance of overflow in the
2821 // intermediate computations. However, we can still overflow even when the
2822 // final result would fit.
2823
2824 if (n == 0 || n == k) return 1;
2825 if (k > n) return 0;
2826
2827 if (k > n/2)
2828 k = n-k;
2829
2830 uint64_t r = 1;
2831 for (uint64_t i = 1; i <= k; ++i) {
2832 r = umul_ov(r, n-(i-1), Overflow);
2833 r /= i;
2834 }
2835 return r;
2836}
2837
2838/// Determine if any of the operands in this SCEV are a constant or if
2839/// any of the add or multiply expressions in this SCEV contain a constant.
2840static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2841 struct FindConstantInAddMulChain {
2842 bool FoundConstant = false;
2843
2844 bool follow(const SCEV *S) {
2845 FoundConstant |= isa<SCEVConstant>(S);
2846 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2847 }
2848
2849 bool isDone() const {
2850 return FoundConstant;
2851 }
2852 };
2853
2854 FindConstantInAddMulChain F;
2855 SCEVTraversal<FindConstantInAddMulChain> ST(F);
2856 ST.visitAll(StartExpr);
2857 return F.FoundConstant;
2858}
2859
2860/// Get a canonical multiply expression, or something simpler if possible.
2861const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2862 SCEV::NoWrapFlags Flags,
2863 unsigned Depth) {
2864 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&((Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
"only nuw or nsw allowed") ? static_cast<void> (0) : __assert_fail
("Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && \"only nuw or nsw allowed\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2865, __PRETTY_FUNCTION__))
2865 "only nuw or nsw allowed")((Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
"only nuw or nsw allowed") ? static_cast<void> (0) : __assert_fail
("Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && \"only nuw or nsw allowed\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2865, __PRETTY_FUNCTION__))
;
2866 assert(!Ops.empty() && "Cannot get empty mul!")((!Ops.empty() && "Cannot get empty mul!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty mul!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2866, __PRETTY_FUNCTION__))
;
2867 if (Ops.size() == 1) return Ops[0];
2868#ifndef NDEBUG
2869 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2870 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2871 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVMulExpr operand types don't match!") ? static_cast<void
> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVMulExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2872, __PRETTY_FUNCTION__))
2872 "SCEVMulExpr operand types don't match!")((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVMulExpr operand types don't match!") ? static_cast<void
> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVMulExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 2872, __PRETTY_FUNCTION__))
;
2873#endif
2874
2875 // Sort by complexity, this groups all similar expression types together.
2876 GroupByComplexity(Ops, &LI, DT);
2877
2878 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2879
2880 // Limit recursion calls depth.
2881 if (Depth > MaxArithDepth)
2882 return getOrCreateMulExpr(Ops, Flags);
2883
2884 // If there are any constants, fold them together.
2885 unsigned Idx = 0;
2886 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2887
2888 if (Ops.size() == 2)
2889 // C1*(C2+V) -> C1*C2 + C1*V
2890 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2891 // If any of Add's ops are Adds or Muls with a constant, apply this
2892 // transformation as well.
2893 //
2894 // TODO: There are some cases where this transformation is not
2895 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
2896 // this transformation should be narrowed down.
2897 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2898 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2899 SCEV::FlagAnyWrap, Depth + 1),
2900 getMulExpr(LHSC, Add->getOperand(1),
2901 SCEV::FlagAnyWrap, Depth + 1),
2902 SCEV::FlagAnyWrap, Depth + 1);
2903
2904 ++Idx;
2905 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2906 // We found two constants, fold them together!
2907 ConstantInt *Fold =
2908 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2909 Ops[0] = getConstant(Fold);
2910 Ops.erase(Ops.begin()+1); // Erase the folded element
2911 if (Ops.size() == 1) return Ops[0];
2912 LHSC = cast<SCEVConstant>(Ops[0]);
2913 }
2914
2915 // If we are left with a constant one being multiplied, strip it off.
2916 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2917 Ops.erase(Ops.begin());
2918 --Idx;
2919 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2920 // If we have a multiply of zero, it will always be zero.
2921 return Ops[0];
2922 } else if (Ops[0]->isAllOnesValue()) {
2923 // If we have a mul by -1 of an add, try distributing the -1 among the
2924 // add operands.
2925 if (Ops.size() == 2) {
2926 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2927 SmallVector<const SCEV *, 4> NewOps;
2928 bool AnyFolded = false;
2929 for (const SCEV *AddOp : Add->operands()) {
2930 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2931 Depth + 1);
2932 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2933 NewOps.push_back(Mul);
2934 }
2935 if (AnyFolded)
2936 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2937 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2938 // Negation preserves a recurrence's no self-wrap property.
2939 SmallVector<const SCEV *, 4> Operands;
2940 for (const SCEV *AddRecOp : AddRec->operands())
2941 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2942 Depth + 1));
2943
2944 return getAddRecExpr(Operands, AddRec->getLoop(),
2945 AddRec->getNoWrapFlags(SCEV::FlagNW));
2946 }
2947 }
2948 }
2949
2950 if (Ops.size() == 1)
2951 return Ops[0];
2952 }
2953
2954 // Skip over the add expression until we get to a multiply.
2955 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2956 ++Idx;
2957
2958 // If there are mul operands inline them all into this expression.
2959 if (Idx < Ops.size()) {
2960 bool DeletedMul = false;
2961 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2962 if (Ops.size() > MulOpsInlineThreshold)
2963 break;
2964 // If we have an mul, expand the mul operands onto the end of the
2965 // operands list.
2966 Ops.erase(Ops.begin()+Idx);
2967 Ops.append(Mul->op_begin(), Mul->op_end());
2968 DeletedMul = true;
2969 }
2970
2971 // If we deleted at least one mul, we added operands to the end of the
2972 // list, and they are not necessarily sorted. Recurse to resort and
2973 // resimplify any operands we just acquired.
2974 if (DeletedMul)
2975 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2976 }
2977
2978 // If there are any add recurrences in the operands list, see if any other
2979 // added values are loop invariant. If so, we can fold them into the
2980 // recurrence.
2981 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2982 ++Idx;
2983
2984 // Scan over all recurrences, trying to fold loop invariants into them.
2985 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2986 // Scan all of the other operands to this mul and add them to the vector
2987 // if they are loop invariant w.r.t. the recurrence.
2988 SmallVector<const SCEV *, 8> LIOps;
2989 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2990 const Loop *AddRecLoop = AddRec->getLoop();
2991 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2992 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2993 LIOps.push_back(Ops[i]);
2994 Ops.erase(Ops.begin()+i);
2995 --i; --e;
2996 }
2997
2998 // If we found some loop invariants, fold them into the recurrence.
2999 if (!LIOps.empty()) {
3000 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3001 SmallVector<const SCEV *, 4> NewOps;
3002 NewOps.reserve(AddRec->getNumOperands());
3003 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3004 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3005 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3006 SCEV::FlagAnyWrap, Depth + 1));
3007
3008 // Build the new addrec. Propagate the NUW and NSW flags if both the
3009 // outer mul and the inner addrec are guaranteed to have no overflow.
3010 //
3011 // No self-wrap cannot be guaranteed after changing the step size, but
3012 // will be inferred if either NUW or NSW is true.
3013 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
3014 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
3015
3016 // If all of the other operands were loop invariant, we are done.
3017 if (Ops.size() == 1) return NewRec;
3018
3019 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3020 for (unsigned i = 0;; ++i)
3021 if (Ops[i] == AddRec) {
3022 Ops[i] = NewRec;
3023 break;
3024 }
3025 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3026 }
3027
3028 // Okay, if there weren't any loop invariants to be folded, check to see
3029 // if there are multiple AddRec's with the same loop induction variable
3030 // being multiplied together. If so, we can fold them.
3031
3032 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3033 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3034 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3035 // ]]],+,...up to x=2n}.
3036 // Note that the arguments to choose() are always integers with values
3037 // known at compile time, never SCEV objects.
3038 //
3039 // The implementation avoids pointless extra computations when the two
3040 // addrec's are of different length (mathematically, it's equivalent to
3041 // an infinite stream of zeros on the right).
3042 bool OpsModified = false;
3043 for (unsigned OtherIdx = Idx+1;
3044 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3045 ++OtherIdx) {
3046 const SCEVAddRecExpr *OtherAddRec =
3047 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3048 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3049 continue;
3050
3051 // Limit max number of arguments to avoid creation of unreasonably big
3052 // SCEVAddRecs with very complex operands.
3053 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3054 MaxAddRecSize)
3055 continue;
3056
3057 bool Overflow = false;
3058 Type *Ty = AddRec->getType();
3059 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3060 SmallVector<const SCEV*, 7> AddRecOps;
3061 for (int x = 0, xe = AddRec->getNumOperands() +
3062 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3063 const SCEV *Term = getZero(Ty);
3064 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3065 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3066 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3067 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3068 z < ze && !Overflow; ++z) {
3069 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3070 uint64_t Coeff;
3071 if (LargerThan64Bits)
3072 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3073 else
3074 Coeff = Coeff1*Coeff2;
3075 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3076 const SCEV *Term1 = AddRec->getOperand(y-z);
3077 const SCEV *Term2 = OtherAddRec->getOperand(z);
3078 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
3079 SCEV::FlagAnyWrap, Depth + 1),
3080 SCEV::FlagAnyWrap, Depth + 1);
3081 }
3082 }
3083 AddRecOps.push_back(Term);
3084 }
3085 if (!Overflow) {
3086 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3087 SCEV::FlagAnyWrap);
3088 if (Ops.size() == 2) return NewAddRec;
3089 Ops[Idx] = NewAddRec;
3090 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3091 OpsModified = true;
3092 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3093 if (!AddRec)
3094 break;
3095 }
3096 }
3097 if (OpsModified)
3098 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3099
3100 // Otherwise couldn't fold anything into this recurrence. Move onto the
3101 // next one.
3102 }
3103
3104 // Okay, it looks like we really DO need an mul expr. Check to see if we
3105 // already have one, otherwise create a new one.
3106 return getOrCreateMulExpr(Ops, Flags);
3107}
3108
3109/// Represents an unsigned remainder expression based on unsigned division.
3110const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3111 const SCEV *RHS) {
3112 assert(getEffectiveSCEVType(LHS->getType()) ==((getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType
(RHS->getType()) && "SCEVURemExpr operand types don't match!"
) ? static_cast<void> (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVURemExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3114, __PRETTY_FUNCTION__))
3113 getEffectiveSCEVType(RHS->getType()) &&((getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType
(RHS->getType()) && "SCEVURemExpr operand types don't match!"
) ? static_cast<void> (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVURemExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3114, __PRETTY_FUNCTION__))
3114 "SCEVURemExpr operand types don't match!")((getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType
(RHS->getType()) && "SCEVURemExpr operand types don't match!"
) ? static_cast<void> (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVURemExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3114, __PRETTY_FUNCTION__))
;
3115
3116 // Short-circuit easy cases
3117 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3118 // If constant is one, the result is trivial
3119 if (RHSC->getValue()->isOne())
3120 return getZero(LHS->getType()); // X urem 1 --> 0
3121
3122 // If constant is a power of two, fold into a zext(trunc(LHS)).
3123 if (RHSC->getAPInt().isPowerOf2()) {
3124 Type *FullTy = LHS->getType();
3125 Type *TruncTy =
3126 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3127 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3128 }
3129 }
3130
3131 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3132 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3133 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3134 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3135}
3136
3137/// Get a canonical unsigned division expression, or something simpler if
3138/// possible.
3139const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3140 const SCEV *RHS) {
3141 assert(getEffectiveSCEVType(LHS->getType()) ==((getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType
(RHS->getType()) && "SCEVUDivExpr operand types don't match!"
) ? static_cast<void> (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVUDivExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3143, __PRETTY_FUNCTION__))
3142 getEffectiveSCEVType(RHS->getType()) &&((getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType
(RHS->getType()) && "SCEVUDivExpr operand types don't match!"
) ? static_cast<void> (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVUDivExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3143, __PRETTY_FUNCTION__))
3143 "SCEVUDivExpr operand types don't match!")((getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType
(RHS->getType()) && "SCEVUDivExpr operand types don't match!"
) ? static_cast<void> (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVUDivExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3143, __PRETTY_FUNCTION__))
;
3144
3145 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3146 if (RHSC->getValue()->isOne())
3147 return LHS; // X udiv 1 --> x
3148 // If the denominator is zero, the result of the udiv is undefined. Don't
3149 // try to analyze it, because the resolution chosen here may differ from
3150 // the resolution chosen in other parts of the compiler.
3151 if (!RHSC->getValue()->isZero()) {
3152 // Determine if the division can be folded into the operands of
3153 // its operands.
3154 // TODO: Generalize this to non-constants by using known-bits information.
3155 Type *Ty = LHS->getType();
3156 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3157 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3158 // For non-power-of-two values, effectively round the value up to the
3159 // nearest power of two.
3160 if (!RHSC->getAPInt().isPowerOf2())
3161 ++MaxShiftAmt;
3162 IntegerType *ExtTy =
3163 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3164 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3165 if (const SCEVConstant *Step =
3166 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3167 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3168 const APInt &StepInt = Step->getAPInt();
3169 const APInt &DivInt = RHSC->getAPInt();
3170 if (!StepInt.urem(DivInt) &&
3171 getZeroExtendExpr(AR, ExtTy) ==
3172 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3173 getZeroExtendExpr(Step, ExtTy),
3174 AR->getLoop(), SCEV::FlagAnyWrap)) {
3175 SmallVector<const SCEV *, 4> Operands;
3176 for (const SCEV *Op : AR->operands())
3177 Operands.push_back(getUDivExpr(Op, RHS));
3178 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3179 }
3180 /// Get a canonical UDivExpr for a recurrence.
3181 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3182 // We can currently only fold X%N if X is constant.
3183 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3184 if (StartC && !DivInt.urem(StepInt) &&
3185 getZeroExtendExpr(AR, ExtTy) ==
3186 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3187 getZeroExtendExpr(Step, ExtTy),
3188 AR->getLoop(), SCEV::FlagAnyWrap)) {
3189 const APInt &StartInt = StartC->getAPInt();
3190 const APInt &StartRem = StartInt.urem(StepInt);
3191 if (StartRem != 0)
3192 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3193 AR->getLoop(), SCEV::FlagNW);
3194 }
3195 }
3196 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3197 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3198 SmallVector<const SCEV *, 4> Operands;
3199 for (const SCEV *Op : M->operands())
3200 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3201 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3202 // Find an operand that's safely divisible.
3203 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3204 const SCEV *Op = M->getOperand(i);
3205 const SCEV *Div = getUDivExpr(Op, RHSC);
3206 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3207 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3208 M->op_end());
3209 Operands[i] = Div;
3210 return getMulExpr(Operands);
3211 }
3212 }
3213 }
3214
3215 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3216 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3217 if (auto *DivisorConstant =
3218 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3219 bool Overflow = false;
3220 APInt NewRHS =
3221 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3222 if (Overflow) {
3223 return getConstant(RHSC->getType(), 0, false);
3224 }
3225 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3226 }
3227 }
3228
3229 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3230 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3231 SmallVector<const SCEV *, 4> Operands;
3232 for (const SCEV *Op : A->operands())
3233 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3234 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3235 Operands.clear();
3236 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3237 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3238 if (isa<SCEVUDivExpr>(Op) ||
3239 getMulExpr(Op, RHS) != A->getOperand(i))
3240 break;
3241 Operands.push_back(Op);
3242 }
3243 if (Operands.size() == A->getNumOperands())
3244 return getAddExpr(Operands);
3245 }
3246 }
3247
3248 // Fold if both operands are constant.
3249 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3250 Constant *LHSCV = LHSC->getValue();
3251 Constant *RHSCV = RHSC->getValue();
3252 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3253 RHSCV)));
3254 }
3255 }
3256 }
3257
3258 FoldingSetNodeID ID;
3259 ID.AddInteger(scUDivExpr);
3260 ID.AddPointer(LHS);
3261 ID.AddPointer(RHS);
3262 void *IP = nullptr;
3263 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3264 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3265 LHS, RHS);
3266 UniqueSCEVs.InsertNode(S, IP);
3267 addToLoopUseLists(S);
3268 return S;
3269}
3270
3271static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3272 APInt A = C1->getAPInt().abs();
3273 APInt B = C2->getAPInt().abs();
3274 uint32_t ABW = A.getBitWidth();
3275 uint32_t BBW = B.getBitWidth();
3276
3277 if (ABW > BBW)
3278 B = B.zext(ABW);
3279 else if (ABW < BBW)
3280 A = A.zext(BBW);
3281
3282 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3283}
3284
3285/// Get a canonical unsigned division expression, or something simpler if
3286/// possible. There is no representation for an exact udiv in SCEV IR, but we
3287/// can attempt to remove factors from the LHS and RHS. We can't do this when
3288/// it's not exact because the udiv may be clearing bits.
3289const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3290 const SCEV *RHS) {
3291 // TODO: we could try to find factors in all sorts of things, but for now we
3292 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3293 // end of this file for inspiration.
3294
3295 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3296 if (!Mul || !Mul->hasNoUnsignedWrap())
3297 return getUDivExpr(LHS, RHS);
3298
3299 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3300 // If the mulexpr multiplies by a constant, then that constant must be the
3301 // first element of the mulexpr.
3302 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3303 if (LHSCst == RHSCst) {
3304 SmallVector<const SCEV *, 2> Operands;
3305 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3306 return getMulExpr(Operands);
3307 }
3308
3309 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3310 // that there's a factor provided by one of the other terms. We need to
3311 // check.
3312 APInt Factor = gcd(LHSCst, RHSCst);
3313 if (!Factor.isIntN(1)) {
3314 LHSCst =
3315 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3316 RHSCst =
3317 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3318 SmallVector<const SCEV *, 2> Operands;
3319 Operands.push_back(LHSCst);
3320 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3321 LHS = getMulExpr(Operands);
3322 RHS = RHSCst;
3323 Mul = dyn_cast<SCEVMulExpr>(LHS);
3324 if (!Mul)
3325 return getUDivExactExpr(LHS, RHS);
3326 }
3327 }
3328 }
3329
3330 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3331 if (Mul->getOperand(i) == RHS) {
3332 SmallVector<const SCEV *, 2> Operands;
3333 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3334 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3335 return getMulExpr(Operands);
3336 }
3337 }
3338
3339 return getUDivExpr(LHS, RHS);
3340}
3341
3342/// Get an add recurrence expression for the specified loop. Simplify the
3343/// expression as much as possible.
3344const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3345 const Loop *L,
3346 SCEV::NoWrapFlags Flags) {
3347 SmallVector<const SCEV *, 4> Operands;
3348 Operands.push_back(Start);
3349 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3350 if (StepChrec->getLoop() == L) {
3351 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3352 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3353 }
3354
3355 Operands.push_back(Step);
3356 return getAddRecExpr(Operands, L, Flags);
3357}
3358
3359/// Get an add recurrence expression for the specified loop. Simplify the
3360/// expression as much as possible.
3361const SCEV *
3362ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3363 const Loop *L, SCEV::NoWrapFlags Flags) {
3364 if (Operands.size() == 1) return Operands[0];
3365#ifndef NDEBUG
3366 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3367 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3368 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&((getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
"SCEVAddRecExpr operand types don't match!") ? static_cast<
void> (0) : __assert_fail ("getEffectiveSCEVType(Operands[i]->getType()) == ETy && \"SCEVAddRecExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3369, __PRETTY_FUNCTION__))
3369 "SCEVAddRecExpr operand types don't match!")((getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
"SCEVAddRecExpr operand types don't match!") ? static_cast<
void> (0) : __assert_fail ("getEffectiveSCEVType(Operands[i]->getType()) == ETy && \"SCEVAddRecExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3369, __PRETTY_FUNCTION__))
;
3370 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3371 assert(isLoopInvariant(Operands[i], L) &&((isLoopInvariant(Operands[i], L) && "SCEVAddRecExpr operand is not loop-invariant!"
) ? static_cast<void> (0) : __assert_fail ("isLoopInvariant(Operands[i], L) && \"SCEVAddRecExpr operand is not loop-invariant!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3372, __PRETTY_FUNCTION__))
3372 "SCEVAddRecExpr operand is not loop-invariant!")((isLoopInvariant(Operands[i], L) && "SCEVAddRecExpr operand is not loop-invariant!"
) ? static_cast<void> (0) : __assert_fail ("isLoopInvariant(Operands[i], L) && \"SCEVAddRecExpr operand is not loop-invariant!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3372, __PRETTY_FUNCTION__))
;
3373#endif
3374
3375 if (Operands.back()->isZero()) {
3376 Operands.pop_back();
3377 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3378 }
3379
3380 // It's tempting to want to call getMaxBackedgeTakenCount count here and
3381 // use that information to infer NUW and NSW flags. However, computing a
3382 // BE count requires calling getAddRecExpr, so we may not yet have a
3383 // meaningful BE count at this point (and if we don't, we'd be stuck
3384 // with a SCEVCouldNotCompute as the cached BE count).
3385
3386 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3387
3388 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3389 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3390 const Loop *NestedLoop = NestedAR->getLoop();
3391 if (L->contains(NestedLoop)
3392 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3393 : (!NestedLoop->contains(L) &&
3394 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3395 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3396 NestedAR->op_end());
3397 Operands[0] = NestedAR->getStart();
3398 // AddRecs require their operands be loop-invariant with respect to their
3399 // loops. Don't perform this transformation if it would break this
3400 // requirement.
3401 bool AllInvariant = all_of(
3402 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3403
3404 if (AllInvariant) {
3405 // Create a recurrence for the outer loop with the same step size.
3406 //
3407 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3408 // inner recurrence has the same property.
3409 SCEV::NoWrapFlags OuterFlags =
3410 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3411
3412 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3413 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3414 return isLoopInvariant(Op, NestedLoop);
3415 });
3416
3417 if (AllInvariant) {
3418 // Ok, both add recurrences are valid after the transformation.
3419 //
3420 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3421 // the outer recurrence has the same property.
3422 SCEV::NoWrapFlags InnerFlags =
3423 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3424 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3425 }
3426 }
3427 // Reset Operands to its original state.
3428 Operands[0] = NestedAR;
3429 }
3430 }
3431
3432 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3433 // already have one, otherwise create a new one.
3434 return getOrCreateAddRecExpr(Operands, L, Flags);
3435}
3436
3437const SCEV *
3438ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3439 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3440 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3441 // getSCEV(Base)->getType() has the same address space as Base->getType()
3442 // because SCEV::getType() preserves the address space.
3443 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3444 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3445 // instruction to its SCEV, because the Instruction may be guarded by control
3446 // flow and the no-overflow bits may not be valid for the expression in any
3447 // context. This can be fixed similarly to how these flags are handled for
3448 // adds.
3449 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3450 : SCEV::FlagAnyWrap;
3451
3452 const SCEV *TotalOffset = getZero(IntPtrTy);
3453 // The array size is unimportant. The first thing we do on CurTy is getting
3454 // its element type.
3455 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3456 for (const SCEV *IndexExpr : IndexExprs) {
3457 // Compute the (potentially symbolic) offset in bytes for this index.
3458 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3459 // For a struct, add the member offset.
3460 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3461 unsigned FieldNo = Index->getZExtValue();
3462 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3463
3464 // Add the field offset to the running total offset.
3465 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3466
3467 // Update CurTy to the type of the field at Index.
3468 CurTy = STy->getTypeAtIndex(Index);
3469 } else {
3470 // Update CurTy to its element type.
3471 CurTy = cast<SequentialType>(CurTy)->getElementType();
3472 // For an array, add the element offset, explicitly scaled.
3473 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3474 // Getelementptr indices are signed.
3475 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3476
3477 // Multiply the index by the element size to compute the element offset.
3478 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3479
3480 // Add the element offset to the running total offset.
3481 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3482 }
3483 }
3484
3485 // Add the total offset from all the GEP indices to the base.
3486 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3487}
3488
3489const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3490 const SCEV *RHS) {
3491 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3492 return getSMaxExpr(Ops);
3493}
3494
3495const SCEV *
3496ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3497 assert(!Ops.empty() && "Cannot get empty smax!")((!Ops.empty() && "Cannot get empty smax!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty smax!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3497, __PRETTY_FUNCTION__))
;
3498 if (Ops.size() == 1) return Ops[0];
3499#ifndef NDEBUG
3500 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3501 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3502 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVSMaxExpr operand types don't match!") ? static_cast<
void> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVSMaxExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3503, __PRETTY_FUNCTION__))
3503 "SCEVSMaxExpr operand types don't match!")((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVSMaxExpr operand types don't match!") ? static_cast<
void> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVSMaxExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3503, __PRETTY_FUNCTION__))
;
3504#endif
3505
3506 // Sort by complexity, this groups all similar expression types together.
3507 GroupByComplexity(Ops, &LI, DT);
3508
3509 // If there are any constants, fold them together.
3510 unsigned Idx = 0;
3511 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3512 ++Idx;
3513 assert(Idx < Ops.size())((Idx < Ops.size()) ? static_cast<void> (0) : __assert_fail
("Idx < Ops.size()", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3513, __PRETTY_FUNCTION__))
;
3514 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3515 // We found two constants, fold them together!
3516 ConstantInt *Fold = ConstantInt::get(
3517 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3518 Ops[0] = getConstant(Fold);
3519 Ops.erase(Ops.begin()+1); // Erase the folded element
3520 if (Ops.size() == 1) return Ops[0];
3521 LHSC = cast<SCEVConstant>(Ops[0]);
3522 }
3523
3524 // If we are left with a constant minimum-int, strip it off.
3525 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3526 Ops.erase(Ops.begin());
3527 --Idx;
3528 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3529 // If we have an smax with a constant maximum-int, it will always be
3530 // maximum-int.
3531 return Ops[0];
3532 }
3533
3534 if (Ops.size() == 1) return Ops[0];
3535 }
3536
3537 // Find the first SMax
3538 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3539 ++Idx;
3540
3541 // Check to see if one of the operands is an SMax. If so, expand its operands
3542 // onto our operand list, and recurse to simplify.
3543 if (Idx < Ops.size()) {
3544 bool DeletedSMax = false;
3545 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3546 Ops.erase(Ops.begin()+Idx);
3547 Ops.append(SMax->op_begin(), SMax->op_end());
3548 DeletedSMax = true;
3549 }
3550
3551 if (DeletedSMax)
3552 return getSMaxExpr(Ops);
3553 }
3554
3555 // Okay, check to see if the same value occurs in the operand list twice. If
3556 // so, delete one. Since we sorted the list, these values are required to
3557 // be adjacent.
3558 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3559 // X smax Y smax Y --> X smax Y
3560 // X smax Y --> X, if X is always greater than Y
3561 if (Ops[i] == Ops[i+1] ||
3562 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3563 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3564 --i; --e;
3565 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3566 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3567 --i; --e;
3568 }
3569
3570 if (Ops.size() == 1) return Ops[0];
3571
3572 assert(!Ops.empty() && "Reduced smax down to nothing!")((!Ops.empty() && "Reduced smax down to nothing!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"Reduced smax down to nothing!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3572, __PRETTY_FUNCTION__))
;
3573
3574 // Okay, it looks like we really DO need an smax expr. Check to see if we
3575 // already have one, otherwise create a new one.
3576 FoldingSetNodeID ID;
3577 ID.AddInteger(scSMaxExpr);
3578 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3579 ID.AddPointer(Ops[i]);
3580 void *IP = nullptr;
3581 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3582 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3583 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3584 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3585 O, Ops.size());
3586 UniqueSCEVs.InsertNode(S, IP);
3587 addToLoopUseLists(S);
3588 return S;
3589}
3590
3591const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3592 const SCEV *RHS) {
3593 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3594 return getUMaxExpr(Ops);
3595}
3596
3597const SCEV *
3598ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3599 assert(!Ops.empty() && "Cannot get empty umax!")((!Ops.empty() && "Cannot get empty umax!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty umax!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3599, __PRETTY_FUNCTION__))
;
3600 if (Ops.size() == 1) return Ops[0];
3601#ifndef NDEBUG
3602 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3603 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3604 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVUMaxExpr operand types don't match!") ? static_cast<
void> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVUMaxExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3605, __PRETTY_FUNCTION__))
3605 "SCEVUMaxExpr operand types don't match!")((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVUMaxExpr operand types don't match!") ? static_cast<
void> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVUMaxExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3605, __PRETTY_FUNCTION__))
;
3606#endif
3607
3608 // Sort by complexity, this groups all similar expression types together.
3609 GroupByComplexity(Ops, &LI, DT);
3610
3611 // If there are any constants, fold them together.
3612 unsigned Idx = 0;
3613 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3614 ++Idx;
3615 assert(Idx < Ops.size())((Idx < Ops.size()) ? static_cast<void> (0) : __assert_fail
("Idx < Ops.size()", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3615, __PRETTY_FUNCTION__))
;
3616 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3617 // We found two constants, fold them together!
3618 ConstantInt *Fold = ConstantInt::get(
3619 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3620 Ops[0] = getConstant(Fold);
3621 Ops.erase(Ops.begin()+1); // Erase the folded element
3622 if (Ops.size() == 1) return Ops[0];
3623 LHSC = cast<SCEVConstant>(Ops[0]);
3624 }
3625
3626 // If we are left with a constant minimum-int, strip it off.
3627 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3628 Ops.erase(Ops.begin());
3629 --Idx;
3630 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3631 // If we have an umax with a constant maximum-int, it will always be
3632 // maximum-int.
3633 return Ops[0];
3634 }
3635
3636 if (Ops.size() == 1) return Ops[0];
3637 }
3638
3639 // Find the first UMax
3640 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3641 ++Idx;
3642
3643 // Check to see if one of the operands is a UMax. If so, expand its operands
3644 // onto our operand list, and recurse to simplify.
3645 if (Idx < Ops.size()) {
3646 bool DeletedUMax = false;
3647 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3648 Ops.erase(Ops.begin()+Idx);
3649 Ops.append(UMax->op_begin(), UMax->op_end());
3650 DeletedUMax = true;
3651 }
3652
3653 if (DeletedUMax)
3654 return getUMaxExpr(Ops);
3655 }
3656
3657 // Okay, check to see if the same value occurs in the operand list twice. If
3658 // so, delete one. Since we sorted the list, these values are required to
3659 // be adjacent.
3660 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3661 // X umax Y umax Y --> X umax Y
3662 // X umax Y --> X, if X is always greater than Y
3663 if (Ops[i] == Ops[i + 1] || isKnownViaNonRecursiveReasoning(
3664 ICmpInst::ICMP_UGE, Ops[i], Ops[i + 1])) {
3665 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3666 --i; --e;
3667 } else if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, Ops[i],
3668 Ops[i + 1])) {
3669 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3670 --i; --e;
3671 }
3672
3673 if (Ops.size() == 1) return Ops[0];
3674
3675 assert(!Ops.empty() && "Reduced umax down to nothing!")((!Ops.empty() && "Reduced umax down to nothing!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"Reduced umax down to nothing!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3675, __PRETTY_FUNCTION__))
;
3676
3677 // Okay, it looks like we really DO need a umax expr. Check to see if we
3678 // already have one, otherwise create a new one.
3679 FoldingSetNodeID ID;
3680 ID.AddInteger(scUMaxExpr);
3681 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3682 ID.AddPointer(Ops[i]);
3683 void *IP = nullptr;
3684 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3685 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3686 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3687 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3688 O, Ops.size());
3689 UniqueSCEVs.InsertNode(S, IP);
3690 addToLoopUseLists(S);
3691 return S;
3692}
3693
3694const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3695 const SCEV *RHS) {
3696 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3697 return getSMinExpr(Ops);
3698}
3699
3700const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3701 // ~smax(~x, ~y, ~z) == smin(x, y, z).
3702 SmallVector<const SCEV *, 2> NotOps;
3703 for (auto *S : Ops)
3704 NotOps.push_back(getNotSCEV(S));
3705 return getNotSCEV(getSMaxExpr(NotOps));
3706}
3707
3708const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3709 const SCEV *RHS) {
3710 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3711 return getUMinExpr(Ops);
3712}
3713
3714const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3715 assert(!Ops.empty() && "At least one operand must be!")((!Ops.empty() && "At least one operand must be!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"At least one operand must be!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3715, __PRETTY_FUNCTION__))
;
3716 // Trivial case.
3717 if (Ops.size() == 1)
3718 return Ops[0];
3719
3720 // ~umax(~x, ~y, ~z) == umin(x, y, z).
3721 SmallVector<const SCEV *, 2> NotOps;
3722 for (auto *S : Ops)
3723 NotOps.push_back(getNotSCEV(S));
3724 return getNotSCEV(getUMaxExpr(NotOps));
3725}
3726
3727const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3728 // We can bypass creating a target-independent
3729 // constant expression and then folding it back into a ConstantInt.
3730 // This is just a compile-time optimization.
3731 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3732}
3733
3734const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3735 StructType *STy,
3736 unsigned FieldNo) {
3737 // We can bypass creating a target-independent
3738 // constant expression and then folding it back into a ConstantInt.
3739 // This is just a compile-time optimization.
3740 return getConstant(
3741 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3742}
3743
3744const SCEV *ScalarEvolution::getUnknown(Value *V) {
3745 // Don't attempt to do anything other than create a SCEVUnknown object
3746 // here. createSCEV only calls getUnknown after checking for all other
3747 // interesting possibilities, and any other code that calls getUnknown
3748 // is doing so in order to hide a value from SCEV canonicalization.
3749
3750 FoldingSetNodeID ID;
3751 ID.AddInteger(scUnknown);
3752 ID.AddPointer(V);
3753 void *IP = nullptr;
3754 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3755 assert(cast<SCEVUnknown>(S)->getValue() == V &&((cast<SCEVUnknown>(S)->getValue() == V && "Stale SCEVUnknown in uniquing map!"
) ? static_cast<void> (0) : __assert_fail ("cast<SCEVUnknown>(S)->getValue() == V && \"Stale SCEVUnknown in uniquing map!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3756, __PRETTY_FUNCTION__))
3756 "Stale SCEVUnknown in uniquing map!")((cast<SCEVUnknown>(S)->getValue() == V && "Stale SCEVUnknown in uniquing map!"
) ? static_cast<void> (0) : __assert_fail ("cast<SCEVUnknown>(S)->getValue() == V && \"Stale SCEVUnknown in uniquing map!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3756, __PRETTY_FUNCTION__))
;
3757 return S;
3758 }
3759 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3760 FirstUnknown);
3761 FirstUnknown = cast<SCEVUnknown>(S);
3762 UniqueSCEVs.InsertNode(S, IP);
3763 return S;
3764}
3765
3766//===----------------------------------------------------------------------===//
3767// Basic SCEV Analysis and PHI Idiom Recognition Code
3768//
3769
3770/// Test if values of the given type are analyzable within the SCEV
3771/// framework. This primarily includes integer types, and it can optionally
3772/// include pointer types if the ScalarEvolution class has access to
3773/// target-specific information.
3774bool ScalarEvolution::isSCEVable(Type *Ty) const {
3775 // Integers and pointers are always SCEVable.
3776 return Ty->isIntOrPtrTy();
3777}
3778
3779/// Return the size in bits of the specified type, for which isSCEVable must
3780/// return true.
3781uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3782 assert(isSCEVable(Ty) && "Type is not SCEVable!")((isSCEVable(Ty) && "Type is not SCEVable!") ? static_cast
<void> (0) : __assert_fail ("isSCEVable(Ty) && \"Type is not SCEVable!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3782, __PRETTY_FUNCTION__))
;
3783 if (Ty->isPointerTy())
3784 return getDataLayout().getIndexTypeSizeInBits(Ty);
3785 return getDataLayout().getTypeSizeInBits(Ty);
3786}
3787
3788/// Return a type with the same bitwidth as the given type and which represents
3789/// how SCEV will treat the given type, for which isSCEVable must return
3790/// true. For pointer types, this is the pointer-sized integer type.
3791Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3792 assert(isSCEVable(Ty) && "Type is not SCEVable!")((isSCEVable(Ty) && "Type is not SCEVable!") ? static_cast
<void> (0) : __assert_fail ("isSCEVable(Ty) && \"Type is not SCEVable!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3792, __PRETTY_FUNCTION__))
;
3793
3794 if (Ty->isIntegerTy())
3795 return Ty;
3796
3797 // The only other support type is pointer.
3798 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!")((Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"
) ? static_cast<void> (0) : __assert_fail ("Ty->isPointerTy() && \"Unexpected non-pointer non-integer type!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3798, __PRETTY_FUNCTION__))
;
3799 return getDataLayout().getIntPtrType(Ty);
3800}
3801
3802Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3803 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3804}
3805
3806const SCEV *ScalarEvolution::getCouldNotCompute() {
3807 return CouldNotCompute.get();
3808}
3809
3810bool ScalarEvolution::checkValidity(const SCEV *S) const {
3811 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3812 auto *SU = dyn_cast<SCEVUnknown>(S);
3813 return SU && SU->getValue() == nullptr;
3814 });
3815
3816 return !ContainsNulls;
3817}
3818
3819bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3820 HasRecMapType::iterator I = HasRecMap.find(S);
3821 if (I != HasRecMap.end())
3822 return I->second;
3823
3824 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3825 HasRecMap.insert({S, FoundAddRec});
3826 return FoundAddRec;
3827}
3828
3829/// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3830/// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3831/// offset I, then return {S', I}, else return {\p S, nullptr}.
3832static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3833 const auto *Add = dyn_cast<SCEVAddExpr>(S);
3834 if (!Add)
3835 return {S, nullptr};
3836
3837 if (Add->getNumOperands() != 2)
3838 return {S, nullptr};
3839
3840 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3841 if (!ConstOp)
3842 return {S, nullptr};
3843
3844 return {Add->getOperand(1), ConstOp->getValue()};
3845}
3846
3847/// Return the ValueOffsetPair set for \p S. \p S can be represented
3848/// by the value and offset from any ValueOffsetPair in the set.
3849SetVector<ScalarEvolution::ValueOffsetPair> *
3850ScalarEvolution::getSCEVValues(const SCEV *S) {
3851 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3852 if (SI == ExprValueMap.end())
3853 return nullptr;
3854#ifndef NDEBUG
3855 if (VerifySCEVMap) {
3856 // Check there is no dangling Value in the set returned.
3857 for (const auto &VE : SI->second)
3858 assert(ValueExprMap.count(VE.first))((ValueExprMap.count(VE.first)) ? static_cast<void> (0)
: __assert_fail ("ValueExprMap.count(VE.first)", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3858, __PRETTY_FUNCTION__))
;
3859 }
3860#endif
3861 return &SI->second;
3862}
3863
3864/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3865/// cannot be used separately. eraseValueFromMap should be used to remove
3866/// V from ValueExprMap and ExprValueMap at the same time.
3867void ScalarEvolution::eraseValueFromMap(Value *V) {
3868 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3869 if (I != ValueExprMap.end()) {
3870 const SCEV *S = I->second;
3871 // Remove {V, 0} from the set of ExprValueMap[S]
3872 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3873 SV->remove({V, nullptr});
3874
3875 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3876 const SCEV *Stripped;
3877 ConstantInt *Offset;
3878 std::tie(Stripped, Offset) = splitAddExpr(S);
3879 if (Offset != nullptr) {
3880 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3881 SV->remove({V, Offset});
3882 }
3883 ValueExprMap.erase(V);
3884 }
3885}
3886
3887/// Check whether value has nuw/nsw/exact set but SCEV does not.
3888/// TODO: In reality it is better to check the poison recursevely
3889/// but this is better than nothing.
3890static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3891 if (auto *I = dyn_cast<Instruction>(V)) {
3892 if (isa<OverflowingBinaryOperator>(I)) {
3893 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3894 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3895 return true;
3896 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3897 return true;
3898 }
3899 } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3900 return true;
3901 }
3902 return false;
3903}
3904
3905/// Return an existing SCEV if it exists, otherwise analyze the expression and
3906/// create a new one.
3907const SCEV *ScalarEvolution::getSCEV(Value *V) {
3908 assert(isSCEVable(V->getType()) && "Value is not SCEVable!")((isSCEVable(V->getType()) && "Value is not SCEVable!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(V->getType()) && \"Value is not SCEVable!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3908, __PRETTY_FUNCTION__))
;
3909
3910 const SCEV *S = getExistingSCEV(V);
3911 if (S == nullptr) {
3912 S = createSCEV(V);
3913 // During PHI resolution, it is possible to create two SCEVs for the same
3914 // V, so it is needed to double check whether V->S is inserted into
3915 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3916 std::pair<ValueExprMapType::iterator, bool> Pair =
3917 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3918 if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3919 ExprValueMap[S].insert({V, nullptr});
3920
3921 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3922 // ExprValueMap.
3923 const SCEV *Stripped = S;
3924 ConstantInt *Offset = nullptr;
3925 std::tie(Stripped, Offset) = splitAddExpr(S);
3926 // If stripped is SCEVUnknown, don't bother to save
3927 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3928 // increase the complexity of the expansion code.
3929 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3930 // because it may generate add/sub instead of GEP in SCEV expansion.
3931 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3932 !isa<GetElementPtrInst>(V))
3933 ExprValueMap[Stripped].insert({V, Offset});
3934 }
3935 }
3936 return S;
3937}
3938
3939const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3940 assert(isSCEVable(V->getType()) && "Value is not SCEVable!")((isSCEVable(V->getType()) && "Value is not SCEVable!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(V->getType()) && \"Value is not SCEVable!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 3940, __PRETTY_FUNCTION__))
;
3941
3942 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3943 if (I != ValueExprMap.end()) {
3944 const SCEV *S = I->second;
3945 if (checkValidity(S))
3946 return S;
3947 eraseValueFromMap(V);
3948 forgetMemoizedResults(S);
3949 }
3950 return nullptr;
3951}
3952
3953/// Return a SCEV corresponding to -V = -1*V
3954const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3955 SCEV::NoWrapFlags Flags) {
3956 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3957 return getConstant(
3958 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3959
3960 Type *Ty = V->getType();
3961 Ty = getEffectiveSCEVType(Ty);
3962 return getMulExpr(
3963 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3964}
3965
3966/// Return a SCEV corresponding to ~V = -1-V
3967const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3968 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3969 return getConstant(
3970 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3971
3972 Type *Ty = V->getType();
3973 Ty = getEffectiveSCEVType(Ty);
3974 const SCEV *AllOnes =
3975 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3976 return getMinusSCEV(AllOnes, V);
3977}
3978
3979const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3980 SCEV::NoWrapFlags Flags,
3981 unsigned Depth) {
3982 // Fast path: X - X --> 0.
3983 if (LHS == RHS)
3984 return getZero(LHS->getType());
3985
3986 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3987 // makes it so that we cannot make much use of NUW.
3988 auto AddFlags = SCEV::FlagAnyWrap;
3989 const bool RHSIsNotMinSigned =
3990 !getSignedRangeMin(RHS).isMinSignedValue();
3991 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3992 // Let M be the minimum representable signed value. Then (-1)*RHS
3993 // signed-wraps if and only if RHS is M. That can happen even for
3994 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3995 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3996 // (-1)*RHS, we need to prove that RHS != M.
3997 //
3998 // If LHS is non-negative and we know that LHS - RHS does not
3999 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4000 // either by proving that RHS > M or that LHS >= 0.
4001 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4002 AddFlags = SCEV::FlagNSW;
4003 }
4004 }
4005
4006 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4007 // RHS is NSW and LHS >= 0.
4008 //
4009 // The difficulty here is that the NSW flag may have been proven
4010 // relative to a loop that is to be found in a recurrence in LHS and
4011 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4012 // larger scope than intended.
4013 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4014
4015 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4016}
4017
4018const SCEV *
4019ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
4020 Type *SrcTy = V->getType();
4021 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot truncate or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4022, __PRETTY_FUNCTION__))
4022 "Cannot truncate or zero extend with non-integer arguments!")((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot truncate or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4022, __PRETTY_FUNCTION__))
;
4023 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4024 return V; // No conversion
4025 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4026 return getTruncateExpr(V, Ty);
4027 return getZeroExtendExpr(V, Ty);
4028}
4029
4030const SCEV *
4031ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
4032 Type *Ty) {
4033 Type *SrcTy = V->getType();
4034 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot truncate or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4035, __PRETTY_FUNCTION__))
4035 "Cannot truncate or zero extend with non-integer arguments!")((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot truncate or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4035, __PRETTY_FUNCTION__))
;
4036 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4037 return V; // No conversion
4038 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4039 return getTruncateExpr(V, Ty);
4040 return getSignExtendExpr(V, Ty);
4041}
4042
4043const SCEV *
4044ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4045 Type *SrcTy = V->getType();
4046 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot noop or zero extend with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4047, __PRETTY_FUNCTION__))
18
Within the expansion of the macro 'assert':
a
Called C++ object pointer is null
4047 "Cannot noop or zero extend with non-integer arguments!")((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot noop or zero extend with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4047, __PRETTY_FUNCTION__))
;
4048 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrZeroExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrZeroExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4049, __PRETTY_FUNCTION__))
4049 "getNoopOrZeroExtend cannot truncate!")((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrZeroExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrZeroExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4049, __PRETTY_FUNCTION__))
;
4050 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4051 return V; // No conversion
4052 return getZeroExtendExpr(V, Ty);
4053}
4054
4055const SCEV *
4056ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4057 Type *SrcTy = V->getType();
4058 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot noop or sign extend with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or sign extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4059, __PRETTY_FUNCTION__))
4059 "Cannot noop or sign extend with non-integer arguments!")((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot noop or sign extend with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or sign extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4059, __PRETTY_FUNCTION__))
;
4060 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrSignExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrSignExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4061, __PRETTY_FUNCTION__))
4061 "getNoopOrSignExtend cannot truncate!")((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrSignExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrSignExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4061, __PRETTY_FUNCTION__))
;
4062 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4063 return V; // No conversion
4064 return getSignExtendExpr(V, Ty);
4065}
4066
4067const SCEV *
4068ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4069 Type *SrcTy = V->getType();
4070 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot noop or any extend with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or any extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4071, __PRETTY_FUNCTION__))
4071 "Cannot noop or any extend with non-integer arguments!")((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot noop or any extend with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or any extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4071, __PRETTY_FUNCTION__))
;
4072 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrAnyExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrAnyExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4073, __PRETTY_FUNCTION__))
4073 "getNoopOrAnyExtend cannot truncate!")((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrAnyExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrAnyExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4073, __PRETTY_FUNCTION__))
;
4074 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4075 return V; // No conversion
4076 return getAnyExtendExpr(V, Ty);
4077}
4078
4079const SCEV *
4080ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4081 Type *SrcTy = V->getType();
4082 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot truncate or noop with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or noop with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4083, __PRETTY_FUNCTION__))
4083 "Cannot truncate or noop with non-integer arguments!")((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot truncate or noop with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or noop with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4083, __PRETTY_FUNCTION__))
;
4084 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&((getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
"getTruncateOrNoop cannot extend!") ? static_cast<void>
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && \"getTruncateOrNoop cannot extend!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4085, __PRETTY_FUNCTION__))
4085 "getTruncateOrNoop cannot extend!")((getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
"getTruncateOrNoop cannot extend!") ? static_cast<void>
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && \"getTruncateOrNoop cannot extend!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4085, __PRETTY_FUNCTION__))
;
4086 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4087 return V; // No conversion
4088 return getTruncateExpr(V, Ty);
4089}
4090
4091const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4092 const SCEV *RHS) {
4093 const SCEV *PromotedLHS = LHS;
4094 const SCEV *PromotedRHS = RHS;
4095
4096 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4097 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4098 else
4099 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4100
4101 return getUMaxExpr(PromotedLHS, PromotedRHS);
4102}
4103
4104const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4105 const SCEV *RHS) {
4106 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4107 return getUMinFromMismatchedTypes(Ops);
4108}
4109
4110const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4111 SmallVectorImpl<const SCEV *> &Ops) {
4112 assert(!Ops.empty() && "At least one operand must be!")((!Ops.empty() && "At least one operand must be!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"At least one operand must be!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4112, __PRETTY_FUNCTION__))
;
4113 // Trivial case.
4114 if (Ops.size() == 1)
11
Assuming the condition is false
12
Taking false branch
4115 return Ops[0];
4116
4117 // Find the max type first.
4118 Type *MaxType = nullptr;
13
'MaxType' initialized to a null pointer value
4119 for (auto *S : Ops)
14
Assuming '__begin1' is equal to '__end1'
4120 if (MaxType)
4121 MaxType = getWiderType(MaxType, S->getType());
4122 else
4123 MaxType = S->getType();
4124
4125 // Extend all ops to max type.
4126 SmallVector<const SCEV *, 2> PromotedOps;
4127 for (auto *S : Ops)
15
Assuming '__begin1' is not equal to '__end1'
4128 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
16
Passing null pointer value via 2nd parameter 'Ty'
17
Calling 'ScalarEvolution::getNoopOrZeroExtend'
4129
4130 // Generate umin.
4131 return getUMinExpr(PromotedOps);
4132}
4133
4134const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4135 // A pointer operand may evaluate to a nonpointer expression, such as null.
4136 if (!V->getType()->isPointerTy())
4137 return V;
4138
4139 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4140 return getPointerBase(Cast->getOperand());
4141 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4142 const SCEV *PtrOp = nullptr;
4143 for (const SCEV *NAryOp : NAry->operands()) {
4144 if (NAryOp->getType()->isPointerTy()) {
4145 // Cannot find the base of an expression with multiple pointer operands.
4146 if (PtrOp)
4147 return V;
4148 PtrOp = NAryOp;
4149 }
4150 }
4151 if (!PtrOp)
4152 return V;
4153 return getPointerBase(PtrOp);
4154 }
4155 return V;
4156}
4157
4158/// Push users of the given Instruction onto the given Worklist.
4159static void
4160PushDefUseChildren(Instruction *I,
4161 SmallVectorImpl<Instruction *> &Worklist) {
4162 // Push the def-use children onto the Worklist stack.
4163 for (User *U : I->users())
4164 Worklist.push_back(cast<Instruction>(U));
4165}
4166
4167void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4168 SmallVector<Instruction *, 16> Worklist;
4169 PushDefUseChildren(PN, Worklist);
4170
4171 SmallPtrSet<Instruction *, 8> Visited;
4172 Visited.insert(PN);
4173 while (!Worklist.empty()) {
4174 Instruction *I = Worklist.pop_back_val();
4175 if (!Visited.insert(I).second)
4176 continue;
4177
4178 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4179 if (It != ValueExprMap.end()) {
4180 const SCEV *Old = It->second;
4181
4182 // Short-circuit the def-use traversal if the symbolic name
4183 // ceases to appear in expressions.
4184 if (Old != SymName && !hasOperand(Old, SymName))
4185 continue;
4186
4187 // SCEVUnknown for a PHI either means that it has an unrecognized
4188 // structure, it's a PHI that's in the progress of being computed
4189 // by createNodeForPHI, or it's a single-value PHI. In the first case,
4190 // additional loop trip count information isn't going to change anything.
4191 // In the second case, createNodeForPHI will perform the necessary
4192 // updates on its own when it gets to that point. In the third, we do
4193 // want to forget the SCEVUnknown.
4194 if (!isa<PHINode>(I) ||
4195 !isa<SCEVUnknown>(Old) ||
4196 (I != PN && Old == SymName)) {
4197 eraseValueFromMap(It->first);
4198 forgetMemoizedResults(Old);
4199 }
4200 }
4201
4202 PushDefUseChildren(I, Worklist);
4203 }
4204}
4205
4206namespace {
4207
4208/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4209/// expression in case its Loop is L. If it is not L then
4210/// if IgnoreOtherLoops is true then use AddRec itself
4211/// otherwise rewrite cannot be done.
4212/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4213class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4214public:
4215 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4216 bool IgnoreOtherLoops = true) {
4217 SCEVInitRewriter Rewriter(L, SE);
4218 const SCEV *Result = Rewriter.visit(S);
4219 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4220 return SE.getCouldNotCompute();
4221 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4222 ? SE.getCouldNotCompute()
4223 : Result;
4224 }
4225
4226 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4227 if (!SE.isLoopInvariant(Expr, L))
4228 SeenLoopVariantSCEVUnknown = true;
4229 return Expr;
4230 }
4231
4232 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4233 // Only re-write AddRecExprs for this loop.
4234 if (Expr->getLoop() == L)
4235 return Expr->getStart();
4236 SeenOtherLoops = true;
4237 return Expr;
4238 }
4239
4240 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4241
4242 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4243
4244private:
4245 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4246 : SCEVRewriteVisitor(SE), L(L) {}
4247
4248 const Loop *L;
4249 bool SeenLoopVariantSCEVUnknown = false;
4250 bool SeenOtherLoops = false;
4251};
4252
4253/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4254/// increment expression in case its Loop is L. If it is not L then
4255/// use AddRec itself.
4256/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4257class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4258public:
4259 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4260 SCEVPostIncRewriter Rewriter(L, SE);
4261 const SCEV *Result = Rewriter.visit(S);
4262 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4263 ? SE.getCouldNotCompute()
4264 : Result;
4265 }
4266
4267 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4268 if (!SE.isLoopInvariant(Expr, L))
4269 SeenLoopVariantSCEVUnknown = true;
4270 return Expr;
4271 }
4272
4273 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4274 // Only re-write AddRecExprs for this loop.
4275 if (Expr->getLoop() == L)
4276 return Expr->getPostIncExpr(SE);
4277 SeenOtherLoops = true;
4278 return Expr;
4279 }
4280
4281 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4282
4283 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4284
4285private:
4286 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4287 : SCEVRewriteVisitor(SE), L(L) {}
4288
4289 const Loop *L;
4290 bool SeenLoopVariantSCEVUnknown = false;
4291 bool SeenOtherLoops = false;
4292};
4293
4294/// This class evaluates the compare condition by matching it against the
4295/// condition of loop latch. If there is a match we assume a true value
4296/// for the condition while building SCEV nodes.
4297class SCEVBackedgeConditionFolder
4298 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4299public:
4300 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4301 ScalarEvolution &SE) {
4302 bool IsPosBECond = false;
4303 Value *BECond = nullptr;
4304 if (BasicBlock *Latch = L->getLoopLatch()) {
4305 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4306 if (BI && BI->isConditional()) {
4307 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&((BI->getSuccessor(0) != BI->getSuccessor(1) &&
"Both outgoing branches should not target same header!") ? static_cast
<void> (0) : __assert_fail ("BI->getSuccessor(0) != BI->getSuccessor(1) && \"Both outgoing branches should not target same header!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4308, __PRETTY_FUNCTION__))
4308 "Both outgoing branches should not target same header!")((BI->getSuccessor(0) != BI->getSuccessor(1) &&
"Both outgoing branches should not target same header!") ? static_cast
<void> (0) : __assert_fail ("BI->getSuccessor(0) != BI->getSuccessor(1) && \"Both outgoing branches should not target same header!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4308, __PRETTY_FUNCTION__))
;
4309 BECond = BI->getCondition();
4310 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4311 } else {
4312 return S;
4313 }
4314 }
4315 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4316 return Rewriter.visit(S);
4317 }
4318
4319 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4320 const SCEV *Result = Expr;
4321 bool InvariantF = SE.isLoopInvariant(Expr, L);
4322
4323 if (!InvariantF) {
4324 Instruction *I = cast<Instruction>(Expr->getValue());
4325 switch (I->getOpcode()) {
4326 case Instruction::Select: {
4327 SelectInst *SI = cast<SelectInst>(I);
4328 Optional<const SCEV *> Res =
4329 compareWithBackedgeCondition(SI->getCondition());
4330 if (Res.hasValue()) {
4331 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4332 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4333 }
4334 break;
4335 }
4336 default: {
4337 Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4338 if (Res.hasValue())
4339 Result = Res.getValue();
4340 break;
4341 }
4342 }
4343 }
4344 return Result;
4345 }
4346
4347private:
4348 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4349 bool IsPosBECond, ScalarEvolution &SE)
4350 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4351 IsPositiveBECond(IsPosBECond) {}
4352
4353 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4354
4355 const Loop *L;
4356 /// Loop back condition.
4357 Value *BackedgeCond = nullptr;
4358 /// Set to true if loop back is on positive branch condition.
4359 bool IsPositiveBECond;
4360};
4361
4362Optional<const SCEV *>
4363SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4364
4365 // If value matches the backedge condition for loop latch,
4366 // then return a constant evolution node based on loopback
4367 // branch taken.
4368 if (BackedgeCond == IC)
4369 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4370 : SE.getZero(Type::getInt1Ty(SE.getContext()));
4371 return None;
4372}
4373
4374class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4375public:
4376 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4377 ScalarEvolution &SE) {
4378 SCEVShiftRewriter Rewriter(L, SE);
4379 const SCEV *Result = Rewriter.visit(S);
4380 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4381 }
4382
4383 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4384 // Only allow AddRecExprs for this loop.
4385 if (!SE.isLoopInvariant(Expr, L))
4386 Valid = false;
4387 return Expr;
4388 }
4389
4390 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4391 if (Expr->getLoop() == L && Expr->isAffine())
4392 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4393 Valid = false;
4394 return Expr;
4395 }
4396
4397 bool isValid() { return Valid; }
4398
4399private:
4400 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4401 : SCEVRewriteVisitor(SE), L(L) {}
4402
4403 const Loop *L;
4404 bool Valid = true;
4405};
4406
4407} // end anonymous namespace
4408
4409SCEV::NoWrapFlags
4410ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4411 if (!AR->isAffine())
4412 return SCEV::FlagAnyWrap;
4413
4414 using OBO = OverflowingBinaryOperator;
4415
4416 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4417
4418 if (!AR->hasNoSignedWrap()) {
4419 ConstantRange AddRecRange = getSignedRange(AR);
4420 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4421
4422 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4423 Instruction::Add, IncRange, OBO::NoSignedWrap);
4424 if (NSWRegion.contains(AddRecRange))
4425 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4426 }
4427
4428 if (!AR->hasNoUnsignedWrap()) {
4429 ConstantRange AddRecRange = getUnsignedRange(AR);
4430 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4431
4432 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4433 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4434 if (NUWRegion.contains(AddRecRange))
4435 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4436 }
4437
4438 return Result;
4439}
4440
4441namespace {
4442
4443/// Represents an abstract binary operation. This may exist as a
4444/// normal instruction or constant expression, or may have been
4445/// derived from an expression tree.
4446struct BinaryOp {
4447 unsigned Opcode;
4448 Value *LHS;
4449 Value *RHS;
4450 bool IsNSW = false;
4451 bool IsNUW = false;
4452
4453 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4454 /// constant expression.
4455 Operator *Op = nullptr;
4456
4457 explicit BinaryOp(Operator *Op)
4458 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4459 Op(Op) {
4460 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4461 IsNSW = OBO->hasNoSignedWrap();
4462 IsNUW = OBO->hasNoUnsignedWrap();
4463 }
4464 }
4465
4466 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4467 bool IsNUW = false)
4468 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4469};
4470
4471} // end anonymous namespace
4472
4473/// Try to map \p V into a BinaryOp, and return \c None on failure.
4474static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4475 auto *Op = dyn_cast<Operator>(V);
4476 if (!Op)
4477 return None;
4478
4479 // Implementation detail: all the cleverness here should happen without
4480 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4481 // SCEV expressions when possible, and we should not break that.
4482
4483 switch (Op->getOpcode()) {
4484 case Instruction::Add:
4485 case Instruction::Sub:
4486 case Instruction::Mul:
4487 case Instruction::UDiv:
4488 case Instruction::URem:
4489 case Instruction::And:
4490 case Instruction::Or:
4491 case Instruction::AShr:
4492 case Instruction::Shl:
4493 return BinaryOp(Op);
4494
4495 case Instruction::Xor:
4496 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4497 // If the RHS of the xor is a signmask, then this is just an add.
4498 // Instcombine turns add of signmask into xor as a strength reduction step.
4499 if (RHSC->getValue().isSignMask())
4500 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4501 return BinaryOp(Op);
4502
4503 case Instruction::LShr:
4504 // Turn logical shift right of a constant into a unsigned divide.
4505 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4506 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4507
4508 // If the shift count is not less than the bitwidth, the result of
4509 // the shift is undefined. Don't try to analyze it, because the
4510 // resolution chosen here may differ from the resolution chosen in
4511 // other parts of the compiler.
4512 if (SA->getValue().ult(BitWidth)) {
4513 Constant *X =
4514 ConstantInt::get(SA->getContext(),
4515 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4516 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4517 }
4518 }
4519 return BinaryOp(Op);
4520
4521 case Instruction::ExtractValue: {
4522 auto *EVI = cast<ExtractValueInst>(Op);
4523 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4524 break;
4525
4526 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4527 if (!CI)
4528 break;
4529
4530 if (auto *F = CI->getCalledFunction())
4531 switch (F->getIntrinsicID()) {
4532 case Intrinsic::sadd_with_overflow:
4533 case Intrinsic::uadd_with_overflow:
4534 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4535 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4536 CI->getArgOperand(1));
4537
4538 // Now that we know that all uses of the arithmetic-result component of
4539 // CI are guarded by the overflow check, we can go ahead and pretend
4540 // that the arithmetic is non-overflowing.
4541 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4542 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4543 CI->getArgOperand(1), /* IsNSW = */ true,
4544 /* IsNUW = */ false);
4545 else
4546 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4547 CI->getArgOperand(1), /* IsNSW = */ false,
4548 /* IsNUW*/ true);
4549 case Intrinsic::ssub_with_overflow:
4550 case Intrinsic::usub_with_overflow:
4551 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4552 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4553 CI->getArgOperand(1));
4554
4555 // The same reasoning as sadd/uadd above.
4556 if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow)
4557 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4558 CI->getArgOperand(1), /* IsNSW = */ true,
4559 /* IsNUW = */ false);
4560 else
4561 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4562 CI->getArgOperand(1), /* IsNSW = */ false,
4563 /* IsNUW = */ true);
4564 case Intrinsic::smul_with_overflow:
4565 case Intrinsic::umul_with_overflow:
4566 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4567 CI->getArgOperand(1));
4568 default:
4569 break;
4570 }
4571 break;
4572 }
4573
4574 default:
4575 break;
4576 }
4577
4578 return None;
4579}
4580
4581/// Helper function to createAddRecFromPHIWithCasts. We have a phi
4582/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4583/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4584/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4585/// follows one of the following patterns:
4586/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4587/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4588/// If the SCEV expression of \p Op conforms with one of the expected patterns
4589/// we return the type of the truncation operation, and indicate whether the
4590/// truncated type should be treated as signed/unsigned by setting
4591/// \p Signed to true/false, respectively.
4592static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4593 bool &Signed, ScalarEvolution &SE) {
4594 // The case where Op == SymbolicPHI (that is, with no type conversions on
4595 // the way) is handled by the regular add recurrence creating logic and
4596 // would have already been triggered in createAddRecForPHI. Reaching it here
4597 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4598 // because one of the other operands of the SCEVAddExpr updating this PHI is
4599 // not invariant).
4600 //
4601 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4602 // this case predicates that allow us to prove that Op == SymbolicPHI will
4603 // be added.
4604 if (Op == SymbolicPHI)
4605 return nullptr;
4606
4607 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4608 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4609 if (SourceBits != NewBits)
4610 return nullptr;
4611
4612 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4613 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4614 if (!SExt && !ZExt)
4615 return nullptr;
4616 const SCEVTruncateExpr *Trunc =
4617 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4618 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4619 if (!Trunc)
4620 return nullptr;
4621 const SCEV *X = Trunc->getOperand();
4622 if (X != SymbolicPHI)
4623 return nullptr;
4624 Signed = SExt != nullptr;
4625 return Trunc->getType();
4626}
4627
4628static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4629 if (!PN->getType()->isIntegerTy())
4630 return nullptr;
4631 const Loop *L = LI.getLoopFor(PN->getParent());
4632 if (!L || L->getHeader() != PN->getParent())
4633 return nullptr;
4634 return L;
4635}
4636
4637// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4638// computation that updates the phi follows the following pattern:
4639// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4640// which correspond to a phi->trunc->sext/zext->add->phi update chain.
4641// If so, try to see if it can be rewritten as an AddRecExpr under some
4642// Predicates. If successful, return them as a pair. Also cache the results
4643// of the analysis.
4644//
4645// Example usage scenario:
4646// Say the Rewriter is called for the following SCEV:
4647// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4648// where:
4649// %X = phi i64 (%Start, %BEValue)
4650// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4651// and call this function with %SymbolicPHI = %X.
4652//
4653// The analysis will find that the value coming around the backedge has
4654// the following SCEV:
4655// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4656// Upon concluding that this matches the desired pattern, the function
4657// will return the pair {NewAddRec, SmallPredsVec} where:
4658// NewAddRec = {%Start,+,%Step}
4659// SmallPredsVec = {P1, P2, P3} as follows:
4660// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4661// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4662// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4663// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4664// under the predicates {P1,P2,P3}.
4665// This predicated rewrite will be cached in PredicatedSCEVRewrites:
4666// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4667//
4668// TODO's:
4669//
4670// 1) Extend the Induction descriptor to also support inductions that involve
4671// casts: When needed (namely, when we are called in the context of the
4672// vectorizer induction analysis), a Set of cast instructions will be
4673// populated by this method, and provided back to isInductionPHI. This is
4674// needed to allow the vectorizer to properly record them to be ignored by
4675// the cost model and to avoid vectorizing them (otherwise these casts,
4676// which are redundant under the runtime overflow checks, will be
4677// vectorized, which can be costly).
4678//
4679// 2) Support additional induction/PHISCEV patterns: We also want to support
4680// inductions where the sext-trunc / zext-trunc operations (partly) occur
4681// after the induction update operation (the induction increment):
4682//
4683// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4684// which correspond to a phi->add->trunc->sext/zext->phi update chain.
4685//
4686// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4687// which correspond to a phi->trunc->add->sext/zext->phi update chain.
4688//
4689// 3) Outline common code with createAddRecFromPHI to avoid duplication.
4690Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4691ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4692 SmallVector<const SCEVPredicate *, 3> Predicates;
4693
4694 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4695 // return an AddRec expression under some predicate.
4696
4697 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4698 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4699 assert(L && "Expecting an integer loop header phi")((L && "Expecting an integer loop header phi") ? static_cast
<void> (0) : __assert_fail ("L && \"Expecting an integer loop header phi\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4699, __PRETTY_FUNCTION__))
;
4700
4701 // The loop may have multiple entrances or multiple exits; we can analyze
4702 // this phi as an addrec if it has a unique entry value and a unique
4703 // backedge value.
4704 Value *BEValueV = nullptr, *StartValueV = nullptr;
4705 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4706 Value *V = PN->getIncomingValue(i);
4707 if (L->contains(PN->getIncomingBlock(i))) {
4708 if (!BEValueV) {
4709 BEValueV = V;
4710 } else if (BEValueV != V) {
4711 BEValueV = nullptr;
4712 break;
4713 }
4714 } else if (!StartValueV) {
4715 StartValueV = V;
4716 } else if (StartValueV != V) {
4717 StartValueV = nullptr;
4718 break;
4719 }
4720 }
4721 if (!BEValueV || !StartValueV)
4722 return None;
4723
4724 const SCEV *BEValue = getSCEV(BEValueV);
4725
4726 // If the value coming around the backedge is an add with the symbolic
4727 // value we just inserted, possibly with casts that we can ignore under
4728 // an appropriate runtime guard, then we found a simple induction variable!
4729 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4730 if (!Add)
4731 return None;
4732
4733 // If there is a single occurrence of the symbolic value, possibly
4734 // casted, replace it with a recurrence.
4735 unsigned FoundIndex = Add->getNumOperands();
4736 Type *TruncTy = nullptr;
4737 bool Signed;
4738 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4739 if ((TruncTy =
4740 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4741 if (FoundIndex == e) {
4742 FoundIndex = i;
4743 break;
4744 }
4745
4746 if (FoundIndex == Add->getNumOperands())
4747 return None;
4748
4749 // Create an add with everything but the specified operand.
4750 SmallVector<const SCEV *, 8> Ops;
4751 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4752 if (i != FoundIndex)
4753 Ops.push_back(Add->getOperand(i));
4754 const SCEV *Accum = getAddExpr(Ops);
4755
4756 // The runtime checks will not be valid if the step amount is
4757 // varying inside the loop.
4758 if (!isLoopInvariant(Accum, L))
4759 return None;
4760
4761 // *** Part2: Create the predicates
4762
4763 // Analysis was successful: we have a phi-with-cast pattern for which we
4764 // can return an AddRec expression under the following predicates:
4765 //
4766 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4767 // fits within the truncated type (does not overflow) for i = 0 to n-1.
4768 // P2: An Equal predicate that guarantees that
4769 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4770 // P3: An Equal predicate that guarantees that
4771 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4772 //
4773 // As we next prove, the above predicates guarantee that:
4774 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4775 //
4776 //
4777 // More formally, we want to prove that:
4778 // Expr(i+1) = Start + (i+1) * Accum
4779 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4780 //
4781 // Given that:
4782 // 1) Expr(0) = Start
4783 // 2) Expr(1) = Start + Accum
4784 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4785 // 3) Induction hypothesis (step i):
4786 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4787 //
4788 // Proof:
4789 // Expr(i+1) =
4790 // = Start + (i+1)*Accum
4791 // = (Start + i*Accum) + Accum
4792 // = Expr(i) + Accum
4793 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4794 // :: from step i
4795 //
4796 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4797 //
4798 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4799 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
4800 // + Accum :: from P3
4801 //
4802 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4803 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4804 //
4805 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4806 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4807 //
4808 // By induction, the same applies to all iterations 1<=i<n:
4809 //
4810
4811 // Create a truncated addrec for which we will add a no overflow check (P1).
4812 const SCEV *StartVal = getSCEV(StartValueV);
4813 const SCEV *PHISCEV =
4814 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4815 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4816
4817 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4818 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4819 // will be constant.
4820 //
4821 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4822 // add P1.
4823 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4824 SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4825 Signed ? SCEVWrapPredicate::IncrementNSSW
4826 : SCEVWrapPredicate::IncrementNUSW;
4827 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4828 Predicates.push_back(AddRecPred);
4829 }
4830
4831 // Create the Equal Predicates P2,P3:
4832
4833 // It is possible that the predicates P2 and/or P3 are computable at
4834 // compile time due to StartVal and/or Accum being constants.
4835 // If either one is, then we can check that now and escape if either P2
4836 // or P3 is false.
4837
4838 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4839 // for each of StartVal and Accum
4840 auto getExtendedExpr = [&](const SCEV *Expr,
4841 bool CreateSignExtend) -> const SCEV * {
4842 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant")((isLoopInvariant(Expr, L) && "Expr is expected to be invariant"
) ? static_cast<void> (0) : __assert_fail ("isLoopInvariant(Expr, L) && \"Expr is expected to be invariant\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4842, __PRETTY_FUNCTION__))
;
4843 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4844 const SCEV *ExtendedExpr =
4845 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4846 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4847 return ExtendedExpr;
4848 };
4849
4850 // Given:
4851 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4852 // = getExtendedExpr(Expr)
4853 // Determine whether the predicate P: Expr == ExtendedExpr
4854 // is known to be false at compile time
4855 auto PredIsKnownFalse = [&](const SCEV *Expr,
4856 const SCEV *ExtendedExpr) -> bool {
4857 return Expr != ExtendedExpr &&
4858 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4859 };
4860
4861 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4862 if (PredIsKnownFalse(StartVal, StartExtended)) {
4863 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "P2 is compile-time false\n"
;; } } while (false)
;
4864 return None;
4865 }
4866
4867 // The Step is always Signed (because the overflow checks are either
4868 // NSSW or NUSW)
4869 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4870 if (PredIsKnownFalse(Accum, AccumExtended)) {
4871 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "P3 is compile-time false\n"
;; } } while (false)
;
4872 return None;
4873 }
4874
4875 auto AppendPredicate = [&](const SCEV *Expr,
4876 const SCEV *ExtendedExpr) -> void {
4877 if (Expr != ExtendedExpr &&
4878 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4879 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4880 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "Added Predicate: " <<
*Pred; } } while (false)
;
4881 Predicates.push_back(Pred);
4882 }
4883 };
4884
4885 AppendPredicate(StartVal, StartExtended);
4886 AppendPredicate(Accum, AccumExtended);
4887
4888 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4889 // which the casts had been folded away. The caller can rewrite SymbolicPHI
4890 // into NewAR if it will also add the runtime overflow checks specified in
4891 // Predicates.
4892 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4893
4894 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4895 std::make_pair(NewAR, Predicates);
4896 // Remember the result of the analysis for this SCEV at this locayyytion.
4897 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4898 return PredRewrite;
4899}
4900
4901Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4902ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4903 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4904 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4905 if (!L)
4906 return None;
4907
4908 // Check to see if we already analyzed this PHI.
4909 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4910 if (I != PredicatedSCEVRewrites.end()) {
4911 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4912 I->second;
4913 // Analysis was done before and failed to create an AddRec:
4914 if (Rewrite.first == SymbolicPHI)
4915 return None;
4916 // Analysis was done before and succeeded to create an AddRec under
4917 // a predicate:
4918 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec")((isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"
) ? static_cast<void> (0) : __assert_fail ("isa<SCEVAddRecExpr>(Rewrite.first) && \"Expected an AddRec\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4918, __PRETTY_FUNCTION__))
;
4919 assert(!(Rewrite.second).empty() && "Expected to find Predicates")((!(Rewrite.second).empty() && "Expected to find Predicates"
) ? static_cast<void> (0) : __assert_fail ("!(Rewrite.second).empty() && \"Expected to find Predicates\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4919, __PRETTY_FUNCTION__))
;
4920 return Rewrite;
4921 }
4922
4923 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4924 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4925
4926 // Record in the cache that the analysis failed
4927 if (!Rewrite) {
4928 SmallVector<const SCEVPredicate *, 3> Predicates;
4929 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4930 return None;
4931 }
4932
4933 return Rewrite;
4934}
4935
4936// FIXME: This utility is currently required because the Rewriter currently
4937// does not rewrite this expression:
4938// {0, +, (sext ix (trunc iy to ix) to iy)}
4939// into {0, +, %step},
4940// even when the following Equal predicate exists:
4941// "%step == (sext ix (trunc iy to ix) to iy)".
4942bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4943 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4944 if (AR1 == AR2)
4945 return true;
4946
4947 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4948 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4949 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4950 return false;
4951 return true;
4952 };
4953
4954 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4955 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4956 return false;
4957 return true;
4958}
4959
4960/// A helper function for createAddRecFromPHI to handle simple cases.
4961///
4962/// This function tries to find an AddRec expression for the simplest (yet most
4963/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4964/// If it fails, createAddRecFromPHI will use a more general, but slow,
4965/// technique for finding the AddRec expression.
4966const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4967 Value *BEValueV,
4968 Value *StartValueV) {
4969 const Loop *L = LI.getLoopFor(PN->getParent());
4970 assert(L && L->getHeader() == PN->getParent())((L && L->getHeader() == PN->getParent()) ? static_cast
<void> (0) : __assert_fail ("L && L->getHeader() == PN->getParent()"
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4970, __PRETTY_FUNCTION__))
;
4971 assert(BEValueV && StartValueV)((BEValueV && StartValueV) ? static_cast<void> (
0) : __assert_fail ("BEValueV && StartValueV", "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 4971, __PRETTY_FUNCTION__))
;
4972
4973 auto BO = MatchBinaryOp(BEValueV, DT);
4974 if (!BO)
4975 return nullptr;
4976
4977 if (BO->Opcode != Instruction::Add)
4978 return nullptr;
4979
4980 const SCEV *Accum = nullptr;
4981 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4982 Accum = getSCEV(BO->RHS);
4983 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4984 Accum = getSCEV(BO->LHS);
4985
4986 if (!Accum)
4987 return nullptr;
4988
4989 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4990 if (BO->IsNUW)
4991 Flags = setFlags(Flags, SCEV::FlagNUW);
4992 if (BO->IsNSW)
4993 Flags = setFlags(Flags, SCEV::FlagNSW);
4994
4995 const SCEV *StartVal = getSCEV(StartValueV);
4996 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4997
4998 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4999
5000 // We can add Flags to the post-inc expression only if we
5001 // know that it is *undefined behavior* for BEValueV to
5002 // overflow.
5003 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5004 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5005 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5006
5007 return PHISCEV;
5008}
5009
5010const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5011 const Loop *L = LI.getLoopFor(PN->getParent());
5012 if (!L || L->getHeader() != PN->getParent())
5013 return nullptr;
5014
5015 // The loop may have multiple entrances or multiple exits; we can analyze
5016 // this phi as an addrec if it has a unique entry value and a unique
5017 // backedge value.
5018 Value *BEValueV = nullptr, *StartValueV = nullptr;
5019 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5020 Value *V = PN->getIncomingValue(i);
5021 if (L->contains(PN->getIncomingBlock(i))) {
5022 if (!BEValueV) {
5023 BEValueV = V;
5024 } else if (BEValueV != V) {
5025 BEValueV = nullptr;
5026 break;
5027 }
5028 } else if (!StartValueV) {
5029 StartValueV = V;
5030 } else if (StartValueV != V) {
5031 StartValueV = nullptr;
5032 break;
5033 }
5034 }
5035 if (!BEValueV || !StartValueV)
5036 return nullptr;
5037
5038 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&((ValueExprMap.find_as(PN) == ValueExprMap.end() && "PHI node already processed?"
) ? static_cast<void> (0) : __assert_fail ("ValueExprMap.find_as(PN) == ValueExprMap.end() && \"PHI node already processed?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 5039, __PRETTY_FUNCTION__))
5039 "PHI node already processed?")((ValueExprMap.find_as(PN) == ValueExprMap.end() && "PHI node already processed?"
) ? static_cast<void> (0) : __assert_fail ("ValueExprMap.find_as(PN) == ValueExprMap.end() && \"PHI node already processed?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 5039, __PRETTY_FUNCTION__))
;
5040
5041 // First, try to find AddRec expression without creating a fictituos symbolic
5042 // value for PN.
5043 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5044 return S;
5045
5046 // Handle PHI node value symbolically.
5047 const SCEV *SymbolicName = getUnknown(PN);
5048 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5049
5050 // Using this symbolic name for the PHI, analyze the value coming around
5051 // the back-edge.
5052 const SCEV *BEValue = getSCEV(BEValueV);
5053
5054 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5055 // has a special value for the first iteration of the loop.
5056
5057 // If the value coming around the backedge is an add with the symbolic
5058 // value we just inserted, then we found a simple induction variable!
5059 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5060 // If there is a single occurrence of the symbolic value, replace it
5061 // with a recurrence.
5062 unsigned FoundIndex = Add->getNumOperands();
5063 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5064 if (Add->getOperand(i) == SymbolicName)
5065 if (FoundIndex == e) {
5066 FoundIndex = i;
5067 break;
5068 }
5069
5070 if (FoundIndex != Add->getNumOperands()) {
5071 // Create an add with everything but the specified operand.
5072 SmallVector<const SCEV *, 8> Ops;
5073 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5074 if (i != FoundIndex)
5075 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5076 L, *this));
5077 const SCEV *Accum = getAddExpr(Ops);
5078
5079 // This is not a valid addrec if the step amount is varying each
5080 // loop iteration, but is not itself an addrec in this loop.
5081 if (isLoopInvariant(Accum, L) ||
5082 (isa<SCEVAddRecExpr>(Accum) &&
5083 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5084 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5085
5086 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5087 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5088 if (BO->IsNUW)
5089 Flags = setFlags(Flags, SCEV::FlagNUW);
5090 if (BO->IsNSW)
5091 Flags = setFlags(Flags, SCEV::FlagNSW);
5092 }
5093 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5094 // If the increment is an inbounds GEP, then we know the address
5095 // space cannot be wrapped around. We cannot make any guarantee
5096 // about signed or unsigned overflow because pointers are
5097 // unsigned but we may have a negative index from the base
5098 // pointer. We can guarantee that no unsigned wrap occurs if the
5099 // indices form a positive value.
5100 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5101 Flags = setFlags(Flags, SCEV::FlagNW);
5102
5103 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5104 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5105 Flags = setFlags(Flags, SCEV::FlagNUW);
5106 }
5107
5108 // We cannot transfer nuw and nsw flags from subtraction
5109 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5110 // for instance.
5111 }
5112
5113 const SCEV *StartVal = getSCEV(StartValueV);
5114 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5115
5116 // Okay, for the entire analysis of this edge we assumed the PHI
5117 // to be symbolic. We now need to go back and purge all of the
5118 // entries for the scalars that use the symbolic expression.
5119 forgetSymbolicName(PN, SymbolicName);
5120 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5121
5122 // We can add Flags to the post-inc expression only if we
5123 // know that it is *undefined behavior* for BEValueV to
5124 // overflow.
5125 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5126 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5127 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5128
5129 return PHISCEV;
5130 }
5131 }
5132 } else {
5133 // Otherwise, this could be a loop like this:
5134 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5135 // In this case, j = {1,+,1} and BEValue is j.
5136 // Because the other in-value of i (0) fits the evolution of BEValue
5137 // i really is an addrec evolution.
5138 //
5139 // We can generalize this saying that i is the shifted value of BEValue
5140 // by one iteration:
5141 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5142 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5143 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5144 if (Shifted != getCouldNotCompute() &&
5145 Start != getCouldNotCompute()) {
5146 const SCEV *StartVal = getSCEV(StartValueV);
5147 if (Start == StartVal) {
5148 // Okay, for the entire analysis of this edge we assumed the PHI
5149 // to be symbolic. We now need to go back and purge all of the
5150 // entries for the scalars that use the symbolic expression.
5151 forgetSymbolicName(PN, SymbolicName);
5152 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5153 return Shifted;
5154 }
5155 }
5156 }
5157
5158 // Remove the temporary PHI node SCEV that has been inserted while intending
5159 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5160 // as it will prevent later (possibly simpler) SCEV expressions to be added
5161 // to the ValueExprMap.
5162 eraseValueFromMap(PN);
5163
5164 return nullptr;
5165}
5166
5167// Checks if the SCEV S is available at BB. S is considered available at BB
5168// if S can be materialized at BB without introducing a fault.
5169static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5170 BasicBlock *BB) {
5171 struct CheckAvailable {
5172 bool TraversalDone = false;
5173 bool Available = true;
5174
5175 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
5176 BasicBlock *BB = nullptr;
5177 DominatorTree &DT;
5178
5179 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5180 : L(L), BB(BB), DT(DT) {}
5181
5182 bool setUnavailable() {
5183 TraversalDone = true;
5184 Available = false;
5185 return false;
5186 }
5187
5188 bool follow(const SCEV *S) {
5189 switch (S->getSCEVType()) {
5190 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5191 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5192 // These expressions are available if their operand(s) is/are.
5193 return true;
5194
5195 case scAddRecExpr: {
5196 // We allow add recurrences that are on the loop BB is in, or some
5197 // outer loop. This guarantees availability because the value of the
5198 // add recurrence at BB is simply the "current" value of the induction
5199 // variable. We can relax this in the future; for instance an add
5200 // recurrence on a sibling dominating loop is also available at BB.
5201 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5202 if (L && (ARLoop == L || ARLoop->contains(L)))
5203 return true;
5204
5205 return setUnavailable();
5206 }
5207
5208 case scUnknown: {
5209 // For SCEVUnknown, we check for simple dominance.
5210 const auto *SU = cast<SCEVUnknown>(S);
5211 Value *V = SU->getValue();
5212
5213 if (isa<Argument>(V))
5214 return false;
5215
5216 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5217 return false;
5218
5219 return setUnavailable();
5220 }
5221
5222 case scUDivExpr:
5223 case scCouldNotCompute:
5224 // We do not try to smart about these at all.
5225 return setUnavailable();
5226 }
5227 llvm_unreachable("switch should be fully covered!")::llvm::llvm_unreachable_internal("switch should be fully covered!"
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 5227)
;
5228 }
5229
5230 bool isDone() { return TraversalDone; }
5231 };
5232
5233 CheckAvailable CA(L, BB, DT);
5234 SCEVTraversal<CheckAvailable> ST(CA);
5235
5236 ST.visitAll(S);
5237 return CA.Available;
5238}
5239
5240// Try to match a control flow sequence that branches out at BI and merges back
5241// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5242// match.
5243static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5244 Value *&C, Value *&LHS, Value *&RHS) {
5245 C = BI->getCondition();
5246
5247 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5248 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5249
5250 if (!LeftEdge.isSingleEdge())
5251 return false;
5252
5253 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()")((RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"
) ? static_cast<void> (0) : __assert_fail ("RightEdge.isSingleEdge() && \"Follows from LeftEdge.isSingleEdge()\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 5253, __PRETTY_FUNCTION__))
;
5254
5255 Use &LeftUse = Merge->getOperandUse(0);
5256 Use &RightUse = Merge->getOperandUse(1);
5257
5258 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5259 LHS = LeftUse;
5260 RHS = RightUse;
5261 return true;
5262 }
5263
5264 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5265 LHS = RightUse;
5266 RHS = LeftUse;
5267 return true;
5268 }
5269
5270 return false;
5271}
5272
5273const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5274 auto IsReachable =
5275 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5276 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5277 const Loop *L = LI.getLoopFor(PN->getParent());
5278
5279 // We don't want to break LCSSA, even in a SCEV expression tree.
5280 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5281 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5282 return nullptr;
5283
5284 // Try to match
5285 //
5286 // br %cond, label %left, label %right
5287 // left:
5288 // br label %merge
5289 // right:
5290 // br label %merge
5291 // merge:
5292 // V = phi [ %x, %left ], [ %y, %right ]
5293 //
5294 // as "select %cond, %x, %y"
5295
5296 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5297 assert(IDom && "At least the entry block should dominate PN")((IDom && "At least the entry block should dominate PN"
) ? static_cast<void> (0) : __assert_fail ("IDom && \"At least the entry block should dominate PN\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 5297, __PRETTY_FUNCTION__))
;
5298
5299 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5300 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5301
5302 if (BI && BI->isConditional() &&
5303 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5304 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5305 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5306 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5307 }
5308
5309 return nullptr;
5310}
5311
5312const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5313 if (const SCEV *S = createAddRecFromPHI(PN))
5314 return S;
5315
5316 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5317 return S;
5318
5319 // If the PHI has a single incoming value, follow that value, unless the
5320 // PHI's incoming blocks are in a different loop, in which case doing so
5321 // risks breaking LCSSA form. Instcombine would normally zap these, but
5322 // it doesn't have DominatorTree information, so it may miss cases.
5323 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5324 if (LI.replacementPreservesLCSSAForm(PN, V))
5325 return getSCEV(V);
5326
5327 // If it's not a loop phi, we can't handle it yet.
5328 return getUnknown(PN);
5329}
5330
5331const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5332 Value *Cond,
5333 Value *TrueVal,
5334 Value *FalseVal) {
5335 // Handle "constant" branch or select. This can occur for instance when a
5336 // loop pass transforms an inner loop and moves on to process the outer loop.
5337 if (auto *CI = dyn_cast<ConstantInt>(Cond))
5338 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5339
5340 // Try to match some simple smax or umax patterns.
5341 auto *ICI = dyn_cast<ICmpInst>(Cond);
5342 if (!ICI)
5343 return getUnknown(I);
5344
5345 Value *LHS = ICI->getOperand(0);
5346 Value *RHS = ICI->getOperand(1);
5347
5348 switch (ICI->getPredicate()) {
5349 case ICmpInst::ICMP_SLT:
5350 case ICmpInst::ICMP_SLE:
5351 std::swap(LHS, RHS);
5352 LLVM_FALLTHROUGH[[clang::fallthrough]];
5353 case ICmpInst::ICMP_SGT:
5354 case ICmpInst::ICMP_SGE:
5355 // a >s b ? a+x : b+x -> smax(a, b)+x
5356 // a >s b ? b+x : a+x -> smin(a, b)+x
5357 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5358 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5359 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5360 const SCEV *LA = getSCEV(TrueVal);
5361 const SCEV *RA = getSCEV(FalseVal);
5362 const SCEV *LDiff = getMinusSCEV(LA, LS);
5363 const SCEV *RDiff = getMinusSCEV(RA, RS);
5364 if (LDiff == RDiff)
5365 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5366 LDiff = getMinusSCEV(LA, RS);
5367 RDiff = getMinusSCEV(RA, LS);
5368 if (LDiff == RDiff)
5369 return getAddExpr(getSMinExpr(LS, RS), LDiff);
5370 }
5371 break;
5372 case ICmpInst::ICMP_ULT:
5373 case ICmpInst::ICMP_ULE:
5374 std::swap(LHS, RHS);
5375 LLVM_FALLTHROUGH[[clang::fallthrough]];
5376 case ICmpInst::ICMP_UGT:
5377 case ICmpInst::ICMP_UGE:
5378 // a >u b ? a+x : b+x -> umax(a, b)+x
5379 // a >u b ? b+x : a+x -> umin(a, b)+x
5380 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5381 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5382 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5383 const SCEV *LA = getSCEV(TrueVal);
5384 const SCEV *RA = getSCEV(FalseVal);
5385 const SCEV *LDiff = getMinusSCEV(LA, LS);
5386 const SCEV *RDiff = getMinusSCEV(RA, RS);
5387 if (LDiff == RDiff)
5388 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5389 LDiff = getMinusSCEV(LA, RS);
5390 RDiff = getMinusSCEV(RA, LS);
5391 if (LDiff == RDiff)
5392 return getAddExpr(getUMinExpr(LS, RS), LDiff);
5393 }
5394 break;
5395 case ICmpInst::ICMP_NE:
5396 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
5397 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5398 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5399 const SCEV *One = getOne(I->getType());
5400 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5401 const SCEV *LA = getSCEV(TrueVal);
5402 const SCEV *RA = getSCEV(FalseVal);
5403 const SCEV *LDiff = getMinusSCEV(LA, LS);
5404 const SCEV *RDiff = getMinusSCEV(RA, One);
5405 if (LDiff == RDiff)
5406 return getAddExpr(getUMaxExpr(One, LS), LDiff);
5407 }
5408 break;
5409 case ICmpInst::ICMP_EQ:
5410 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
5411 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5412 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5413 const SCEV *One = getOne(I->getType());
5414 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5415 const SCEV *LA = getSCEV(TrueVal);
5416 const SCEV *RA = getSCEV(FalseVal);
5417 const SCEV *LDiff = getMinusSCEV(LA, One);
5418 const SCEV *RDiff = getMinusSCEV(RA, LS);
5419 if (LDiff == RDiff)
5420 return getAddExpr(getUMaxExpr(One, LS), LDiff);
5421 }
5422 break;
5423 default:
5424 break;
5425 }
5426
5427 return getUnknown(I);
5428}
5429
5430/// Expand GEP instructions into add and multiply operations. This allows them
5431/// to be analyzed by regular SCEV code.
5432const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5433 // Don't attempt to analyze GEPs over unsized objects.
5434 if (!GEP->getSourceElementType()->isSized())
5435 return getUnknown(GEP);
5436
5437 SmallVector<const SCEV *, 4> IndexExprs;
5438 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5439 IndexExprs.push_back(getSCEV(*Index));
5440 return getGEPExpr(GEP, IndexExprs);
5441}
5442
5443uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5444 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5445 return C->getAPInt().countTrailingZeros();
5446
5447 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5448 return std::min(GetMinTrailingZeros(T->getOperand()),
5449 (uint32_t)getTypeSizeInBits(T->getType()));
5450
5451 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5452 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5453 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5454 ? getTypeSizeInBits(E->getType())
5455 : OpRes;
5456 }
5457
5458 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5459 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5460 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5461 ? getTypeSizeInBits(E->getType())
5462 : OpRes;
5463 }
5464
5465 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5466 // The result is the min of all operands results.
5467 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5468 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5469 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5470 return MinOpRes;
5471 }
5472
5473 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5474 // The result is the sum of all operands results.
5475 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5476 uint32_t BitWidth = getTypeSizeInBits(M->getType());
5477 for (unsigned i = 1, e = M->getNumOperands();
5478 SumOpRes != BitWidth && i != e; ++i)
5479 SumOpRes =
5480 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5481 return SumOpRes;
5482 }
5483
5484 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5485 // The result is the min of all operands results.
5486 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5487 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5488 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5489 return MinOpRes;
5490 }
5491
5492 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5493 // The result is the min of all operands results.
5494 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5495 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5496 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5497 return MinOpRes;
5498 }
5499
5500 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5501 // The result is the min of all operands results.
5502 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5503 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5504 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5505 return MinOpRes;
5506 }
5507
5508 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5509 // For a SCEVUnknown, ask ValueTracking.
5510 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5511 return Known.countMinTrailingZeros();
5512 }
5513
5514 // SCEVUDivExpr
5515 return 0;
5516}
5517
5518uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5519 auto I = MinTrailingZerosCache.find(S);
5520 if (I != MinTrailingZerosCache.end())
5521 return I->second;
5522
5523 uint32_t Result = GetMinTrailingZerosImpl(S);
5524 auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5525 assert(InsertPair.second && "Should insert a new key")((InsertPair.second && "Should insert a new key") ? static_cast
<void> (0) : __assert_fail ("InsertPair.second && \"Should insert a new key\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 5525, __PRETTY_FUNCTION__))
;
5526 return InsertPair.first->second;
5527}
5528
5529/// Helper method to assign a range to V from metadata present in the IR.
5530static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5531 if (Instruction *I = dyn_cast<Instruction>(V))
5532 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5533 return getConstantRangeFromMetadata(*MD);
5534
5535 return None;
5536}
5537
5538/// Determine the range for a particular SCEV. If SignHint is
5539/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5540/// with a "cleaner" unsigned (resp. signed) representation.
5541const ConstantRange &
5542ScalarEvolution::getRangeRef(const SCEV *S,
5543 ScalarEvolution::RangeSignHint SignHint) {
5544 DenseMap<const SCEV *, ConstantRange> &Cache =
5545 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5546 : SignedRanges;
5547
5548 // See if we've computed this range already.
5549 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5550 if (I != Cache.end())
5551 return I->second;
5552
5553 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5554 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5555
5556 unsigned BitWidth = getTypeSizeInBits(S->getType());
5557 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5558
5559 // If the value has known zeros, the maximum value will have those known zeros
5560 // as well.
5561 uint32_t TZ = GetMinTrailingZeros(S);
5562 if (TZ != 0) {
5563 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5564 ConservativeResult =
5565 ConstantRange(APInt::getMinValue(BitWidth),
5566 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5567 else
5568 ConservativeResult = ConstantRange(
5569 APInt::getSignedMinValue(BitWidth),
5570 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5571 }
5572
5573 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5574 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5575 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5576 X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5577 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
5578 }
5579
5580 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5581 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5582 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5583 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5584 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5585 }
5586
5587 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5588 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5589 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5590 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5591 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5592 }
5593
5594 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5595 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5596 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5597 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5598 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5599 }
5600
5601 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5602 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5603 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5604 return setRange(UDiv, SignHint,
5605 ConservativeResult.intersectWith(X.udiv(Y)));
5606 }
5607
5608 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5609 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5610 return setRange(ZExt, SignHint,
5611 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
5612 }
5613
5614 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5615 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5616 return setRange(SExt, SignHint,
5617 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
5618 }
5619
5620 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5621 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5622 return setRange(Trunc, SignHint,
5623 ConservativeResult.intersectWith(X.truncate(BitWidth)));
5624 }
5625
5626 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5627 // If there's no unsigned wrap, the value will never be less than its
5628 // initial value.
5629 if (AddRec->hasNoUnsignedWrap())
5630 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5631 if (!C->getValue()->isZero())
5632 ConservativeResult = ConservativeResult.intersectWith(
5633 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
5634
5635 // If there's no signed wrap, and all the operands have the same sign or
5636 // zero, the value won't ever change sign.
5637 if (AddRec->hasNoSignedWrap()) {
5638 bool AllNonNeg = true;
5639 bool AllNonPos = true;
5640 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5641 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5642 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5643 }
5644 if (AllNonNeg)
5645 ConservativeResult = ConservativeResult.intersectWith(
5646 ConstantRange(APInt(BitWidth, 0),
5647 APInt::getSignedMinValue(BitWidth)));
5648 else if (AllNonPos)
5649 ConservativeResult = ConservativeResult.intersectWith(
5650 ConstantRange(APInt::getSignedMinValue(BitWidth),
5651 APInt(BitWidth, 1)));
5652 }
5653
5654 // TODO: non-affine addrec
5655 if (AddRec->isAffine()) {
5656 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
5657 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5658 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5659 auto RangeFromAffine = getRangeForAffineAR(
5660 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5661 BitWidth);
5662 if (!RangeFromAffine.isFullSet())
5663 ConservativeResult =
5664 ConservativeResult.intersectWith(RangeFromAffine);
5665
5666 auto RangeFromFactoring = getRangeViaFactoring(
5667 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5668 BitWidth);
5669 if (!RangeFromFactoring.isFullSet())
5670 ConservativeResult =
5671 ConservativeResult.intersectWith(RangeFromFactoring);
5672 }
5673 }
5674
5675 return setRange(AddRec, SignHint, std::move(ConservativeResult));
5676 }
5677
5678 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5679 // Check if the IR explicitly contains !range metadata.
5680 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5681 if (MDRange.hasValue())
5682 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
5683
5684 // Split here to avoid paying the compile-time cost of calling both
5685 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
5686 // if needed.
5687 const DataLayout &DL = getDataLayout();
5688 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5689 // For a SCEVUnknown, ask ValueTracking.
5690 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5691 if (Known.One != ~Known.Zero + 1)
5692 ConservativeResult =
5693 ConservativeResult.intersectWith(ConstantRange(Known.One,
5694 ~Known.Zero + 1));
5695 } else {
5696 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&((SignHint == ScalarEvolution::HINT_RANGE_SIGNED && "generalize as needed!"
) ? static_cast<void> (0) : __assert_fail ("SignHint == ScalarEvolution::HINT_RANGE_SIGNED && \"generalize as needed!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 5697, __PRETTY_FUNCTION__))
5697 "generalize as needed!")((SignHint == ScalarEvolution::HINT_RANGE_SIGNED && "generalize as needed!"
) ? static_cast<void> (0) : __assert_fail ("SignHint == ScalarEvolution::HINT_RANGE_SIGNED && \"generalize as needed!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 5697, __PRETTY_FUNCTION__))
;
5698 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5699 if (NS > 1)
5700 ConservativeResult = ConservativeResult.intersectWith(
5701 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5702 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
5703 }
5704
5705 // A range of Phi is a subset of union of all ranges of its input.
5706 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5707 // Make sure that we do not run over cycled Phis.
5708 if (PendingPhiRanges.insert(Phi).second) {
5709 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5710 for (auto &Op : Phi->operands()) {
5711 auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5712 RangeFromOps = RangeFromOps.unionWith(OpRange);
5713 // No point to continue if we already have a full set.
5714 if (RangeFromOps.isFullSet())
5715 break;
5716 }
5717 ConservativeResult = ConservativeResult.intersectWith(RangeFromOps);
5718 bool Erased = PendingPhiRanges.erase(Phi);
5719 assert(Erased && "Failed to erase Phi properly?")((Erased && "Failed to erase Phi properly?") ? static_cast
<void> (0) : __assert_fail ("Erased && \"Failed to erase Phi properly?\""
, "/build/llvm-toolchain-snapshot-8~svn345461/lib/Analysis/ScalarEvolution.cpp"
, 5719, __PRETTY_FUNCTION__))
;
5720 (void) Erased;
5721 }
5722 }
5723
5724 return setRange(U, SignHint, std::move(ConservativeResult));
5725 }
5726
5727 return setRange(S, SignHint, std::move(ConservativeResult));
5728}
5729
5730// Given a StartRange, Step and MaxBECount for an expression compute a range of
5731// values that the expression can take. Initially, the expression has a value
5732// from StartRange and then is changed by Step up to MaxBECount times. Signed
5733// argument defines if we treat Step as signed or unsigned.
5734static ConstantRange getRangeForAffineARHelper(APInt Step,
5735 const ConstantRange &StartRange,
5736 const APInt &MaxBECount,
5737 unsigned BitWidth, bool Signed) {