Bug Summary

File:llvm/lib/Analysis/ScalarEvolution.cpp
Warning:line 6442, column 23
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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/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/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.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++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/ScalarEvolution.cpp

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Analysis/ScalarEvolution.cpp

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