Bug Summary

File:build/source/llvm/lib/Analysis/ScalarEvolution.cpp
Warning:line 4611, column 32
Dereference of null pointer (loaded from variable 'PtrOp')

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ScalarEvolution.cpp -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 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-17/lib/clang/17 -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Analysis -I /build/source/llvm/lib/Analysis -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/source/= -source-date-epoch 1683717183 -O2 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/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/STLExtras.h"
68#include "llvm/ADT/ScopeExit.h"
69#include "llvm/ADT/Sequence.h"
70#include "llvm/ADT/SmallPtrSet.h"
71#include "llvm/ADT/SmallSet.h"
72#include "llvm/ADT/SmallVector.h"
73#include "llvm/ADT/Statistic.h"
74#include "llvm/ADT/StringRef.h"
75#include "llvm/Analysis/AssumptionCache.h"
76#include "llvm/Analysis/ConstantFolding.h"
77#include "llvm/Analysis/InstructionSimplify.h"
78#include "llvm/Analysis/LoopInfo.h"
79#include "llvm/Analysis/MemoryBuiltins.h"
80#include "llvm/Analysis/ScalarEvolutionExpressions.h"
81#include "llvm/Analysis/TargetLibraryInfo.h"
82#include "llvm/Analysis/ValueTracking.h"
83#include "llvm/Config/llvm-config.h"
84#include "llvm/IR/Argument.h"
85#include "llvm/IR/BasicBlock.h"
86#include "llvm/IR/CFG.h"
87#include "llvm/IR/Constant.h"
88#include "llvm/IR/ConstantRange.h"
89#include "llvm/IR/Constants.h"
90#include "llvm/IR/DataLayout.h"
91#include "llvm/IR/DerivedTypes.h"
92#include "llvm/IR/Dominators.h"
93#include "llvm/IR/Function.h"
94#include "llvm/IR/GlobalAlias.h"
95#include "llvm/IR/GlobalValue.h"
96#include "llvm/IR/InstIterator.h"
97#include "llvm/IR/InstrTypes.h"
98#include "llvm/IR/Instruction.h"
99#include "llvm/IR/Instructions.h"
100#include "llvm/IR/IntrinsicInst.h"
101#include "llvm/IR/Intrinsics.h"
102#include "llvm/IR/LLVMContext.h"
103#include "llvm/IR/Operator.h"
104#include "llvm/IR/PatternMatch.h"
105#include "llvm/IR/Type.h"
106#include "llvm/IR/Use.h"
107#include "llvm/IR/User.h"
108#include "llvm/IR/Value.h"
109#include "llvm/IR/Verifier.h"
110#include "llvm/InitializePasses.h"
111#include "llvm/Pass.h"
112#include "llvm/Support/Casting.h"
113#include "llvm/Support/CommandLine.h"
114#include "llvm/Support/Compiler.h"
115#include "llvm/Support/Debug.h"
116#include "llvm/Support/ErrorHandling.h"
117#include "llvm/Support/KnownBits.h"
118#include "llvm/Support/SaveAndRestore.h"
119#include "llvm/Support/raw_ostream.h"
120#include <algorithm>
121#include <cassert>
122#include <climits>
123#include <cstdint>
124#include <cstdlib>
125#include <map>
126#include <memory>
127#include <numeric>
128#include <optional>
129#include <tuple>
130#include <utility>
131#include <vector>
132
133using namespace llvm;
134using namespace PatternMatch;
135
136#define DEBUG_TYPE"scalar-evolution" "scalar-evolution"
137
138STATISTIC(NumTripCountsComputed,static llvm::Statistic NumTripCountsComputed = {"scalar-evolution"
, "NumTripCountsComputed", "Number of loops with predictable loop counts"
}
139 "Number of loops with predictable loop counts")static llvm::Statistic NumTripCountsComputed = {"scalar-evolution"
, "NumTripCountsComputed", "Number of loops with predictable loop counts"
}
;
140STATISTIC(NumTripCountsNotComputed,static llvm::Statistic NumTripCountsNotComputed = {"scalar-evolution"
, "NumTripCountsNotComputed", "Number of loops without predictable loop counts"
}
141 "Number of loops without predictable loop counts")static llvm::Statistic NumTripCountsNotComputed = {"scalar-evolution"
, "NumTripCountsNotComputed", "Number of loops without predictable loop counts"
}
;
142STATISTIC(NumBruteForceTripCountsComputed,static llvm::Statistic NumBruteForceTripCountsComputed = {"scalar-evolution"
, "NumBruteForceTripCountsComputed", "Number of loops with trip counts computed by force"
}
143 "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"
}
;
144
145#ifdef EXPENSIVE_CHECKS
146bool llvm::VerifySCEV = true;
147#else
148bool llvm::VerifySCEV = false;
149#endif
150
151static cl::opt<unsigned>
152 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
153 cl::desc("Maximum number of iterations SCEV will "
154 "symbolically execute a constant "
155 "derived loop"),
156 cl::init(100));
157
158static cl::opt<bool, true> VerifySCEVOpt(
159 "verify-scev", cl::Hidden, cl::location(VerifySCEV),
160 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
161static cl::opt<bool> VerifySCEVStrict(
162 "verify-scev-strict", cl::Hidden,
163 cl::desc("Enable stricter verification with -verify-scev is passed"));
164static cl::opt<bool>
165 VerifySCEVMap("verify-scev-maps", cl::Hidden,
166 cl::desc("Verify no dangling value in ScalarEvolution's "
167 "ExprValueMap (slow)"));
168
169static cl::opt<bool> VerifyIR(
170 "scev-verify-ir", cl::Hidden,
171 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
172 cl::init(false));
173
174static cl::opt<unsigned> MulOpsInlineThreshold(
175 "scev-mulops-inline-threshold", cl::Hidden,
176 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
177 cl::init(32));
178
179static cl::opt<unsigned> AddOpsInlineThreshold(
180 "scev-addops-inline-threshold", cl::Hidden,
181 cl::desc("Threshold for inlining addition operands into a SCEV"),
182 cl::init(500));
183
184static cl::opt<unsigned> MaxSCEVCompareDepth(
185 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
186 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
187 cl::init(32));
188
189static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
190 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
191 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
192 cl::init(2));
193
194static cl::opt<unsigned> MaxValueCompareDepth(
195 "scalar-evolution-max-value-compare-depth", cl::Hidden,
196 cl::desc("Maximum depth of recursive value complexity comparisons"),
197 cl::init(2));
198
199static cl::opt<unsigned>
200 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
201 cl::desc("Maximum depth of recursive arithmetics"),
202 cl::init(32));
203
204static cl::opt<unsigned> MaxConstantEvolvingDepth(
205 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
206 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
207
208static cl::opt<unsigned>
209 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
210 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
211 cl::init(8));
212
213static cl::opt<unsigned>
214 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
215 cl::desc("Max coefficients in AddRec during evolving"),
216 cl::init(8));
217
218static cl::opt<unsigned>
219 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
220 cl::desc("Size of the expression which is considered huge"),
221 cl::init(4096));
222
223static cl::opt<unsigned> RangeIterThreshold(
224 "scev-range-iter-threshold", cl::Hidden,
225 cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
226 cl::init(32));
227
228static cl::opt<bool>
229ClassifyExpressions("scalar-evolution-classify-expressions",
230 cl::Hidden, cl::init(true),
231 cl::desc("When printing analysis, include information on every instruction"));
232
233static cl::opt<bool> UseExpensiveRangeSharpening(
234 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
235 cl::init(false),
236 cl::desc("Use more powerful methods of sharpening expression ranges. May "
237 "be costly in terms of compile time"));
238
239static cl::opt<unsigned> MaxPhiSCCAnalysisSize(
240 "scalar-evolution-max-scc-analysis-depth", cl::Hidden,
241 cl::desc("Maximum amount of nodes to process while searching SCEVUnknown "
242 "Phi strongly connected components"),
243 cl::init(8));
244
245static cl::opt<bool>
246 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
247 cl::desc("Handle <= and >= in finite loops"),
248 cl::init(true));
249
250static cl::opt<bool> UseContextForNoWrapFlagInference(
251 "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
252 cl::desc("Infer nuw/nsw flags using context where suitable"),
253 cl::init(true));
254
255//===----------------------------------------------------------------------===//
256// SCEV class definitions
257//===----------------------------------------------------------------------===//
258
259//===----------------------------------------------------------------------===//
260// Implementation of the SCEV class.
261//
262
263#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
264LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void SCEV::dump() const {
265 print(dbgs());
266 dbgs() << '\n';
267}
268#endif
269
270void SCEV::print(raw_ostream &OS) const {
271 switch (getSCEVType()) {
272 case scConstant:
273 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
274 return;
275 case scVScale:
276 OS << "vscale";
277 return;
278 case scPtrToInt: {
279 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
280 const SCEV *Op = PtrToInt->getOperand();
281 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
282 << *PtrToInt->getType() << ")";
283 return;
284 }
285 case scTruncate: {
286 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
287 const SCEV *Op = Trunc->getOperand();
288 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
289 << *Trunc->getType() << ")";
290 return;
291 }
292 case scZeroExtend: {
293 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
294 const SCEV *Op = ZExt->getOperand();
295 OS << "(zext " << *Op->getType() << " " << *Op << " to "
296 << *ZExt->getType() << ")";
297 return;
298 }
299 case scSignExtend: {
300 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
301 const SCEV *Op = SExt->getOperand();
302 OS << "(sext " << *Op->getType() << " " << *Op << " to "
303 << *SExt->getType() << ")";
304 return;
305 }
306 case scAddRecExpr: {
307 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
308 OS << "{" << *AR->getOperand(0);
309 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
310 OS << ",+," << *AR->getOperand(i);
311 OS << "}<";
312 if (AR->hasNoUnsignedWrap())
313 OS << "nuw><";
314 if (AR->hasNoSignedWrap())
315 OS << "nsw><";
316 if (AR->hasNoSelfWrap() &&
317 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
318 OS << "nw><";
319 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
320 OS << ">";
321 return;
322 }
323 case scAddExpr:
324 case scMulExpr:
325 case scUMaxExpr:
326 case scSMaxExpr:
327 case scUMinExpr:
328 case scSMinExpr:
329 case scSequentialUMinExpr: {
330 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
331 const char *OpStr = nullptr;
332 switch (NAry->getSCEVType()) {
333 case scAddExpr: OpStr = " + "; break;
334 case scMulExpr: OpStr = " * "; break;
335 case scUMaxExpr: OpStr = " umax "; break;
336 case scSMaxExpr: OpStr = " smax "; break;
337 case scUMinExpr:
338 OpStr = " umin ";
339 break;
340 case scSMinExpr:
341 OpStr = " smin ";
342 break;
343 case scSequentialUMinExpr:
344 OpStr = " umin_seq ";
345 break;
346 default:
347 llvm_unreachable("There are no other nary expression types.")::llvm::llvm_unreachable_internal("There are no other nary expression types."
, "llvm/lib/Analysis/ScalarEvolution.cpp", 347)
;
348 }
349 OS << "(";
350 ListSeparator LS(OpStr);
351 for (const SCEV *Op : NAry->operands())
352 OS << LS << *Op;
353 OS << ")";
354 switch (NAry->getSCEVType()) {
355 case scAddExpr:
356 case scMulExpr:
357 if (NAry->hasNoUnsignedWrap())
358 OS << "<nuw>";
359 if (NAry->hasNoSignedWrap())
360 OS << "<nsw>";
361 break;
362 default:
363 // Nothing to print for other nary expressions.
364 break;
365 }
366 return;
367 }
368 case scUDivExpr: {
369 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
370 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
371 return;
372 }
373 case scUnknown:
374 cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
375 return;
376 case scCouldNotCompute:
377 OS << "***COULDNOTCOMPUTE***";
378 return;
379 }
380 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 380)
;
381}
382
383Type *SCEV::getType() const {
384 switch (getSCEVType()) {
385 case scConstant:
386 return cast<SCEVConstant>(this)->getType();
387 case scVScale:
388 return cast<SCEVVScale>(this)->getType();
389 case scPtrToInt:
390 case scTruncate:
391 case scZeroExtend:
392 case scSignExtend:
393 return cast<SCEVCastExpr>(this)->getType();
394 case scAddRecExpr:
395 return cast<SCEVAddRecExpr>(this)->getType();
396 case scMulExpr:
397 return cast<SCEVMulExpr>(this)->getType();
398 case scUMaxExpr:
399 case scSMaxExpr:
400 case scUMinExpr:
401 case scSMinExpr:
402 return cast<SCEVMinMaxExpr>(this)->getType();
403 case scSequentialUMinExpr:
404 return cast<SCEVSequentialMinMaxExpr>(this)->getType();
405 case scAddExpr:
406 return cast<SCEVAddExpr>(this)->getType();
407 case scUDivExpr:
408 return cast<SCEVUDivExpr>(this)->getType();
409 case scUnknown:
410 return cast<SCEVUnknown>(this)->getType();
411 case scCouldNotCompute:
412 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 412)
;
413 }
414 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 414)
;
415}
416
417ArrayRef<const SCEV *> SCEV::operands() const {
418 switch (getSCEVType()) {
419 case scConstant:
420 case scVScale:
421 case scUnknown:
422 return {};
423 case scPtrToInt:
424 case scTruncate:
425 case scZeroExtend:
426 case scSignExtend:
427 return cast<SCEVCastExpr>(this)->operands();
428 case scAddRecExpr:
429 case scAddExpr:
430 case scMulExpr:
431 case scUMaxExpr:
432 case scSMaxExpr:
433 case scUMinExpr:
434 case scSMinExpr:
435 case scSequentialUMinExpr:
436 return cast<SCEVNAryExpr>(this)->operands();
437 case scUDivExpr:
438 return cast<SCEVUDivExpr>(this)->operands();
439 case scCouldNotCompute:
440 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 440)
;
441 }
442 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 442)
;
443}
444
445bool SCEV::isZero() const {
446 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
447 return SC->getValue()->isZero();
448 return false;
449}
450
451bool SCEV::isOne() const {
452 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
453 return SC->getValue()->isOne();
454 return false;
455}
456
457bool SCEV::isAllOnesValue() const {
458 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
459 return SC->getValue()->isMinusOne();
460 return false;
461}
462
463bool SCEV::isNonConstantNegative() const {
464 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
465 if (!Mul) return false;
466
467 // If there is a constant factor, it will be first.
468 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
469 if (!SC) return false;
470
471 // Return true if the value is negative, this matches things like (-42 * V).
472 return SC->getAPInt().isNegative();
473}
474
475SCEVCouldNotCompute::SCEVCouldNotCompute() :
476 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
477
478bool SCEVCouldNotCompute::classof(const SCEV *S) {
479 return S->getSCEVType() == scCouldNotCompute;
480}
481
482const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
483 FoldingSetNodeID ID;
484 ID.AddInteger(scConstant);
485 ID.AddPointer(V);
486 void *IP = nullptr;
487 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
488 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
489 UniqueSCEVs.InsertNode(S, IP);
490 return S;
491}
492
493const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
494 return getConstant(ConstantInt::get(getContext(), Val));
495}
496
497const SCEV *
498ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
499 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
500 return getConstant(ConstantInt::get(ITy, V, isSigned));
501}
502
503const SCEV *ScalarEvolution::getVScale(Type *Ty) {
504 FoldingSetNodeID ID;
505 ID.AddInteger(scVScale);
506 ID.AddPointer(Ty);
507 void *IP = nullptr;
508 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
509 return S;
510 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
511 UniqueSCEVs.InsertNode(S, IP);
512 return S;
513}
514
515SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
516 const SCEV *op, Type *ty)
517 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {}
518
519SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
520 Type *ITy)
521 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
522 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&(static_cast <bool> (getOperand()->getType()->isPointerTy
() && Ty->isIntegerTy() && "Must be a non-bit-width-changing pointer-to-integer cast!"
) ? void (0) : __assert_fail ("getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() && \"Must be a non-bit-width-changing pointer-to-integer cast!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 523, __extension__
__PRETTY_FUNCTION__))
523 "Must be a non-bit-width-changing pointer-to-integer cast!")(static_cast <bool> (getOperand()->getType()->isPointerTy
() && Ty->isIntegerTy() && "Must be a non-bit-width-changing pointer-to-integer cast!"
) ? void (0) : __assert_fail ("getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() && \"Must be a non-bit-width-changing pointer-to-integer cast!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 523, __extension__
__PRETTY_FUNCTION__))
;
524}
525
526SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
527 SCEVTypes SCEVTy, const SCEV *op,
528 Type *ty)
529 : SCEVCastExpr(ID, SCEVTy, op, ty) {}
530
531SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
532 Type *ty)
533 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
534 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&(static_cast <bool> (getOperand()->getType()->isIntOrPtrTy
() && Ty->isIntOrPtrTy() && "Cannot truncate non-integer value!"
) ? void (0) : __assert_fail ("getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate non-integer value!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 535, __extension__
__PRETTY_FUNCTION__))
535 "Cannot truncate non-integer value!")(static_cast <bool> (getOperand()->getType()->isIntOrPtrTy
() && Ty->isIntOrPtrTy() && "Cannot truncate non-integer value!"
) ? void (0) : __assert_fail ("getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate non-integer value!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 535, __extension__
__PRETTY_FUNCTION__))
;
536}
537
538SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
539 const SCEV *op, Type *ty)
540 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
541 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&(static_cast <bool> (getOperand()->getType()->isIntOrPtrTy
() && Ty->isIntOrPtrTy() && "Cannot zero extend non-integer value!"
) ? void (0) : __assert_fail ("getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot zero extend non-integer value!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 542, __extension__
__PRETTY_FUNCTION__))
542 "Cannot zero extend non-integer value!")(static_cast <bool> (getOperand()->getType()->isIntOrPtrTy
() && Ty->isIntOrPtrTy() && "Cannot zero extend non-integer value!"
) ? void (0) : __assert_fail ("getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot zero extend non-integer value!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 542, __extension__
__PRETTY_FUNCTION__))
;
543}
544
545SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
546 const SCEV *op, Type *ty)
547 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
548 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&(static_cast <bool> (getOperand()->getType()->isIntOrPtrTy
() && Ty->isIntOrPtrTy() && "Cannot sign extend non-integer value!"
) ? void (0) : __assert_fail ("getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot sign extend non-integer value!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 549, __extension__
__PRETTY_FUNCTION__))
549 "Cannot sign extend non-integer value!")(static_cast <bool> (getOperand()->getType()->isIntOrPtrTy
() && Ty->isIntOrPtrTy() && "Cannot sign extend non-integer value!"
) ? void (0) : __assert_fail ("getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot sign extend non-integer value!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 549, __extension__
__PRETTY_FUNCTION__))
;
550}
551
552void SCEVUnknown::deleted() {
553 // Clear this SCEVUnknown from various maps.
554 SE->forgetMemoizedResults(this);
555
556 // Remove this SCEVUnknown from the uniquing map.
557 SE->UniqueSCEVs.RemoveNode(this);
558
559 // Release the value.
560 setValPtr(nullptr);
561}
562
563void SCEVUnknown::allUsesReplacedWith(Value *New) {
564 // Clear this SCEVUnknown from various maps.
565 SE->forgetMemoizedResults(this);
566
567 // Remove this SCEVUnknown from the uniquing map.
568 SE->UniqueSCEVs.RemoveNode(this);
569
570 // Replace the value pointer in case someone is still using this SCEVUnknown.
571 setValPtr(New);
572}
573
574//===----------------------------------------------------------------------===//
575// SCEV Utilities
576//===----------------------------------------------------------------------===//
577
578/// Compare the two values \p LV and \p RV in terms of their "complexity" where
579/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
580/// operands in SCEV expressions. \p EqCache is a set of pairs of values that
581/// have been previously deemed to be "equally complex" by this routine. It is
582/// intended to avoid exponential time complexity in cases like:
583///
584/// %a = f(%x, %y)
585/// %b = f(%a, %a)
586/// %c = f(%b, %b)
587///
588/// %d = f(%x, %y)
589/// %e = f(%d, %d)
590/// %f = f(%e, %e)
591///
592/// CompareValueComplexity(%f, %c)
593///
594/// Since we do not continue running this routine on expression trees once we
595/// have seen unequal values, there is no need to track them in the cache.
596static int
597CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
598 const LoopInfo *const LI, Value *LV, Value *RV,
599 unsigned Depth) {
600 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
601 return 0;
602
603 // Order pointer values after integer values. This helps SCEVExpander form
604 // GEPs.
605 bool LIsPointer = LV->getType()->isPointerTy(),
606 RIsPointer = RV->getType()->isPointerTy();
607 if (LIsPointer != RIsPointer)
608 return (int)LIsPointer - (int)RIsPointer;
609
610 // Compare getValueID values.
611 unsigned LID = LV->getValueID(), RID = RV->getValueID();
612 if (LID != RID)
613 return (int)LID - (int)RID;
614
615 // Sort arguments by their position.
616 if (const auto *LA = dyn_cast<Argument>(LV)) {
617 const auto *RA = cast<Argument>(RV);
618 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
619 return (int)LArgNo - (int)RArgNo;
620 }
621
622 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
623 const auto *RGV = cast<GlobalValue>(RV);
624
625 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
626 auto LT = GV->getLinkage();
627 return !(GlobalValue::isPrivateLinkage(LT) ||
628 GlobalValue::isInternalLinkage(LT));
629 };
630
631 // Use the names to distinguish the two values, but only if the
632 // names are semantically important.
633 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
634 return LGV->getName().compare(RGV->getName());
635 }
636
637 // For instructions, compare their loop depth, and their operand count. This
638 // is pretty loose.
639 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
640 const auto *RInst = cast<Instruction>(RV);
641
642 // Compare loop depths.
643 const BasicBlock *LParent = LInst->getParent(),
644 *RParent = RInst->getParent();
645 if (LParent != RParent) {
646 unsigned LDepth = LI->getLoopDepth(LParent),
647 RDepth = LI->getLoopDepth(RParent);
648 if (LDepth != RDepth)
649 return (int)LDepth - (int)RDepth;
650 }
651
652 // Compare the number of operands.
653 unsigned LNumOps = LInst->getNumOperands(),
654 RNumOps = RInst->getNumOperands();
655 if (LNumOps != RNumOps)
656 return (int)LNumOps - (int)RNumOps;
657
658 for (unsigned Idx : seq(0u, LNumOps)) {
659 int Result =
660 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
661 RInst->getOperand(Idx), Depth + 1);
662 if (Result != 0)
663 return Result;
664 }
665 }
666
667 EqCacheValue.unionSets(LV, RV);
668 return 0;
669}
670
671// Return negative, zero, or positive, if LHS is less than, equal to, or greater
672// than RHS, respectively. A three-way result allows recursive comparisons to be
673// more efficient.
674// If the max analysis depth was reached, return std::nullopt, assuming we do
675// not know if they are equivalent for sure.
676static std::optional<int>
677CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
678 EquivalenceClasses<const Value *> &EqCacheValue,
679 const LoopInfo *const LI, const SCEV *LHS,
680 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
681 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
682 if (LHS == RHS)
683 return 0;
684
685 // Primarily, sort the SCEVs by their getSCEVType().
686 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
687 if (LType != RType)
688 return (int)LType - (int)RType;
689
690 if (EqCacheSCEV.isEquivalent(LHS, RHS))
691 return 0;
692
693 if (Depth > MaxSCEVCompareDepth)
694 return std::nullopt;
695
696 // Aside from the getSCEVType() ordering, the particular ordering
697 // isn't very important except that it's beneficial to be consistent,
698 // so that (a + b) and (b + a) don't end up as different expressions.
699 switch (LType) {
700 case scUnknown: {
701 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
702 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
703
704 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
705 RU->getValue(), Depth + 1);
706 if (X == 0)
707 EqCacheSCEV.unionSets(LHS, RHS);
708 return X;
709 }
710
711 case scConstant: {
712 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
713 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
714
715 // Compare constant values.
716 const APInt &LA = LC->getAPInt();
717 const APInt &RA = RC->getAPInt();
718 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
719 if (LBitWidth != RBitWidth)
720 return (int)LBitWidth - (int)RBitWidth;
721 return LA.ult(RA) ? -1 : 1;
722 }
723
724 case scVScale: {
725 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
726 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
727 return LTy->getBitWidth() - RTy->getBitWidth();
728 }
729
730 case scAddRecExpr: {
731 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
732 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
733
734 // There is always a dominance between two recs that are used by one SCEV,
735 // so we can safely sort recs by loop header dominance. We require such
736 // order in getAddExpr.
737 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
738 if (LLoop != RLoop) {
739 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
740 assert(LHead != RHead && "Two loops share the same header?")(static_cast <bool> (LHead != RHead && "Two loops share the same header?"
) ? void (0) : __assert_fail ("LHead != RHead && \"Two loops share the same header?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 740, __extension__
__PRETTY_FUNCTION__))
;
741 if (DT.dominates(LHead, RHead))
742 return 1;
743 assert(DT.dominates(RHead, LHead) &&(static_cast <bool> (DT.dominates(RHead, LHead) &&
"No dominance between recurrences used by one SCEV?") ? void
(0) : __assert_fail ("DT.dominates(RHead, LHead) && \"No dominance between recurrences used by one SCEV?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 744, __extension__
__PRETTY_FUNCTION__))
744 "No dominance between recurrences used by one SCEV?")(static_cast <bool> (DT.dominates(RHead, LHead) &&
"No dominance between recurrences used by one SCEV?") ? void
(0) : __assert_fail ("DT.dominates(RHead, LHead) && \"No dominance between recurrences used by one SCEV?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 744, __extension__
__PRETTY_FUNCTION__))
;
745 return -1;
746 }
747
748 [[fallthrough]];
749 }
750
751 case scTruncate:
752 case scZeroExtend:
753 case scSignExtend:
754 case scPtrToInt:
755 case scAddExpr:
756 case scMulExpr:
757 case scUDivExpr:
758 case scSMaxExpr:
759 case scUMaxExpr:
760 case scSMinExpr:
761 case scUMinExpr:
762 case scSequentialUMinExpr: {
763 ArrayRef<const SCEV *> LOps = LHS->operands();
764 ArrayRef<const SCEV *> ROps = RHS->operands();
765
766 // Lexicographically compare n-ary-like expressions.
767 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
768 if (LNumOps != RNumOps)
769 return (int)LNumOps - (int)RNumOps;
770
771 for (unsigned i = 0; i != LNumOps; ++i) {
772 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LOps[i],
773 ROps[i], DT, Depth + 1);
774 if (X != 0)
775 return X;
776 }
777 EqCacheSCEV.unionSets(LHS, RHS);
778 return 0;
779 }
780
781 case scCouldNotCompute:
782 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 782)
;
783 }
784 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 784)
;
785}
786
787/// Given a list of SCEV objects, order them by their complexity, and group
788/// objects of the same complexity together by value. When this routine is
789/// finished, we know that any duplicates in the vector are consecutive and that
790/// complexity is monotonically increasing.
791///
792/// Note that we go take special precautions to ensure that we get deterministic
793/// results from this routine. In other words, we don't want the results of
794/// this to depend on where the addresses of various SCEV objects happened to
795/// land in memory.
796static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
797 LoopInfo *LI, DominatorTree &DT) {
798 if (Ops.size() < 2) return; // Noop
799
800 EquivalenceClasses<const SCEV *> EqCacheSCEV;
801 EquivalenceClasses<const Value *> EqCacheValue;
802
803 // Whether LHS has provably less complexity than RHS.
804 auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
805 auto Complexity =
806 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
807 return Complexity && *Complexity < 0;
808 };
809 if (Ops.size() == 2) {
810 // This is the common case, which also happens to be trivially simple.
811 // Special case it.
812 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
813 if (IsLessComplex(RHS, LHS))
814 std::swap(LHS, RHS);
815 return;
816 }
817
818 // Do the rough sort by complexity.
819 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
820 return IsLessComplex(LHS, RHS);
821 });
822
823 // Now that we are sorted by complexity, group elements of the same
824 // complexity. Note that this is, at worst, N^2, but the vector is likely to
825 // be extremely short in practice. Note that we take this approach because we
826 // do not want to depend on the addresses of the objects we are grouping.
827 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
828 const SCEV *S = Ops[i];
829 unsigned Complexity = S->getSCEVType();
830
831 // If there are any objects of the same complexity and same value as this
832 // one, group them.
833 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
834 if (Ops[j] == S) { // Found a duplicate.
835 // Move it to immediately after i'th element.
836 std::swap(Ops[i+1], Ops[j]);
837 ++i; // no need to rescan it.
838 if (i == e-2) return; // Done!
839 }
840 }
841 }
842}
843
844/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
845/// least HugeExprThreshold nodes).
846static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
847 return any_of(Ops, [](const SCEV *S) {
848 return S->getExpressionSize() >= HugeExprThreshold;
849 });
850}
851
852//===----------------------------------------------------------------------===//
853// Simple SCEV method implementations
854//===----------------------------------------------------------------------===//
855
856/// Compute BC(It, K). The result has width W. Assume, K > 0.
857static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
858 ScalarEvolution &SE,
859 Type *ResultTy) {
860 // Handle the simplest case efficiently.
861 if (K == 1)
862 return SE.getTruncateOrZeroExtend(It, ResultTy);
863
864 // We are using the following formula for BC(It, K):
865 //
866 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
867 //
868 // Suppose, W is the bitwidth of the return value. We must be prepared for
869 // overflow. Hence, we must assure that the result of our computation is
870 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
871 // safe in modular arithmetic.
872 //
873 // However, this code doesn't use exactly that formula; the formula it uses
874 // is something like the following, where T is the number of factors of 2 in
875 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
876 // exponentiation:
877 //
878 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
879 //
880 // This formula is trivially equivalent to the previous formula. However,
881 // this formula can be implemented much more efficiently. The trick is that
882 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
883 // arithmetic. To do exact division in modular arithmetic, all we have
884 // to do is multiply by the inverse. Therefore, this step can be done at
885 // width W.
886 //
887 // The next issue is how to safely do the division by 2^T. The way this
888 // is done is by doing the multiplication step at a width of at least W + T
889 // bits. This way, the bottom W+T bits of the product are accurate. Then,
890 // when we perform the division by 2^T (which is equivalent to a right shift
891 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
892 // truncated out after the division by 2^T.
893 //
894 // In comparison to just directly using the first formula, this technique
895 // is much more efficient; using the first formula requires W * K bits,
896 // but this formula less than W + K bits. Also, the first formula requires
897 // a division step, whereas this formula only requires multiplies and shifts.
898 //
899 // It doesn't matter whether the subtraction step is done in the calculation
900 // width or the input iteration count's width; if the subtraction overflows,
901 // the result must be zero anyway. We prefer here to do it in the width of
902 // the induction variable because it helps a lot for certain cases; CodeGen
903 // isn't smart enough to ignore the overflow, which leads to much less
904 // efficient code if the width of the subtraction is wider than the native
905 // register width.
906 //
907 // (It's possible to not widen at all by pulling out factors of 2 before
908 // the multiplication; for example, K=2 can be calculated as
909 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
910 // extra arithmetic, so it's not an obvious win, and it gets
911 // much more complicated for K > 3.)
912
913 // Protection from insane SCEVs; this bound is conservative,
914 // but it probably doesn't matter.
915 if (K > 1000)
916 return SE.getCouldNotCompute();
917
918 unsigned W = SE.getTypeSizeInBits(ResultTy);
919
920 // Calculate K! / 2^T and T; we divide out the factors of two before
921 // multiplying for calculating K! / 2^T to avoid overflow.
922 // Other overflow doesn't matter because we only care about the bottom
923 // W bits of the result.
924 APInt OddFactorial(W, 1);
925 unsigned T = 1;
926 for (unsigned i = 3; i <= K; ++i) {
927 APInt Mult(W, i);
928 unsigned TwoFactors = Mult.countr_zero();
929 T += TwoFactors;
930 Mult.lshrInPlace(TwoFactors);
931 OddFactorial *= Mult;
932 }
933
934 // We need at least W + T bits for the multiplication step
935 unsigned CalculationBits = W + T;
936
937 // Calculate 2^T, at width T+W.
938 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
939
940 // Calculate the multiplicative inverse of K! / 2^T;
941 // this multiplication factor will perform the exact division by
942 // K! / 2^T.
943 APInt Mod = APInt::getSignedMinValue(W+1);
944 APInt MultiplyFactor = OddFactorial.zext(W+1);
945 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
946 MultiplyFactor = MultiplyFactor.trunc(W);
947
948 // Calculate the product, at width T+W
949 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
950 CalculationBits);
951 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
952 for (unsigned i = 1; i != K; ++i) {
953 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
954 Dividend = SE.getMulExpr(Dividend,
955 SE.getTruncateOrZeroExtend(S, CalculationTy));
956 }
957
958 // Divide by 2^T
959 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
960
961 // Truncate the result, and divide by K! / 2^T.
962
963 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
964 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
965}
966
967/// Return the value of this chain of recurrences at the specified iteration
968/// number. We can evaluate this recurrence by multiplying each element in the
969/// chain by the binomial coefficient corresponding to it. In other words, we
970/// can evaluate {A,+,B,+,C,+,D} as:
971///
972/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
973///
974/// where BC(It, k) stands for binomial coefficient.
975const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
976 ScalarEvolution &SE) const {
977 return evaluateAtIteration(operands(), It, SE);
978}
979
980const SCEV *
981SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands,
982 const SCEV *It, ScalarEvolution &SE) {
983 assert(Operands.size() > 0)(static_cast <bool> (Operands.size() > 0) ? void (0)
: __assert_fail ("Operands.size() > 0", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 983, __extension__ __PRETTY_FUNCTION__))
;
984 const SCEV *Result = Operands[0];
985 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
986 // The computation is correct in the face of overflow provided that the
987 // multiplication is performed _after_ the evaluation of the binomial
988 // coefficient.
989 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
990 if (isa<SCEVCouldNotCompute>(Coeff))
991 return Coeff;
992
993 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
994 }
995 return Result;
996}
997
998//===----------------------------------------------------------------------===//
999// SCEV Expression folder implementations
1000//===----------------------------------------------------------------------===//
1001
1002const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op,
1003 unsigned Depth) {
1004 assert(Depth <= 1 &&(static_cast <bool> (Depth <= 1 && "getLosslessPtrToIntExpr() should self-recurse at most once."
) ? void (0) : __assert_fail ("Depth <= 1 && \"getLosslessPtrToIntExpr() should self-recurse at most once.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1005, __extension__
__PRETTY_FUNCTION__))
1005 "getLosslessPtrToIntExpr() should self-recurse at most once.")(static_cast <bool> (Depth <= 1 && "getLosslessPtrToIntExpr() should self-recurse at most once."
) ? void (0) : __assert_fail ("Depth <= 1 && \"getLosslessPtrToIntExpr() should self-recurse at most once.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1005, __extension__
__PRETTY_FUNCTION__))
;
1006
1007 // We could be called with an integer-typed operands during SCEV rewrites.
1008 // Since the operand is an integer already, just perform zext/trunc/self cast.
1009 if (!Op->getType()->isPointerTy())
1010 return Op;
1011
1012 // What would be an ID for such a SCEV cast expression?
1013 FoldingSetNodeID ID;
1014 ID.AddInteger(scPtrToInt);
1015 ID.AddPointer(Op);
1016
1017 void *IP = nullptr;
1018
1019 // Is there already an expression for such a cast?
1020 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1021 return S;
1022
1023 // It isn't legal for optimizations to construct new ptrtoint expressions
1024 // for non-integral pointers.
1025 if (getDataLayout().isNonIntegralPointerType(Op->getType()))
1026 return getCouldNotCompute();
1027
1028 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1029
1030 // We can only trivially model ptrtoint if SCEV's effective (integer) type
1031 // is sufficiently wide to represent all possible pointer values.
1032 // We could theoretically teach SCEV to truncate wider pointers, but
1033 // that isn't implemented for now.
1034 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) !=
1035 getDataLayout().getTypeSizeInBits(IntPtrTy))
1036 return getCouldNotCompute();
1037
1038 // If not, is this expression something we can't reduce any further?
1039 if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
1040 // Perform some basic constant folding. If the operand of the ptr2int cast
1041 // is a null pointer, don't create a ptr2int SCEV expression (that will be
1042 // left as-is), but produce a zero constant.
1043 // NOTE: We could handle a more general case, but lack motivational cases.
1044 if (isa<ConstantPointerNull>(U->getValue()))
1045 return getZero(IntPtrTy);
1046
1047 // Create an explicit cast node.
1048 // We can reuse the existing insert position since if we get here,
1049 // we won't have made any changes which would invalidate it.
1050 SCEV *S = new (SCEVAllocator)
1051 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1052 UniqueSCEVs.InsertNode(S, IP);
1053 registerUser(S, Op);
1054 return S;
1055 }
1056
1057 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "(static_cast <bool> (Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
"non-SCEVUnknown's.") ? void (0) : __assert_fail ("Depth == 0 && \"getLosslessPtrToIntExpr() should not self-recurse for \" \"non-SCEVUnknown's.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1058, __extension__
__PRETTY_FUNCTION__))
1058 "non-SCEVUnknown's.")(static_cast <bool> (Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
"non-SCEVUnknown's.") ? void (0) : __assert_fail ("Depth == 0 && \"getLosslessPtrToIntExpr() should not self-recurse for \" \"non-SCEVUnknown's.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1058, __extension__
__PRETTY_FUNCTION__))
;
1059
1060 // Otherwise, we've got some expression that is more complex than just a
1061 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1062 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1063 // only, and the expressions must otherwise be integer-typed.
1064 // So sink the cast down to the SCEVUnknown's.
1065
1066 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1067 /// which computes a pointer-typed value, and rewrites the whole expression
1068 /// tree so that *all* the computations are done on integers, and the only
1069 /// pointer-typed operands in the expression are SCEVUnknown.
1070 class SCEVPtrToIntSinkingRewriter
1071 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1072 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1073
1074 public:
1075 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1076
1077 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1078 SCEVPtrToIntSinkingRewriter Rewriter(SE);
1079 return Rewriter.visit(Scev);
1080 }
1081
1082 const SCEV *visit(const SCEV *S) {
1083 Type *STy = S->getType();
1084 // If the expression is not pointer-typed, just keep it as-is.
1085 if (!STy->isPointerTy())
1086 return S;
1087 // Else, recursively sink the cast down into it.
1088 return Base::visit(S);
1089 }
1090
1091 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1092 SmallVector<const SCEV *, 2> Operands;
1093 bool Changed = false;
1094 for (const auto *Op : Expr->operands()) {
1095 Operands.push_back(visit(Op));
1096 Changed |= Op != Operands.back();
1097 }
1098 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1099 }
1100
1101 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1102 SmallVector<const SCEV *, 2> Operands;
1103 bool Changed = false;
1104 for (const auto *Op : Expr->operands()) {
1105 Operands.push_back(visit(Op));
1106 Changed |= Op != Operands.back();
1107 }
1108 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1109 }
1110
1111 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1112 assert(Expr->getType()->isPointerTy() &&(static_cast <bool> (Expr->getType()->isPointerTy
() && "Should only reach pointer-typed SCEVUnknown's."
) ? void (0) : __assert_fail ("Expr->getType()->isPointerTy() && \"Should only reach pointer-typed SCEVUnknown's.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1113, __extension__
__PRETTY_FUNCTION__))
1113 "Should only reach pointer-typed SCEVUnknown's.")(static_cast <bool> (Expr->getType()->isPointerTy
() && "Should only reach pointer-typed SCEVUnknown's."
) ? void (0) : __assert_fail ("Expr->getType()->isPointerTy() && \"Should only reach pointer-typed SCEVUnknown's.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1113, __extension__
__PRETTY_FUNCTION__))
;
1114 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
1115 }
1116 };
1117
1118 // And actually perform the cast sinking.
1119 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1120 assert(IntOp->getType()->isIntegerTy() &&(static_cast <bool> (IntOp->getType()->isIntegerTy
() && "We must have succeeded in sinking the cast, " "and ending up with an integer-typed expression!"
) ? void (0) : __assert_fail ("IntOp->getType()->isIntegerTy() && \"We must have succeeded in sinking the cast, \" \"and ending up with an integer-typed expression!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1122, __extension__
__PRETTY_FUNCTION__))
1121 "We must have succeeded in sinking the cast, "(static_cast <bool> (IntOp->getType()->isIntegerTy
() && "We must have succeeded in sinking the cast, " "and ending up with an integer-typed expression!"
) ? void (0) : __assert_fail ("IntOp->getType()->isIntegerTy() && \"We must have succeeded in sinking the cast, \" \"and ending up with an integer-typed expression!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1122, __extension__
__PRETTY_FUNCTION__))
1122 "and ending up with an integer-typed expression!")(static_cast <bool> (IntOp->getType()->isIntegerTy
() && "We must have succeeded in sinking the cast, " "and ending up with an integer-typed expression!"
) ? void (0) : __assert_fail ("IntOp->getType()->isIntegerTy() && \"We must have succeeded in sinking the cast, \" \"and ending up with an integer-typed expression!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1122, __extension__
__PRETTY_FUNCTION__))
;
1123 return IntOp;
1124}
1125
1126const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) {
1127 assert(Ty->isIntegerTy() && "Target type must be an integer type!")(static_cast <bool> (Ty->isIntegerTy() && "Target type must be an integer type!"
) ? void (0) : __assert_fail ("Ty->isIntegerTy() && \"Target type must be an integer type!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1127, __extension__
__PRETTY_FUNCTION__))
;
1128
1129 const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
1130 if (isa<SCEVCouldNotCompute>(IntOp))
1131 return IntOp;
1132
1133 return getTruncateOrZeroExtend(IntOp, Ty);
1134}
1135
1136const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1137 unsigned Depth) {
1138 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&(static_cast <bool> (getTypeSizeInBits(Op->getType()
) > getTypeSizeInBits(Ty) && "This is not a truncating conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && \"This is not a truncating conversion!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1139, __extension__
__PRETTY_FUNCTION__))
1139 "This is not a truncating conversion!")(static_cast <bool> (getTypeSizeInBits(Op->getType()
) > getTypeSizeInBits(Ty) && "This is not a truncating conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && \"This is not a truncating conversion!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1139, __extension__
__PRETTY_FUNCTION__))
;
1140 assert(isSCEVable(Ty) &&(static_cast <bool> (isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1141, __extension__
__PRETTY_FUNCTION__))
1141 "This is not a conversion to a SCEVable type!")(static_cast <bool> (isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1141, __extension__
__PRETTY_FUNCTION__))
;
1142 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!")(static_cast <bool> (!Op->getType()->isPointerTy(
) && "Can't truncate pointer!") ? void (0) : __assert_fail
("!Op->getType()->isPointerTy() && \"Can't truncate pointer!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1142, __extension__
__PRETTY_FUNCTION__))
;
1143 Ty = getEffectiveSCEVType(Ty);
1144
1145 FoldingSetNodeID ID;
1146 ID.AddInteger(scTruncate);
1147 ID.AddPointer(Op);
1148 ID.AddPointer(Ty);
1149 void *IP = nullptr;
1150 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1151
1152 // Fold if the operand is constant.
1153 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1154 return getConstant(
1155 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1156
1157 // trunc(trunc(x)) --> trunc(x)
1158 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1159 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1160
1161 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1162 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1163 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1164
1165 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1166 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1167 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1168
1169 if (Depth > MaxCastDepth) {
1170 SCEV *S =
1171 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1172 UniqueSCEVs.InsertNode(S, IP);
1173 registerUser(S, Op);
1174 return S;
1175 }
1176
1177 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1178 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1179 // if after transforming we have at most one truncate, not counting truncates
1180 // that replace other casts.
1181 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1182 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1183 SmallVector<const SCEV *, 4> Operands;
1184 unsigned numTruncs = 0;
1185 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1186 ++i) {
1187 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1188 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1189 isa<SCEVTruncateExpr>(S))
1190 numTruncs++;
1191 Operands.push_back(S);
1192 }
1193 if (numTruncs < 2) {
1194 if (isa<SCEVAddExpr>(Op))
1195 return getAddExpr(Operands);
1196 if (isa<SCEVMulExpr>(Op))
1197 return getMulExpr(Operands);
1198 llvm_unreachable("Unexpected SCEV type for Op.")::llvm::llvm_unreachable_internal("Unexpected SCEV type for Op."
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1198)
;
1199 }
1200 // Although we checked in the beginning that ID is not in the cache, it is
1201 // possible that during recursion and different modification ID was inserted
1202 // into the cache. So if we find it, just return it.
1203 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1204 return S;
1205 }
1206
1207 // If the input value is a chrec scev, truncate the chrec's operands.
1208 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1209 SmallVector<const SCEV *, 4> Operands;
1210 for (const SCEV *Op : AddRec->operands())
1211 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1212 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1213 }
1214
1215 // Return zero if truncating to known zeros.
1216 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1217 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1218 return getZero(Ty);
1219
1220 // The cast wasn't folded; create an explicit cast node. We can reuse
1221 // the existing insert position since if we get here, we won't have
1222 // made any changes which would invalidate it.
1223 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1224 Op, Ty);
1225 UniqueSCEVs.InsertNode(S, IP);
1226 registerUser(S, Op);
1227 return S;
1228}
1229
1230// Get the limit of a recurrence such that incrementing by Step cannot cause
1231// signed overflow as long as the value of the recurrence within the
1232// loop does not exceed this limit before incrementing.
1233static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1234 ICmpInst::Predicate *Pred,
1235 ScalarEvolution *SE) {
1236 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1237 if (SE->isKnownPositive(Step)) {
1238 *Pred = ICmpInst::ICMP_SLT;
1239 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1240 SE->getSignedRangeMax(Step));
1241 }
1242 if (SE->isKnownNegative(Step)) {
1243 *Pred = ICmpInst::ICMP_SGT;
1244 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1245 SE->getSignedRangeMin(Step));
1246 }
1247 return nullptr;
1248}
1249
1250// Get the limit of a recurrence such that incrementing by Step cannot cause
1251// unsigned overflow as long as the value of the recurrence within the loop does
1252// not exceed this limit before incrementing.
1253static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1254 ICmpInst::Predicate *Pred,
1255 ScalarEvolution *SE) {
1256 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1257 *Pred = ICmpInst::ICMP_ULT;
1258
1259 return SE->getConstant(APInt::getMinValue(BitWidth) -
1260 SE->getUnsignedRangeMax(Step));
1261}
1262
1263namespace {
1264
1265struct ExtendOpTraitsBase {
1266 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1267 unsigned);
1268};
1269
1270// Used to make code generic over signed and unsigned overflow.
1271template <typename ExtendOp> struct ExtendOpTraits {
1272 // Members present:
1273 //
1274 // static const SCEV::NoWrapFlags WrapType;
1275 //
1276 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1277 //
1278 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1279 // ICmpInst::Predicate *Pred,
1280 // ScalarEvolution *SE);
1281};
1282
1283template <>
1284struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1285 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1286
1287 static const GetExtendExprTy GetExtendExpr;
1288
1289 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1290 ICmpInst::Predicate *Pred,
1291 ScalarEvolution *SE) {
1292 return getSignedOverflowLimitForStep(Step, Pred, SE);
1293 }
1294};
1295
1296const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1297 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1298
1299template <>
1300struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1301 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1302
1303 static const GetExtendExprTy GetExtendExpr;
1304
1305 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1306 ICmpInst::Predicate *Pred,
1307 ScalarEvolution *SE) {
1308 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1309 }
1310};
1311
1312const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1313 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1314
1315} // end anonymous namespace
1316
1317// The recurrence AR has been shown to have no signed/unsigned wrap or something
1318// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1319// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1320// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1321// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1322// expression "Step + sext/zext(PreIncAR)" is congruent with
1323// "sext/zext(PostIncAR)"
1324template <typename ExtendOpTy>
1325static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1326 ScalarEvolution *SE, unsigned Depth) {
1327 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1328 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1329
1330 const Loop *L = AR->getLoop();
1331 const SCEV *Start = AR->getStart();
1332 const SCEV *Step = AR->getStepRecurrence(*SE);
1333
1334 // Check for a simple looking step prior to loop entry.
1335 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1336 if (!SA)
1337 return nullptr;
1338
1339 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1340 // subtraction is expensive. For this purpose, perform a quick and dirty
1341 // difference, by checking for Step in the operand list.
1342 SmallVector<const SCEV *, 4> DiffOps;
1343 for (const SCEV *Op : SA->operands())
1344 if (Op != Step)
1345 DiffOps.push_back(Op);
1346
1347 if (DiffOps.size() == SA->getNumOperands())
1348 return nullptr;
1349
1350 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1351 // `Step`:
1352
1353 // 1. NSW/NUW flags on the step increment.
1354 auto PreStartFlags =
1355 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1356 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1357 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1358 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1359
1360 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1361 // "S+X does not sign/unsign-overflow".
1362 //
1363
1364 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1365 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1366 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1367 return PreStart;
1368
1369 // 2. Direct overflow check on the step operation's expression.
1370 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1371 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1372 const SCEV *OperandExtendedStart =
1373 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1374 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1375 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1376 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1377 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1378 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1379 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1380 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1381 }
1382 return PreStart;
1383 }
1384
1385 // 3. Loop precondition.
1386 ICmpInst::Predicate Pred;
1387 const SCEV *OverflowLimit =
1388 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1389
1390 if (OverflowLimit &&
1391 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1392 return PreStart;
1393
1394 return nullptr;
1395}
1396
1397// Get the normalized zero or sign extended expression for this AddRec's Start.
1398template <typename ExtendOpTy>
1399static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1400 ScalarEvolution *SE,
1401 unsigned Depth) {
1402 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1403
1404 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1405 if (!PreStart)
1406 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1407
1408 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1409 Depth),
1410 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1411}
1412
1413// Try to prove away overflow by looking at "nearby" add recurrences. A
1414// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1415// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1416//
1417// Formally:
1418//
1419// {S,+,X} == {S-T,+,X} + T
1420// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1421//
1422// If ({S-T,+,X} + T) does not overflow ... (1)
1423//
1424// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1425//
1426// If {S-T,+,X} does not overflow ... (2)
1427//
1428// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1429// == {Ext(S-T)+Ext(T),+,Ext(X)}
1430//
1431// If (S-T)+T does not overflow ... (3)
1432//
1433// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1434// == {Ext(S),+,Ext(X)} == LHS
1435//
1436// Thus, if (1), (2) and (3) are true for some T, then
1437// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1438//
1439// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1440// does not overflow" restricted to the 0th iteration. Therefore we only need
1441// to check for (1) and (2).
1442//
1443// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1444// is `Delta` (defined below).
1445template <typename ExtendOpTy>
1446bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1447 const SCEV *Step,
1448 const Loop *L) {
1449 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1450
1451 // We restrict `Start` to a constant to prevent SCEV from spending too much
1452 // time here. It is correct (but more expensive) to continue with a
1453 // non-constant `Start` and do a general SCEV subtraction to compute
1454 // `PreStart` below.
1455 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1456 if (!StartC)
1457 return false;
1458
1459 APInt StartAI = StartC->getAPInt();
1460
1461 for (unsigned Delta : {-2, -1, 1, 2}) {
1462 const SCEV *PreStart = getConstant(StartAI - Delta);
1463
1464 FoldingSetNodeID ID;
1465 ID.AddInteger(scAddRecExpr);
1466 ID.AddPointer(PreStart);
1467 ID.AddPointer(Step);
1468 ID.AddPointer(L);
1469 void *IP = nullptr;
1470 const auto *PreAR =
1471 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1472
1473 // Give up if we don't already have the add recurrence we need because
1474 // actually constructing an add recurrence is relatively expensive.
1475 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1476 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1477 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1478 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1479 DeltaS, &Pred, this);
1480 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1481 return true;
1482 }
1483 }
1484
1485 return false;
1486}
1487
1488// Finds an integer D for an expression (C + x + y + ...) such that the top
1489// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1490// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1491// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1492// the (C + x + y + ...) expression is \p WholeAddExpr.
1493static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1494 const SCEVConstant *ConstantTerm,
1495 const SCEVAddExpr *WholeAddExpr) {
1496 const APInt &C = ConstantTerm->getAPInt();
1497 const unsigned BitWidth = C.getBitWidth();
1498 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1499 uint32_t TZ = BitWidth;
1500 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1501 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1502 if (TZ) {
1503 // Set D to be as many least significant bits of C as possible while still
1504 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1505 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1506 }
1507 return APInt(BitWidth, 0);
1508}
1509
1510// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1511// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1512// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1513// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1514static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1515 const APInt &ConstantStart,
1516 const SCEV *Step) {
1517 const unsigned BitWidth = ConstantStart.getBitWidth();
1518 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1519 if (TZ)
1520 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1521 : ConstantStart;
1522 return APInt(BitWidth, 0);
1523}
1524
1525static void insertFoldCacheEntry(
1526 const ScalarEvolution::FoldID &ID, const SCEV *S,
1527 DenseMap<ScalarEvolution::FoldID, const SCEV *> &FoldCache,
1528 DenseMap<const SCEV *, SmallVector<ScalarEvolution::FoldID, 2>>
1529 &FoldCacheUser) {
1530 auto I = FoldCache.insert({ID, S});
1531 if (!I.second) {
1532 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1533 // entry.
1534 auto &UserIDs = FoldCacheUser[I.first->second];
1535 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs")(static_cast <bool> (count(UserIDs, ID) == 1 &&
"unexpected duplicates in UserIDs") ? void (0) : __assert_fail
("count(UserIDs, ID) == 1 && \"unexpected duplicates in UserIDs\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1535, __extension__
__PRETTY_FUNCTION__))
;
1536 for (unsigned I = 0; I != UserIDs.size(); ++I)
1537 if (UserIDs[I] == ID) {
1538 std::swap(UserIDs[I], UserIDs.back());
1539 break;
1540 }
1541 UserIDs.pop_back();
1542 I.first->second = S;
1543 }
1544 auto R = FoldCacheUser.insert({S, {}});
1545 R.first->second.push_back(ID);
1546}
1547
1548const SCEV *
1549ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1550 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&(static_cast <bool> (getTypeSizeInBits(Op->getType()
) < getTypeSizeInBits(Ty) && "This is not an extending conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1551, __extension__
__PRETTY_FUNCTION__))
1551 "This is not an extending conversion!")(static_cast <bool> (getTypeSizeInBits(Op->getType()
) < getTypeSizeInBits(Ty) && "This is not an extending conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1551, __extension__
__PRETTY_FUNCTION__))
;
1552 assert(isSCEVable(Ty) &&(static_cast <bool> (isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1553, __extension__
__PRETTY_FUNCTION__))
1553 "This is not a conversion to a SCEVable type!")(static_cast <bool> (isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1553, __extension__
__PRETTY_FUNCTION__))
;
1554 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!")(static_cast <bool> (!Op->getType()->isPointerTy(
) && "Can't extend pointer!") ? void (0) : __assert_fail
("!Op->getType()->isPointerTy() && \"Can't extend pointer!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1554, __extension__
__PRETTY_FUNCTION__))
;
1555 Ty = getEffectiveSCEVType(Ty);
1556
1557 FoldID ID;
1558 ID.addInteger(scZeroExtend);
1559 ID.addPointer(Op);
1560 ID.addPointer(Ty);
1561 auto Iter = FoldCache.find(ID);
1562 if (Iter != FoldCache.end())
1563 return Iter->second;
1564
1565 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1566 if (!isa<SCEVZeroExtendExpr>(S))
1567 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1568 return S;
1569}
1570
1571const SCEV *ScalarEvolution::getZeroExtendExprImpl(const SCEV *Op, Type *Ty,
1572 unsigned Depth) {
1573 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&(static_cast <bool> (getTypeSizeInBits(Op->getType()
) < getTypeSizeInBits(Ty) && "This is not an extending conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1574, __extension__
__PRETTY_FUNCTION__))
1574 "This is not an extending conversion!")(static_cast <bool> (getTypeSizeInBits(Op->getType()
) < getTypeSizeInBits(Ty) && "This is not an extending conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1574, __extension__
__PRETTY_FUNCTION__))
;
1575 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!")(static_cast <bool> (isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1575, __extension__
__PRETTY_FUNCTION__))
;
1576 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!")(static_cast <bool> (!Op->getType()->isPointerTy(
) && "Can't extend pointer!") ? void (0) : __assert_fail
("!Op->getType()->isPointerTy() && \"Can't extend pointer!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1576, __extension__
__PRETTY_FUNCTION__))
;
1577
1578 // Fold if the operand is constant.
1579 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1580 return getConstant(
1581 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1582
1583 // zext(zext(x)) --> zext(x)
1584 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1585 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1586
1587 // Before doing any expensive analysis, check to see if we've already
1588 // computed a SCEV for this Op and Ty.
1589 FoldingSetNodeID ID;
1590 ID.AddInteger(scZeroExtend);
1591 ID.AddPointer(Op);
1592 ID.AddPointer(Ty);
1593 void *IP = nullptr;
1594 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1595 if (Depth > MaxCastDepth) {
1596 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1597 Op, Ty);
1598 UniqueSCEVs.InsertNode(S, IP);
1599 registerUser(S, Op);
1600 return S;
1601 }
1602
1603 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1604 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1605 // It's possible the bits taken off by the truncate were all zero bits. If
1606 // so, we should be able to simplify this further.
1607 const SCEV *X = ST->getOperand();
1608 ConstantRange CR = getUnsignedRange(X);
1609 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1610 unsigned NewBits = getTypeSizeInBits(Ty);
1611 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1612 CR.zextOrTrunc(NewBits)))
1613 return getTruncateOrZeroExtend(X, Ty, Depth);
1614 }
1615
1616 // If the input value is a chrec scev, and we can prove that the value
1617 // did not overflow the old, smaller, value, we can zero extend all of the
1618 // operands (often constants). This allows analysis of something like
1619 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1620 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1621 if (AR->isAffine()) {
1622 const SCEV *Start = AR->getStart();
1623 const SCEV *Step = AR->getStepRecurrence(*this);
1624 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1625 const Loop *L = AR->getLoop();
1626
1627 // If we have special knowledge that this addrec won't overflow,
1628 // we don't need to do any further analysis.
1629 if (AR->hasNoUnsignedWrap()) {
1630 Start =
1631 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1632 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1633 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1634 }
1635
1636 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1637 // Note that this serves two purposes: It filters out loops that are
1638 // simply not analyzable, and it covers the case where this code is
1639 // being called from within backedge-taken count analysis, such that
1640 // attempting to ask for the backedge-taken count would likely result
1641 // in infinite recursion. In the later case, the analysis code will
1642 // cope with a conservative value, and it will take care to purge
1643 // that value once it has finished.
1644 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1645 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1646 // Manually compute the final value for AR, checking for overflow.
1647
1648 // Check whether the backedge-taken count can be losslessly casted to
1649 // the addrec's type. The count is always unsigned.
1650 const SCEV *CastedMaxBECount =
1651 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1652 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1653 CastedMaxBECount, MaxBECount->getType(), Depth);
1654 if (MaxBECount == RecastedMaxBECount) {
1655 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1656 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1657 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1658 SCEV::FlagAnyWrap, Depth + 1);
1659 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1660 SCEV::FlagAnyWrap,
1661 Depth + 1),
1662 WideTy, Depth + 1);
1663 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1664 const SCEV *WideMaxBECount =
1665 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1666 const SCEV *OperandExtendedAdd =
1667 getAddExpr(WideStart,
1668 getMulExpr(WideMaxBECount,
1669 getZeroExtendExpr(Step, WideTy, Depth + 1),
1670 SCEV::FlagAnyWrap, Depth + 1),
1671 SCEV::FlagAnyWrap, Depth + 1);
1672 if (ZAdd == OperandExtendedAdd) {
1673 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1674 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1675 // Return the expression with the addrec on the outside.
1676 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1677 Depth + 1);
1678 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1679 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1680 }
1681 // Similar to above, only this time treat the step value as signed.
1682 // This covers loops that count down.
1683 OperandExtendedAdd =
1684 getAddExpr(WideStart,
1685 getMulExpr(WideMaxBECount,
1686 getSignExtendExpr(Step, WideTy, Depth + 1),
1687 SCEV::FlagAnyWrap, Depth + 1),
1688 SCEV::FlagAnyWrap, Depth + 1);
1689 if (ZAdd == OperandExtendedAdd) {
1690 // Cache knowledge of AR NW, which is propagated to this AddRec.
1691 // Negative step causes unsigned wrap, but it still can't self-wrap.
1692 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1693 // Return the expression with the addrec on the outside.
1694 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1695 Depth + 1);
1696 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1697 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1698 }
1699 }
1700 }
1701
1702 // Normally, in the cases we can prove no-overflow via a
1703 // backedge guarding condition, we can also compute a backedge
1704 // taken count for the loop. The exceptions are assumptions and
1705 // guards present in the loop -- SCEV is not great at exploiting
1706 // these to compute max backedge taken counts, but can still use
1707 // these to prove lack of overflow. Use this fact to avoid
1708 // doing extra work that may not pay off.
1709 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1710 !AC.assumptions().empty()) {
1711
1712 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1713 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1714 if (AR->hasNoUnsignedWrap()) {
1715 // Same as nuw case above - duplicated here to avoid a compile time
1716 // issue. It's not clear that the order of checks does matter, but
1717 // it's one of two issue possible causes for a change which was
1718 // reverted. Be conservative for the moment.
1719 Start =
1720 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1721 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1722 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1723 }
1724
1725 // For a negative step, we can extend the operands iff doing so only
1726 // traverses values in the range zext([0,UINT_MAX]).
1727 if (isKnownNegative(Step)) {
1728 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1729 getSignedRangeMin(Step));
1730 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1731 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1732 // Cache knowledge of AR NW, which is propagated to this
1733 // AddRec. Negative step causes unsigned wrap, but it
1734 // still can't self-wrap.
1735 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1736 // Return the expression with the addrec on the outside.
1737 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1738 Depth + 1);
1739 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1740 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1741 }
1742 }
1743 }
1744
1745 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1746 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1747 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1748 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1749 const APInt &C = SC->getAPInt();
1750 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1751 if (D != 0) {
1752 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1753 const SCEV *SResidual =
1754 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1755 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1756 return getAddExpr(SZExtD, SZExtR,
1757 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1758 Depth + 1);
1759 }
1760 }
1761
1762 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1763 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1764 Start =
1765 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1766 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1767 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1768 }
1769 }
1770
1771 // zext(A % B) --> zext(A) % zext(B)
1772 {
1773 const SCEV *LHS;
1774 const SCEV *RHS;
1775 if (matchURem(Op, LHS, RHS))
1776 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1777 getZeroExtendExpr(RHS, Ty, Depth + 1));
1778 }
1779
1780 // zext(A / B) --> zext(A) / zext(B).
1781 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1782 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1783 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1784
1785 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1786 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1787 if (SA->hasNoUnsignedWrap()) {
1788 // If the addition does not unsign overflow then we can, by definition,
1789 // commute the zero extension with the addition operation.
1790 SmallVector<const SCEV *, 4> Ops;
1791 for (const auto *Op : SA->operands())
1792 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1793 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1794 }
1795
1796 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1797 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1798 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1799 //
1800 // Often address arithmetics contain expressions like
1801 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1802 // This transformation is useful while proving that such expressions are
1803 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1804 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1805 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1806 if (D != 0) {
1807 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1808 const SCEV *SResidual =
1809 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1810 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1811 return getAddExpr(SZExtD, SZExtR,
1812 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1813 Depth + 1);
1814 }
1815 }
1816 }
1817
1818 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1819 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1820 if (SM->hasNoUnsignedWrap()) {
1821 // If the multiply does not unsign overflow then we can, by definition,
1822 // commute the zero extension with the multiply operation.
1823 SmallVector<const SCEV *, 4> Ops;
1824 for (const auto *Op : SM->operands())
1825 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1826 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1827 }
1828
1829 // zext(2^K * (trunc X to iN)) to iM ->
1830 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1831 //
1832 // Proof:
1833 //
1834 // zext(2^K * (trunc X to iN)) to iM
1835 // = zext((trunc X to iN) << K) to iM
1836 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1837 // (because shl removes the top K bits)
1838 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1839 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1840 //
1841 if (SM->getNumOperands() == 2)
1842 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1843 if (MulLHS->getAPInt().isPowerOf2())
1844 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1845 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1846 MulLHS->getAPInt().logBase2();
1847 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1848 return getMulExpr(
1849 getZeroExtendExpr(MulLHS, Ty),
1850 getZeroExtendExpr(
1851 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1852 SCEV::FlagNUW, Depth + 1);
1853 }
1854 }
1855
1856 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1857 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1858 if (isa<SCEVUMinExpr>(Op) || isa<SCEVUMaxExpr>(Op)) {
1859 auto *MinMax = cast<SCEVMinMaxExpr>(Op);
1860 SmallVector<const SCEV *, 4> Operands;
1861 for (auto *Operand : MinMax->operands())
1862 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1863 if (isa<SCEVUMinExpr>(MinMax))
1864 return getUMinExpr(Operands);
1865 return getUMaxExpr(Operands);
1866 }
1867
1868 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1869 if (auto *MinMax = dyn_cast<SCEVSequentialMinMaxExpr>(Op)) {
1870 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!")(static_cast <bool> (isa<SCEVSequentialUMinExpr>(
MinMax) && "Not supported!") ? void (0) : __assert_fail
("isa<SCEVSequentialUMinExpr>(MinMax) && \"Not supported!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1870, __extension__
__PRETTY_FUNCTION__))
;
1871 SmallVector<const SCEV *, 4> Operands;
1872 for (auto *Operand : MinMax->operands())
1873 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1874 return getUMinExpr(Operands, /*Sequential*/ true);
1875 }
1876
1877 // The cast wasn't folded; create an explicit cast node.
1878 // Recompute the insert position, as it may have been invalidated.
1879 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1880 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1881 Op, Ty);
1882 UniqueSCEVs.InsertNode(S, IP);
1883 registerUser(S, Op);
1884 return S;
1885}
1886
1887const SCEV *
1888ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1889 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&(static_cast <bool> (getTypeSizeInBits(Op->getType()
) < getTypeSizeInBits(Ty) && "This is not an extending conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1890, __extension__
__PRETTY_FUNCTION__))
1890 "This is not an extending conversion!")(static_cast <bool> (getTypeSizeInBits(Op->getType()
) < getTypeSizeInBits(Ty) && "This is not an extending conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1890, __extension__
__PRETTY_FUNCTION__))
;
1891 assert(isSCEVable(Ty) &&(static_cast <bool> (isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1892, __extension__
__PRETTY_FUNCTION__))
1892 "This is not a conversion to a SCEVable type!")(static_cast <bool> (isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1892, __extension__
__PRETTY_FUNCTION__))
;
1893 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!")(static_cast <bool> (!Op->getType()->isPointerTy(
) && "Can't extend pointer!") ? void (0) : __assert_fail
("!Op->getType()->isPointerTy() && \"Can't extend pointer!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1893, __extension__
__PRETTY_FUNCTION__))
;
1894 Ty = getEffectiveSCEVType(Ty);
1895
1896 FoldID ID;
1897 ID.addInteger(scSignExtend);
1898 ID.addPointer(Op);
1899 ID.addPointer(Ty);
1900 auto Iter = FoldCache.find(ID);
1901 if (Iter != FoldCache.end())
1902 return Iter->second;
1903
1904 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1905 if (!isa<SCEVSignExtendExpr>(S))
1906 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1907 return S;
1908}
1909
1910const SCEV *ScalarEvolution::getSignExtendExprImpl(const SCEV *Op, Type *Ty,
1911 unsigned Depth) {
1912 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&(static_cast <bool> (getTypeSizeInBits(Op->getType()
) < getTypeSizeInBits(Ty) && "This is not an extending conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1913, __extension__
__PRETTY_FUNCTION__))
1913 "This is not an extending conversion!")(static_cast <bool> (getTypeSizeInBits(Op->getType()
) < getTypeSizeInBits(Ty) && "This is not an extending conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1913, __extension__
__PRETTY_FUNCTION__))
;
1914 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!")(static_cast <bool> (isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1914, __extension__
__PRETTY_FUNCTION__))
;
1915 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!")(static_cast <bool> (!Op->getType()->isPointerTy(
) && "Can't extend pointer!") ? void (0) : __assert_fail
("!Op->getType()->isPointerTy() && \"Can't extend pointer!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 1915, __extension__
__PRETTY_FUNCTION__))
;
1916 Ty = getEffectiveSCEVType(Ty);
1917
1918 // Fold if the operand is constant.
1919 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1920 return getConstant(
1921 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1922
1923 // sext(sext(x)) --> sext(x)
1924 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1925 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1926
1927 // sext(zext(x)) --> zext(x)
1928 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1929 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1930
1931 // Before doing any expensive analysis, check to see if we've already
1932 // computed a SCEV for this Op and Ty.
1933 FoldingSetNodeID ID;
1934 ID.AddInteger(scSignExtend);
1935 ID.AddPointer(Op);
1936 ID.AddPointer(Ty);
1937 void *IP = nullptr;
1938 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1939 // Limit recursion depth.
1940 if (Depth > MaxCastDepth) {
1941 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1942 Op, Ty);
1943 UniqueSCEVs.InsertNode(S, IP);
1944 registerUser(S, Op);
1945 return S;
1946 }
1947
1948 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1949 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1950 // It's possible the bits taken off by the truncate were all sign bits. If
1951 // so, we should be able to simplify this further.
1952 const SCEV *X = ST->getOperand();
1953 ConstantRange CR = getSignedRange(X);
1954 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1955 unsigned NewBits = getTypeSizeInBits(Ty);
1956 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1957 CR.sextOrTrunc(NewBits)))
1958 return getTruncateOrSignExtend(X, Ty, Depth);
1959 }
1960
1961 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1962 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1963 if (SA->hasNoSignedWrap()) {
1964 // If the addition does not sign overflow then we can, by definition,
1965 // commute the sign extension with the addition operation.
1966 SmallVector<const SCEV *, 4> Ops;
1967 for (const auto *Op : SA->operands())
1968 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1969 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1970 }
1971
1972 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1973 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1974 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1975 //
1976 // For instance, this will bring two seemingly different expressions:
1977 // 1 + sext(5 + 20 * %x + 24 * %y) and
1978 // sext(6 + 20 * %x + 24 * %y)
1979 // to the same form:
1980 // 2 + sext(4 + 20 * %x + 24 * %y)
1981 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1982 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1983 if (D != 0) {
1984 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1985 const SCEV *SResidual =
1986 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1987 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1988 return getAddExpr(SSExtD, SSExtR,
1989 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1990 Depth + 1);
1991 }
1992 }
1993 }
1994 // If the input value is a chrec scev, and we can prove that the value
1995 // did not overflow the old, smaller, value, we can sign extend all of the
1996 // operands (often constants). This allows analysis of something like
1997 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1998 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1999 if (AR->isAffine()) {
2000 const SCEV *Start = AR->getStart();
2001 const SCEV *Step = AR->getStepRecurrence(*this);
2002 unsigned BitWidth = getTypeSizeInBits(AR->getType());
2003 const Loop *L = AR->getLoop();
2004
2005 // If we have special knowledge that this addrec won't overflow,
2006 // we don't need to do any further analysis.
2007 if (AR->hasNoSignedWrap()) {
2008 Start =
2009 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2010 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2011 return getAddRecExpr(Start, Step, L, SCEV::FlagNSW);
2012 }
2013
2014 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2015 // Note that this serves two purposes: It filters out loops that are
2016 // simply not analyzable, and it covers the case where this code is
2017 // being called from within backedge-taken count analysis, such that
2018 // attempting to ask for the backedge-taken count would likely result
2019 // in infinite recursion. In the later case, the analysis code will
2020 // cope with a conservative value, and it will take care to purge
2021 // that value once it has finished.
2022 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2023 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2024 // Manually compute the final value for AR, checking for
2025 // overflow.
2026
2027 // Check whether the backedge-taken count can be losslessly casted to
2028 // the addrec's type. The count is always unsigned.
2029 const SCEV *CastedMaxBECount =
2030 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2031 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2032 CastedMaxBECount, MaxBECount->getType(), Depth);
2033 if (MaxBECount == RecastedMaxBECount) {
2034 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2035 // Check whether Start+Step*MaxBECount has no signed overflow.
2036 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2037 SCEV::FlagAnyWrap, Depth + 1);
2038 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2039 SCEV::FlagAnyWrap,
2040 Depth + 1),
2041 WideTy, Depth + 1);
2042 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2043 const SCEV *WideMaxBECount =
2044 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2045 const SCEV *OperandExtendedAdd =
2046 getAddExpr(WideStart,
2047 getMulExpr(WideMaxBECount,
2048 getSignExtendExpr(Step, WideTy, Depth + 1),
2049 SCEV::FlagAnyWrap, Depth + 1),
2050 SCEV::FlagAnyWrap, Depth + 1);
2051 if (SAdd == OperandExtendedAdd) {
2052 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2053 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2054 // Return the expression with the addrec on the outside.
2055 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2056 Depth + 1);
2057 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2058 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2059 }
2060 // Similar to above, only this time treat the step value as unsigned.
2061 // This covers loops that count up with an unsigned step.
2062 OperandExtendedAdd =
2063 getAddExpr(WideStart,
2064 getMulExpr(WideMaxBECount,
2065 getZeroExtendExpr(Step, WideTy, Depth + 1),
2066 SCEV::FlagAnyWrap, Depth + 1),
2067 SCEV::FlagAnyWrap, Depth + 1);
2068 if (SAdd == OperandExtendedAdd) {
2069 // If AR wraps around then
2070 //
2071 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2072 // => SAdd != OperandExtendedAdd
2073 //
2074 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2075 // (SAdd == OperandExtendedAdd => AR is NW)
2076
2077 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2078
2079 // Return the expression with the addrec on the outside.
2080 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2081 Depth + 1);
2082 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2083 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2084 }
2085 }
2086 }
2087
2088 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2089 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2090 if (AR->hasNoSignedWrap()) {
2091 // Same as nsw case above - duplicated here to avoid a compile time
2092 // issue. It's not clear that the order of checks does matter, but
2093 // it's one of two issue possible causes for a change which was
2094 // reverted. Be conservative for the moment.
2095 Start =
2096 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2097 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2098 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2099 }
2100
2101 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2102 // if D + (C - D + Step * n) could be proven to not signed wrap
2103 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2104 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2105 const APInt &C = SC->getAPInt();
2106 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2107 if (D != 0) {
2108 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2109 const SCEV *SResidual =
2110 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2111 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2112 return getAddExpr(SSExtD, SSExtR,
2113 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2114 Depth + 1);
2115 }
2116 }
2117
2118 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2119 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2120 Start =
2121 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2122 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2123 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2124 }
2125 }
2126
2127 // If the input value is provably positive and we could not simplify
2128 // away the sext build a zext instead.
2129 if (isKnownNonNegative(Op))
2130 return getZeroExtendExpr(Op, Ty, Depth + 1);
2131
2132 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2133 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2134 if (isa<SCEVSMinExpr>(Op) || isa<SCEVSMaxExpr>(Op)) {
2135 auto *MinMax = cast<SCEVMinMaxExpr>(Op);
2136 SmallVector<const SCEV *, 4> Operands;
2137 for (auto *Operand : MinMax->operands())
2138 Operands.push_back(getSignExtendExpr(Operand, Ty));
2139 if (isa<SCEVSMinExpr>(MinMax))
2140 return getSMinExpr(Operands);
2141 return getSMaxExpr(Operands);
2142 }
2143
2144 // The cast wasn't folded; create an explicit cast node.
2145 // Recompute the insert position, as it may have been invalidated.
2146 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2147 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2148 Op, Ty);
2149 UniqueSCEVs.InsertNode(S, IP);
2150 registerUser(S, { Op });
2151 return S;
2152}
2153
2154const SCEV *ScalarEvolution::getCastExpr(SCEVTypes Kind, const SCEV *Op,
2155 Type *Ty) {
2156 switch (Kind) {
2157 case scTruncate:
2158 return getTruncateExpr(Op, Ty);
2159 case scZeroExtend:
2160 return getZeroExtendExpr(Op, Ty);
2161 case scSignExtend:
2162 return getSignExtendExpr(Op, Ty);
2163 case scPtrToInt:
2164 return getPtrToIntExpr(Op, Ty);
2165 default:
2166 llvm_unreachable("Not a SCEV cast expression!")::llvm::llvm_unreachable_internal("Not a SCEV cast expression!"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 2166)
;
2167 }
2168}
2169
2170/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2171/// unspecified bits out to the given type.
2172const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2173 Type *Ty) {
2174 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&(static_cast <bool> (getTypeSizeInBits(Op->getType()
) < getTypeSizeInBits(Ty) && "This is not an extending conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 2175, __extension__
__PRETTY_FUNCTION__))
2175 "This is not an extending conversion!")(static_cast <bool> (getTypeSizeInBits(Op->getType()
) < getTypeSizeInBits(Ty) && "This is not an extending conversion!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 2175, __extension__
__PRETTY_FUNCTION__))
;
2176 assert(isSCEVable(Ty) &&(static_cast <bool> (isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 2177, __extension__
__PRETTY_FUNCTION__))
2177 "This is not a conversion to a SCEVable type!")(static_cast <bool> (isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 2177, __extension__
__PRETTY_FUNCTION__))
;
2178 Ty = getEffectiveSCEVType(Ty);
2179
2180 // Sign-extend negative constants.
2181 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2182 if (SC->getAPInt().isNegative())
2183 return getSignExtendExpr(Op, Ty);
2184
2185 // Peel off a truncate cast.
2186 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2187 const SCEV *NewOp = T->getOperand();
2188 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2189 return getAnyExtendExpr(NewOp, Ty);
2190 return getTruncateOrNoop(NewOp, Ty);
2191 }
2192
2193 // Next try a zext cast. If the cast is folded, use it.
2194 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2195 if (!isa<SCEVZeroExtendExpr>(ZExt))
2196 return ZExt;
2197
2198 // Next try a sext cast. If the cast is folded, use it.
2199 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2200 if (!isa<SCEVSignExtendExpr>(SExt))
2201 return SExt;
2202
2203 // Force the cast to be folded into the operands of an addrec.
2204 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2205 SmallVector<const SCEV *, 4> Ops;
2206 for (const SCEV *Op : AR->operands())
2207 Ops.push_back(getAnyExtendExpr(Op, Ty));
2208 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2209 }
2210
2211 // If the expression is obviously signed, use the sext cast value.
2212 if (isa<SCEVSMaxExpr>(Op))
2213 return SExt;
2214
2215 // Absent any other information, use the zext cast value.
2216 return ZExt;
2217}
2218
2219/// Process the given Ops list, which is a list of operands to be added under
2220/// the given scale, update the given map. This is a helper function for
2221/// getAddRecExpr. As an example of what it does, given a sequence of operands
2222/// that would form an add expression like this:
2223///
2224/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2225///
2226/// where A and B are constants, update the map with these values:
2227///
2228/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2229///
2230/// and add 13 + A*B*29 to AccumulatedConstant.
2231/// This will allow getAddRecExpr to produce this:
2232///
2233/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2234///
2235/// This form often exposes folding opportunities that are hidden in
2236/// the original operand list.
2237///
2238/// Return true iff it appears that any interesting folding opportunities
2239/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2240/// the common case where no interesting opportunities are present, and
2241/// is also used as a check to avoid infinite recursion.
2242static bool
2243CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2244 SmallVectorImpl<const SCEV *> &NewOps,
2245 APInt &AccumulatedConstant,
2246 ArrayRef<const SCEV *> Ops, const APInt &Scale,
2247 ScalarEvolution &SE) {
2248 bool Interesting = false;
2249
2250 // Iterate over the add operands. They are sorted, with constants first.
2251 unsigned i = 0;
2252 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2253 ++i;
2254 // Pull a buried constant out to the outside.
2255 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2256 Interesting = true;
2257 AccumulatedConstant += Scale * C->getAPInt();
2258 }
2259
2260 // Next comes everything else. We're especially interested in multiplies
2261 // here, but they're in the middle, so just visit the rest with one loop.
2262 for (; i != Ops.size(); ++i) {
2263 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2264 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2265 APInt NewScale =
2266 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2267 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2268 // A multiplication of a constant with another add; recurse.
2269 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2270 Interesting |=
2271 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2272 Add->operands(), NewScale, SE);
2273 } else {
2274 // A multiplication of a constant with some other value. Update
2275 // the map.
2276 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
2277 const SCEV *Key = SE.getMulExpr(MulOps);
2278 auto Pair = M.insert({Key, NewScale});
2279 if (Pair.second) {
2280 NewOps.push_back(Pair.first->first);
2281 } else {
2282 Pair.first->second += NewScale;
2283 // The map already had an entry for this value, which may indicate
2284 // a folding opportunity.
2285 Interesting = true;
2286 }
2287 }
2288 } else {
2289 // An ordinary operand. Update the map.
2290 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2291 M.insert({Ops[i], Scale});
2292 if (Pair.second) {
2293 NewOps.push_back(Pair.first->first);
2294 } else {
2295 Pair.first->second += Scale;
2296 // The map already had an entry for this value, which may indicate
2297 // a folding opportunity.
2298 Interesting = true;
2299 }
2300 }
2301 }
2302
2303 return Interesting;
2304}
2305
2306bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
2307 const SCEV *LHS, const SCEV *RHS,
2308 const Instruction *CtxI) {
2309 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
2310 SCEV::NoWrapFlags, unsigned);
2311 switch (BinOp) {
2312 default:
2313 llvm_unreachable("Unsupported binary op")::llvm::llvm_unreachable_internal("Unsupported binary op", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 2313)
;
2314 case Instruction::Add:
2315 Operation = &ScalarEvolution::getAddExpr;
2316 break;
2317 case Instruction::Sub:
2318 Operation = &ScalarEvolution::getMinusSCEV;
2319 break;
2320 case Instruction::Mul:
2321 Operation = &ScalarEvolution::getMulExpr;
2322 break;
2323 }
2324
2325 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2326 Signed ? &ScalarEvolution::getSignExtendExpr
2327 : &ScalarEvolution::getZeroExtendExpr;
2328
2329 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2330 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2331 auto *WideTy =
2332 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2333
2334 const SCEV *A = (this->*Extension)(
2335 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2336 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2337 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2338 const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2339 if (A == B)
2340 return true;
2341 // Can we use context to prove the fact we need?
2342 if (!CtxI)
2343 return false;
2344 // TODO: Support mul.
2345 if (BinOp == Instruction::Mul)
2346 return false;
2347 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2348 // TODO: Lift this limitation.
2349 if (!RHSC)
2350 return false;
2351 APInt C = RHSC->getAPInt();
2352 unsigned NumBits = C.getBitWidth();
2353 bool IsSub = (BinOp == Instruction::Sub);
2354 bool IsNegativeConst = (Signed && C.isNegative());
2355 // Compute the direction and magnitude by which we need to check overflow.
2356 bool OverflowDown = IsSub ^ IsNegativeConst;
2357 APInt Magnitude = C;
2358 if (IsNegativeConst) {
2359 if (C == APInt::getSignedMinValue(NumBits))
2360 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2361 // want to deal with that.
2362 return false;
2363 Magnitude = -C;
2364 }
2365
2366 ICmpInst::Predicate Pred = Signed ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
2367 if (OverflowDown) {
2368 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2369 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2370 : APInt::getMinValue(NumBits);
2371 APInt Limit = Min + Magnitude;
2372 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2373 } else {
2374 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2375 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2376 : APInt::getMaxValue(NumBits);
2377 APInt Limit = Max - Magnitude;
2378 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2379 }
2380}
2381
2382std::optional<SCEV::NoWrapFlags>
2383ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp(
2384 const OverflowingBinaryOperator *OBO) {
2385 // It cannot be done any better.
2386 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2387 return std::nullopt;
2388
2389 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2390
2391 if (OBO->hasNoUnsignedWrap())
2392 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2393 if (OBO->hasNoSignedWrap())
2394 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2395
2396 bool Deduced = false;
2397
2398 if (OBO->getOpcode() != Instruction::Add &&
2399 OBO->getOpcode() != Instruction::Sub &&
2400 OBO->getOpcode() != Instruction::Mul)
2401 return std::nullopt;
2402
2403 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2404 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2405
2406 const Instruction *CtxI =
2407 UseContextForNoWrapFlagInference ? dyn_cast<Instruction>(OBO) : nullptr;
2408 if (!OBO->hasNoUnsignedWrap() &&
2409 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2410 /* Signed */ false, LHS, RHS, CtxI)) {
2411 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2412 Deduced = true;
2413 }
2414
2415 if (!OBO->hasNoSignedWrap() &&
2416 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
2417 /* Signed */ true, LHS, RHS, CtxI)) {
2418 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2419 Deduced = true;
2420 }
2421
2422 if (Deduced)
2423 return Flags;
2424 return std::nullopt;
2425}
2426
2427// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2428// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2429// can't-overflow flags for the operation if possible.
2430static SCEV::NoWrapFlags
2431StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2432 const ArrayRef<const SCEV *> Ops,
2433 SCEV::NoWrapFlags Flags) {
2434 using namespace std::placeholders;
2435
2436 using OBO = OverflowingBinaryOperator;
2437
2438 bool CanAnalyze =
2439 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2440 (void)CanAnalyze;
2441 assert(CanAnalyze && "don't call from other places!")(static_cast <bool> (CanAnalyze && "don't call from other places!"
) ? void (0) : __assert_fail ("CanAnalyze && \"don't call from other places!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 2441, __extension__
__PRETTY_FUNCTION__))
;
2442
2443 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2444 SCEV::NoWrapFlags SignOrUnsignWrap =
2445 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2446
2447 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2448 auto IsKnownNonNegative = [&](const SCEV *S) {
2449 return SE->isKnownNonNegative(S);
2450 };
2451
2452 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2453 Flags =
2454 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2455
2456 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2457
2458 if (SignOrUnsignWrap != SignOrUnsignMask &&
2459 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2460 isa<SCEVConstant>(Ops[0])) {
2461
2462 auto Opcode = [&] {
2463 switch (Type) {
2464 case scAddExpr:
2465 return Instruction::Add;
2466 case scMulExpr:
2467 return Instruction::Mul;
2468 default:
2469 llvm_unreachable("Unexpected SCEV op.")::llvm::llvm_unreachable_internal("Unexpected SCEV op.", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 2469)
;
2470 }
2471 }();
2472
2473 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2474
2475 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2476 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2477 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2478 Opcode, C, OBO::NoSignedWrap);
2479 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2480 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2481 }
2482
2483 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2484 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2485 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2486 Opcode, C, OBO::NoUnsignedWrap);
2487 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2488 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2489 }
2490 }
2491
2492 // <0,+,nonnegative><nw> is also nuw
2493 // TODO: Add corresponding nsw case
2494 if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) &&
2495 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2496 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2497 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2498
2499 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2500 if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) &&
2501 Ops.size() == 2) {
2502 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2503 if (UDiv->getOperand(1) == Ops[1])
2504 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2505 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2506 if (UDiv->getOperand(1) == Ops[0])
2507 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2508 }
2509
2510 return Flags;
2511}
2512
2513bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2514 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2515}
2516
2517/// Get a canonical add expression, or something simpler if possible.
2518const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2519 SCEV::NoWrapFlags OrigFlags,
2520 unsigned Depth) {
2521 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&(static_cast <bool> (!(OrigFlags & ~(SCEV::FlagNUW |
SCEV::FlagNSW)) && "only nuw or nsw allowed") ? void
(0) : __assert_fail ("!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && \"only nuw or nsw allowed\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 2522, __extension__
__PRETTY_FUNCTION__))
2522 "only nuw or nsw allowed")(static_cast <bool> (!(OrigFlags & ~(SCEV::FlagNUW |
SCEV::FlagNSW)) && "only nuw or nsw allowed") ? void
(0) : __assert_fail ("!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && \"only nuw or nsw allowed\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 2522, __extension__
__PRETTY_FUNCTION__))
;
2523 assert(!Ops.empty() && "Cannot get empty add!")(static_cast <bool> (!Ops.empty() && "Cannot get empty add!"
) ? void (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty add!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 2523, __extension__
__PRETTY_FUNCTION__))
;
2524 if (Ops.size() == 1) return Ops[0];
2525#ifndef NDEBUG
2526 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2527 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2528 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&(static_cast <bool> (getEffectiveSCEVType(Ops[i]->getType
()) == ETy && "SCEVAddExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVAddExpr operand types don't match!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 2529, __extension__
__PRETTY_FUNCTION__))
2529 "SCEVAddExpr operand types don't match!")(static_cast <bool> (getEffectiveSCEVType(Ops[i]->getType
()) == ETy && "SCEVAddExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVAddExpr operand types don't match!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 2529, __extension__
__PRETTY_FUNCTION__))
;
2530 unsigned NumPtrs = count_if(
2531 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2532 assert(NumPtrs <= 1 && "add has at most one pointer operand")(static_cast <bool> (NumPtrs <= 1 && "add has at most one pointer operand"
) ? void (0) : __assert_fail ("NumPtrs <= 1 && \"add has at most one pointer operand\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 2532, __extension__
__PRETTY_FUNCTION__))
;
2533#endif
2534
2535 // Sort by complexity, this groups all similar expression types together.
2536 GroupByComplexity(Ops, &LI, DT);
2537
2538 // If there are any constants, fold them together.
2539 unsigned Idx = 0;
2540 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2541 ++Idx;
2542 assert(Idx < Ops.size())(static_cast <bool> (Idx < Ops.size()) ? void (0) : __assert_fail
("Idx < Ops.size()", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 2542, __extension__ __PRETTY_FUNCTION__))
;
2543 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2544 // We found two constants, fold them together!
2545 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2546 if (Ops.size() == 2) return Ops[0];
2547 Ops.erase(Ops.begin()+1); // Erase the folded element
2548 LHSC = cast<SCEVConstant>(Ops[0]);
2549 }
2550
2551 // If we are left with a constant zero being added, strip it off.
2552 if (LHSC->getValue()->isZero()) {
2553 Ops.erase(Ops.begin());
2554 --Idx;
2555 }
2556
2557 if (Ops.size() == 1) return Ops[0];
2558 }
2559
2560 // Delay expensive flag strengthening until necessary.
2561 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2562 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2563 };
2564
2565 // Limit recursion calls depth.
2566 if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2567 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2568
2569 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2570 // Don't strengthen flags if we have no new information.
2571 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2572 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2573 Add->setNoWrapFlags(ComputeFlags(Ops));
2574 return S;
2575 }
2576
2577 // Okay, check to see if the same value occurs in the operand list more than
2578 // once. If so, merge them together into an multiply expression. Since we
2579 // sorted the list, these values are required to be adjacent.
2580 Type *Ty = Ops[0]->getType();
2581 bool FoundMatch = false;
2582 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2583 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2584 // Scan ahead to count how many equal operands there are.
2585 unsigned Count = 2;
2586 while (i+Count != e && Ops[i+Count] == Ops[i])
2587 ++Count;
2588 // Merge the values into a multiply.
2589 const SCEV *Scale = getConstant(Ty, Count);
2590 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2591 if (Ops.size() == Count)
2592 return Mul;
2593 Ops[i] = Mul;
2594 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2595 --i; e -= Count - 1;
2596 FoundMatch = true;
2597 }
2598 if (FoundMatch)
2599 return getAddExpr(Ops, OrigFlags, Depth + 1);
2600
2601 // Check for truncates. If all the operands are truncated from the same
2602 // type, see if factoring out the truncate would permit the result to be
2603 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2604 // if the contents of the resulting outer trunc fold to something simple.
2605 auto FindTruncSrcType = [&]() -> Type * {
2606 // We're ultimately looking to fold an addrec of truncs and muls of only
2607 // constants and truncs, so if we find any other types of SCEV
2608 // as operands of the addrec then we bail and return nullptr here.
2609 // Otherwise, we return the type of the operand of a trunc that we find.
2610 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2611 return T->getOperand()->getType();
2612 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2613 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2614 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2615 return T->getOperand()->getType();
2616 }
2617 return nullptr;
2618 };
2619 if (auto *SrcType = FindTruncSrcType()) {
2620 SmallVector<const SCEV *, 8> LargeOps;
2621 bool Ok = true;
2622 // Check all the operands to see if they can be represented in the
2623 // source type of the truncate.
2624 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2625 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2626 if (T->getOperand()->getType() != SrcType) {
2627 Ok = false;
2628 break;
2629 }
2630 LargeOps.push_back(T->getOperand());
2631 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2632 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2633 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2634 SmallVector<const SCEV *, 8> LargeMulOps;
2635 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2636 if (const SCEVTruncateExpr *T =
2637 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2638 if (T->getOperand()->getType() != SrcType) {
2639 Ok = false;
2640 break;
2641 }
2642 LargeMulOps.push_back(T->getOperand());
2643 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2644 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2645 } else {
2646 Ok = false;
2647 break;
2648 }
2649 }
2650 if (Ok)
2651 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2652 } else {
2653 Ok = false;
2654 break;
2655 }
2656 }
2657 if (Ok) {
2658 // Evaluate the expression in the larger type.
2659 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2660 // If it folds to something simple, use it. Otherwise, don't.
2661 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2662 return getTruncateExpr(Fold, Ty);
2663 }
2664 }
2665
2666 if (Ops.size() == 2) {
2667 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2668 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2669 // C1).
2670 const SCEV *A = Ops[0];
2671 const SCEV *B = Ops[1];
2672 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2673 auto *C = dyn_cast<SCEVConstant>(A);
2674 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2675 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2676 auto C2 = C->getAPInt();
2677 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2678
2679 APInt ConstAdd = C1 + C2;
2680 auto AddFlags = AddExpr->getNoWrapFlags();
2681 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2682 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) &&
2683 ConstAdd.ule(C1)) {
2684 PreservedFlags =
2685 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW);
2686 }
2687
2688 // Adding a constant with the same sign and small magnitude is NSW, if the
2689 // original AddExpr was NSW.
2690 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) &&
2691 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2692 ConstAdd.abs().ule(C1.abs())) {
2693 PreservedFlags =
2694 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW);
2695 }
2696
2697 if (PreservedFlags != SCEV::FlagAnyWrap) {
2698 SmallVector<const SCEV *, 4> NewOps(AddExpr->operands());
2699 NewOps[0] = getConstant(ConstAdd);
2700 return getAddExpr(NewOps, PreservedFlags);
2701 }
2702 }
2703 }
2704
2705 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2706 if (Ops.size() == 2) {
2707 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]);
2708 if (Mul && Mul->getNumOperands() == 2 &&
2709 Mul->getOperand(0)->isAllOnesValue()) {
2710 const SCEV *X;
2711 const SCEV *Y;
2712 if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) {
2713 return getMulExpr(Y, getUDivExpr(X, Y));
2714 }
2715 }
2716 }
2717
2718 // Skip past any other cast SCEVs.
2719 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2720 ++Idx;
2721
2722 // If there are add operands they would be next.
2723 if (Idx < Ops.size()) {
2724 bool DeletedAdd = false;
2725 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2726 // common NUW flag for expression after inlining. Other flags cannot be
2727 // preserved, because they may depend on the original order of operations.
2728 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2729 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2730 if (Ops.size() > AddOpsInlineThreshold ||
2731 Add->getNumOperands() > AddOpsInlineThreshold)
2732 break;
2733 // If we have an add, expand the add operands onto the end of the operands
2734 // list.
2735 Ops.erase(Ops.begin()+Idx);
2736 append_range(Ops, Add->operands());
2737 DeletedAdd = true;
2738 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2739 }
2740
2741 // If we deleted at least one add, we added operands to the end of the list,
2742 // and they are not necessarily sorted. Recurse to resort and resimplify
2743 // any operands we just acquired.
2744 if (DeletedAdd)
2745 return getAddExpr(Ops, CommonFlags, Depth + 1);
2746 }
2747
2748 // Skip over the add expression until we get to a multiply.
2749 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2750 ++Idx;
2751
2752 // Check to see if there are any folding opportunities present with
2753 // operands multiplied by constant values.
2754 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2755 uint64_t BitWidth = getTypeSizeInBits(Ty);
2756 DenseMap<const SCEV *, APInt> M;
2757 SmallVector<const SCEV *, 8> NewOps;
2758 APInt AccumulatedConstant(BitWidth, 0);
2759 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2760 Ops, APInt(BitWidth, 1), *this)) {
2761 struct APIntCompare {
2762 bool operator()(const APInt &LHS, const APInt &RHS) const {
2763 return LHS.ult(RHS);
2764 }
2765 };
2766
2767 // Some interesting folding opportunity is present, so its worthwhile to
2768 // re-generate the operands list. Group the operands by constant scale,
2769 // to avoid multiplying by the same constant scale multiple times.
2770 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2771 for (const SCEV *NewOp : NewOps)
2772 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2773 // Re-generate the operands list.
2774 Ops.clear();
2775 if (AccumulatedConstant != 0)
2776 Ops.push_back(getConstant(AccumulatedConstant));
2777 for (auto &MulOp : MulOpLists) {
2778 if (MulOp.first == 1) {
2779 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2780 } else if (MulOp.first != 0) {
2781 Ops.push_back(getMulExpr(
2782 getConstant(MulOp.first),
2783 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2784 SCEV::FlagAnyWrap, Depth + 1));
2785 }
2786 }
2787 if (Ops.empty())
2788 return getZero(Ty);
2789 if (Ops.size() == 1)
2790 return Ops[0];
2791 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2792 }
2793 }
2794
2795 // If we are adding something to a multiply expression, make sure the
2796 // something is not already an operand of the multiply. If so, merge it into
2797 // the multiply.
2798 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2799 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2800 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2801 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2802 if (isa<SCEVConstant>(MulOpSCEV))
2803 continue;
2804 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2805 if (MulOpSCEV == Ops[AddOp]) {
2806 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2807 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2808 if (Mul->getNumOperands() != 2) {
2809 // If the multiply has more than two operands, we must get the
2810 // Y*Z term.
2811 SmallVector<const SCEV *, 4> MulOps(
2812 Mul->operands().take_front(MulOp));
2813 append_range(MulOps, Mul->operands().drop_front(MulOp + 1));
2814 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2815 }
2816 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2817 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2818 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2819 SCEV::FlagAnyWrap, Depth + 1);
2820 if (Ops.size() == 2) return OuterMul;
2821 if (AddOp < Idx) {
2822 Ops.erase(Ops.begin()+AddOp);
2823 Ops.erase(Ops.begin()+Idx-1);
2824 } else {
2825 Ops.erase(Ops.begin()+Idx);
2826 Ops.erase(Ops.begin()+AddOp-1);
2827 }
2828 Ops.push_back(OuterMul);
2829 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2830 }
2831
2832 // Check this multiply against other multiplies being added together.
2833 for (unsigned OtherMulIdx = Idx+1;
2834 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2835 ++OtherMulIdx) {
2836 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2837 // If MulOp occurs in OtherMul, we can fold the two multiplies
2838 // together.
2839 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2840 OMulOp != e; ++OMulOp)
2841 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2842 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2843 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2844 if (Mul->getNumOperands() != 2) {
2845 SmallVector<const SCEV *, 4> MulOps(
2846 Mul->operands().take_front(MulOp));
2847 append_range(MulOps, Mul->operands().drop_front(MulOp+1));
2848 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2849 }
2850 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2851 if (OtherMul->getNumOperands() != 2) {
2852 SmallVector<const SCEV *, 4> MulOps(
2853 OtherMul->operands().take_front(OMulOp));
2854 append_range(MulOps, OtherMul->operands().drop_front(OMulOp+1));
2855 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2856 }
2857 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2858 const SCEV *InnerMulSum =
2859 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2860 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2861 SCEV::FlagAnyWrap, Depth + 1);
2862 if (Ops.size() == 2) return OuterMul;
2863 Ops.erase(Ops.begin()+Idx);
2864 Ops.erase(Ops.begin()+OtherMulIdx-1);
2865 Ops.push_back(OuterMul);
2866 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2867 }
2868 }
2869 }
2870 }
2871
2872 // If there are any add recurrences in the operands list, see if any other
2873 // added values are loop invariant. If so, we can fold them into the
2874 // recurrence.
2875 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2876 ++Idx;
2877
2878 // Scan over all recurrences, trying to fold loop invariants into them.
2879 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2880 // Scan all of the other operands to this add and add them to the vector if
2881 // they are loop invariant w.r.t. the recurrence.
2882 SmallVector<const SCEV *, 8> LIOps;
2883 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2884 const Loop *AddRecLoop = AddRec->getLoop();
2885 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2886 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2887 LIOps.push_back(Ops[i]);
2888 Ops.erase(Ops.begin()+i);
2889 --i; --e;
2890 }
2891
2892 // If we found some loop invariants, fold them into the recurrence.
2893 if (!LIOps.empty()) {
2894 // Compute nowrap flags for the addition of the loop-invariant ops and
2895 // the addrec. Temporarily push it as an operand for that purpose. These
2896 // flags are valid in the scope of the addrec only.
2897 LIOps.push_back(AddRec);
2898 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2899 LIOps.pop_back();
2900
2901 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2902 LIOps.push_back(AddRec->getStart());
2903
2904 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2905
2906 // It is not in general safe to propagate flags valid on an add within
2907 // the addrec scope to one outside it. We must prove that the inner
2908 // scope is guaranteed to execute if the outer one does to be able to
2909 // safely propagate. We know the program is undefined if poison is
2910 // produced on the inner scoped addrec. We also know that *for this use*
2911 // the outer scoped add can't overflow (because of the flags we just
2912 // computed for the inner scoped add) without the program being undefined.
2913 // Proving that entry to the outer scope neccesitates entry to the inner
2914 // scope, thus proves the program undefined if the flags would be violated
2915 // in the outer scope.
2916 SCEV::NoWrapFlags AddFlags = Flags;
2917 if (AddFlags != SCEV::FlagAnyWrap) {
2918 auto *DefI = getDefiningScopeBound(LIOps);
2919 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2920 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2921 AddFlags = SCEV::FlagAnyWrap;
2922 }
2923 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2924
2925 // Build the new addrec. Propagate the NUW and NSW flags if both the
2926 // outer add and the inner addrec are guaranteed to have no overflow.
2927 // Always propagate NW.
2928 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2929 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2930
2931 // If all of the other operands were loop invariant, we are done.
2932 if (Ops.size() == 1) return NewRec;
2933
2934 // Otherwise, add the folded AddRec by the non-invariant parts.
2935 for (unsigned i = 0;; ++i)
2936 if (Ops[i] == AddRec) {
2937 Ops[i] = NewRec;
2938 break;
2939 }
2940 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2941 }
2942
2943 // Okay, if there weren't any loop invariants to be folded, check to see if
2944 // there are multiple AddRec's with the same loop induction variable being
2945 // added together. If so, we can fold them.
2946 for (unsigned OtherIdx = Idx+1;
2947 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2948 ++OtherIdx) {
2949 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2950 // so that the 1st found AddRecExpr is dominated by all others.
2951 assert(DT.dominates((static_cast <bool> (DT.dominates( cast<SCEVAddRecExpr
>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->
getLoop()->getHeader()) && "AddRecExprs are not sorted in reverse dominance order?"
) ? void (0) : __assert_fail ("DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->getLoop()->getHeader()) && \"AddRecExprs are not sorted in reverse dominance order?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 2954, __extension__
__PRETTY_FUNCTION__))
2952 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),(static_cast <bool> (DT.dominates( cast<SCEVAddRecExpr
>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->
getLoop()->getHeader()) && "AddRecExprs are not sorted in reverse dominance order?"
) ? void (0) : __assert_fail ("DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->getLoop()->getHeader()) && \"AddRecExprs are not sorted in reverse dominance order?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 2954, __extension__
__PRETTY_FUNCTION__))
2953 AddRec->getLoop()->getHeader()) &&(static_cast <bool> (DT.dominates( cast<SCEVAddRecExpr
>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->
getLoop()->getHeader()) && "AddRecExprs are not sorted in reverse dominance order?"
) ? void (0) : __assert_fail ("DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->getLoop()->getHeader()) && \"AddRecExprs are not sorted in reverse dominance order?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 2954, __extension__
__PRETTY_FUNCTION__))
2954 "AddRecExprs are not sorted in reverse dominance order?")(static_cast <bool> (DT.dominates( cast<SCEVAddRecExpr
>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->
getLoop()->getHeader()) && "AddRecExprs are not sorted in reverse dominance order?"
) ? void (0) : __assert_fail ("DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->getLoop()->getHeader()) && \"AddRecExprs are not sorted in reverse dominance order?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 2954, __extension__
__PRETTY_FUNCTION__))
;
2955 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2956 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2957 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
2958 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2959 ++OtherIdx) {
2960 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2961 if (OtherAddRec->getLoop() == AddRecLoop) {
2962 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2963 i != e; ++i) {
2964 if (i >= AddRecOps.size()) {
2965 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2966 break;
2967 }
2968 SmallVector<const SCEV *, 2> TwoOps = {
2969 AddRecOps[i], OtherAddRec->getOperand(i)};
2970 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2971 }
2972 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2973 }
2974 }
2975 // Step size has changed, so we cannot guarantee no self-wraparound.
2976 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2977 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2978 }
2979 }
2980
2981 // Otherwise couldn't fold anything into this recurrence. Move onto the
2982 // next one.
2983 }
2984
2985 // Okay, it looks like we really DO need an add expr. Check to see if we
2986 // already have one, otherwise create a new one.
2987 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2988}
2989
2990const SCEV *
2991ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2992 SCEV::NoWrapFlags Flags) {
2993 FoldingSetNodeID ID;
2994 ID.AddInteger(scAddExpr);
2995 for (const SCEV *Op : Ops)
2996 ID.AddPointer(Op);
2997 void *IP = nullptr;
2998 SCEVAddExpr *S =
2999 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3000 if (!S) {
3001 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3002 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3003 S = new (SCEVAllocator)
3004 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
3005 UniqueSCEVs.InsertNode(S, IP);
3006 registerUser(S, Ops);
3007 }
3008 S->setNoWrapFlags(Flags);
3009 return S;
3010}
3011
3012const SCEV *
3013ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
3014 const Loop *L, SCEV::NoWrapFlags Flags) {
3015 FoldingSetNodeID ID;
3016 ID.AddInteger(scAddRecExpr);
3017 for (const SCEV *Op : Ops)
3018 ID.AddPointer(Op);
3019 ID.AddPointer(L);
3020 void *IP = nullptr;
3021 SCEVAddRecExpr *S =
3022 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3023 if (!S) {
3024 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3025 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3026 S = new (SCEVAllocator)
3027 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3028 UniqueSCEVs.InsertNode(S, IP);
3029 LoopUsers[L].push_back(S);
3030 registerUser(S, Ops);
3031 }
3032 setNoWrapFlags(S, Flags);
3033 return S;
3034}
3035
3036const SCEV *
3037ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
3038 SCEV::NoWrapFlags Flags) {
3039 FoldingSetNodeID ID;
3040 ID.AddInteger(scMulExpr);
3041 for (const SCEV *Op : Ops)
3042 ID.AddPointer(Op);
3043 void *IP = nullptr;
3044 SCEVMulExpr *S =
3045 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3046 if (!S) {
3047 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3048 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3049 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3050 O, Ops.size());
3051 UniqueSCEVs.InsertNode(S, IP);
3052 registerUser(S, Ops);
3053 }
3054 S->setNoWrapFlags(Flags);
3055 return S;
3056}
3057
3058static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3059 uint64_t k = i*j;
3060 if (j > 1 && k / j != i) Overflow = true;
3061 return k;
3062}
3063
3064/// Compute the result of "n choose k", the binomial coefficient. If an
3065/// intermediate computation overflows, Overflow will be set and the return will
3066/// be garbage. Overflow is not cleared on absence of overflow.
3067static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3068 // We use the multiplicative formula:
3069 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3070 // At each iteration, we take the n-th term of the numeral and divide by the
3071 // (k-n)th term of the denominator. This division will always produce an
3072 // integral result, and helps reduce the chance of overflow in the
3073 // intermediate computations. However, we can still overflow even when the
3074 // final result would fit.
3075
3076 if (n == 0 || n == k) return 1;
3077 if (k > n) return 0;
3078
3079 if (k > n/2)
3080 k = n-k;
3081
3082 uint64_t r = 1;
3083 for (uint64_t i = 1; i <= k; ++i) {
3084 r = umul_ov(r, n-(i-1), Overflow);
3085 r /= i;
3086 }
3087 return r;
3088}
3089
3090/// Determine if any of the operands in this SCEV are a constant or if
3091/// any of the add or multiply expressions in this SCEV contain a constant.
3092static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3093 struct FindConstantInAddMulChain {
3094 bool FoundConstant = false;
3095
3096 bool follow(const SCEV *S) {
3097 FoundConstant |= isa<SCEVConstant>(S);
3098 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3099 }
3100
3101 bool isDone() const {
3102 return FoundConstant;
3103 }
3104 };
3105
3106 FindConstantInAddMulChain F;
3107 SCEVTraversal<FindConstantInAddMulChain> ST(F);
3108 ST.visitAll(StartExpr);
3109 return F.FoundConstant;
3110}
3111
3112/// Get a canonical multiply expression, or something simpler if possible.
3113const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
3114 SCEV::NoWrapFlags OrigFlags,
3115 unsigned Depth) {
3116 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&(static_cast <bool> (OrigFlags == maskFlags(OrigFlags, SCEV
::FlagNUW | SCEV::FlagNSW) && "only nuw or nsw allowed"
) ? void (0) : __assert_fail ("OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && \"only nuw or nsw allowed\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3117, __extension__
__PRETTY_FUNCTION__))
3117 "only nuw or nsw allowed")(static_cast <bool> (OrigFlags == maskFlags(OrigFlags, SCEV
::FlagNUW | SCEV::FlagNSW) && "only nuw or nsw allowed"
) ? void (0) : __assert_fail ("OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && \"only nuw or nsw allowed\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3117, __extension__
__PRETTY_FUNCTION__))
;
3118 assert(!Ops.empty() && "Cannot get empty mul!")(static_cast <bool> (!Ops.empty() && "Cannot get empty mul!"
) ? void (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty mul!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3118, __extension__
__PRETTY_FUNCTION__))
;
3119 if (Ops.size() == 1) return Ops[0];
3120#ifndef NDEBUG
3121 Type *ETy = Ops[0]->getType();
3122 assert(!ETy->isPointerTy())(static_cast <bool> (!ETy->isPointerTy()) ? void (0)
: __assert_fail ("!ETy->isPointerTy()", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 3122, __extension__ __PRETTY_FUNCTION__))
;
3123 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3124 assert(Ops[i]->getType() == ETy &&(static_cast <bool> (Ops[i]->getType() == ETy &&
"SCEVMulExpr operand types don't match!") ? void (0) : __assert_fail
("Ops[i]->getType() == ETy && \"SCEVMulExpr operand types don't match!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3125, __extension__
__PRETTY_FUNCTION__))
3125 "SCEVMulExpr operand types don't match!")(static_cast <bool> (Ops[i]->getType() == ETy &&
"SCEVMulExpr operand types don't match!") ? void (0) : __assert_fail
("Ops[i]->getType() == ETy && \"SCEVMulExpr operand types don't match!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3125, __extension__
__PRETTY_FUNCTION__))
;
3126#endif
3127
3128 // Sort by complexity, this groups all similar expression types together.
3129 GroupByComplexity(Ops, &LI, DT);
3130
3131 // If there are any constants, fold them together.
3132 unsigned Idx = 0;
3133 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3134 ++Idx;
3135 assert(Idx < Ops.size())(static_cast <bool> (Idx < Ops.size()) ? void (0) : __assert_fail
("Idx < Ops.size()", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 3135, __extension__ __PRETTY_FUNCTION__))
;
3136 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3137 // We found two constants, fold them together!
3138 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
3139 if (Ops.size() == 2) return Ops[0];
3140 Ops.erase(Ops.begin()+1); // Erase the folded element
3141 LHSC = cast<SCEVConstant>(Ops[0]);
3142 }
3143
3144 // If we have a multiply of zero, it will always be zero.
3145 if (LHSC->getValue()->isZero())
3146 return LHSC;
3147
3148 // If we are left with a constant one being multiplied, strip it off.
3149 if (LHSC->getValue()->isOne()) {
3150 Ops.erase(Ops.begin());
3151 --Idx;
3152 }
3153
3154 if (Ops.size() == 1)
3155 return Ops[0];
3156 }
3157
3158 // Delay expensive flag strengthening until necessary.
3159 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
3160 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3161 };
3162
3163 // Limit recursion calls depth.
3164 if (Depth > MaxArithDepth || hasHugeExpression(Ops))
3165 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3166
3167 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3168 // Don't strengthen flags if we have no new information.
3169 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3170 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3171 Mul->setNoWrapFlags(ComputeFlags(Ops));
3172 return S;
3173 }
3174
3175 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3176 if (Ops.size() == 2) {
3177 // C1*(C2+V) -> C1*C2 + C1*V
3178 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
3179 // If any of Add's ops are Adds or Muls with a constant, apply this
3180 // transformation as well.
3181 //
3182 // TODO: There are some cases where this transformation is not
3183 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3184 // this transformation should be narrowed down.
3185 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) {
3186 const SCEV *LHS = getMulExpr(LHSC, Add->getOperand(0),
3187 SCEV::FlagAnyWrap, Depth + 1);
3188 const SCEV *RHS = getMulExpr(LHSC, Add->getOperand(1),
3189 SCEV::FlagAnyWrap, Depth + 1);
3190 return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3191 }
3192
3193 if (Ops[0]->isAllOnesValue()) {
3194 // If we have a mul by -1 of an add, try distributing the -1 among the
3195 // add operands.
3196 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3197 SmallVector<const SCEV *, 4> NewOps;
3198 bool AnyFolded = false;
3199 for (const SCEV *AddOp : Add->operands()) {
3200 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
3201 Depth + 1);
3202 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3203 NewOps.push_back(Mul);
3204 }
3205 if (AnyFolded)
3206 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3207 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3208 // Negation preserves a recurrence's no self-wrap property.
3209 SmallVector<const SCEV *, 4> Operands;
3210 for (const SCEV *AddRecOp : AddRec->operands())
3211 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
3212 Depth + 1));
3213 // Let M be the minimum representable signed value. AddRec with nsw
3214 // multiplied by -1 can have signed overflow if and only if it takes a
3215 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3216 // maximum signed value. In all other cases signed overflow is
3217 // impossible.
3218 auto FlagsMask = SCEV::FlagNW;
3219 if (hasFlags(AddRec->getNoWrapFlags(), SCEV::FlagNSW)) {
3220 auto MinInt =
3221 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3222 if (getSignedRangeMin(AddRec) != MinInt)
3223 FlagsMask = setFlags(FlagsMask, SCEV::FlagNSW);
3224 }
3225 return getAddRecExpr(Operands, AddRec->getLoop(),
3226 AddRec->getNoWrapFlags(FlagsMask));
3227 }
3228 }
3229 }
3230 }
3231
3232 // Skip over the add expression until we get to a multiply.
3233 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3234 ++Idx;
3235
3236 // If there are mul operands inline them all into this expression.
3237 if (Idx < Ops.size()) {
3238 bool DeletedMul = false;
3239 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3240 if (Ops.size() > MulOpsInlineThreshold)
3241 break;
3242 // If we have an mul, expand the mul operands onto the end of the
3243 // operands list.
3244 Ops.erase(Ops.begin()+Idx);
3245 append_range(Ops, Mul->operands());
3246 DeletedMul = true;
3247 }
3248
3249 // If we deleted at least one mul, we added operands to the end of the
3250 // list, and they are not necessarily sorted. Recurse to resort and
3251 // resimplify any operands we just acquired.
3252 if (DeletedMul)
3253 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3254 }
3255
3256 // If there are any add recurrences in the operands list, see if any other
3257 // added values are loop invariant. If so, we can fold them into the
3258 // recurrence.
3259 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3260 ++Idx;
3261
3262 // Scan over all recurrences, trying to fold loop invariants into them.
3263 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3264 // Scan all of the other operands to this mul and add them to the vector
3265 // if they are loop invariant w.r.t. the recurrence.
3266 SmallVector<const SCEV *, 8> LIOps;
3267 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3268 const Loop *AddRecLoop = AddRec->getLoop();
3269 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3270 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3271 LIOps.push_back(Ops[i]);
3272 Ops.erase(Ops.begin()+i);
3273 --i; --e;
3274 }
3275
3276 // If we found some loop invariants, fold them into the recurrence.
3277 if (!LIOps.empty()) {
3278 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3279 SmallVector<const SCEV *, 4> NewOps;
3280 NewOps.reserve(AddRec->getNumOperands());
3281 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3282 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3283 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3284 SCEV::FlagAnyWrap, Depth + 1));
3285
3286 // Build the new addrec. Propagate the NUW and NSW flags if both the
3287 // outer mul and the inner addrec are guaranteed to have no overflow.
3288 //
3289 // No self-wrap cannot be guaranteed after changing the step size, but
3290 // will be inferred if either NUW or NSW is true.
3291 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
3292 const SCEV *NewRec = getAddRecExpr(
3293 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
3294
3295 // If all of the other operands were loop invariant, we are done.
3296 if (Ops.size() == 1) return NewRec;
3297
3298 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3299 for (unsigned i = 0;; ++i)
3300 if (Ops[i] == AddRec) {
3301 Ops[i] = NewRec;
3302 break;
3303 }
3304 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3305 }
3306
3307 // Okay, if there weren't any loop invariants to be folded, check to see
3308 // if there are multiple AddRec's with the same loop induction variable
3309 // being multiplied together. If so, we can fold them.
3310
3311 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3312 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3313 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3314 // ]]],+,...up to x=2n}.
3315 // Note that the arguments to choose() are always integers with values
3316 // known at compile time, never SCEV objects.
3317 //
3318 // The implementation avoids pointless extra computations when the two
3319 // addrec's are of different length (mathematically, it's equivalent to
3320 // an infinite stream of zeros on the right).
3321 bool OpsModified = false;
3322 for (unsigned OtherIdx = Idx+1;
3323 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3324 ++OtherIdx) {
3325 const SCEVAddRecExpr *OtherAddRec =
3326 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3327 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3328 continue;
3329
3330 // Limit max number of arguments to avoid creation of unreasonably big
3331 // SCEVAddRecs with very complex operands.
3332 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3333 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3334 continue;
3335
3336 bool Overflow = false;
3337 Type *Ty = AddRec->getType();
3338 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3339 SmallVector<const SCEV*, 7> AddRecOps;
3340 for (int x = 0, xe = AddRec->getNumOperands() +
3341 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3342 SmallVector <const SCEV *, 7> SumOps;
3343 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3344 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3345 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3346 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3347 z < ze && !Overflow; ++z) {
3348 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3349 uint64_t Coeff;
3350 if (LargerThan64Bits)
3351 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3352 else
3353 Coeff = Coeff1*Coeff2;
3354 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3355 const SCEV *Term1 = AddRec->getOperand(y-z);
3356 const SCEV *Term2 = OtherAddRec->getOperand(z);
3357 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3358 SCEV::FlagAnyWrap, Depth + 1));
3359 }
3360 }
3361 if (SumOps.empty())
3362 SumOps.push_back(getZero(Ty));
3363 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3364 }
3365 if (!Overflow) {
3366 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3367 SCEV::FlagAnyWrap);
3368 if (Ops.size() == 2) return NewAddRec;
3369 Ops[Idx] = NewAddRec;
3370 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3371 OpsModified = true;
3372 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3373 if (!AddRec)
3374 break;
3375 }
3376 }
3377 if (OpsModified)
3378 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3379
3380 // Otherwise couldn't fold anything into this recurrence. Move onto the
3381 // next one.
3382 }
3383
3384 // Okay, it looks like we really DO need an mul expr. Check to see if we
3385 // already have one, otherwise create a new one.
3386 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3387}
3388
3389/// Represents an unsigned remainder expression based on unsigned division.
3390const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3391 const SCEV *RHS) {
3392 assert(getEffectiveSCEVType(LHS->getType()) ==(static_cast <bool> (getEffectiveSCEVType(LHS->getType
()) == getEffectiveSCEVType(RHS->getType()) && "SCEVURemExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVURemExpr operand types don't match!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3394, __extension__
__PRETTY_FUNCTION__))
3393 getEffectiveSCEVType(RHS->getType()) &&(static_cast <bool> (getEffectiveSCEVType(LHS->getType
()) == getEffectiveSCEVType(RHS->getType()) && "SCEVURemExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVURemExpr operand types don't match!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3394, __extension__
__PRETTY_FUNCTION__))
3394 "SCEVURemExpr operand types don't match!")(static_cast <bool> (getEffectiveSCEVType(LHS->getType
()) == getEffectiveSCEVType(RHS->getType()) && "SCEVURemExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVURemExpr operand types don't match!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3394, __extension__
__PRETTY_FUNCTION__))
;
3395
3396 // Short-circuit easy cases
3397 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3398 // If constant is one, the result is trivial
3399 if (RHSC->getValue()->isOne())
3400 return getZero(LHS->getType()); // X urem 1 --> 0
3401
3402 // If constant is a power of two, fold into a zext(trunc(LHS)).
3403 if (RHSC->getAPInt().isPowerOf2()) {
3404 Type *FullTy = LHS->getType();
3405 Type *TruncTy =
3406 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3407 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3408 }
3409 }
3410
3411 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3412 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3413 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3414 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3415}
3416
3417/// Get a canonical unsigned division expression, or something simpler if
3418/// possible.
3419const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3420 const SCEV *RHS) {
3421 assert(!LHS->getType()->isPointerTy() &&(static_cast <bool> (!LHS->getType()->isPointerTy
() && "SCEVUDivExpr operand can't be pointer!") ? void
(0) : __assert_fail ("!LHS->getType()->isPointerTy() && \"SCEVUDivExpr operand can't be pointer!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3422, __extension__
__PRETTY_FUNCTION__))
3422 "SCEVUDivExpr operand can't be pointer!")(static_cast <bool> (!LHS->getType()->isPointerTy
() && "SCEVUDivExpr operand can't be pointer!") ? void
(0) : __assert_fail ("!LHS->getType()->isPointerTy() && \"SCEVUDivExpr operand can't be pointer!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3422, __extension__
__PRETTY_FUNCTION__))
;
3423 assert(LHS->getType() == RHS->getType() &&(static_cast <bool> (LHS->getType() == RHS->getType
() && "SCEVUDivExpr operand types don't match!") ? void
(0) : __assert_fail ("LHS->getType() == RHS->getType() && \"SCEVUDivExpr operand types don't match!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3424, __extension__
__PRETTY_FUNCTION__))
3424 "SCEVUDivExpr operand types don't match!")(static_cast <bool> (LHS->getType() == RHS->getType
() && "SCEVUDivExpr operand types don't match!") ? void
(0) : __assert_fail ("LHS->getType() == RHS->getType() && \"SCEVUDivExpr operand types don't match!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3424, __extension__
__PRETTY_FUNCTION__))
;
3425
3426 FoldingSetNodeID ID;
3427 ID.AddInteger(scUDivExpr);
3428 ID.AddPointer(LHS);
3429 ID.AddPointer(RHS);
3430 void *IP = nullptr;
3431 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3432 return S;
3433
3434 // 0 udiv Y == 0
3435 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3436 if (LHSC->getValue()->isZero())
3437 return LHS;
3438
3439 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3440 if (RHSC->getValue()->isOne())
3441 return LHS; // X udiv 1 --> x
3442 // If the denominator is zero, the result of the udiv is undefined. Don't
3443 // try to analyze it, because the resolution chosen here may differ from
3444 // the resolution chosen in other parts of the compiler.
3445 if (!RHSC->getValue()->isZero()) {
3446 // Determine if the division can be folded into the operands of
3447 // its operands.
3448 // TODO: Generalize this to non-constants by using known-bits information.
3449 Type *Ty = LHS->getType();
3450 unsigned LZ = RHSC->getAPInt().countl_zero();
3451 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3452 // For non-power-of-two values, effectively round the value up to the
3453 // nearest power of two.
3454 if (!RHSC->getAPInt().isPowerOf2())
3455 ++MaxShiftAmt;
3456 IntegerType *ExtTy =
3457 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3458 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3459 if (const SCEVConstant *Step =
3460 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3461 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3462 const APInt &StepInt = Step->getAPInt();
3463 const APInt &DivInt = RHSC->getAPInt();
3464 if (!StepInt.urem(DivInt) &&
3465 getZeroExtendExpr(AR, ExtTy) ==
3466 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3467 getZeroExtendExpr(Step, ExtTy),
3468 AR->getLoop(), SCEV::FlagAnyWrap)) {
3469 SmallVector<const SCEV *, 4> Operands;
3470 for (const SCEV *Op : AR->operands())
3471 Operands.push_back(getUDivExpr(Op, RHS));
3472 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3473 }
3474 /// Get a canonical UDivExpr for a recurrence.
3475 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3476 // We can currently only fold X%N if X is constant.
3477 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3478 if (StartC && !DivInt.urem(StepInt) &&
3479 getZeroExtendExpr(AR, ExtTy) ==
3480 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3481 getZeroExtendExpr(Step, ExtTy),
3482 AR->getLoop(), SCEV::FlagAnyWrap)) {
3483 const APInt &StartInt = StartC->getAPInt();
3484 const APInt &StartRem = StartInt.urem(StepInt);
3485 if (StartRem != 0) {
3486 const SCEV *NewLHS =
3487 getAddRecExpr(getConstant(StartInt - StartRem), Step,
3488 AR->getLoop(), SCEV::FlagNW);
3489 if (LHS != NewLHS) {
3490 LHS = NewLHS;
3491
3492 // Reset the ID to include the new LHS, and check if it is
3493 // already cached.
3494 ID.clear();
3495 ID.AddInteger(scUDivExpr);
3496 ID.AddPointer(LHS);
3497 ID.AddPointer(RHS);
3498 IP = nullptr;
3499 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3500 return S;
3501 }
3502 }
3503 }
3504 }
3505 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3506 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3507 SmallVector<const SCEV *, 4> Operands;
3508 for (const SCEV *Op : M->operands())
3509 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3510 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3511 // Find an operand that's safely divisible.
3512 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3513 const SCEV *Op = M->getOperand(i);
3514 const SCEV *Div = getUDivExpr(Op, RHSC);
3515 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3516 Operands = SmallVector<const SCEV *, 4>(M->operands());
3517 Operands[i] = Div;
3518 return getMulExpr(Operands);
3519 }
3520 }
3521 }
3522
3523 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3524 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3525 if (auto *DivisorConstant =
3526 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3527 bool Overflow = false;
3528 APInt NewRHS =
3529 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3530 if (Overflow) {
3531 return getConstant(RHSC->getType(), 0, false);
3532 }
3533 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3534 }
3535 }
3536
3537 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3538 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3539 SmallVector<const SCEV *, 4> Operands;
3540 for (const SCEV *Op : A->operands())
3541 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3542 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3543 Operands.clear();
3544 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3545 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3546 if (isa<SCEVUDivExpr>(Op) ||
3547 getMulExpr(Op, RHS) != A->getOperand(i))
3548 break;
3549 Operands.push_back(Op);
3550 }
3551 if (Operands.size() == A->getNumOperands())
3552 return getAddExpr(Operands);
3553 }
3554 }
3555
3556 // Fold if both operands are constant.
3557 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3558 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3559 }
3560 }
3561
3562 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3563 // changes). Make sure we get a new one.
3564 IP = nullptr;
3565 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3566 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3567 LHS, RHS);
3568 UniqueSCEVs.InsertNode(S, IP);
3569 registerUser(S, {LHS, RHS});
3570 return S;
3571}
3572
3573APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3574 APInt A = C1->getAPInt().abs();
3575 APInt B = C2->getAPInt().abs();
3576 uint32_t ABW = A.getBitWidth();
3577 uint32_t BBW = B.getBitWidth();
3578
3579 if (ABW > BBW)
3580 B = B.zext(ABW);
3581 else if (ABW < BBW)
3582 A = A.zext(BBW);
3583
3584 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3585}
3586
3587/// Get a canonical unsigned division expression, or something simpler if
3588/// possible. There is no representation for an exact udiv in SCEV IR, but we
3589/// can attempt to remove factors from the LHS and RHS. We can't do this when
3590/// it's not exact because the udiv may be clearing bits.
3591const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3592 const SCEV *RHS) {
3593 // TODO: we could try to find factors in all sorts of things, but for now we
3594 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3595 // end of this file for inspiration.
3596
3597 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3598 if (!Mul || !Mul->hasNoUnsignedWrap())
3599 return getUDivExpr(LHS, RHS);
3600
3601 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3602 // If the mulexpr multiplies by a constant, then that constant must be the
3603 // first element of the mulexpr.
3604 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3605 if (LHSCst == RHSCst) {
3606 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
3607 return getMulExpr(Operands);
3608 }
3609
3610 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3611 // that there's a factor provided by one of the other terms. We need to
3612 // check.
3613 APInt Factor = gcd(LHSCst, RHSCst);
3614 if (!Factor.isIntN(1)) {
3615 LHSCst =
3616 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3617 RHSCst =
3618 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3619 SmallVector<const SCEV *, 2> Operands;
3620 Operands.push_back(LHSCst);
3621 append_range(Operands, Mul->operands().drop_front());
3622 LHS = getMulExpr(Operands);
3623 RHS = RHSCst;
3624 Mul = dyn_cast<SCEVMulExpr>(LHS);
3625 if (!Mul)
3626 return getUDivExactExpr(LHS, RHS);
3627 }
3628 }
3629 }
3630
3631 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3632 if (Mul->getOperand(i) == RHS) {
3633 SmallVector<const SCEV *, 2> Operands;
3634 append_range(Operands, Mul->operands().take_front(i));
3635 append_range(Operands, Mul->operands().drop_front(i + 1));
3636 return getMulExpr(Operands);
3637 }
3638 }
3639
3640 return getUDivExpr(LHS, RHS);
3641}
3642
3643/// Get an add recurrence expression for the specified loop. Simplify the
3644/// expression as much as possible.
3645const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3646 const Loop *L,
3647 SCEV::NoWrapFlags Flags) {
3648 SmallVector<const SCEV *, 4> Operands;
3649 Operands.push_back(Start);
3650 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3651 if (StepChrec->getLoop() == L) {
3652 append_range(Operands, StepChrec->operands());
3653 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3654 }
3655
3656 Operands.push_back(Step);
3657 return getAddRecExpr(Operands, L, Flags);
3658}
3659
3660/// Get an add recurrence expression for the specified loop. Simplify the
3661/// expression as much as possible.
3662const SCEV *
3663ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3664 const Loop *L, SCEV::NoWrapFlags Flags) {
3665 if (Operands.size() == 1) return Operands[0];
3666#ifndef NDEBUG
3667 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3668 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
3669 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&(static_cast <bool> (getEffectiveSCEVType(Operands[i]->
getType()) == ETy && "SCEVAddRecExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(Operands[i]->getType()) == ETy && \"SCEVAddRecExpr operand types don't match!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3670, __extension__
__PRETTY_FUNCTION__))
3670 "SCEVAddRecExpr operand types don't match!")(static_cast <bool> (getEffectiveSCEVType(Operands[i]->
getType()) == ETy && "SCEVAddRecExpr operand types don't match!"
) ? void (0) : __assert_fail ("getEffectiveSCEVType(Operands[i]->getType()) == ETy && \"SCEVAddRecExpr operand types don't match!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3670, __extension__
__PRETTY_FUNCTION__))
;
3671 assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer")(static_cast <bool> (!Operands[i]->getType()->isPointerTy
() && "Step must be integer") ? void (0) : __assert_fail
("!Operands[i]->getType()->isPointerTy() && \"Step must be integer\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3671, __extension__
__PRETTY_FUNCTION__))
;
3672 }
3673 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3674 assert(isLoopInvariant(Operands[i], L) &&(static_cast <bool> (isLoopInvariant(Operands[i], L) &&
"SCEVAddRecExpr operand is not loop-invariant!") ? void (0) :
__assert_fail ("isLoopInvariant(Operands[i], L) && \"SCEVAddRecExpr operand is not loop-invariant!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3675, __extension__
__PRETTY_FUNCTION__))
3675 "SCEVAddRecExpr operand is not loop-invariant!")(static_cast <bool> (isLoopInvariant(Operands[i], L) &&
"SCEVAddRecExpr operand is not loop-invariant!") ? void (0) :
__assert_fail ("isLoopInvariant(Operands[i], L) && \"SCEVAddRecExpr operand is not loop-invariant!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3675, __extension__
__PRETTY_FUNCTION__))
;
3676#endif
3677
3678 if (Operands.back()->isZero()) {
3679 Operands.pop_back();
3680 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3681 }
3682
3683 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3684 // use that information to infer NUW and NSW flags. However, computing a
3685 // BE count requires calling getAddRecExpr, so we may not yet have a
3686 // meaningful BE count at this point (and if we don't, we'd be stuck
3687 // with a SCEVCouldNotCompute as the cached BE count).
3688
3689 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3690
3691 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3692 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3693 const Loop *NestedLoop = NestedAR->getLoop();
3694 if (L->contains(NestedLoop)
3695 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3696 : (!NestedLoop->contains(L) &&
3697 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3698 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
3699 Operands[0] = NestedAR->getStart();
3700 // AddRecs require their operands be loop-invariant with respect to their
3701 // loops. Don't perform this transformation if it would break this
3702 // requirement.
3703 bool AllInvariant = all_of(
3704 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3705
3706 if (AllInvariant) {
3707 // Create a recurrence for the outer loop with the same step size.
3708 //
3709 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3710 // inner recurrence has the same property.
3711 SCEV::NoWrapFlags OuterFlags =
3712 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3713
3714 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3715 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3716 return isLoopInvariant(Op, NestedLoop);
3717 });
3718
3719 if (AllInvariant) {
3720 // Ok, both add recurrences are valid after the transformation.
3721 //
3722 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3723 // the outer recurrence has the same property.
3724 SCEV::NoWrapFlags InnerFlags =
3725 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3726 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3727 }
3728 }
3729 // Reset Operands to its original state.
3730 Operands[0] = NestedAR;
3731 }
3732 }
3733
3734 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3735 // already have one, otherwise create a new one.
3736 return getOrCreateAddRecExpr(Operands, L, Flags);
3737}
3738
3739const SCEV *
3740ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3741 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3742 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3743 // getSCEV(Base)->getType() has the same address space as Base->getType()
3744 // because SCEV::getType() preserves the address space.
3745 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3746 const bool AssumeInBoundsFlags = [&]() {
3747 if (!GEP->isInBounds())
3748 return false;
3749
3750 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3751 // but to do that, we have to ensure that said flag is valid in the entire
3752 // defined scope of the SCEV.
3753 auto *GEPI = dyn_cast<Instruction>(GEP);
3754 // TODO: non-instructions have global scope. We might be able to prove
3755 // some global scope cases
3756 return GEPI && isSCEVExprNeverPoison(GEPI);
3757 }();
3758
3759 SCEV::NoWrapFlags OffsetWrap =
3760 AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3761
3762 Type *CurTy = GEP->getType();
3763 bool FirstIter = true;
3764 SmallVector<const SCEV *, 4> Offsets;
3765 for (const SCEV *IndexExpr : IndexExprs) {
3766 // Compute the (potentially symbolic) offset in bytes for this index.
3767 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3768 // For a struct, add the member offset.
3769 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3770 unsigned FieldNo = Index->getZExtValue();
3771 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3772 Offsets.push_back(FieldOffset);
3773
3774 // Update CurTy to the type of the field at Index.
3775 CurTy = STy->getTypeAtIndex(Index);
3776 } else {
3777 // Update CurTy to its element type.
3778 if (FirstIter) {
3779 assert(isa<PointerType>(CurTy) &&(static_cast <bool> (isa<PointerType>(CurTy) &&
"The first index of a GEP indexes a pointer") ? void (0) : __assert_fail
("isa<PointerType>(CurTy) && \"The first index of a GEP indexes a pointer\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3780, __extension__
__PRETTY_FUNCTION__))
3780 "The first index of a GEP indexes a pointer")(static_cast <bool> (isa<PointerType>(CurTy) &&
"The first index of a GEP indexes a pointer") ? void (0) : __assert_fail
("isa<PointerType>(CurTy) && \"The first index of a GEP indexes a pointer\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3780, __extension__
__PRETTY_FUNCTION__))
;
3781 CurTy = GEP->getSourceElementType();
3782 FirstIter = false;
3783 } else {
3784 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3785 }
3786 // For an array, add the element offset, explicitly scaled.
3787 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3788 // Getelementptr indices are signed.
3789 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3790
3791 // Multiply the index by the element size to compute the element offset.
3792 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3793 Offsets.push_back(LocalOffset);
3794 }
3795 }
3796
3797 // Handle degenerate case of GEP without offsets.
3798 if (Offsets.empty())
3799 return BaseExpr;
3800
3801 // Add the offsets together, assuming nsw if inbounds.
3802 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3803 // Add the base address and the offset. We cannot use the nsw flag, as the
3804 // base address is unsigned. However, if we know that the offset is
3805 // non-negative, we can use nuw.
3806 SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset)
3807 ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3808 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3809 assert(BaseExpr->getType() == GEPExpr->getType() &&(static_cast <bool> (BaseExpr->getType() == GEPExpr->
getType() && "GEP should not change type mid-flight."
) ? void (0) : __assert_fail ("BaseExpr->getType() == GEPExpr->getType() && \"GEP should not change type mid-flight.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3810, __extension__
__PRETTY_FUNCTION__))
3810 "GEP should not change type mid-flight.")(static_cast <bool> (BaseExpr->getType() == GEPExpr->
getType() && "GEP should not change type mid-flight."
) ? void (0) : __assert_fail ("BaseExpr->getType() == GEPExpr->getType() && \"GEP should not change type mid-flight.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3810, __extension__
__PRETTY_FUNCTION__))
;
3811 return GEPExpr;
3812}
3813
3814SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3815 ArrayRef<const SCEV *> Ops) {
3816 FoldingSetNodeID ID;
3817 ID.AddInteger(SCEVType);
3818 for (const SCEV *Op : Ops)
3819 ID.AddPointer(Op);
3820 void *IP = nullptr;
3821 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3822}
3823
3824const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3825 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3826 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3827}
3828
3829const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3830 SmallVectorImpl<const SCEV *> &Ops) {
3831 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!")(static_cast <bool> (SCEVMinMaxExpr::isMinMaxType(Kind)
&& "Not a SCEVMinMaxExpr!") ? void (0) : __assert_fail
("SCEVMinMaxExpr::isMinMaxType(Kind) && \"Not a SCEVMinMaxExpr!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3831, __extension__
__PRETTY_FUNCTION__))
;
3832 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!")(static_cast <bool> (!Ops.empty() && "Cannot get empty (u|s)(min|max)!"
) ? void (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty (u|s)(min|max)!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3832, __extension__
__PRETTY_FUNCTION__))
;
3833 if (Ops.size() == 1) return Ops[0];
3834#ifndef NDEBUG
3835 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3836 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3837 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&(static_cast <bool> (getEffectiveSCEVType(Ops[i]->getType
()) == ETy && "Operand types don't match!") ? void (0
) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"Operand types don't match!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3838, __extension__
__PRETTY_FUNCTION__))
3838 "Operand types don't match!")(static_cast <bool> (getEffectiveSCEVType(Ops[i]->getType
()) == ETy && "Operand types don't match!") ? void (0
) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"Operand types don't match!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3838, __extension__
__PRETTY_FUNCTION__))
;
3839 assert(Ops[0]->getType()->isPointerTy() ==(static_cast <bool> (Ops[0]->getType()->isPointerTy
() == Ops[i]->getType()->isPointerTy() && "min/max should be consistently pointerish"
) ? void (0) : __assert_fail ("Ops[0]->getType()->isPointerTy() == Ops[i]->getType()->isPointerTy() && \"min/max should be consistently pointerish\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3841, __extension__
__PRETTY_FUNCTION__))
3840 Ops[i]->getType()->isPointerTy() &&(static_cast <bool> (Ops[0]->getType()->isPointerTy
() == Ops[i]->getType()->isPointerTy() && "min/max should be consistently pointerish"
) ? void (0) : __assert_fail ("Ops[0]->getType()->isPointerTy() == Ops[i]->getType()->isPointerTy() && \"min/max should be consistently pointerish\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3841, __extension__
__PRETTY_FUNCTION__))
3841 "min/max should be consistently pointerish")(static_cast <bool> (Ops[0]->getType()->isPointerTy
() == Ops[i]->getType()->isPointerTy() && "min/max should be consistently pointerish"
) ? void (0) : __assert_fail ("Ops[0]->getType()->isPointerTy() == Ops[i]->getType()->isPointerTy() && \"min/max should be consistently pointerish\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3841, __extension__
__PRETTY_FUNCTION__))
;
3842 }
3843#endif
3844
3845 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3846 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3847
3848 // Sort by complexity, this groups all similar expression types together.
3849 GroupByComplexity(Ops, &LI, DT);
3850
3851 // Check if we have created the same expression before.
3852 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3853 return S;
3854 }
3855
3856 // If there are any constants, fold them together.
3857 unsigned Idx = 0;
3858 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3859 ++Idx;
3860 assert(Idx < Ops.size())(static_cast <bool> (Idx < Ops.size()) ? void (0) : __assert_fail
("Idx < Ops.size()", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 3860, __extension__ __PRETTY_FUNCTION__))
;
3861 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3862 switch (Kind) {
3863 case scSMaxExpr:
3864 return APIntOps::smax(LHS, RHS);
3865 case scSMinExpr:
3866 return APIntOps::smin(LHS, RHS);
3867 case scUMaxExpr:
3868 return APIntOps::umax(LHS, RHS);
3869 case scUMinExpr:
3870 return APIntOps::umin(LHS, RHS);
3871 default:
3872 llvm_unreachable("Unknown SCEV min/max opcode")::llvm::llvm_unreachable_internal("Unknown SCEV min/max opcode"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3872)
;
3873 }
3874 };
3875
3876 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3877 // We found two constants, fold them together!
3878 ConstantInt *Fold = ConstantInt::get(
3879 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3880 Ops[0] = getConstant(Fold);
3881 Ops.erase(Ops.begin()+1); // Erase the folded element
3882 if (Ops.size() == 1) return Ops[0];
3883 LHSC = cast<SCEVConstant>(Ops[0]);
3884 }
3885
3886 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3887 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3888
3889 if (IsMax ? IsMinV : IsMaxV) {
3890 // If we are left with a constant minimum(/maximum)-int, strip it off.
3891 Ops.erase(Ops.begin());
3892 --Idx;
3893 } else if (IsMax ? IsMaxV : IsMinV) {
3894 // If we have a max(/min) with a constant maximum(/minimum)-int,
3895 // it will always be the extremum.
3896 return LHSC;
3897 }
3898
3899 if (Ops.size() == 1) return Ops[0];
3900 }
3901
3902 // Find the first operation of the same kind
3903 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3904 ++Idx;
3905
3906 // Check to see if one of the operands is of the same kind. If so, expand its
3907 // operands onto our operand list, and recurse to simplify.
3908 if (Idx < Ops.size()) {
3909 bool DeletedAny = false;
3910 while (Ops[Idx]->getSCEVType() == Kind) {
3911 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3912 Ops.erase(Ops.begin()+Idx);
3913 append_range(Ops, SMME->operands());
3914 DeletedAny = true;
3915 }
3916
3917 if (DeletedAny)
3918 return getMinMaxExpr(Kind, Ops);
3919 }
3920
3921 // Okay, check to see if the same value occurs in the operand list twice. If
3922 // so, delete one. Since we sorted the list, these values are required to
3923 // be adjacent.
3924 llvm::CmpInst::Predicate GEPred =
3925 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3926 llvm::CmpInst::Predicate LEPred =
3927 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3928 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3929 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3930 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3931 if (Ops[i] == Ops[i + 1] ||
3932 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3933 // X op Y op Y --> X op Y
3934 // X op Y --> X, if we know X, Y are ordered appropriately
3935 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3936 --i;
3937 --e;
3938 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3939 Ops[i + 1])) {
3940 // X op Y --> Y, if we know X, Y are ordered appropriately
3941 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3942 --i;
3943 --e;
3944 }
3945 }
3946
3947 if (Ops.size() == 1) return Ops[0];
3948
3949 assert(!Ops.empty() && "Reduced smax down to nothing!")(static_cast <bool> (!Ops.empty() && "Reduced smax down to nothing!"
) ? void (0) : __assert_fail ("!Ops.empty() && \"Reduced smax down to nothing!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3949, __extension__
__PRETTY_FUNCTION__))
;
3950
3951 // Okay, it looks like we really DO need an expr. Check to see if we
3952 // already have one, otherwise create a new one.
3953 FoldingSetNodeID ID;
3954 ID.AddInteger(Kind);
3955 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3956 ID.AddPointer(Ops[i]);
3957 void *IP = nullptr;
3958 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3959 if (ExistingSCEV)
3960 return ExistingSCEV;
3961 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3962 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3963 SCEV *S = new (SCEVAllocator)
3964 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3965
3966 UniqueSCEVs.InsertNode(S, IP);
3967 registerUser(S, Ops);
3968 return S;
3969}
3970
3971namespace {
3972
3973class SCEVSequentialMinMaxDeduplicatingVisitor final
3974 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3975 std::optional<const SCEV *>> {
3976 using RetVal = std::optional<const SCEV *>;
3977 using Base = SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, RetVal>;
3978
3979 ScalarEvolution &SE;
3980 const SCEVTypes RootKind; // Must be a sequential min/max expression.
3981 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3982 SmallPtrSet<const SCEV *, 16> SeenOps;
3983
3984 bool canRecurseInto(SCEVTypes Kind) const {
3985 // We can only recurse into the SCEV expression of the same effective type
3986 // as the type of our root SCEV expression.
3987 return RootKind == Kind || NonSequentialRootKind == Kind;
3988 };
3989
3990 RetVal visitAnyMinMaxExpr(const SCEV *S) {
3991 assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) &&(static_cast <bool> ((isa<SCEVMinMaxExpr>(S) || isa
<SCEVSequentialMinMaxExpr>(S)) && "Only for min/max expressions."
) ? void (0) : __assert_fail ("(isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) && \"Only for min/max expressions.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3992, __extension__
__PRETTY_FUNCTION__))
3992 "Only for min/max expressions.")(static_cast <bool> ((isa<SCEVMinMaxExpr>(S) || isa
<SCEVSequentialMinMaxExpr>(S)) && "Only for min/max expressions."
) ? void (0) : __assert_fail ("(isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) && \"Only for min/max expressions.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 3992, __extension__
__PRETTY_FUNCTION__))
;
3993 SCEVTypes Kind = S->getSCEVType();
3994
3995 if (!canRecurseInto(Kind))
3996 return S;
3997
3998 auto *NAry = cast<SCEVNAryExpr>(S);
3999 SmallVector<const SCEV *> NewOps;
4000 bool Changed = visit(Kind, NAry->operands(), NewOps);
4001
4002 if (!Changed)
4003 return S;
4004 if (NewOps.empty())
4005 return std::nullopt;
4006
4007 return isa<SCEVSequentialMinMaxExpr>(S)
4008 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4009 : SE.getMinMaxExpr(Kind, NewOps);
4010 }
4011
4012 RetVal visit(const SCEV *S) {
4013 // Has the whole operand been seen already?
4014 if (!SeenOps.insert(S).second)
4015 return std::nullopt;
4016 return Base::visit(S);
4017 }
4018
4019public:
4020 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4021 SCEVTypes RootKind)
4022 : SE(SE), RootKind(RootKind),
4023 NonSequentialRootKind(
4024 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4025 RootKind)) {}
4026
4027 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps,
4028 SmallVectorImpl<const SCEV *> &NewOps) {
4029 bool Changed = false;
4030 SmallVector<const SCEV *> Ops;
4031 Ops.reserve(OrigOps.size());
4032
4033 for (const SCEV *Op : OrigOps) {
4034 RetVal NewOp = visit(Op);
4035 if (NewOp != Op)
4036 Changed = true;
4037 if (NewOp)
4038 Ops.emplace_back(*NewOp);
4039 }
4040
4041 if (Changed)
4042 NewOps = std::move(Ops);
4043 return Changed;
4044 }
4045
4046 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
4047
4048 RetVal visitVScale(const SCEVVScale *VScale) { return VScale; }
4049
4050 RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; }
4051
4052 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
4053
4054 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
4055
4056 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
4057
4058 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
4059
4060 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
4061
4062 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
4063
4064 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
4065
4066 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
4067 return visitAnyMinMaxExpr(Expr);
4068 }
4069
4070 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
4071 return visitAnyMinMaxExpr(Expr);
4072 }
4073
4074 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
4075 return visitAnyMinMaxExpr(Expr);
4076 }
4077
4078 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4079 return visitAnyMinMaxExpr(Expr);
4080 }
4081
4082 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4083 return visitAnyMinMaxExpr(Expr);
4084 }
4085
4086 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4087
4088 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4089};
4090
4091} // namespace
4092
4093static bool scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind) {
4094 switch (Kind) {
4095 case scConstant:
4096 case scVScale:
4097 case scTruncate:
4098 case scZeroExtend:
4099 case scSignExtend:
4100 case scPtrToInt:
4101 case scAddExpr:
4102 case scMulExpr:
4103 case scUDivExpr:
4104 case scAddRecExpr:
4105 case scUMaxExpr:
4106 case scSMaxExpr:
4107 case scUMinExpr:
4108 case scSMinExpr:
4109 case scUnknown:
4110 // If any operand is poison, the whole expression is poison.
4111 return true;
4112 case scSequentialUMinExpr:
4113 // FIXME: if the *first* operand is poison, the whole expression is poison.
4114 return false; // Pessimistically, say that it does not propagate poison.
4115 case scCouldNotCompute:
4116 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4116)
;
4117 }
4118 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 4118)
;
4119}
4120
4121/// Return true if V is poison given that AssumedPoison is already poison.
4122static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4123 // The only way poison may be introduced in a SCEV expression is from a
4124 // poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4125 // not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4126 // introduce poison -- they encode guaranteed, non-speculated knowledge.
4127 //
4128 // Additionally, all SCEV nodes propagate poison from inputs to outputs,
4129 // with the notable exception of umin_seq, where only poison from the first
4130 // operand is (unconditionally) propagated.
4131 struct SCEVPoisonCollector {
4132 bool LookThroughMaybePoisonBlocking;
4133 SmallPtrSet<const SCEV *, 4> MaybePoison;
4134 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4135 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4136
4137 bool follow(const SCEV *S) {
4138 if (!LookThroughMaybePoisonBlocking &&
4139 !scevUnconditionallyPropagatesPoisonFromOperands(S->getSCEVType()))
4140 return false;
4141
4142 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4143 if (!isGuaranteedNotToBePoison(SU->getValue()))
4144 MaybePoison.insert(S);
4145 }
4146 return true;
4147 }
4148 bool isDone() const { return false; }
4149 };
4150
4151 // First collect all SCEVs that might result in AssumedPoison to be poison.
4152 // We need to look through potentially poison-blocking operations here,
4153 // because we want to find all SCEVs that *might* result in poison, not only
4154 // those that are *required* to.
4155 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4156 visitAll(AssumedPoison, PC1);
4157
4158 // AssumedPoison is never poison. As the assumption is false, the implication
4159 // is true. Don't bother walking the other SCEV in this case.
4160 if (PC1.MaybePoison.empty())
4161 return true;
4162
4163 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4164 // as well. We cannot look through potentially poison-blocking operations
4165 // here, as their arguments only *may* make the result poison.
4166 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4167 visitAll(S, PC2);
4168
4169 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4170 // it will also make S poison by being part of PC2.MaybePoison.
4171 return all_of(PC1.MaybePoison,
4172 [&](const SCEV *S) { return PC2.MaybePoison.contains(S); });
4173}
4174
4175const SCEV *
4176ScalarEvolution::getSequentialMinMaxExpr(SCEVTypes Kind,
4177 SmallVectorImpl<const SCEV *> &Ops) {
4178 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&(static_cast <bool> (SCEVSequentialMinMaxExpr::isSequentialMinMaxType
(Kind) && "Not a SCEVSequentialMinMaxExpr!") ? void (
0) : __assert_fail ("SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) && \"Not a SCEVSequentialMinMaxExpr!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4179, __extension__
__PRETTY_FUNCTION__))
4179 "Not a SCEVSequentialMinMaxExpr!")(static_cast <bool> (SCEVSequentialMinMaxExpr::isSequentialMinMaxType
(Kind) && "Not a SCEVSequentialMinMaxExpr!") ? void (
0) : __assert_fail ("SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) && \"Not a SCEVSequentialMinMaxExpr!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4179, __extension__
__PRETTY_FUNCTION__))
;
4180 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!")(static_cast <bool> (!Ops.empty() && "Cannot get empty (u|s)(min|max)!"
) ? void (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty (u|s)(min|max)!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4180, __extension__
__PRETTY_FUNCTION__))
;
4181 if (Ops.size() == 1)
4182 return Ops[0];
4183#ifndef NDEBUG
4184 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4185 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4186 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&(static_cast <bool> (getEffectiveSCEVType(Ops[i]->getType
()) == ETy && "Operand types don't match!") ? void (0
) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"Operand types don't match!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4187, __extension__
__PRETTY_FUNCTION__))
4187 "Operand types don't match!")(static_cast <bool> (getEffectiveSCEVType(Ops[i]->getType
()) == ETy && "Operand types don't match!") ? void (0
) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"Operand types don't match!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4187, __extension__
__PRETTY_FUNCTION__))
;
4188 assert(Ops[0]->getType()->isPointerTy() ==(static_cast <bool> (Ops[0]->getType()->isPointerTy
() == Ops[i]->getType()->isPointerTy() && "min/max should be consistently pointerish"
) ? void (0) : __assert_fail ("Ops[0]->getType()->isPointerTy() == Ops[i]->getType()->isPointerTy() && \"min/max should be consistently pointerish\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4190, __extension__
__PRETTY_FUNCTION__))
4189 Ops[i]->getType()->isPointerTy() &&(static_cast <bool> (Ops[0]->getType()->isPointerTy
() == Ops[i]->getType()->isPointerTy() && "min/max should be consistently pointerish"
) ? void (0) : __assert_fail ("Ops[0]->getType()->isPointerTy() == Ops[i]->getType()->isPointerTy() && \"min/max should be consistently pointerish\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4190, __extension__
__PRETTY_FUNCTION__))
4190 "min/max should be consistently pointerish")(static_cast <bool> (Ops[0]->getType()->isPointerTy
() == Ops[i]->getType()->isPointerTy() && "min/max should be consistently pointerish"
) ? void (0) : __assert_fail ("Ops[0]->getType()->isPointerTy() == Ops[i]->getType()->isPointerTy() && \"min/max should be consistently pointerish\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4190, __extension__
__PRETTY_FUNCTION__))
;
4191 }
4192#endif
4193
4194 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4195 // so we can *NOT* do any kind of sorting of the expressions!
4196
4197 // Check if we have created the same expression before.
4198 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4199 return S;
4200
4201 // FIXME: there are *some* simplifications that we can do here.
4202
4203 // Keep only the first instance of an operand.
4204 {
4205 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4206 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4207 if (Changed)
4208 return getSequentialMinMaxExpr(Kind, Ops);
4209 }
4210
4211 // Check to see if one of the operands is of the same kind. If so, expand its
4212 // operands onto our operand list, and recurse to simplify.
4213 {
4214 unsigned Idx = 0;
4215 bool DeletedAny = false;
4216 while (Idx < Ops.size()) {
4217 if (Ops[Idx]->getSCEVType() != Kind) {
4218 ++Idx;
4219 continue;
4220 }
4221 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4222 Ops.erase(Ops.begin() + Idx);
4223 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4224 SMME->operands().end());
4225 DeletedAny = true;
4226 }
4227
4228 if (DeletedAny)
4229 return getSequentialMinMaxExpr(Kind, Ops);
4230 }
4231
4232 const SCEV *SaturationPoint;
4233 ICmpInst::Predicate Pred;
4234 switch (Kind) {
4235 case scSequentialUMinExpr:
4236 SaturationPoint = getZero(Ops[0]->getType());
4237 Pred = ICmpInst::ICMP_ULE;
4238 break;
4239 default:
4240 llvm_unreachable("Not a sequential min/max type.")::llvm::llvm_unreachable_internal("Not a sequential min/max type."
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4240)
;
4241 }
4242
4243 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4244 // We can replace %x umin_seq %y with %x umin %y if either:
4245 // * %y being poison implies %x is also poison.
4246 // * %x cannot be the saturating value (e.g. zero for umin).
4247 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4248 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4249 SaturationPoint)) {
4250 SmallVector<const SCEV *> SeqOps = {Ops[i - 1], Ops[i]};
4251 Ops[i - 1] = getMinMaxExpr(
4252 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Kind),
4253 SeqOps);
4254 Ops.erase(Ops.begin() + i);
4255 return getSequentialMinMaxExpr(Kind, Ops);
4256 }
4257 // Fold %x umin_seq %y to %x if %x ule %y.
4258 // TODO: We might be able to prove the predicate for a later operand.
4259 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4260 Ops.erase(Ops.begin() + i);
4261 return getSequentialMinMaxExpr(Kind, Ops);
4262 }
4263 }
4264
4265 // Okay, it looks like we really DO need an expr. Check to see if we
4266 // already have one, otherwise create a new one.
4267 FoldingSetNodeID ID;
4268 ID.AddInteger(Kind);
4269 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
4270 ID.AddPointer(Ops[i]);
4271 void *IP = nullptr;
4272 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4273 if (ExistingSCEV)
4274 return ExistingSCEV;
4275
4276 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
4277 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
4278 SCEV *S = new (SCEVAllocator)
4279 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4280
4281 UniqueSCEVs.InsertNode(S, IP);
4282 registerUser(S, Ops);
4283 return S;
4284}
4285
4286const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4287 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4288 return getSMaxExpr(Ops);
4289}
4290
4291const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4292 return getMinMaxExpr(scSMaxExpr, Ops);
4293}
4294
4295const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
4296 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
4297 return getUMaxExpr(Ops);
4298}
4299
4300const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
4301 return getMinMaxExpr(scUMaxExpr, Ops);
4302}
4303
4304const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
4305 const SCEV *RHS) {
4306 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4307 return getSMinExpr(Ops);
4308}
4309
4310const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
4311 return getMinMaxExpr(scSMinExpr, Ops);
4312}
4313
4314const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS,
4315 bool Sequential) {
4316 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4317 return getUMinExpr(Ops, Sequential);
4318}
4319
4320const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops,
4321 bool Sequential) {
4322 return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops)
4323 : getMinMaxExpr(scUMinExpr, Ops);
4324}
4325
4326const SCEV *
4327ScalarEvolution::getSizeOfExpr(Type *IntTy, TypeSize Size) {
4328 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4329 if (Size.isScalable())
4330 Res = getMulExpr(Res, getVScale(IntTy));
4331 return Res;
4332}
4333
4334const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
4335 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4336}
4337
4338const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
4339 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4340}
4341
4342const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
4343 StructType *STy,
4344 unsigned FieldNo) {
4345 // We can bypass creating a target-independent constant expression and then
4346 // folding it back into a ConstantInt. This is just a compile-time
4347 // optimization.
4348 return getConstant(
4349 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
4350}
4351
4352const SCEV *ScalarEvolution::getUnknown(Value *V) {
4353 // Don't attempt to do anything other than create a SCEVUnknown object
4354 // here. createSCEV only calls getUnknown after checking for all other
4355 // interesting possibilities, and any other code that calls getUnknown
4356 // is doing so in order to hide a value from SCEV canonicalization.
4357
4358 FoldingSetNodeID ID;
4359 ID.AddInteger(scUnknown);
4360 ID.AddPointer(V);
4361 void *IP = nullptr;
4362 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4363 assert(cast<SCEVUnknown>(S)->getValue() == V &&(static_cast <bool> (cast<SCEVUnknown>(S)->getValue
() == V && "Stale SCEVUnknown in uniquing map!") ? void
(0) : __assert_fail ("cast<SCEVUnknown>(S)->getValue() == V && \"Stale SCEVUnknown in uniquing map!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4364, __extension__
__PRETTY_FUNCTION__))
4364 "Stale SCEVUnknown in uniquing map!")(static_cast <bool> (cast<SCEVUnknown>(S)->getValue
() == V && "Stale SCEVUnknown in uniquing map!") ? void
(0) : __assert_fail ("cast<SCEVUnknown>(S)->getValue() == V && \"Stale SCEVUnknown in uniquing map!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4364, __extension__
__PRETTY_FUNCTION__))
;
4365 return S;
4366 }
4367 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4368 FirstUnknown);
4369 FirstUnknown = cast<SCEVUnknown>(S);
4370 UniqueSCEVs.InsertNode(S, IP);
4371 return S;
4372}
4373
4374//===----------------------------------------------------------------------===//
4375// Basic SCEV Analysis and PHI Idiom Recognition Code
4376//
4377
4378/// Test if values of the given type are analyzable within the SCEV
4379/// framework. This primarily includes integer types, and it can optionally
4380/// include pointer types if the ScalarEvolution class has access to
4381/// target-specific information.
4382bool ScalarEvolution::isSCEVable(Type *Ty) const {
4383 // Integers and pointers are always SCEVable.
4384 return Ty->isIntOrPtrTy();
4385}
4386
4387/// Return the size in bits of the specified type, for which isSCEVable must
4388/// return true.
4389uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
4390 assert(isSCEVable(Ty) && "Type is not SCEVable!")(static_cast <bool> (isSCEVable(Ty) && "Type is not SCEVable!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"Type is not SCEVable!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4390, __extension__
__PRETTY_FUNCTION__))
;
4391 if (Ty->isPointerTy())
4392 return getDataLayout().getIndexTypeSizeInBits(Ty);
4393 return getDataLayout().getTypeSizeInBits(Ty);
4394}
4395
4396/// Return a type with the same bitwidth as the given type and which represents
4397/// how SCEV will treat the given type, for which isSCEVable must return
4398/// true. For pointer types, this is the pointer index sized integer type.
4399Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
4400 assert(isSCEVable(Ty) && "Type is not SCEVable!")(static_cast <bool> (isSCEVable(Ty) && "Type is not SCEVable!"
) ? void (0) : __assert_fail ("isSCEVable(Ty) && \"Type is not SCEVable!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4400, __extension__
__PRETTY_FUNCTION__))
;
4401
4402 if (Ty->isIntegerTy())
4403 return Ty;
4404
4405 // The only other support type is pointer.
4406 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!")(static_cast <bool> (Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"
) ? void (0) : __assert_fail ("Ty->isPointerTy() && \"Unexpected non-pointer non-integer type!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4406, __extension__
__PRETTY_FUNCTION__))
;
4407 return getDataLayout().getIndexType(Ty);
4408}
4409
4410Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
4411 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4412}
4413
4414bool ScalarEvolution::instructionCouldExistWitthOperands(const SCEV *A,
4415 const SCEV *B) {
4416 /// For a valid use point to exist, the defining scope of one operand
4417 /// must dominate the other.
4418 bool PreciseA, PreciseB;
4419 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4420 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4421 if (!PreciseA || !PreciseB)
4422 // Can't tell.
4423 return false;
4424 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4425 DT.dominates(ScopeB, ScopeA);
4426}
4427
4428
4429const SCEV *ScalarEvolution::getCouldNotCompute() {
4430 return CouldNotCompute.get();
4431}
4432
4433bool ScalarEvolution::checkValidity(const SCEV *S) const {
4434 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4435 auto *SU = dyn_cast<SCEVUnknown>(S);
4436 return SU && SU->getValue() == nullptr;
4437 });
4438
4439 return !ContainsNulls;
4440}
4441
4442bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
4443 HasRecMapType::iterator I = HasRecMap.find(S);
4444 if (I != HasRecMap.end())
4445 return I->second;
4446
4447 bool FoundAddRec =
4448 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4449 HasRecMap.insert({S, FoundAddRec});
4450 return FoundAddRec;
4451}
4452
4453/// Return the ValueOffsetPair set for \p S. \p S can be represented
4454/// by the value and offset from any ValueOffsetPair in the set.
4455ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4456 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4457 if (SI == ExprValueMap.end())
4458 return std::nullopt;
4459#ifndef NDEBUG
4460 if (VerifySCEVMap) {
4461 // Check there is no dangling Value in the set returned.
4462 for (Value *V : SI->second)
4463 assert(ValueExprMap.count(V))(static_cast <bool> (ValueExprMap.count(V)) ? void (0) :
__assert_fail ("ValueExprMap.count(V)", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 4463, __extension__ __PRETTY_FUNCTION__))
;
4464 }
4465#endif
4466 return SI->second.getArrayRef();
4467}
4468
4469/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4470/// cannot be used separately. eraseValueFromMap should be used to remove
4471/// V from ValueExprMap and ExprValueMap at the same time.
4472void ScalarEvolution::eraseValueFromMap(Value *V) {
4473 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4474 if (I != ValueExprMap.end()) {
4475 auto EVIt = ExprValueMap.find(I->second);
4476 bool Removed = EVIt->second.remove(V);
4477 (void) Removed;
4478 assert(Removed && "Value not in ExprValueMap?")(static_cast <bool> (Removed && "Value not in ExprValueMap?"
) ? void (0) : __assert_fail ("Removed && \"Value not in ExprValueMap?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4478, __extension__
__PRETTY_FUNCTION__))
;
4479 ValueExprMap.erase(I);
4480 }
4481}
4482
4483void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4484 // A recursive query may have already computed the SCEV. It should be
4485 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4486 // inferred nowrap flags.
4487 auto It = ValueExprMap.find_as(V);
4488 if (It == ValueExprMap.end()) {
4489 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4490 ExprValueMap[S].insert(V);
4491 }
4492}
4493
4494/// Determine whether this instruction is either not SCEVable or will always
4495/// produce a SCEVUnknown. We do not have to walk past such instructions when
4496/// invalidating.
4497static bool isAlwaysUnknown(const Instruction *I) {
4498 switch (I->getOpcode()) {
4499 case Instruction::Load:
4500 return true;
4501 default:
4502 return false;
4503 }
4504}
4505
4506/// Return an existing SCEV if it exists, otherwise analyze the expression and
4507/// create a new one.
4508const SCEV *ScalarEvolution::getSCEV(Value *V) {
4509 assert(isSCEVable(V->getType()) && "Value is not SCEVable!")(static_cast <bool> (isSCEVable(V->getType()) &&
"Value is not SCEVable!") ? void (0) : __assert_fail ("isSCEVable(V->getType()) && \"Value is not SCEVable!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4509, __extension__
__PRETTY_FUNCTION__))
;
4510
4511 if (const SCEV *S = getExistingSCEV(V))
4512 return S;
4513 const SCEV *S = createSCEVIter(V);
4514 assert((!isa<Instruction>(V) || !isAlwaysUnknown(cast<Instruction>(V)) ||(static_cast <bool> ((!isa<Instruction>(V) || !isAlwaysUnknown
(cast<Instruction>(V)) || isa<SCEVUnknown>(S)) &&
"isAlwaysUnknown() instruction is not SCEVUnknown") ? void (
0) : __assert_fail ("(!isa<Instruction>(V) || !isAlwaysUnknown(cast<Instruction>(V)) || isa<SCEVUnknown>(S)) && \"isAlwaysUnknown() instruction is not SCEVUnknown\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4516, __extension__
__PRETTY_FUNCTION__))
4515 isa<SCEVUnknown>(S)) &&(static_cast <bool> ((!isa<Instruction>(V) || !isAlwaysUnknown
(cast<Instruction>(V)) || isa<SCEVUnknown>(S)) &&
"isAlwaysUnknown() instruction is not SCEVUnknown") ? void (
0) : __assert_fail ("(!isa<Instruction>(V) || !isAlwaysUnknown(cast<Instruction>(V)) || isa<SCEVUnknown>(S)) && \"isAlwaysUnknown() instruction is not SCEVUnknown\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4516, __extension__
__PRETTY_FUNCTION__))
4516 "isAlwaysUnknown() instruction is not SCEVUnknown")(static_cast <bool> ((!isa<Instruction>(V) || !isAlwaysUnknown
(cast<Instruction>(V)) || isa<SCEVUnknown>(S)) &&
"isAlwaysUnknown() instruction is not SCEVUnknown") ? void (
0) : __assert_fail ("(!isa<Instruction>(V) || !isAlwaysUnknown(cast<Instruction>(V)) || isa<SCEVUnknown>(S)) && \"isAlwaysUnknown() instruction is not SCEVUnknown\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4516, __extension__
__PRETTY_FUNCTION__))
;
4517 return S;
4518}
4519
4520const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
4521 assert(isSCEVable(V->getType()) && "Value is not SCEVable!")(static_cast <bool> (isSCEVable(V->getType()) &&
"Value is not SCEVable!") ? void (0) : __assert_fail ("isSCEVable(V->getType()) && \"Value is not SCEVable!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4521, __extension__
__PRETTY_FUNCTION__))
;
4522
4523 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4524 if (I != ValueExprMap.end()) {
4525 const SCEV *S = I->second;
4526 assert(checkValidity(S) &&(static_cast <bool> (checkValidity(S) && "existing SCEV has not been properly invalidated"
) ? void (0) : __assert_fail ("checkValidity(S) && \"existing SCEV has not been properly invalidated\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4527, __extension__
__PRETTY_FUNCTION__))
4527 "existing SCEV has not been properly invalidated")(static_cast <bool> (checkValidity(S) && "existing SCEV has not been properly invalidated"
) ? void (0) : __assert_fail ("checkValidity(S) && \"existing SCEV has not been properly invalidated\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4527, __extension__
__PRETTY_FUNCTION__))
;
4528 return S;
4529 }
4530 return nullptr;
4531}
4532
4533/// Return a SCEV corresponding to -V = -1*V
4534const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
4535 SCEV::NoWrapFlags Flags) {
4536 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4537 return getConstant(
4538 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4539
4540 Type *Ty = V->getType();
4541 Ty = getEffectiveSCEVType(Ty);
4542 return getMulExpr(V, getMinusOne(Ty), Flags);
4543}
4544
4545/// If Expr computes ~A, return A else return nullptr
4546static const SCEV *MatchNotExpr(const SCEV *Expr) {
4547 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
4548 if (!Add || Add->getNumOperands() != 2 ||
4549 !Add->getOperand(0)->isAllOnesValue())
4550 return nullptr;
4551
4552 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
4553 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
4554 !AddRHS->getOperand(0)->isAllOnesValue())
4555 return nullptr;
4556
4557 return AddRHS->getOperand(1);
4558}
4559
4560/// Return a SCEV corresponding to ~V = -1-V
4561const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
4562 assert(!V->getType()->isPointerTy() && "Can't negate pointer")(static_cast <bool> (!V->getType()->isPointerTy()
&& "Can't negate pointer") ? void (0) : __assert_fail
("!V->getType()->isPointerTy() && \"Can't negate pointer\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4562, __extension__
__PRETTY_FUNCTION__))
;
4563
4564 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4565 return getConstant(
4566 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4567
4568 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4569 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4570 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4571 SmallVector<const SCEV *, 2> MatchedOperands;
4572 for (const SCEV *Operand : MME->operands()) {
4573 const SCEV *Matched = MatchNotExpr(Operand);
4574 if (!Matched)
4575 return (const SCEV *)nullptr;
4576 MatchedOperands.push_back(Matched);
4577 }
4578 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4579 MatchedOperands);
4580 };
4581 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4582 return Replaced;
4583 }
4584
4585 Type *Ty = V->getType();
4586 Ty = getEffectiveSCEVType(Ty);
4587 return getMinusSCEV(getMinusOne(Ty), V);
4588}
4589
4590const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) {
4591 assert(P->getType()->isPointerTy())(static_cast <bool> (P->getType()->isPointerTy())
? void (0) : __assert_fail ("P->getType()->isPointerTy()"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4591, __extension__
__PRETTY_FUNCTION__))
;
10
'?' condition is true
4592
4593 if (auto *AddRec
11.1
'AddRec' is null
= dyn_cast<SCEVAddRecExpr>(P)) {
11
Assuming 'P' is not a 'CastReturnType'
12
Taking false branch
4594 // The base of an AddRec is the first operand.
4595 SmallVector<const SCEV *> Ops{AddRec->operands()};
4596 Ops[0] = removePointerBase(Ops[0]);
4597 // Don't try to transfer nowrap flags for now. We could in some cases
4598 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4599 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4600 }
4601 if (auto *Add
13.1
'Add' is non-null
= dyn_cast<SCEVAddExpr>(P)) {
13
Assuming 'P' is a 'CastReturnType'
14
Taking true branch
4602 // The base of an Add is the pointer operand.
4603 SmallVector<const SCEV *> Ops{Add->operands()};
4604 const SCEV **PtrOp = nullptr;
15
'PtrOp' initialized to a null pointer value
4605 for (const SCEV *&AddOp : Ops) {
16
Assuming '__begin2' is equal to '__end2'
4606 if (AddOp->getType()->isPointerTy()) {
4607 assert(!PtrOp && "Cannot have multiple pointer ops")(static_cast <bool> (!PtrOp && "Cannot have multiple pointer ops"
) ? void (0) : __assert_fail ("!PtrOp && \"Cannot have multiple pointer ops\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4607, __extension__
__PRETTY_FUNCTION__))
;
4608 PtrOp = &AddOp;
4609 }
4610 }
4611 *PtrOp = removePointerBase(*PtrOp);
17
Dereference of null pointer (loaded from variable 'PtrOp')
4612 // Don't try to transfer nowrap flags for now. We could in some cases
4613 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4614 return getAddExpr(Ops);
4615 }
4616 // Any other expression must be a pointer base.
4617 return getZero(P->getType());
4618}
4619
4620const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4621 SCEV::NoWrapFlags Flags,
4622 unsigned Depth) {
4623 // Fast path: X - X --> 0.
4624 if (LHS == RHS)
5
Assuming 'LHS' is not equal to 'RHS'
6
Taking false branch
4625 return getZero(LHS->getType());
4626
4627 // If we subtract two pointers with different pointer bases, bail.
4628 // Eventually, we're going to add an assertion to getMulExpr that we
4629 // can't multiply by a pointer.
4630 if (RHS->getType()->isPointerTy()) {
4631 if (!LHS->getType()->isPointerTy() ||
8
Taking false branch
4632 getPointerBase(LHS) != getPointerBase(RHS))
7
Assuming the condition is false
4633 return getCouldNotCompute();
4634 LHS = removePointerBase(LHS);
9
Calling 'ScalarEvolution::removePointerBase'
4635 RHS = removePointerBase(RHS);
4636 }
4637
4638 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4639 // makes it so that we cannot make much use of NUW.
4640 auto AddFlags = SCEV::FlagAnyWrap;
4641 const bool RHSIsNotMinSigned =
4642 !getSignedRangeMin(RHS).isMinSignedValue();
4643 if (hasFlags(Flags, SCEV::FlagNSW)) {
4644 // Let M be the minimum representable signed value. Then (-1)*RHS
4645 // signed-wraps if and only if RHS is M. That can happen even for
4646 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4647 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4648 // (-1)*RHS, we need to prove that RHS != M.
4649 //
4650 // If LHS is non-negative and we know that LHS - RHS does not
4651 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4652 // either by proving that RHS > M or that LHS >= 0.
4653 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4654 AddFlags = SCEV::FlagNSW;
4655 }
4656 }
4657
4658 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4659 // RHS is NSW and LHS >= 0.
4660 //
4661 // The difficulty here is that the NSW flag may have been proven
4662 // relative to a loop that is to be found in a recurrence in LHS and
4663 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4664 // larger scope than intended.
4665 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4666
4667 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4668}
4669
4670const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4671 unsigned Depth) {
4672 Type *SrcTy = V->getType();
4673 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&(static_cast <bool> (SrcTy->isIntOrPtrTy() &&
Ty->isIntOrPtrTy() && "Cannot truncate or zero extend with non-integer arguments!"
) ? void (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or zero extend with non-integer arguments!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4674, __extension__
__PRETTY_FUNCTION__))
4674 "Cannot truncate or zero extend with non-integer arguments!")(static_cast <bool> (SrcTy->isIntOrPtrTy() &&
Ty->isIntOrPtrTy() && "Cannot truncate or zero extend with non-integer arguments!"
) ? void (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or zero extend with non-integer arguments!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4674, __extension__
__PRETTY_FUNCTION__))
;
4675 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4676 return V; // No conversion
4677 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4678 return getTruncateExpr(V, Ty, Depth);
4679 return getZeroExtendExpr(V, Ty, Depth);
4680}
4681
4682const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4683 unsigned Depth) {
4684 Type *SrcTy = V->getType();
4685 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&(static_cast <bool> (SrcTy->isIntOrPtrTy() &&
Ty->isIntOrPtrTy() && "Cannot truncate or zero extend with non-integer arguments!"
) ? void (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or zero extend with non-integer arguments!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4686, __extension__
__PRETTY_FUNCTION__))
4686 "Cannot truncate or zero extend with non-integer arguments!")(static_cast <bool> (SrcTy->isIntOrPtrTy() &&
Ty->isIntOrPtrTy() && "Cannot truncate or zero extend with non-integer arguments!"
) ? void (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or zero extend with non-integer arguments!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4686, __extension__
__PRETTY_FUNCTION__))
;
4687 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4688 return V; // No conversion
4689 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4690 return getTruncateExpr(V, Ty, Depth);
4691 return getSignExtendExpr(V, Ty, Depth);
4692}
4693
4694const SCEV *
4695ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4696 Type *SrcTy = V->getType();
4697 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&(static_cast <bool> (SrcTy->isIntOrPtrTy() &&
Ty->isIntOrPtrTy() && "Cannot noop or zero extend with non-integer arguments!"
) ? void (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or zero extend with non-integer arguments!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4698, __extension__
__PRETTY_FUNCTION__))
4698 "Cannot noop or zero extend with non-integer arguments!")(static_cast <bool> (SrcTy->isIntOrPtrTy() &&
Ty->isIntOrPtrTy() && "Cannot noop or zero extend with non-integer arguments!"
) ? void (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or zero extend with non-integer arguments!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4698, __extension__
__PRETTY_FUNCTION__))
;
4699 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&(static_cast <bool> (getTypeSizeInBits(SrcTy) <= getTypeSizeInBits
(Ty) && "getNoopOrZeroExtend cannot truncate!") ? void
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrZeroExtend cannot truncate!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4700, __extension__
__PRETTY_FUNCTION__))
4700 "getNoopOrZeroExtend cannot truncate!")(static_cast <bool> (getTypeSizeInBits(SrcTy) <= getTypeSizeInBits
(Ty) && "getNoopOrZeroExtend cannot truncate!") ? void
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrZeroExtend cannot truncate!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4700, __extension__
__PRETTY_FUNCTION__))
;
4701 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4702 return V; // No conversion
4703 return getZeroExtendExpr(V, Ty);
4704}
4705
4706const SCEV *
4707ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4708 Type *SrcTy = V->getType();
4709 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&(static_cast <bool> (SrcTy->isIntOrPtrTy() &&
Ty->isIntOrPtrTy() && "Cannot noop or sign extend with non-integer arguments!"
) ? void (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or sign extend with non-integer arguments!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4710, __extension__
__PRETTY_FUNCTION__))
4710 "Cannot noop or sign extend with non-integer arguments!")(static_cast <bool> (SrcTy->isIntOrPtrTy() &&
Ty->isIntOrPtrTy() && "Cannot noop or sign extend with non-integer arguments!"
) ? void (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or sign extend with non-integer arguments!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4710, __extension__
__PRETTY_FUNCTION__))
;
4711 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&(static_cast <bool> (getTypeSizeInBits(SrcTy) <= getTypeSizeInBits
(Ty) && "getNoopOrSignExtend cannot truncate!") ? void
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrSignExtend cannot truncate!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4712, __extension__
__PRETTY_FUNCTION__))
4712 "getNoopOrSignExtend cannot truncate!")(static_cast <bool> (getTypeSizeInBits(SrcTy) <= getTypeSizeInBits
(Ty) && "getNoopOrSignExtend cannot truncate!") ? void
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrSignExtend cannot truncate!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4712, __extension__
__PRETTY_FUNCTION__))
;
4713 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4714 return V; // No conversion
4715 return getSignExtendExpr(V, Ty);
4716}
4717
4718const SCEV *
4719ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4720 Type *SrcTy = V->getType();
4721 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&(static_cast <bool> (SrcTy->isIntOrPtrTy() &&
Ty->isIntOrPtrTy() && "Cannot noop or any extend with non-integer arguments!"
) ? void (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or any extend with non-integer arguments!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4722, __extension__
__PRETTY_FUNCTION__))
4722 "Cannot noop or any extend with non-integer arguments!")(static_cast <bool> (SrcTy->isIntOrPtrTy() &&
Ty->isIntOrPtrTy() && "Cannot noop or any extend with non-integer arguments!"
) ? void (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or any extend with non-integer arguments!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4722, __extension__
__PRETTY_FUNCTION__))
;
4723 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&(static_cast <bool> (getTypeSizeInBits(SrcTy) <= getTypeSizeInBits
(Ty) && "getNoopOrAnyExtend cannot truncate!") ? void
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrAnyExtend cannot truncate!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4724, __extension__
__PRETTY_FUNCTION__))
4724 "getNoopOrAnyExtend cannot truncate!")(static_cast <bool> (getTypeSizeInBits(SrcTy) <= getTypeSizeInBits
(Ty) && "getNoopOrAnyExtend cannot truncate!") ? void
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrAnyExtend cannot truncate!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4724, __extension__
__PRETTY_FUNCTION__))
;
4725 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4726 return V; // No conversion
4727 return getAnyExtendExpr(V, Ty);
4728}
4729
4730const SCEV *
4731ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4732 Type *SrcTy = V->getType();
4733 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&(static_cast <bool> (SrcTy->isIntOrPtrTy() &&
Ty->isIntOrPtrTy() && "Cannot truncate or noop with non-integer arguments!"
) ? void (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or noop with non-integer arguments!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4734, __extension__
__PRETTY_FUNCTION__))
4734 "Cannot truncate or noop with non-integer arguments!")(static_cast <bool> (SrcTy->isIntOrPtrTy() &&
Ty->isIntOrPtrTy() && "Cannot truncate or noop with non-integer arguments!"
) ? void (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or noop with non-integer arguments!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4734, __extension__
__PRETTY_FUNCTION__))
;
4735 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&(static_cast <bool> (getTypeSizeInBits(SrcTy) >= getTypeSizeInBits
(Ty) && "getTruncateOrNoop cannot extend!") ? void (0
) : __assert_fail ("getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && \"getTruncateOrNoop cannot extend!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4736, __extension__
__PRETTY_FUNCTION__))
4736 "getTruncateOrNoop cannot extend!")(static_cast <bool> (getTypeSizeInBits(SrcTy) >= getTypeSizeInBits
(Ty) && "getTruncateOrNoop cannot extend!") ? void (0
) : __assert_fail ("getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && \"getTruncateOrNoop cannot extend!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4736, __extension__
__PRETTY_FUNCTION__))
;
4737 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4738 return V; // No conversion
4739 return getTruncateExpr(V, Ty);
4740}
4741
4742const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4743 const SCEV *RHS) {
4744 const SCEV *PromotedLHS = LHS;
4745 const SCEV *PromotedRHS = RHS;
4746
4747 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4748 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4749 else
4750 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4751
4752 return getUMaxExpr(PromotedLHS, PromotedRHS);
4753}
4754
4755const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4756 const SCEV *RHS,
4757 bool Sequential) {
4758 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4759 return getUMinFromMismatchedTypes(Ops, Sequential);
4760}
4761
4762const SCEV *
4763ScalarEvolution::getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops,
4764 bool Sequential) {
4765 assert(!Ops.empty() && "At least one operand must be!")(static_cast <bool> (!Ops.empty() && "At least one operand must be!"
) ? void (0) : __assert_fail ("!Ops.empty() && \"At least one operand must be!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4765, __extension__
__PRETTY_FUNCTION__))
;
4766 // Trivial case.
4767 if (Ops.size() == 1)
4768 return Ops[0];
4769
4770 // Find the max type first.
4771 Type *MaxType = nullptr;
4772 for (const auto *S : Ops)
4773 if (MaxType)
4774 MaxType = getWiderType(MaxType, S->getType());
4775 else
4776 MaxType = S->getType();
4777 assert(MaxType && "Failed to find maximum type!")(static_cast <bool> (MaxType && "Failed to find maximum type!"
) ? void (0) : __assert_fail ("MaxType && \"Failed to find maximum type!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4777, __extension__
__PRETTY_FUNCTION__))
;
4778
4779 // Extend all ops to max type.
4780 SmallVector<const SCEV *, 2> PromotedOps;
4781 for (const auto *S : Ops)
4782 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4783
4784 // Generate umin.
4785 return getUMinExpr(PromotedOps, Sequential);
4786}
4787
4788const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4789 // A pointer operand may evaluate to a nonpointer expression, such as null.
4790 if (!V->getType()->isPointerTy())
4791 return V;
4792
4793 while (true) {
4794 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4795 V = AddRec->getStart();
4796 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4797 const SCEV *PtrOp = nullptr;
4798 for (const SCEV *AddOp : Add->operands()) {
4799 if (AddOp->getType()->isPointerTy()) {
4800 assert(!PtrOp && "Cannot have multiple pointer ops")(static_cast <bool> (!PtrOp && "Cannot have multiple pointer ops"
) ? void (0) : __assert_fail ("!PtrOp && \"Cannot have multiple pointer ops\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4800, __extension__
__PRETTY_FUNCTION__))
;
4801 PtrOp = AddOp;
4802 }
4803 }
4804 assert(PtrOp && "Must have pointer op")(static_cast <bool> (PtrOp && "Must have pointer op"
) ? void (0) : __assert_fail ("PtrOp && \"Must have pointer op\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4804, __extension__
__PRETTY_FUNCTION__))
;
4805 V = PtrOp;
4806 } else // Not something we can look further into.
4807 return V;
4808 }
4809}
4810
4811/// Push users of the given Instruction onto the given Worklist.
4812static void PushDefUseChildren(Instruction *I,
4813 SmallVectorImpl<Instruction *> &Worklist,
4814 SmallPtrSetImpl<Instruction *> &Visited) {
4815 // Push the def-use children onto the Worklist stack.
4816 for (User *U : I->users()) {
4817 auto *UserInsn = cast<Instruction>(U);
4818 if (isAlwaysUnknown(UserInsn))
4819 continue;
4820 if (Visited.insert(UserInsn).second)
4821 Worklist.push_back(UserInsn);
4822 }
4823}
4824
4825namespace {
4826
4827/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4828/// expression in case its Loop is L. If it is not L then
4829/// if IgnoreOtherLoops is true then use AddRec itself
4830/// otherwise rewrite cannot be done.
4831/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4832class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4833public:
4834 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4835 bool IgnoreOtherLoops = true) {
4836 SCEVInitRewriter Rewriter(L, SE);
4837 const SCEV *Result = Rewriter.visit(S);
4838 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4839 return SE.getCouldNotCompute();
4840 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4841 ? SE.getCouldNotCompute()
4842 : Result;
4843 }
4844
4845 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4846 if (!SE.isLoopInvariant(Expr, L))
4847 SeenLoopVariantSCEVUnknown = true;
4848 return Expr;
4849 }
4850
4851 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4852 // Only re-write AddRecExprs for this loop.
4853 if (Expr->getLoop() == L)
4854 return Expr->getStart();
4855 SeenOtherLoops = true;
4856 return Expr;
4857 }
4858
4859 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4860
4861 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4862
4863private:
4864 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4865 : SCEVRewriteVisitor(SE), L(L) {}
4866
4867 const Loop *L;
4868 bool SeenLoopVariantSCEVUnknown = false;
4869 bool SeenOtherLoops = false;
4870};
4871
4872/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4873/// increment expression in case its Loop is L. If it is not L then
4874/// use AddRec itself.
4875/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4876class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4877public:
4878 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4879 SCEVPostIncRewriter Rewriter(L, SE);
4880 const SCEV *Result = Rewriter.visit(S);
4881 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4882 ? SE.getCouldNotCompute()
4883 : Result;
4884 }
4885
4886 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4887 if (!SE.isLoopInvariant(Expr, L))
4888 SeenLoopVariantSCEVUnknown = true;
4889 return Expr;
4890 }
4891
4892 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4893 // Only re-write AddRecExprs for this loop.
4894 if (Expr->getLoop() == L)
4895 return Expr->getPostIncExpr(SE);
4896 SeenOtherLoops = true;
4897 return Expr;
4898 }
4899
4900 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4901
4902 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4903
4904private:
4905 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4906 : SCEVRewriteVisitor(SE), L(L) {}
4907
4908 const Loop *L;
4909 bool SeenLoopVariantSCEVUnknown = false;
4910 bool SeenOtherLoops = false;
4911};
4912
4913/// This class evaluates the compare condition by matching it against the
4914/// condition of loop latch. If there is a match we assume a true value
4915/// for the condition while building SCEV nodes.
4916class SCEVBackedgeConditionFolder
4917 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4918public:
4919 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4920 ScalarEvolution &SE) {
4921 bool IsPosBECond = false;
4922 Value *BECond = nullptr;
4923 if (BasicBlock *Latch = L->getLoopLatch()) {
4924 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4925 if (BI && BI->isConditional()) {
4926 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&(static_cast <bool> (BI->getSuccessor(0) != BI->getSuccessor
(1) && "Both outgoing branches should not target same header!"
) ? void (0) : __assert_fail ("BI->getSuccessor(0) != BI->getSuccessor(1) && \"Both outgoing branches should not target same header!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4927, __extension__
__PRETTY_FUNCTION__))
4927 "Both outgoing branches should not target same header!")(static_cast <bool> (BI->getSuccessor(0) != BI->getSuccessor
(1) && "Both outgoing branches should not target same header!"
) ? void (0) : __assert_fail ("BI->getSuccessor(0) != BI->getSuccessor(1) && \"Both outgoing branches should not target same header!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 4927, __extension__
__PRETTY_FUNCTION__))
;
4928 BECond = BI->getCondition();
4929 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4930 } else {
4931 return S;
4932 }
4933 }
4934 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4935 return Rewriter.visit(S);
4936 }
4937
4938 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4939 const SCEV *Result = Expr;
4940 bool InvariantF = SE.isLoopInvariant(Expr, L);
4941
4942 if (!InvariantF) {
4943 Instruction *I = cast<Instruction>(Expr->getValue());
4944 switch (I->getOpcode()) {
4945 case Instruction::Select: {
4946 SelectInst *SI = cast<SelectInst>(I);
4947 std::optional<const SCEV *> Res =
4948 compareWithBackedgeCondition(SI->getCondition());
4949 if (Res) {
4950 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4951 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4952 }
4953 break;
4954 }
4955 default: {
4956 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4957 if (Res)
4958 Result = *Res;
4959 break;
4960 }
4961 }
4962 }
4963 return Result;
4964 }
4965
4966private:
4967 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4968 bool IsPosBECond, ScalarEvolution &SE)
4969 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4970 IsPositiveBECond(IsPosBECond) {}
4971
4972 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4973
4974 const Loop *L;
4975 /// Loop back condition.
4976 Value *BackedgeCond = nullptr;
4977 /// Set to true if loop back is on positive branch condition.
4978 bool IsPositiveBECond;
4979};
4980
4981std::optional<const SCEV *>
4982SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4983
4984 // If value matches the backedge condition for loop latch,
4985 // then return a constant evolution node based on loopback
4986 // branch taken.
4987 if (BackedgeCond == IC)
4988 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4989 : SE.getZero(Type::getInt1Ty(SE.getContext()));
4990 return std::nullopt;
4991}
4992
4993class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4994public:
4995 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4996 ScalarEvolution &SE) {
4997 SCEVShiftRewriter Rewriter(L, SE);
4998 const SCEV *Result = Rewriter.visit(S);
4999 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
5000 }
5001
5002 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5003 // Only allow AddRecExprs for this loop.
5004 if (!SE.isLoopInvariant(Expr, L))
5005 Valid = false;
5006 return Expr;
5007 }
5008
5009 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5010 if (Expr->getLoop() == L && Expr->isAffine())
5011 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5012 Valid = false;
5013 return Expr;
5014 }
5015
5016 bool isValid() { return Valid; }
5017
5018private:
5019 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5020 : SCEVRewriteVisitor(SE), L(L) {}
5021
5022 const Loop *L;
5023 bool Valid = true;
5024};
5025
5026} // end anonymous namespace
5027
5028SCEV::NoWrapFlags
5029ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5030 if (!AR->isAffine())
5031 return SCEV::FlagAnyWrap;
5032
5033 using OBO = OverflowingBinaryOperator;
5034
5035 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
5036
5037 if (!AR->hasNoSelfWrap()) {
5038 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5039 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5040 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5041 const APInt &BECountAP = BECountMax->getAPInt();
5042 unsigned NoOverflowBitWidth =
5043 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5044 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5045 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNW);
5046 }
5047 }
5048
5049 if (!AR->hasNoSignedWrap()) {
5050 ConstantRange AddRecRange = getSignedRange(AR);
5051 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
5052
5053 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
5054 Instruction::Add, IncRange, OBO::NoSignedWrap);
5055 if (NSWRegion.contains(AddRecRange))
5056 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
5057 }
5058
5059 if (!AR->hasNoUnsignedWrap()) {
5060 ConstantRange AddRecRange = getUnsignedRange(AR);
5061 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
5062
5063 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
5064 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
5065 if (NUWRegion.contains(AddRecRange))
5066 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
5067 }
5068
5069 return Result;
5070}
5071
5072SCEV::NoWrapFlags
5073ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5074 SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
5075
5076 if (AR->hasNoSignedWrap())
5077 return Result;
5078
5079 if (!AR->isAffine())
5080 return Result;
5081
5082 // This function can be expensive, only try to prove NSW once per AddRec.
5083 if (!SignedWrapViaInductionTried.insert(AR).second)
5084 return Result;
5085
5086 const SCEV *Step = AR->getStepRecurrence(*this);
5087 const Loop *L = AR->getLoop();
5088
5089 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5090 // Note that this serves two purposes: It filters out loops that are
5091 // simply not analyzable, and it covers the case where this code is
5092 // being called from within backedge-taken count analysis, such that
5093 // attempting to ask for the backedge-taken count would likely result
5094 // in infinite recursion. In the later case, the analysis code will
5095 // cope with a conservative value, and it will take care to purge
5096 // that value once it has finished.
5097 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5098
5099 // Normally, in the cases we can prove no-overflow via a
5100 // backedge guarding condition, we can also compute a backedge
5101 // taken count for the loop. The exceptions are assumptions and
5102 // guards present in the loop -- SCEV is not great at exploiting
5103 // these to compute max backedge taken counts, but can still use
5104 // these to prove lack of overflow. Use this fact to avoid
5105 // doing extra work that may not pay off.
5106
5107 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5108 AC.assumptions().empty())
5109 return Result;
5110
5111 // If the backedge is guarded by a comparison with the pre-inc value the
5112 // addrec is safe. Also, if the entry is guarded by a comparison with the
5113 // start value and the backedge is guarded by a comparison with the post-inc
5114 // value, the addrec is safe.
5115 ICmpInst::Predicate Pred;
5116 const SCEV *OverflowLimit =
5117 getSignedOverflowLimitForStep(Step, &Pred, this);
5118 if (OverflowLimit &&
5119 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5120 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5121 Result = setFlags(Result, SCEV::FlagNSW);
5122 }
5123 return Result;
5124}
5125SCEV::NoWrapFlags
5126ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5127 SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
5128
5129 if (AR->hasNoUnsignedWrap())
5130 return Result;
5131
5132 if (!AR->isAffine())
5133 return Result;
5134
5135 // This function can be expensive, only try to prove NUW once per AddRec.
5136 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5137 return Result;
5138
5139 const SCEV *Step = AR->getStepRecurrence(*this);
5140 unsigned BitWidth = getTypeSizeInBits(AR->getType());
5141 const Loop *L = AR->getLoop();
5142
5143 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5144 // Note that this serves two purposes: It filters out loops that are
5145 // simply not analyzable, and it covers the case where this code is
5146 // being called from within backedge-taken count analysis, such that
5147 // attempting to ask for the backedge-taken count would likely result
5148 // in infinite recursion. In the later case, the analysis code will
5149 // cope with a conservative value, and it will take care to purge
5150 // that value once it has finished.
5151 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5152
5153 // Normally, in the cases we can prove no-overflow via a
5154 // backedge guarding condition, we can also compute a backedge
5155 // taken count for the loop. The exceptions are assumptions and
5156 // guards present in the loop -- SCEV is not great at exploiting
5157 // these to compute max backedge taken counts, but can still use
5158 // these to prove lack of overflow. Use this fact to avoid
5159 // doing extra work that may not pay off.
5160
5161 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5162 AC.assumptions().empty())
5163 return Result;
5164
5165 // If the backedge is guarded by a comparison with the pre-inc value the
5166 // addrec is safe. Also, if the entry is guarded by a comparison with the
5167 // start value and the backedge is guarded by a comparison with the post-inc
5168 // value, the addrec is safe.
5169 if (isKnownPositive(Step)) {
5170 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
5171 getUnsignedRangeMax(Step));
5172 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
5173 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
5174 Result = setFlags(Result, SCEV::FlagNUW);
5175 }
5176 }
5177
5178 return Result;
5179}
5180
5181namespace {
5182
5183/// Represents an abstract binary operation. This may exist as a
5184/// normal instruction or constant expression, or may have been
5185/// derived from an expression tree.
5186struct BinaryOp {
5187 unsigned Opcode;
5188 Value *LHS;
5189 Value *RHS;
5190 bool IsNSW = false;
5191 bool IsNUW = false;
5192
5193 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5194 /// constant expression.
5195 Operator *Op = nullptr;
5196
5197 explicit BinaryOp(Operator *Op)
5198 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5199 Op(Op) {
5200 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5201 IsNSW = OBO->hasNoSignedWrap();
5202 IsNUW = OBO->hasNoUnsignedWrap();
5203 }
5204 }
5205
5206 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5207 bool IsNUW = false)
5208 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5209};
5210
5211} // end anonymous namespace
5212
5213/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5214static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5215 AssumptionCache &AC,
5216 const DominatorTree &DT,
5217 const Instruction *CxtI) {
5218 auto *Op = dyn_cast<Operator>(V);
5219 if (!Op)
5220 return std::nullopt;
5221
5222 // Implementation detail: all the cleverness here should happen without
5223 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5224 // SCEV expressions when possible, and we should not break that.
5225
5226 switch (Op->getOpcode()) {
5227 case Instruction::Add:
5228 case Instruction::Sub:
5229 case Instruction::Mul:
5230 case Instruction::UDiv:
5231 case Instruction::URem:
5232 case Instruction::And:
5233 case Instruction::AShr:
5234 case Instruction::Shl:
5235 return BinaryOp(Op);
5236
5237 case Instruction::Or: {
5238 // LLVM loves to convert `add` of operands with no common bits
5239 // into an `or`. But SCEV really doesn't deal with `or` that well,
5240 // so try extra hard to recognize this `or` as an `add`.
5241 if (haveNoCommonBitsSet(Op->getOperand(0), Op->getOperand(1), DL, &AC, CxtI,
5242 &DT, /*UseInstrInfo=*/true))
5243 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5244 /*IsNSW=*/true, /*IsNUW=*/true);
5245 return BinaryOp(Op);
5246 }
5247
5248 case Instruction::Xor:
5249 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5250 // If the RHS of the xor is a signmask, then this is just an add.
5251 // Instcombine turns add of signmask into xor as a strength reduction step.
5252 if (RHSC->getValue().isSignMask())
5253 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5254 // Binary `xor` is a bit-wise `add`.
5255 if (V->getType()->isIntegerTy(1))
5256 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5257 return BinaryOp(Op);
5258
5259 case Instruction::LShr:
5260 // Turn logical shift right of a constant into a unsigned divide.
5261 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5262 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5263
5264 // If the shift count is not less than the bitwidth, the result of
5265 // the shift is undefined. Don't try to analyze it, because the
5266 // resolution chosen here may differ from the resolution chosen in
5267 // other parts of the compiler.
5268 if (SA->getValue().ult(BitWidth)) {
5269 Constant *X =
5270 ConstantInt::get(SA->getContext(),
5271 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5272 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5273 }
5274 }
5275 return BinaryOp(Op);
5276
5277 case Instruction::ExtractValue: {
5278 auto *EVI = cast<ExtractValueInst>(Op);
5279 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5280 break;
5281
5282 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5283 if (!WO)
5284 break;
5285
5286 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5287 bool Signed = WO->isSigned();
5288 // TODO: Should add nuw/nsw flags for mul as well.
5289 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5290 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5291
5292 // Now that we know that all uses of the arithmetic-result component of
5293 // CI are guarded by the overflow check, we can go ahead and pretend
5294 // that the arithmetic is non-overflowing.
5295 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5296 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5297 }
5298
5299 default:
5300 break;
5301 }
5302
5303 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5304 // semantics as a Sub, return a binary sub expression.
5305 if (auto *II = dyn_cast<IntrinsicInst>(V))
5306 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5307 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5308
5309 return std::nullopt;
5310}
5311
5312/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5313/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5314/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5315/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5316/// follows one of the following patterns:
5317/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5318/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5319/// If the SCEV expression of \p Op conforms with one of the expected patterns
5320/// we return the type of the truncation operation, and indicate whether the
5321/// truncated type should be treated as signed/unsigned by setting
5322/// \p Signed to true/false, respectively.
5323static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5324 bool &Signed, ScalarEvolution &SE) {
5325 // The case where Op == SymbolicPHI (that is, with no type conversions on
5326 // the way) is handled by the regular add recurrence creating logic and
5327 // would have already been triggered in createAddRecForPHI. Reaching it here
5328 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5329 // because one of the other operands of the SCEVAddExpr updating this PHI is
5330 // not invariant).
5331 //
5332 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5333 // this case predicates that allow us to prove that Op == SymbolicPHI will
5334 // be added.
5335 if (Op == SymbolicPHI)
5336 return nullptr;
5337
5338 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5339 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5340 if (SourceBits != NewBits)
5341 return nullptr;
5342
5343 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
5344 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
5345 if (!SExt && !ZExt)
5346 return nullptr;
5347 const SCEVTruncateExpr *Trunc =
5348 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
5349 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
5350 if (!Trunc)
5351 return nullptr;
5352 const SCEV *X = Trunc->getOperand();
5353 if (X != SymbolicPHI)
5354 return nullptr;
5355 Signed = SExt != nullptr;
5356 return Trunc->getType();
5357}
5358
5359static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5360 if (!PN->getType()->isIntegerTy())
5361 return nullptr;
5362 const Loop *L = LI.getLoopFor(PN->getParent());
5363 if (!L || L->getHeader() != PN->getParent())
5364 return nullptr;
5365 return L;
5366}
5367
5368// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5369// computation that updates the phi follows the following pattern:
5370// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5371// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5372// If so, try to see if it can be rewritten as an AddRecExpr under some
5373// Predicates. If successful, return them as a pair. Also cache the results
5374// of the analysis.
5375//
5376// Example usage scenario:
5377// Say the Rewriter is called for the following SCEV:
5378// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5379// where:
5380// %X = phi i64 (%Start, %BEValue)
5381// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5382// and call this function with %SymbolicPHI = %X.
5383//
5384// The analysis will find that the value coming around the backedge has
5385// the following SCEV:
5386// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5387// Upon concluding that this matches the desired pattern, the function
5388// will return the pair {NewAddRec, SmallPredsVec} where:
5389// NewAddRec = {%Start,+,%Step}
5390// SmallPredsVec = {P1, P2, P3} as follows:
5391// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5392// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5393// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5394// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5395// under the predicates {P1,P2,P3}.
5396// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5397// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5398//
5399// TODO's:
5400//
5401// 1) Extend the Induction descriptor to also support inductions that involve
5402// casts: When needed (namely, when we are called in the context of the
5403// vectorizer induction analysis), a Set of cast instructions will be
5404// populated by this method, and provided back to isInductionPHI. This is
5405// needed to allow the vectorizer to properly record them to be ignored by
5406// the cost model and to avoid vectorizing them (otherwise these casts,
5407// which are redundant under the runtime overflow checks, will be
5408// vectorized, which can be costly).
5409//
5410// 2) Support additional induction/PHISCEV patterns: We also want to support
5411// inductions where the sext-trunc / zext-trunc operations (partly) occur
5412// after the induction update operation (the induction increment):
5413//
5414// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5415// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5416//
5417// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5418// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5419//
5420// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5421std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5422ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5423 SmallVector<const SCEVPredicate *, 3> Predicates;
5424
5425 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5426 // return an AddRec expression under some predicate.
5427
5428 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5429 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5430 assert(L && "Expecting an integer loop header phi")(static_cast <bool> (L && "Expecting an integer loop header phi"
) ? void (0) : __assert_fail ("L && \"Expecting an integer loop header phi\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 5430, __extension__
__PRETTY_FUNCTION__))
;
5431
5432 // The loop may have multiple entrances or multiple exits; we can analyze
5433 // this phi as an addrec if it has a unique entry value and a unique
5434 // backedge value.
5435 Value *BEValueV = nullptr, *StartValueV = nullptr;
5436 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5437 Value *V = PN->getIncomingValue(i);
5438 if (L->contains(PN->getIncomingBlock(i))) {
5439 if (!BEValueV) {
5440 BEValueV = V;
5441 } else if (BEValueV != V) {
5442 BEValueV = nullptr;
5443 break;
5444 }
5445 } else if (!StartValueV) {
5446 StartValueV = V;
5447 } else if (StartValueV != V) {
5448 StartValueV = nullptr;
5449 break;
5450 }
5451 }
5452 if (!BEValueV || !StartValueV)
5453 return std::nullopt;
5454
5455 const SCEV *BEValue = getSCEV(BEValueV);
5456
5457 // If the value coming around the backedge is an add with the symbolic
5458 // value we just inserted, possibly with casts that we can ignore under
5459 // an appropriate runtime guard, then we found a simple induction variable!
5460 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5461 if (!Add)
5462 return std::nullopt;
5463
5464 // If there is a single occurrence of the symbolic value, possibly
5465 // casted, replace it with a recurrence.
5466 unsigned FoundIndex = Add->getNumOperands();
5467 Type *TruncTy = nullptr;
5468 bool Signed;
5469 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5470 if ((TruncTy =
5471 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5472 if (FoundIndex == e) {
5473 FoundIndex = i;
5474 break;
5475 }
5476
5477 if (FoundIndex == Add->getNumOperands())
5478 return std::nullopt;
5479
5480 // Create an add with everything but the specified operand.
5481 SmallVector<const SCEV *, 8> Ops;
5482 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5483 if (i != FoundIndex)
5484 Ops.push_back(Add->getOperand(i));
5485 const SCEV *Accum = getAddExpr(Ops);
5486
5487 // The runtime checks will not be valid if the step amount is
5488 // varying inside the loop.
5489 if (!isLoopInvariant(Accum, L))
5490 return std::nullopt;
5491
5492 // *** Part2: Create the predicates
5493
5494 // Analysis was successful: we have a phi-with-cast pattern for which we
5495 // can return an AddRec expression under the following predicates:
5496 //
5497 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5498 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5499 // P2: An Equal predicate that guarantees that
5500 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5501 // P3: An Equal predicate that guarantees that
5502 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5503 //
5504 // As we next prove, the above predicates guarantee that:
5505 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5506 //
5507 //
5508 // More formally, we want to prove that:
5509 // Expr(i+1) = Start + (i+1) * Accum
5510 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5511 //
5512 // Given that:
5513 // 1) Expr(0) = Start
5514 // 2) Expr(1) = Start + Accum
5515 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5516 // 3) Induction hypothesis (step i):
5517 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5518 //
5519 // Proof:
5520 // Expr(i+1) =
5521 // = Start + (i+1)*Accum
5522 // = (Start + i*Accum) + Accum
5523 // = Expr(i) + Accum
5524 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5525 // :: from step i
5526 //
5527 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5528 //
5529 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5530 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5531 // + Accum :: from P3
5532 //
5533 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5534 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5535 //
5536 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5537 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5538 //
5539 // By induction, the same applies to all iterations 1<=i<n:
5540 //
5541
5542 // Create a truncated addrec for which we will add a no overflow check (P1).
5543 const SCEV *StartVal = getSCEV(StartValueV);
5544 const SCEV *PHISCEV =
5545 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5546 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5547
5548 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5549 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5550 // will be constant.
5551 //
5552 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5553 // add P1.
5554 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5555 SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
5556 Signed ? SCEVWrapPredicate::IncrementNSSW
5557 : SCEVWrapPredicate::IncrementNUSW;
5558 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5559 Predicates.push_back(AddRecPred);
5560 }
5561
5562 // Create the Equal Predicates P2,P3:
5563
5564 // It is possible that the predicates P2 and/or P3 are computable at
5565 // compile time due to StartVal and/or Accum being constants.
5566 // If either one is, then we can check that now and escape if either P2
5567 // or P3 is false.
5568
5569 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5570 // for each of StartVal and Accum
5571 auto getExtendedExpr = [&](const SCEV *Expr,
5572 bool CreateSignExtend) -> const SCEV * {
5573 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant")(static_cast <bool> (isLoopInvariant(Expr, L) &&
"Expr is expected to be invariant") ? void (0) : __assert_fail
("isLoopInvariant(Expr, L) && \"Expr is expected to be invariant\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 5573, __extension__
__PRETTY_FUNCTION__))
;
5574 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5575 const SCEV *ExtendedExpr =
5576 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5577 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5578 return ExtendedExpr;
5579 };
5580
5581 // Given:
5582 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5583 // = getExtendedExpr(Expr)
5584 // Determine whether the predicate P: Expr == ExtendedExpr
5585 // is known to be false at compile time
5586 auto PredIsKnownFalse = [&](const SCEV *Expr,
5587 const SCEV *ExtendedExpr) -> bool {
5588 return Expr != ExtendedExpr &&
5589 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5590 };
5591
5592 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5593 if (PredIsKnownFalse(StartVal, StartExtended)) {
5594 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)
;
5595 return std::nullopt;
5596 }
5597
5598 // The Step is always Signed (because the overflow checks are either
5599 // NSSW or NUSW)
5600 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5601 if (PredIsKnownFalse(Accum, AccumExtended)) {
5602 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)
;
5603 return std::nullopt;
5604 }
5605
5606 auto AppendPredicate = [&](const SCEV *Expr,
5607 const SCEV *ExtendedExpr) -> void {
5608 if (Expr != ExtendedExpr &&
5609 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5610 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5611 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "Added Predicate: " <<
*Pred; } } while (false)
;
5612 Predicates.push_back(Pred);
5613 }
5614 };
5615
5616 AppendPredicate(StartVal, StartExtended);
5617 AppendPredicate(Accum, AccumExtended);
5618
5619 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5620 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5621 // into NewAR if it will also add the runtime overflow checks specified in
5622 // Predicates.
5623 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5624
5625 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5626 std::make_pair(NewAR, Predicates);
5627 // Remember the result of the analysis for this SCEV at this locayyytion.
5628 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5629 return PredRewrite;
5630}
5631
5632std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5633ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
5634 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5635 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5636 if (!L)
5637 return std::nullopt;
5638
5639 // Check to see if we already analyzed this PHI.
5640 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5641 if (I != PredicatedSCEVRewrites.end()) {
5642 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5643 I->second;
5644 // Analysis was done before and failed to create an AddRec:
5645 if (Rewrite.first == SymbolicPHI)
5646 return std::nullopt;
5647 // Analysis was done before and succeeded to create an AddRec under
5648 // a predicate:
5649 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec")(static_cast <bool> (isa<SCEVAddRecExpr>(Rewrite.
first) && "Expected an AddRec") ? void (0) : __assert_fail
("isa<SCEVAddRecExpr>(Rewrite.first) && \"Expected an AddRec\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 5649, __extension__
__PRETTY_FUNCTION__))
;
5650 assert(!(Rewrite.second).empty() && "Expected to find Predicates")(static_cast <bool> (!(Rewrite.second).empty() &&
"Expected to find Predicates") ? void (0) : __assert_fail ("!(Rewrite.second).empty() && \"Expected to find Predicates\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 5650, __extension__
__PRETTY_FUNCTION__))
;
5651 return Rewrite;
5652 }
5653
5654 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5655 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5656
5657 // Record in the cache that the analysis failed
5658 if (!Rewrite) {
5659 SmallVector<const SCEVPredicate *, 3> Predicates;
5660 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5661 return std::nullopt;
5662 }
5663
5664 return Rewrite;
5665}
5666
5667// FIXME: This utility is currently required because the Rewriter currently
5668// does not rewrite this expression:
5669// {0, +, (sext ix (trunc iy to ix) to iy)}
5670// into {0, +, %step},
5671// even when the following Equal predicate exists:
5672// "%step == (sext ix (trunc iy to ix) to iy)".
5673bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5674 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5675 if (AR1 == AR2)
5676 return true;
5677
5678 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5679 if (Expr1 != Expr2 && !Preds->implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5680 !Preds->implies(SE.getEqualPredicate(Expr2, Expr1)))
5681 return false;
5682 return true;
5683 };
5684
5685 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5686 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5687 return false;
5688 return true;
5689}
5690
5691/// A helper function for createAddRecFromPHI to handle simple cases.
5692///
5693/// This function tries to find an AddRec expression for the simplest (yet most
5694/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5695/// If it fails, createAddRecFromPHI will use a more general, but slow,
5696/// technique for finding the AddRec expression.
5697const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5698 Value *BEValueV,
5699 Value *StartValueV) {
5700 const Loop *L = LI.getLoopFor(PN->getParent());
5701 assert(L && L->getHeader() == PN->getParent())(static_cast <bool> (L && L->getHeader() == PN
->getParent()) ? void (0) : __assert_fail ("L && L->getHeader() == PN->getParent()"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 5701, __extension__
__PRETTY_FUNCTION__))
;
5702 assert(BEValueV && StartValueV)(static_cast <bool> (BEValueV && StartValueV) ?
void (0) : __assert_fail ("BEValueV && StartValueV",
"llvm/lib/Analysis/ScalarEvolution.cpp", 5702, __extension__
__PRETTY_FUNCTION__))
;
5703
5704 auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN);
5705 if (!BO)
5706 return nullptr;
5707
5708 if (BO->Opcode != Instruction::Add)
5709 return nullptr;
5710
5711 const SCEV *Accum = nullptr;
5712 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5713 Accum = getSCEV(BO->RHS);
5714 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5715 Accum = getSCEV(BO->LHS);
5716
5717 if (!Accum)
5718 return nullptr;
5719
5720 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5721 if (BO->IsNUW)
5722 Flags = setFlags(Flags, SCEV::FlagNUW);
5723 if (BO->IsNSW)
5724 Flags = setFlags(Flags, SCEV::FlagNSW);
5725
5726 const SCEV *StartVal = getSCEV(StartValueV);
5727 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5728 insertValueToMap(PN, PHISCEV);
5729
5730 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5731 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR),
5732 (SCEV::NoWrapFlags)(AR->getNoWrapFlags() |
5733 proveNoWrapViaConstantRanges(AR)));
5734 }
5735
5736 // We can add Flags to the post-inc expression only if we
5737 // know that it is *undefined behavior* for BEValueV to
5738 // overflow.
5739 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5740 assert(isLoopInvariant(Accum, L) &&(static_cast <bool> (isLoopInvariant(Accum, L) &&
"Accum is defined outside L, but is not invariant?") ? void (
0) : __assert_fail ("isLoopInvariant(Accum, L) && \"Accum is defined outside L, but is not invariant?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 5741, __extension__
__PRETTY_FUNCTION__))
5741 "Accum is defined outside L, but is not invariant?")(static_cast <bool> (isLoopInvariant(Accum, L) &&
"Accum is defined outside L, but is not invariant?") ? void (
0) : __assert_fail ("isLoopInvariant(Accum, L) && \"Accum is defined outside L, but is not invariant?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 5741, __extension__
__PRETTY_FUNCTION__))
;
5742 if (isAddRecNeverPoison(BEInst, L))
5743 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5744 }
5745
5746 return PHISCEV;
5747}
5748
5749const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5750 const Loop *L = LI.getLoopFor(PN->getParent());
5751 if (!L || L->getHeader() != PN->getParent())
5752 return nullptr;
5753
5754 // The loop may have multiple entrances or multiple exits; we can analyze
5755 // this phi as an addrec if it has a unique entry value and a unique
5756 // backedge value.
5757 Value *BEValueV = nullptr, *StartValueV = nullptr;
5758 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5759 Value *V = PN->getIncomingValue(i);
5760 if (L->contains(PN->getIncomingBlock(i))) {
5761 if (!BEValueV) {
5762 BEValueV = V;
5763 } else if (BEValueV != V) {
5764 BEValueV = nullptr;
5765 break;
5766 }
5767 } else if (!StartValueV) {
5768 StartValueV = V;
5769 } else if (StartValueV != V) {
5770 StartValueV = nullptr;
5771 break;
5772 }
5773 }
5774 if (!BEValueV || !StartValueV)
5775 return nullptr;
5776
5777 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&(static_cast <bool> (ValueExprMap.find_as(PN) == ValueExprMap
.end() && "PHI node already processed?") ? void (0) :
__assert_fail ("ValueExprMap.find_as(PN) == ValueExprMap.end() && \"PHI node already processed?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 5778, __extension__
__PRETTY_FUNCTION__))
5778 "PHI node already processed?")(static_cast <bool> (ValueExprMap.find_as(PN) == ValueExprMap
.end() && "PHI node already processed?") ? void (0) :
__assert_fail ("ValueExprMap.find_as(PN) == ValueExprMap.end() && \"PHI node already processed?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 5778, __extension__
__PRETTY_FUNCTION__))
;
5779
5780 // First, try to find AddRec expression without creating a fictituos symbolic
5781 // value for PN.
5782 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5783 return S;
5784
5785 // Handle PHI node value symbolically.
5786 const SCEV *SymbolicName = getUnknown(PN);
5787 insertValueToMap(PN, SymbolicName);
5788
5789 // Using this symbolic name for the PHI, analyze the value coming around
5790 // the back-edge.
5791 const SCEV *BEValue = getSCEV(BEValueV);
5792
5793 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5794 // has a special value for the first iteration of the loop.
5795
5796 // If the value coming around the backedge is an add with the symbolic
5797 // value we just inserted, then we found a simple induction variable!
5798 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5799 // If there is a single occurrence of the symbolic value, replace it
5800 // with a recurrence.
5801 unsigned FoundIndex = Add->getNumOperands();
5802 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5803 if (Add->getOperand(i) == SymbolicName)
5804 if (FoundIndex == e) {
5805 FoundIndex = i;
5806 break;
5807 }
5808
5809 if (FoundIndex != Add->getNumOperands()) {
5810 // Create an add with everything but the specified operand.
5811 SmallVector<const SCEV *, 8> Ops;
5812 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5813 if (i != FoundIndex)
5814 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5815 L, *this));
5816 const SCEV *Accum = getAddExpr(Ops);
5817
5818 // This is not a valid addrec if the step amount is varying each
5819 // loop iteration, but is not itself an addrec in this loop.
5820 if (isLoopInvariant(Accum, L) ||
5821 (isa<SCEVAddRecExpr>(Accum) &&
5822 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5823 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5824
5825 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5826 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5827 if (BO->IsNUW)
5828 Flags = setFlags(Flags, SCEV::FlagNUW);
5829 if (BO->IsNSW)
5830 Flags = setFlags(Flags, SCEV::FlagNSW);
5831 }
5832 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5833 // If the increment is an inbounds GEP, then we know the address
5834 // space cannot be wrapped around. We cannot make any guarantee
5835 // about signed or unsigned overflow because pointers are
5836 // unsigned but we may have a negative index from the base
5837 // pointer. We can guarantee that no unsigned wrap occurs if the
5838 // indices form a positive value.
5839 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5840 Flags = setFlags(Flags, SCEV::FlagNW);
5841 if (isKnownPositive(Accum))
5842 Flags = setFlags(Flags, SCEV::FlagNUW);
5843 }
5844
5845 // We cannot transfer nuw and nsw flags from subtraction
5846 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5847 // for instance.
5848 }
5849
5850 const SCEV *StartVal = getSCEV(StartValueV);
5851 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5852
5853 // Okay, for the entire analysis of this edge we assumed the PHI
5854 // to be symbolic. We now need to go back and purge all of the
5855 // entries for the scalars that use the symbolic expression.
5856 forgetMemoizedResults(SymbolicName);
5857 insertValueToMap(PN, PHISCEV);
5858
5859 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5860 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR),
5861 (SCEV::NoWrapFlags)(AR->getNoWrapFlags() |
5862 proveNoWrapViaConstantRanges(AR)));
5863 }
5864
5865 // We can add Flags to the post-inc expression only if we
5866 // know that it is *undefined behavior* for BEValueV to
5867 // overflow.
5868 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5869 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5870 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5871
5872 return PHISCEV;
5873 }
5874 }
5875 } else {
5876 // Otherwise, this could be a loop like this:
5877 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5878 // In this case, j = {1,+,1} and BEValue is j.
5879 // Because the other in-value of i (0) fits the evolution of BEValue
5880 // i really is an addrec evolution.
5881 //
5882 // We can generalize this saying that i is the shifted value of BEValue
5883 // by one iteration:
5884 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5885 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5886 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5887 if (Shifted != getCouldNotCompute() &&
5888 Start != getCouldNotCompute()) {
5889 const SCEV *StartVal = getSCEV(StartValueV);
5890 if (Start == StartVal) {
5891 // Okay, for the entire analysis of this edge we assumed the PHI
5892 // to be symbolic. We now need to go back and purge all of the
5893 // entries for the scalars that use the symbolic expression.
5894 forgetMemoizedResults(SymbolicName);
5895 insertValueToMap(PN, Shifted);
5896 return Shifted;
5897 }
5898 }
5899 }
5900
5901 // Remove the temporary PHI node SCEV that has been inserted while intending
5902 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5903 // as it will prevent later (possibly simpler) SCEV expressions to be added
5904 // to the ValueExprMap.
5905 eraseValueFromMap(PN);
5906
5907 return nullptr;
5908}
5909
5910// Try to match a control flow sequence that branches out at BI and merges back
5911// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5912// match.
5913static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5914 Value *&C, Value *&LHS, Value *&RHS) {
5915 C = BI->getCondition();
5916
5917 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5918 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5919
5920 if (!LeftEdge.isSingleEdge())
5921 return false;
5922
5923 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()")(static_cast <bool> (RightEdge.isSingleEdge() &&
"Follows from LeftEdge.isSingleEdge()") ? void (0) : __assert_fail
("RightEdge.isSingleEdge() && \"Follows from LeftEdge.isSingleEdge()\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 5923, __extension__
__PRETTY_FUNCTION__))
;
5924
5925 Use &LeftUse = Merge->getOperandUse(0);
5926 Use &RightUse = Merge->getOperandUse(1);
5927
5928 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5929 LHS = LeftUse;
5930 RHS = RightUse;
5931 return true;
5932 }
5933
5934 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5935 LHS = RightUse;
5936 RHS = LeftUse;
5937 return true;
5938 }
5939
5940 return false;
5941}
5942
5943const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5944 auto IsReachable =
5945 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5946 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5947 // Try to match
5948 //
5949 // br %cond, label %left, label %right
5950 // left:
5951 // br label %merge
5952 // right:
5953 // br label %merge
5954 // merge:
5955 // V = phi [ %x, %left ], [ %y, %right ]
5956 //
5957 // as "select %cond, %x, %y"
5958
5959 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5960 assert(IDom && "At least the entry block should dominate PN")(static_cast <bool> (IDom && "At least the entry block should dominate PN"
) ? void (0) : __assert_fail ("IDom && \"At least the entry block should dominate PN\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 5960, __extension__
__PRETTY_FUNCTION__))
;
5961
5962 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5963 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5964
5965 if (BI && BI->isConditional() &&
5966 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5967 properlyDominates(getSCEV(LHS), PN->getParent()) &&
5968 properlyDominates(getSCEV(RHS), PN->getParent()))
5969 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5970 }
5971
5972 return nullptr;
5973}
5974
5975const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5976 if (const SCEV *S = createAddRecFromPHI(PN))
5977 return S;
5978
5979 if (Value *V = simplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5980 return getSCEV(V);
5981
5982 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5983 return S;
5984
5985 // If it's not a loop phi, we can't handle it yet.
5986 return getUnknown(PN);
5987}
5988
5989bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
5990 SCEVTypes RootKind) {
5991 struct FindClosure {
5992 const SCEV *OperandToFind;
5993 const SCEVTypes RootKind; // Must be a sequential min/max expression.
5994 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
5995
5996 bool Found = false;
5997
5998 bool canRecurseInto(SCEVTypes Kind) const {
5999 // We can only recurse into the SCEV expression of the same effective type
6000 // as the type of our root SCEV expression, and into zero-extensions.
6001 return RootKind == Kind || NonSequentialRootKind == Kind ||
6002 scZeroExtend == Kind;
6003 };
6004
6005 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6006 : OperandToFind(OperandToFind), RootKind(RootKind),
6007 NonSequentialRootKind(
6008 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
6009 RootKind)) {}
6010
6011 bool follow(const SCEV *S) {
6012 Found = S == OperandToFind;
6013
6014 return !isDone() && canRecurseInto(S->getSCEVType());
6015 }
6016
6017 bool isDone() const { return Found; }
6018 };
6019
6020 FindClosure FC(OperandToFind, RootKind);
6021 visitAll(Root, FC);
6022 return FC.Found;
6023}
6024
6025std::optional<const SCEV *>
6026ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6027 ICmpInst *Cond,
6028 Value *TrueVal,
6029 Value *FalseVal) {
6030 // Try to match some simple smax or umax patterns.
6031 auto *ICI = Cond;
6032
6033 Value *LHS = ICI->getOperand(0);
6034 Value *RHS = ICI->getOperand(1);
6035
6036 switch (ICI->getPredicate()) {
6037 case ICmpInst::ICMP_SLT:
6038 case ICmpInst::ICMP_SLE:
6039 case ICmpInst::ICMP_ULT:
6040 case ICmpInst::ICMP_ULE:
6041 std::swap(LHS, RHS);
6042 [[fallthrough]];
6043 case ICmpInst::ICMP_SGT:
6044 case ICmpInst::ICMP_SGE:
6045 case ICmpInst::ICMP_UGT:
6046 case ICmpInst::ICMP_UGE:
6047 // a > b ? a+x : b+x -> max(a, b)+x
6048 // a > b ? b+x : a+x -> min(a, b)+x
6049 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(Ty)) {
6050 bool Signed = ICI->isSigned();
6051 const SCEV *LA = getSCEV(TrueVal);
6052 const SCEV *RA = getSCEV(FalseVal);
6053 const SCEV *LS = getSCEV(LHS);
6054 const SCEV *RS = getSCEV(RHS);
6055 if (LA->getType()->isPointerTy()) {
6056 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6057 // Need to make sure we can't produce weird expressions involving
6058 // negated pointers.
6059 if (LA == LS && RA == RS)
6060 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6061 if (LA == RS && RA == LS)
6062 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6063 }
6064 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6065 if (Op->getType()->isPointerTy()) {
6066 Op = getLosslessPtrToIntExpr(Op);
6067 if (isa<SCEVCouldNotCompute>(Op))
6068 return Op;
6069 }
6070 if (Signed)
6071 Op = getNoopOrSignExtend(Op, Ty);
6072 else
6073 Op = getNoopOrZeroExtend(Op, Ty);
6074 return Op;
6075 };
6076 LS = CoerceOperand(LS);
6077 RS = CoerceOperand(RS);
6078 if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS))
6079 break;
6080 const SCEV *LDiff = getMinusSCEV(LA, LS);
6081 const SCEV *RDiff = getMinusSCEV(RA, RS);
6082 if (LDiff == RDiff)
6083 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6084 LDiff);
6085 LDiff = getMinusSCEV(LA, RS);
6086 RDiff = getMinusSCEV(RA, LS);
6087 if (LDiff == RDiff)
6088 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6089 LDiff);
6090 }
6091 break;
6092 case ICmpInst::ICMP_NE:
6093 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6094 std::swap(TrueVal, FalseVal);
6095 [[fallthrough]];
6096 case ICmpInst::ICMP_EQ:
6097 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6098 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(Ty) &&
6099 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
6100 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6101 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6102 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6103 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6104 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6105 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6106 return getAddExpr(getUMaxExpr(X, C), Y);
6107 }
6108 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6109 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6110 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6111 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6112 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero() &&
6113 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6114 const SCEV *X = getSCEV(LHS);
6115 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6116 X = ZExt->getOperand();
6117 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6118 const SCEV *FalseValExpr = getSCEV(FalseVal);
6119 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6120 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6121 /*Sequential=*/true);
6122 }
6123 }
6124 break;
6125 default:
6126 break;
6127 }
6128
6129 return std::nullopt;
6130}
6131
6132static std::optional<const SCEV *>
6133createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr,
6134 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6135 assert(CondExpr->getType()->isIntegerTy(1) &&(static_cast <bool> (CondExpr->getType()->isIntegerTy
(1) && TrueExpr->getType() == FalseExpr->getType
() && TrueExpr->getType()->isIntegerTy(1) &&
"Unexpected operands of a select.") ? void (0) : __assert_fail
("CondExpr->getType()->isIntegerTy(1) && TrueExpr->getType() == FalseExpr->getType() && TrueExpr->getType()->isIntegerTy(1) && \"Unexpected operands of a select.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6138, __extension__
__PRETTY_FUNCTION__))
6136 TrueExpr->getType() == FalseExpr->getType() &&(static_cast <bool> (CondExpr->getType()->isIntegerTy
(1) && TrueExpr->getType() == FalseExpr->getType
() && TrueExpr->getType()->isIntegerTy(1) &&
"Unexpected operands of a select.") ? void (0) : __assert_fail
("CondExpr->getType()->isIntegerTy(1) && TrueExpr->getType() == FalseExpr->getType() && TrueExpr->getType()->isIntegerTy(1) && \"Unexpected operands of a select.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6138, __extension__
__PRETTY_FUNCTION__))
6137 TrueExpr->getType()->isIntegerTy(1) &&(static_cast <bool> (CondExpr->getType()->isIntegerTy
(1) && TrueExpr->getType() == FalseExpr->getType
() && TrueExpr->getType()->isIntegerTy(1) &&
"Unexpected operands of a select.") ? void (0) : __assert_fail
("CondExpr->getType()->isIntegerTy(1) && TrueExpr->getType() == FalseExpr->getType() && TrueExpr->getType()->isIntegerTy(1) && \"Unexpected operands of a select.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6138, __extension__
__PRETTY_FUNCTION__))
6138 "Unexpected operands of a select.")(static_cast <bool> (CondExpr->getType()->isIntegerTy
(1) && TrueExpr->getType() == FalseExpr->getType
() && TrueExpr->getType()->isIntegerTy(1) &&
"Unexpected operands of a select.") ? void (0) : __assert_fail
("CondExpr->getType()->isIntegerTy(1) && TrueExpr->getType() == FalseExpr->getType() && TrueExpr->getType()->isIntegerTy(1) && \"Unexpected operands of a select.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6138, __extension__
__PRETTY_FUNCTION__))
;
6139
6140 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6141 // --> C + (umin_seq cond, x - C)
6142 //
6143 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6144 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6145 // --> C + (umin_seq ~cond, x - C)
6146
6147 // FIXME: while we can't legally model the case where both of the hands
6148 // are fully variable, we only require that the *difference* is constant.
6149 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6150 return std::nullopt;
6151
6152 const SCEV *X, *C;
6153 if (isa<SCEVConstant>(TrueExpr)) {
6154 CondExpr = SE->getNotSCEV(CondExpr);
6155 X = FalseExpr;
6156 C = TrueExpr;
6157 } else {
6158 X = TrueExpr;
6159 C = FalseExpr;
6160 }
6161 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6162 /*Sequential=*/true));
6163}
6164
6165static std::optional<const SCEV *>
6166createNodeForSelectViaUMinSeq(ScalarEvolution *SE, Value *Cond, Value *TrueVal,
6167 Value *FalseVal) {
6168 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6169 return std::nullopt;
6170
6171 const auto *SECond = SE->getSCEV(Cond);
6172 const auto *SETrue = SE->getSCEV(TrueVal);
6173 const auto *SEFalse = SE->getSCEV(FalseVal);
6174 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6175}
6176
6177const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6178 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6179 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?")(static_cast <bool> (Cond->getType()->isIntegerTy
(1) && "Select condition is not an i1?") ? void (0) :
__assert_fail ("Cond->getType()->isIntegerTy(1) && \"Select condition is not an i1?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6179, __extension__
__PRETTY_FUNCTION__))
;
6180 assert(TrueVal->getType() == FalseVal->getType() &&(static_cast <bool> (TrueVal->getType() == FalseVal->
getType() && V->getType() == TrueVal->getType()
&& "Types of select hands and of the result must match."
) ? void (0) : __assert_fail ("TrueVal->getType() == FalseVal->getType() && V->getType() == TrueVal->getType() && \"Types of select hands and of the result must match.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6182, __extension__
__PRETTY_FUNCTION__))
6181 V->getType() == TrueVal->getType() &&(static_cast <bool> (TrueVal->getType() == FalseVal->
getType() && V->getType() == TrueVal->getType()
&& "Types of select hands and of the result must match."
) ? void (0) : __assert_fail ("TrueVal->getType() == FalseVal->getType() && V->getType() == TrueVal->getType() && \"Types of select hands and of the result must match.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6182, __extension__
__PRETTY_FUNCTION__))
6182 "Types of select hands and of the result must match.")(static_cast <bool> (TrueVal->getType() == FalseVal->
getType() && V->getType() == TrueVal->getType()
&& "Types of select hands and of the result must match."
) ? void (0) : __assert_fail ("TrueVal->getType() == FalseVal->getType() && V->getType() == TrueVal->getType() && \"Types of select hands and of the result must match.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6182, __extension__
__PRETTY_FUNCTION__))
;
6183
6184 // For now, only deal with i1-typed `select`s.
6185 if (!V->getType()->isIntegerTy(1))
6186 return getUnknown(V);
6187
6188 if (std::optional<const SCEV *> S =
6189 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6190 return *S;
6191
6192 return getUnknown(V);
6193}
6194
6195const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6196 Value *TrueVal,
6197 Value *FalseVal) {
6198 // Handle "constant" branch or select. This can occur for instance when a
6199 // loop pass transforms an inner loop and moves on to process the outer loop.
6200 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6201 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6202
6203 if (auto *I = dyn_cast<Instruction>(V)) {
6204 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6205 if (std::optional<const SCEV *> S =
6206 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6207 TrueVal, FalseVal))
6208 return *S;
6209 }
6210 }
6211
6212 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6213}
6214
6215/// Expand GEP instructions into add and multiply operations. This allows them
6216/// to be analyzed by regular SCEV code.
6217const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6218 assert(GEP->getSourceElementType()->isSized() &&(static_cast <bool> (GEP->getSourceElementType()->
isSized() && "GEP source element type must be sized")
? void (0) : __assert_fail ("GEP->getSourceElementType()->isSized() && \"GEP source element type must be sized\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6219, __extension__
__PRETTY_FUNCTION__))
6219 "GEP source element type must be sized")(static_cast <bool> (GEP->getSourceElementType()->
isSized() && "GEP source element type must be sized")
? void (0) : __assert_fail ("GEP->getSourceElementType()->isSized() && \"GEP source element type must be sized\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6219, __extension__
__PRETTY_FUNCTION__))
;
6220
6221 SmallVector<const SCEV *, 4> IndexExprs;
6222 for (Value *Index : GEP->indices())
6223 IndexExprs.push_back(getSCEV(Index));
6224 return getGEPExpr(GEP, IndexExprs);
6225}
6226
6227APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S) {
6228 uint64_t BitWidth = getTypeSizeInBits(S->getType());
6229 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6230 return TrailingZeros >= BitWidth
6231 ? APInt::getZero(BitWidth)
6232 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6233 };
6234 auto GetGCDMultiple = [this](const SCEVNAryExpr *N) {
6235 // The result is GCD of all operands results.
6236 APInt Res = getConstantMultiple(N->getOperand(0));
6237 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6238 Res = APIntOps::GreatestCommonDivisor(
6239 Res, getConstantMultiple(N->getOperand(I)));
6240 return Res;
6241 };
6242
6243 switch (S->getSCEVType()) {
6244 case scConstant:
6245 return cast<SCEVConstant>(S)->getAPInt();
6246 case scPtrToInt:
6247 return getConstantMultiple(cast<SCEVPtrToIntExpr>(S)->getOperand());
6248 case scUDivExpr:
6249 case scVScale:
6250 return APInt(BitWidth, 1);
6251 case scTruncate: {
6252 // Only multiples that are a power of 2 will hold after truncation.
6253 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6254 uint32_t TZ = getMinTrailingZeros(T->getOperand());
6255 return GetShiftedByZeros(TZ);
6256 }
6257 case scZeroExtend: {
6258 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6259 return getConstantMultiple(Z->getOperand()).zext(BitWidth);
6260 }
6261 case scSignExtend: {
6262 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6263 return getConstantMultiple(E->getOperand()).sext(BitWidth);
6264 }
6265 case scMulExpr: {
6266 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6267 if (M->hasNoUnsignedWrap()) {
6268 // The result is the product of all operand results.
6269 APInt Res = getConstantMultiple(M->getOperand(0));
6270 for (const SCEV *Operand : M->operands().drop_front())
6271 Res = Res * getConstantMultiple(Operand);
6272 return Res;
6273 }
6274
6275 // If there are no wrap guarentees, find the trailing zeros, which is the
6276 // sum of trailing zeros for all its operands.
6277 uint32_t TZ = 0;
6278 for (const SCEV *Operand : M->operands())
6279 TZ += getMinTrailingZeros(Operand);
6280 return GetShiftedByZeros(TZ);
6281 }
6282 case scAddExpr:
6283 case scAddRecExpr: {
6284 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6285 if (N->hasNoUnsignedWrap())
6286 return GetGCDMultiple(N);
6287 // Find the trailing bits, which is the minimum of its operands.
6288 uint32_t TZ = getMinTrailingZeros(N->getOperand(0));
6289 for (const SCEV *Operand : N->operands().drop_front())
6290 TZ = std::min(TZ, getMinTrailingZeros(Operand));
6291 return GetShiftedByZeros(TZ);
6292 }
6293 case scUMaxExpr:
6294 case scSMaxExpr:
6295 case scUMinExpr:
6296 case scSMinExpr:
6297 case scSequentialUMinExpr:
6298 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6299 case scUnknown: {
6300 // ask ValueTracking for known bits
6301 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6302 unsigned Known =
6303 computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT)
6304 .countMinTrailingZeros();
6305 return GetShiftedByZeros(Known);
6306 }
6307 case scCouldNotCompute:
6308 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6308)
;
6309 }
6310 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 6310)
;
6311}
6312
6313APInt ScalarEvolution::getConstantMultiple(const SCEV *S) {
6314 auto I = ConstantMultipleCache.find(S);
6315 if (I != ConstantMultipleCache.end())
6316 return I->second;
6317
6318 APInt Result = getConstantMultipleImpl(S);
6319 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6320 assert(InsertPair.second && "Should insert a new key")(static_cast <bool> (InsertPair.second && "Should insert a new key"
) ? void (0) : __assert_fail ("InsertPair.second && \"Should insert a new key\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6320, __extension__
__PRETTY_FUNCTION__))
;
6321 return InsertPair.first->second;
6322}
6323
6324APInt ScalarEvolution::getNonZeroConstantMultiple(const SCEV *S) {
6325 APInt Multiple = getConstantMultiple(S);
6326 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6327}
6328
6329uint32_t ScalarEvolution::getMinTrailingZeros(const SCEV *S) {
6330 return std::min(getConstantMultiple(S).countTrailingZeros(),
6331 (unsigned)getTypeSizeInBits(S->getType()));
6332}
6333
6334/// Helper method to assign a range to V from metadata present in the IR.
6335static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6336 if (Instruction *I = dyn_cast<Instruction>(V))
6337 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6338 return getConstantRangeFromMetadata(*MD);
6339
6340 return std::nullopt;
6341}
6342
6343void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
6344 SCEV::NoWrapFlags Flags) {
6345 if (AddRec->getNoWrapFlags(Flags) != Flags) {
6346 AddRec->setNoWrapFlags(Flags);
6347 UnsignedRanges.erase(AddRec);
6348 SignedRanges.erase(AddRec);
6349 ConstantMultipleCache.erase(AddRec);
6350 }
6351}
6352
6353ConstantRange ScalarEvolution::
6354getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6355 const DataLayout &DL = getDataLayout();
6356
6357 unsigned BitWidth = getTypeSizeInBits(U->getType());
6358 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6359
6360 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6361 // use information about the trip count to improve our available range. Note
6362 // that the trip count independent cases are already handled by known bits.
6363 // WARNING: The definition of recurrence used here is subtly different than
6364 // the one used by AddRec (and thus most of this file). Step is allowed to
6365 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6366 // and other addrecs in the same loop (for non-affine addrecs). The code
6367 // below intentionally handles the case where step is not loop invariant.
6368 auto *P = dyn_cast<PHINode>(U->getValue());
6369 if (!P)
6370 return FullSet;
6371
6372 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6373 // even the values that are not available in these blocks may come from them,
6374 // and this leads to false-positive recurrence test.
6375 for (auto *Pred : predecessors(P->getParent()))
6376 if (!DT.isReachableFromEntry(Pred))
6377 return FullSet;
6378
6379 BinaryOperator *BO;
6380 Value *Start, *Step;
6381 if (!matchSimpleRecurrence(P, BO, Start, Step))
6382 return FullSet;
6383
6384 // If we found a recurrence in reachable code, we must be in a loop. Note
6385 // that BO might be in some subloop of L, and that's completely okay.
6386 auto *L = LI.getLoopFor(P->getParent());
6387 assert(L && L->getHeader() == P->getParent())(static_cast <bool> (L && L->getHeader() == P
->getParent()) ? void (0) : __assert_fail ("L && L->getHeader() == P->getParent()"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6387, __extension__
__PRETTY_FUNCTION__))
;
6388 if (!L->contains(BO->getParent()))
6389 // NOTE: This bailout should be an assert instead. However, asserting
6390 // the condition here exposes a case where LoopFusion is querying SCEV
6391 // with malformed loop information during the midst of the transform.
6392 // There doesn't appear to be an obvious fix, so for the moment bailout
6393 // until the caller issue can be fixed. PR49566 tracks the bug.
6394 return FullSet;
6395
6396 // TODO: Extend to other opcodes such as mul, and div
6397 switch (BO->getOpcode()) {
6398 default:
6399 return FullSet;
6400 case Instruction::AShr:
6401 case Instruction::LShr:
6402 case Instruction::Shl:
6403 break;
6404 };
6405
6406 if (BO->getOperand(0) != P)
6407 // TODO: Handle the power function forms some day.
6408 return FullSet;
6409
6410 unsigned TC = getSmallConstantMaxTripCount(L);
6411 if (!TC || TC >= BitWidth)
6412 return FullSet;
6413
6414 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
6415 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
6416 assert(KnownStart.getBitWidth() == BitWidth &&(static_cast <bool> (KnownStart.getBitWidth() == BitWidth
&& KnownStep.getBitWidth() == BitWidth) ? void (0) :
__assert_fail ("KnownStart.getBitWidth() == BitWidth && KnownStep.getBitWidth() == BitWidth"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6417, __extension__
__PRETTY_FUNCTION__))
6417 KnownStep.getBitWidth() == BitWidth)(static_cast <bool> (KnownStart.getBitWidth() == BitWidth
&& KnownStep.getBitWidth() == BitWidth) ? void (0) :
__assert_fail ("KnownStart.getBitWidth() == BitWidth && KnownStep.getBitWidth() == BitWidth"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6417, __extension__
__PRETTY_FUNCTION__))
;
6418
6419 // Compute total shift amount, being careful of overflow and bitwidths.
6420 auto MaxShiftAmt = KnownStep.getMaxValue();
6421 APInt TCAP(BitWidth, TC-1);
6422 bool Overflow = false;
6423 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6424 if (Overflow)
6425 return FullSet;
6426
6427 switch (BO->getOpcode()) {
6428 default:
6429 llvm_unreachable("filtered out above")::llvm::llvm_unreachable_internal("filtered out above", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 6429)
;
6430 case Instruction::AShr: {
6431 // For each ashr, three cases:
6432 // shift = 0 => unchanged value
6433 // saturation => 0 or -1
6434 // other => a value closer to zero (of the same sign)
6435 // Thus, the end value is closer to zero than the start.
6436 auto KnownEnd = KnownBits::ashr(KnownStart,
6437 KnownBits::makeConstant(TotalShift));
6438 if (KnownStart.isNonNegative())
6439 // Analogous to lshr (simply not yet canonicalized)
6440 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6441 KnownStart.getMaxValue() + 1);
6442 if (KnownStart.isNegative())
6443 // End >=u Start && End <=s Start
6444 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6445 KnownEnd.getMaxValue() + 1);
6446 break;
6447 }
6448 case Instruction::LShr: {
6449 // For each lshr, three cases:
6450 // shift = 0 => unchanged value
6451 // saturation => 0
6452 // other => a smaller positive number
6453 // Thus, the low end of the unsigned range is the last value produced.
6454 auto KnownEnd = KnownBits::lshr(KnownStart,
6455 KnownBits::makeConstant(TotalShift));
6456 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6457 KnownStart.getMaxValue() + 1);
6458 }
6459 case Instruction::Shl: {
6460 // Iff no bits are shifted out, value increases on every shift.
6461 auto KnownEnd = KnownBits::shl(KnownStart,
6462 KnownBits::makeConstant(TotalShift));
6463 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6464 return ConstantRange(KnownStart.getMinValue(),
6465 KnownEnd.getMaxValue() + 1);
6466 break;
6467 }
6468 };
6469 return FullSet;
6470}
6471
6472const ConstantRange &
6473ScalarEvolution::getRangeRefIter(const SCEV *S,
6474 ScalarEvolution::RangeSignHint SignHint) {
6475 DenseMap<const SCEV *, ConstantRange> &Cache =
6476 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6477 : SignedRanges;
6478 SmallVector<const SCEV *> WorkList;
6479 SmallPtrSet<const SCEV *, 8> Seen;
6480
6481 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6482 // SCEVUnknown PHI node.
6483 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6484 if (!Seen.insert(Expr).second)
6485 return;
6486 if (Cache.contains(Expr))
6487 return;
6488 switch (Expr->getSCEVType()) {
6489 case scUnknown:
6490 if (!isa<PHINode>(cast<SCEVUnknown>(Expr)->getValue()))
6491 break;
6492 [[fallthrough]];
6493 case scConstant:
6494 case scVScale:
6495 case scTruncate:
6496 case scZeroExtend:
6497 case scSignExtend:
6498 case scPtrToInt:
6499 case scAddExpr:
6500 case scMulExpr:
6501 case scUDivExpr:
6502 case scAddRecExpr:
6503 case scUMaxExpr:
6504 case scSMaxExpr:
6505 case scUMinExpr:
6506 case scSMinExpr:
6507 case scSequentialUMinExpr:
6508 WorkList.push_back(Expr);
6509 break;
6510 case scCouldNotCompute:
6511 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6511)
;
6512 }
6513 };
6514 AddToWorklist(S);
6515
6516 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6517 for (unsigned I = 0; I != WorkList.size(); ++I) {
6518 const SCEV *P = WorkList[I];
6519 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6520 // If it is not a `SCEVUnknown`, just recurse into operands.
6521 if (!UnknownS) {
6522 for (const SCEV *Op : P->operands())
6523 AddToWorklist(Op);
6524 continue;
6525 }
6526 // `SCEVUnknown`'s require special treatment.
6527 if (const PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6528 if (!PendingPhiRangesIter.insert(P).second)
6529 continue;
6530 for (auto &Op : reverse(P->operands()))
6531 AddToWorklist(getSCEV(Op));
6532 }
6533 }
6534
6535 if (!WorkList.empty()) {
6536 // Use getRangeRef to compute ranges for items in the worklist in reverse
6537 // order. This will force ranges for earlier operands to be computed before
6538 // their users in most cases.
6539 for (const SCEV *P :
6540 reverse(make_range(WorkList.begin() + 1, WorkList.end()))) {
6541 getRangeRef(P, SignHint);
6542
6543 if (auto *UnknownS = dyn_cast<SCEVUnknown>(P))
6544 if (const PHINode *P = dyn_cast<PHINode>(UnknownS->getValue()))
6545 PendingPhiRangesIter.erase(P);
6546 }
6547 }
6548
6549 return getRangeRef(S, SignHint, 0);
6550}
6551
6552/// Determine the range for a particular SCEV. If SignHint is
6553/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6554/// with a "cleaner" unsigned (resp. signed) representation.
6555const ConstantRange &ScalarEvolution::getRangeRef(
6556 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6557 DenseMap<const SCEV *, ConstantRange> &Cache =
6558 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6559 : SignedRanges;
6560 ConstantRange::PreferredRangeType RangeType =
6561 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6562 : ConstantRange::Signed;
6563
6564 // See if we've computed this range already.
6565 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
6566 if (I != Cache.end())
6567 return I->second;
6568
6569 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6570 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6571
6572 // Switch to iteratively computing the range for S, if it is part of a deeply
6573 // nested expression.
6574 if (Depth > RangeIterThreshold)
6575 return getRangeRefIter(S, SignHint);
6576
6577 unsigned BitWidth = getTypeSizeInBits(S->getType());
6578 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6579 using OBO = OverflowingBinaryOperator;
6580
6581 // If the value has known zeros, the maximum value will have those known zeros
6582 // as well.
6583 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6584 APInt Multiple = getNonZeroConstantMultiple(S);
6585 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6586 if (!Remainder.isZero())
6587 ConservativeResult =
6588 ConstantRange(APInt::getMinValue(BitWidth),
6589 APInt::getMaxValue(BitWidth) - Remainder + 1);
6590 }
6591 else {
6592 uint32_t TZ = getMinTrailingZeros(S);
6593 if (TZ != 0) {
6594 ConservativeResult = ConstantRange(
6595 APInt::getSignedMinValue(BitWidth),
6596 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6597 }
6598 }
6599
6600 switch (S->getSCEVType()) {
6601 case scConstant:
6602 llvm_unreachable("Already handled above.")::llvm::llvm_unreachable_internal("Already handled above.", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 6602)
;
6603 case scVScale:
6604 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6605 case scTruncate: {
6606 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6607 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6608 return setRange(
6609 Trunc, SignHint,
6610 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6611 }
6612 case scZeroExtend: {
6613 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6614 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6615 return setRange(
6616 ZExt, SignHint,
6617 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6618 }
6619 case scSignExtend: {
6620 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6621 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6622 return setRange(
6623 SExt, SignHint,
6624 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6625 }
6626 case scPtrToInt: {
6627 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(S);
6628 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint, Depth + 1);
6629 return setRange(PtrToInt, SignHint, X);
6630 }
6631 case scAddExpr: {
6632 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6633 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6634 unsigned WrapType = OBO::AnyWrap;
6635 if (Add->hasNoSignedWrap())
6636 WrapType |= OBO::NoSignedWrap;
6637 if (Add->hasNoUnsignedWrap())
6638 WrapType |= OBO::NoUnsignedWrap;
6639 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
6640 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint, Depth + 1),
6641 WrapType, RangeType);
6642 return setRange(Add, SignHint,
6643 ConservativeResult.intersectWith(X, RangeType));
6644 }
6645 case scMulExpr: {
6646 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6647 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6648 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
6649 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint, Depth + 1));
6650 return setRange(Mul, SignHint,
6651 ConservativeResult.intersectWith(X, RangeType));
6652 }
6653 case scUDivExpr: {
6654 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6655 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6656 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6657 return setRange(UDiv, SignHint,
6658 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6659 }
6660 case scAddRecExpr: {
6661 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6662 // If there's no unsigned wrap, the value will never be less than its
6663 // initial value.
6664 if (AddRec->hasNoUnsignedWrap()) {
6665 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6666 if (!UnsignedMinValue.isZero())
6667 ConservativeResult = ConservativeResult.intersectWith(
6668 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6669 }
6670
6671 // If there's no signed wrap, and all the operands except initial value have
6672 // the same sign or zero, the value won't ever be:
6673 // 1: smaller than initial value if operands are non negative,
6674 // 2: bigger than initial value if operands are non positive.
6675 // For both cases, value can not cross signed min/max boundary.
6676 if (AddRec->hasNoSignedWrap()) {
6677 bool AllNonNeg = true;
6678 bool AllNonPos = true;
6679 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6680 if (!isKnownNonNegative(AddRec->getOperand(i)))
6681 AllNonNeg = false;
6682 if (!isKnownNonPositive(AddRec->getOperand(i)))
6683 AllNonPos = false;
6684 }
6685 if (AllNonNeg)
6686 ConservativeResult = ConservativeResult.intersectWith(
6687 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
6688 APInt::getSignedMinValue(BitWidth)),
6689 RangeType);
6690 else if (AllNonPos)
6691 ConservativeResult = ConservativeResult.intersectWith(
6692 ConstantRange::getNonEmpty(APInt::getSignedMinValue(BitWidth),
6693 getSignedRangeMax(AddRec->getStart()) +
6694 1),
6695 RangeType);
6696 }
6697
6698 // TODO: non-affine addrec
6699 if (AddRec->isAffine()) {
6700 const SCEV *MaxBECount =
6701 getConstantMaxBackedgeTakenCount(AddRec->getLoop());
6702 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
6703 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
6704 auto RangeFromAffine = getRangeForAffineAR(
6705 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6706 BitWidth);
6707 ConservativeResult =
6708 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6709
6710 auto RangeFromFactoring = getRangeViaFactoring(
6711 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
6712 BitWidth);
6713 ConservativeResult =
6714 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6715 }
6716
6717 // Now try symbolic BE count and more powerful methods.
6718 if (UseExpensiveRangeSharpening) {
6719 const SCEV *SymbolicMaxBECount =
6720 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
6721 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6722 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
6723 AddRec->hasNoSelfWrap()) {
6724 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6725 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6726 ConservativeResult =
6727 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6728 }
6729 }
6730 }
6731
6732 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6733 }
6734 case scUMaxExpr:
6735 case scSMaxExpr:
6736 case scUMinExpr:
6737 case scSMinExpr:
6738 case scSequentialUMinExpr: {
6739 Intrinsic::ID ID;
6740 switch (S->getSCEVType()) {
6741 case scUMaxExpr:
6742 ID = Intrinsic::umax;
6743 break;
6744 case scSMaxExpr:
6745 ID = Intrinsic::smax;
6746 break;
6747 case scUMinExpr:
6748 case scSequentialUMinExpr:
6749 ID = Intrinsic::umin;
6750 break;
6751 case scSMinExpr:
6752 ID = Intrinsic::smin;
6753 break;
6754 default:
6755 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.")::llvm::llvm_unreachable_internal("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr."
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6755)
;
6756 }
6757
6758 const auto *NAry = cast<SCEVNAryExpr>(S);
6759 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6760 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6761 X = X.intrinsic(
6762 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6763 return setRange(S, SignHint,
6764 ConservativeResult.intersectWith(X, RangeType));
6765 }
6766 case scUnknown: {
6767 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6768
6769 // Check if the IR explicitly contains !range metadata.
6770 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
6771 if (MDRange)
6772 ConservativeResult =
6773 ConservativeResult.intersectWith(*MDRange, RangeType);
6774
6775 // Use facts about recurrences in the underlying IR. Note that add
6776 // recurrences are AddRecExprs and thus don't hit this path. This
6777 // primarily handles shift recurrences.
6778 auto CR = getRangeForUnknownRecurrence(U);
6779 ConservativeResult = ConservativeResult.intersectWith(CR);
6780
6781 // See if ValueTracking can give us a useful range.
6782 const DataLayout &DL = getDataLayout();
6783 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6784 if (Known.getBitWidth() != BitWidth)
6785 Known = Known.zextOrTrunc(BitWidth);
6786
6787 // ValueTracking may be able to compute a tighter result for the number of
6788 // sign bits than for the value of those sign bits.
6789 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
6790 if (U->getType()->isPointerTy()) {
6791 // If the pointer size is larger than the index size type, this can cause
6792 // NS to be larger than BitWidth. So compensate for this.
6793 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6794 int ptrIdxDiff = ptrSize - BitWidth;
6795 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6796 NS -= ptrIdxDiff;
6797 }
6798
6799 if (NS > 1) {
6800 // If we know any of the sign bits, we know all of the sign bits.
6801 if (!Known.Zero.getHiBits(NS).isZero())
6802 Known.Zero.setHighBits(NS);
6803 if (!Known.One.getHiBits(NS).isZero())
6804 Known.One.setHighBits(NS);
6805 }
6806
6807 if (Known.getMinValue() != Known.getMaxValue() + 1)
6808 ConservativeResult = ConservativeResult.intersectWith(
6809 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6810 RangeType);
6811 if (NS > 1)
6812 ConservativeResult = ConservativeResult.intersectWith(
6813 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6814 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6815 RangeType);
6816
6817 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6818 // Strengthen the range if the underlying IR value is a global using the
6819 // size of the global.
6820 ObjectSizeOpts Opts;
6821 Opts.RoundToAlign = false;
6822 Opts.NullIsUnknownSize = true;
6823 uint64_t ObjSize;
6824 auto *GV = dyn_cast<GlobalVariable>(U->getValue());
6825 if (GV && getObjectSize(U->getValue(), ObjSize, DL, &TLI, Opts) &&
6826 ObjSize > 1) {
6827 // The highest address the object can start is ObjSize bytes before the
6828 // end (unsigned max value). If this value is not a multiple of the
6829 // alignment, the last possible start value is the next lowest multiple
6830 // of the alignment. Note: The computations below cannot overflow,
6831 // because if they would there's no possible start address for the
6832 // object.
6833 APInt MaxVal = APInt::getMaxValue(BitWidth) - APInt(BitWidth, ObjSize);
6834 uint64_t Align = GV->getAlign().valueOrOne().value();
6835 uint64_t Rem = MaxVal.urem(Align);
6836 MaxVal -= APInt(BitWidth, Rem);
6837 ConservativeResult = ConservativeResult.intersectWith(
6838 {ConservativeResult.getUnsignedMin(), MaxVal + 1}, RangeType);
6839 }
6840 }
6841
6842 // A range of Phi is a subset of union of all ranges of its input.
6843 if (PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
6844 // Make sure that we do not run over cycled Phis.
6845 if (PendingPhiRanges.insert(Phi).second) {
6846 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6847
6848 for (const auto &Op : Phi->operands()) {
6849 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
6850 RangeFromOps = RangeFromOps.unionWith(OpRange);
6851 // No point to continue if we already have a full set.
6852 if (RangeFromOps.isFullSet())
6853 break;
6854 }
6855 ConservativeResult =
6856 ConservativeResult.intersectWith(RangeFromOps, RangeType);
6857 bool Erased = PendingPhiRanges.erase(Phi);
6858 assert(Erased && "Failed to erase Phi properly?")(static_cast <bool> (Erased && "Failed to erase Phi properly?"
) ? void (0) : __assert_fail ("Erased && \"Failed to erase Phi properly?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6858, __extension__
__PRETTY_FUNCTION__))
;
6859 (void)Erased;
6860 }
6861 }
6862
6863 // vscale can't be equal to zero
6864 if (const auto *II = dyn_cast<IntrinsicInst>(U->getValue()))
6865 if (II->getIntrinsicID() == Intrinsic::vscale) {
6866 ConstantRange Disallowed = APInt::getZero(BitWidth);
6867 ConservativeResult = ConservativeResult.difference(Disallowed);
6868 }
6869
6870 return setRange(U, SignHint, std::move(ConservativeResult));
6871 }
6872 case scCouldNotCompute:
6873 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6873)
;
6874 }
6875
6876 return setRange(S, SignHint, std::move(ConservativeResult));
6877}
6878
6879// Given a StartRange, Step and MaxBECount for an expression compute a range of
6880// values that the expression can take. Initially, the expression has a value
6881// from StartRange and then is changed by Step up to MaxBECount times. Signed
6882// argument defines if we treat Step as signed or unsigned.
6883static ConstantRange getRangeForAffineARHelper(APInt Step,
6884 const ConstantRange &StartRange,
6885 const APInt &MaxBECount,
6886 unsigned BitWidth, bool Signed) {
6887 // If either Step or MaxBECount is 0, then the expression won't change, and we
6888 // just need to return the initial range.
6889 if (Step == 0 || MaxBECount == 0)
6890 return StartRange;
6891
6892 // If we don't know anything about the initial value (i.e. StartRange is
6893 // FullRange), then we don't know anything about the final range either.
6894 // Return FullRange.
6895 if (StartRange.isFullSet())
6896 return ConstantRange::getFull(BitWidth);
6897
6898 // If Step is signed and negative, then we use its absolute value, but we also
6899 // note that we're moving in the opposite direction.
6900 bool Descending = Signed && Step.isNegative();
6901
6902 if (Signed)
6903 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
6904 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
6905 // This equations hold true due to the well-defined wrap-around behavior of
6906 // APInt.
6907 Step = Step.abs();
6908
6909 // Check if Offset is more than full span of BitWidth. If it is, the
6910 // expression is guaranteed to overflow.
6911 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
6912 return ConstantRange::getFull(BitWidth);
6913
6914 // Offset is by how much the expression can change. Checks above guarantee no
6915 // overflow here.
6916 APInt Offset = Step * MaxBECount;
6917
6918 // Minimum value of the final range will match the minimal value of StartRange
6919 // if the expression is increasing and will be decreased by Offset otherwise.
6920 // Maximum value of the final range will match the maximal value of StartRange
6921 // if the expression is decreasing and will be increased by Offset otherwise.
6922 APInt StartLower = StartRange.getLower();
6923 APInt StartUpper = StartRange.getUpper() - 1;
6924 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
6925 : (StartUpper + std::move(Offset));
6926
6927 // It's possible that the new minimum/maximum value will fall into the initial
6928 // range (due to wrap around). This means that the expression can take any
6929 // value in this bitwidth, and we have to return full range.
6930 if (StartRange.contains(MovedBoundary))
6931 return ConstantRange::getFull(BitWidth);
6932
6933 APInt NewLower =
6934 Descending ? std::move(MovedBoundary) : std::move(StartLower);
6935 APInt NewUpper =
6936 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
6937 NewUpper += 1;
6938
6939 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
6940 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
6941}
6942
6943ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
6944 const SCEV *Step,
6945 const SCEV *MaxBECount,
6946 unsigned BitWidth) {
6947 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&(static_cast <bool> (!isa<SCEVCouldNotCompute>(MaxBECount
) && getTypeSizeInBits(MaxBECount->getType()) <=
BitWidth && "Precondition!") ? void (0) : __assert_fail
("!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && \"Precondition!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6949, __extension__
__PRETTY_FUNCTION__))
6948 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&(static_cast <bool> (!isa<SCEVCouldNotCompute>(MaxBECount
) && getTypeSizeInBits(MaxBECount->getType()) <=
BitWidth && "Precondition!") ? void (0) : __assert_fail
("!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && \"Precondition!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6949, __extension__
__PRETTY_FUNCTION__))
6949 "Precondition!")(static_cast <bool> (!isa<SCEVCouldNotCompute>(MaxBECount
) && getTypeSizeInBits(MaxBECount->getType()) <=
BitWidth && "Precondition!") ? void (0) : __assert_fail
("!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && \"Precondition!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6949, __extension__
__PRETTY_FUNCTION__))
;
6950
6951 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
6952 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
6953
6954 // First, consider step signed.
6955 ConstantRange StartSRange = getSignedRange(Start);
6956 ConstantRange StepSRange = getSignedRange(Step);
6957
6958 // If Step can be both positive and negative, we need to find ranges for the
6959 // maximum absolute step values in both directions and union them.
6960 ConstantRange SR =
6961 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
6962 MaxBECountValue, BitWidth, /* Signed = */ true);
6963 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
6964 StartSRange, MaxBECountValue,
6965 BitWidth, /* Signed = */ true));
6966
6967 // Next, consider step unsigned.
6968 ConstantRange UR = getRangeForAffineARHelper(
6969 getUnsignedRangeMax(Step), getUnsignedRange(Start),
6970 MaxBECountValue, BitWidth, /* Signed = */ false);
6971
6972 // Finally, intersect signed and unsigned ranges.
6973 return SR.intersectWith(UR, ConstantRange::Smallest);
6974}
6975
6976ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
6977 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
6978 ScalarEvolution::RangeSignHint SignHint) {
6979 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n")(static_cast <bool> (AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"
) ? void (0) : __assert_fail ("AddRec->isAffine() && \"Non-affine AddRecs are not suppored!\\n\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6979, __extension__
__PRETTY_FUNCTION__))
;
6980 assert(AddRec->hasNoSelfWrap() &&(static_cast <bool> (AddRec->hasNoSelfWrap() &&
"This only works for non-self-wrapping AddRecs!") ? void (0)
: __assert_fail ("AddRec->hasNoSelfWrap() && \"This only works for non-self-wrapping AddRecs!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6981, __extension__
__PRETTY_FUNCTION__))
6981 "This only works for non-self-wrapping AddRecs!")(static_cast <bool> (AddRec->hasNoSelfWrap() &&
"This only works for non-self-wrapping AddRecs!") ? void (0)
: __assert_fail ("AddRec->hasNoSelfWrap() && \"This only works for non-self-wrapping AddRecs!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 6981, __extension__
__PRETTY_FUNCTION__))
;
6982 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
6983 const SCEV *Step = AddRec->getStepRecurrence(*this);
6984 // Only deal with constant step to save compile time.
6985 if (!isa<SCEVConstant>(Step))
6986 return ConstantRange::getFull(BitWidth);
6987 // Let's make sure that we can prove that we do not self-wrap during
6988 // MaxBECount iterations. We need this because MaxBECount is a maximum
6989 // iteration count estimate, and we might infer nw from some exit for which we
6990 // do not know max exit count (or any other side reasoning).
6991 // TODO: Turn into assert at some point.
6992 if (getTypeSizeInBits(MaxBECount->getType()) >
6993 getTypeSizeInBits(AddRec->getType()))
6994 return ConstantRange::getFull(BitWidth);
6995 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
6996 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
6997 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
6998 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
6999 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7000 MaxItersWithoutWrap))
7001 return ConstantRange::getFull(BitWidth);
7002
7003 ICmpInst::Predicate LEPred =
7004 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
7005 ICmpInst::Predicate GEPred =
7006 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
7007 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7008
7009 // We know that there is no self-wrap. Let's take Start and End values and
7010 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7011 // the iteration. They either lie inside the range [Min(Start, End),
7012 // Max(Start, End)] or outside it:
7013 //
7014 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7015 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7016 //
7017 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7018 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7019 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7020 // Start <= End and step is positive, or Start >= End and step is negative.
7021 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7022 ConstantRange StartRange = getRangeRef(Start, SignHint);
7023 ConstantRange EndRange = getRangeRef(End, SignHint);
7024 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7025 // If they already cover full iteration space, we will know nothing useful
7026 // even if we prove what we want to prove.
7027 if (RangeBetween.isFullSet())
7028 return RangeBetween;
7029 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7030 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7031 : RangeBetween.isWrappedSet();
7032 if (IsWrappedSet)
7033 return ConstantRange::getFull(BitWidth);
7034
7035 if (isKnownPositive(Step) &&
7036 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7037 return RangeBetween;
7038 if (isKnownNegative(Step) &&
7039 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7040 return RangeBetween;
7041 return ConstantRange::getFull(BitWidth);
7042}
7043
7044ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7045 const SCEV *Step,
7046 const SCEV *MaxBECount,
7047 unsigned BitWidth) {
7048 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7049 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7050
7051 struct SelectPattern {
7052 Value *Condition = nullptr;
7053 APInt TrueValue;
7054 APInt FalseValue;
7055
7056 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7057 const SCEV *S) {
7058 std::optional<unsigned> CastOp;
7059 APInt Offset(BitWidth, 0);
7060
7061 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&(static_cast <bool> (SE.getTypeSizeInBits(S->getType
()) == BitWidth && "Should be!") ? void (0) : __assert_fail
("SE.getTypeSizeInBits(S->getType()) == BitWidth && \"Should be!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 7062, __extension__
__PRETTY_FUNCTION__))
7062 "Should be!")(static_cast <bool> (SE.getTypeSizeInBits(S->getType
()) == BitWidth && "Should be!") ? void (0) : __assert_fail
("SE.getTypeSizeInBits(S->getType()) == BitWidth && \"Should be!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 7062, __extension__
__PRETTY_FUNCTION__))
;
7063
7064 // Peel off a constant offset:
7065 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
7066 // In the future we could consider being smarter here and handle
7067 // {Start+Step,+,Step} too.
7068 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
7069 return;
7070
7071 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
7072 S = SA->getOperand(1);
7073 }
7074
7075 // Peel off a cast operation
7076 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7077 CastOp = SCast->getSCEVType();
7078 S = SCast->getOperand();
7079 }
7080
7081 using namespace llvm::PatternMatch;
7082
7083 auto *SU = dyn_cast<SCEVUnknown>(S);
7084 const APInt *TrueVal, *FalseVal;
7085 if (!SU ||
7086 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7087 m_APInt(FalseVal)))) {
7088 Condition = nullptr;
7089 return;
7090 }
7091
7092 TrueValue = *TrueVal;
7093 FalseValue = *FalseVal;
7094
7095 // Re-apply the cast we peeled off earlier
7096 if (CastOp)
7097 switch (*CastOp) {
7098 default:
7099 llvm_unreachable("Unknown SCEV cast type!")::llvm::llvm_unreachable_internal("Unknown SCEV cast type!", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 7099)
;
7100
7101 case scTruncate:
7102 TrueValue = TrueValue.trunc(BitWidth);
7103 FalseValue = FalseValue.trunc(BitWidth);
7104 break;
7105 case scZeroExtend:
7106 TrueValue = TrueValue.zext(BitWidth);
7107 FalseValue = FalseValue.zext(BitWidth);
7108 break;
7109 case scSignExtend:
7110 TrueValue = TrueValue.sext(BitWidth);
7111 FalseValue = FalseValue.sext(BitWidth);
7112 break;
7113 }
7114
7115 // Re-apply the constant offset we peeled off earlier
7116 TrueValue += Offset;
7117 FalseValue += Offset;
7118 }
7119
7120 bool isRecognized() { return Condition != nullptr; }
7121 };
7122
7123 SelectPattern StartPattern(*this, BitWidth, Start);
7124 if (!StartPattern.isRecognized())
7125 return ConstantRange::getFull(BitWidth);
7126
7127 SelectPattern StepPattern(*this, BitWidth, Step);
7128 if (!StepPattern.isRecognized())
7129 return ConstantRange::getFull(BitWidth);
7130
7131 if (StartPattern.Condition != StepPattern.Condition) {
7132 // We don't handle this case today; but we could, by considering four
7133 // possibilities below instead of two. I'm not sure if there are cases where
7134 // that will help over what getRange already does, though.
7135 return ConstantRange::getFull(BitWidth);
7136 }
7137
7138 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7139 // construct arbitrary general SCEV expressions here. This function is called
7140 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7141 // say) can end up caching a suboptimal value.
7142
7143 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7144 // C2352 and C2512 (otherwise it isn't needed).
7145
7146 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7147 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7148 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7149 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7150
7151 ConstantRange TrueRange =
7152 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
7153 ConstantRange FalseRange =
7154 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
7155
7156 return TrueRange.unionWith(FalseRange);
7157}
7158
7159SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7160 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
7161 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7162
7163 // Return early if there are no flags to propagate to the SCEV.
7164 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
7165 if (BinOp->hasNoUnsignedWrap())
7166 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
7167 if (BinOp->hasNoSignedWrap())
7168 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
7169 if (Flags == SCEV::FlagAnyWrap)
7170 return SCEV::FlagAnyWrap;
7171
7172 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
7173}
7174
7175const Instruction *
7176ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7177 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7178 return &*AddRec->getLoop()->getHeader()->begin();
7179 if (auto *U = dyn_cast<SCEVUnknown>(S))
7180 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7181 return I;
7182 return nullptr;
7183}
7184
7185const Instruction *
7186ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops,
7187 bool &Precise) {
7188 Precise = true;
7189 // Do a bounded search of the def relation of the requested SCEVs.
7190 SmallSet<const SCEV *, 16> Visited;
7191 SmallVector<const SCEV *> Worklist;
7192 auto pushOp = [&](const SCEV *S) {
7193 if (!Visited.insert(S).second)
7194 return;
7195 // Threshold of 30 here is arbitrary.
7196 if (Visited.size() > 30) {
7197 Precise = false;
7198 return;
7199 }
7200 Worklist.push_back(S);
7201 };
7202
7203 for (const auto *S : Ops)
7204 pushOp(S);
7205
7206 const Instruction *Bound = nullptr;
7207 while (!Worklist.empty()) {
7208 auto *S = Worklist.pop_back_val();
7209 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7210 if (!Bound || DT.dominates(Bound, DefI))
7211 Bound = DefI;
7212 } else {
7213 for (const auto *Op : S->operands())
7214 pushOp(Op);
7215 }
7216 }
7217 return Bound ? Bound : &*F.getEntryBlock().begin();
7218}
7219
7220const Instruction *
7221ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) {
7222 bool Discard;
7223 return getDefiningScopeBound(Ops, Discard);
7224}
7225
7226bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7227 const Instruction *B) {
7228 if (A->getParent() == B->getParent() &&
7229 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7230 B->getIterator()))
7231 return true;
7232
7233 auto *BLoop = LI.getLoopFor(B->getParent());
7234 if (BLoop && BLoop->getHeader() == B->getParent() &&
7235 BLoop->getLoopPreheader() == A->getParent() &&
7236 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
7237 A->getParent()->end()) &&
7238 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7239 B->getIterator()))
7240 return true;
7241 return false;
7242}
7243
7244
7245bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7246 // Only proceed if we can prove that I does not yield poison.
7247 if (!programUndefinedIfPoison(I))
7248 return false;
7249
7250 // At this point we know that if I is executed, then it does not wrap
7251 // according to at least one of NSW or NUW. If I is not executed, then we do
7252 // not know if the calculation that I represents would wrap. Multiple
7253 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7254 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7255 // derived from other instructions that map to the same SCEV. We cannot make
7256 // that guarantee for cases where I is not executed. So we need to find a
7257 // upper bound on the defining scope for the SCEV, and prove that I is
7258 // executed every time we enter that scope. When the bounding scope is a
7259 // loop (the common case), this is equivalent to proving I executes on every
7260 // iteration of that loop.
7261 SmallVector<const SCEV *> SCEVOps;
7262 for (const Use &Op : I->operands()) {
7263 // I could be an extractvalue from a call to an overflow intrinsic.
7264 // TODO: We can do better here in some cases.
7265 if (isSCEVable(Op->getType()))
7266 SCEVOps.push_back(getSCEV(Op));
7267 }
7268 auto *DefI = getDefiningScopeBound(SCEVOps);
7269 return isGuaranteedToTransferExecutionTo(DefI, I);
7270}
7271
7272bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7273 // If we know that \c I can never be poison period, then that's enough.
7274 if (isSCEVExprNeverPoison(I))
7275 return true;
7276
7277 // If the loop only has one exit, then we know that, if the loop is entered,
7278 // any instruction dominating that exit will be executed. If any such
7279 // instruction would result in UB, the addrec cannot be poison.
7280 //
7281 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7282 // also handles uses outside the loop header (they just need to dominate the
7283 // single exit).
7284
7285 auto *ExitingBB = L->getExitingBlock();
7286 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7287 return false;
7288
7289 SmallPtrSet<const Value *, 16> KnownPoison;
7290 SmallVector<const Instruction *, 8> Worklist;
7291
7292 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7293 // things that are known to be poison under that assumption go on the
7294 // Worklist.
7295 KnownPoison.insert(I);
7296 Worklist.push_back(I);
7297
7298 while (!Worklist.empty()) {
7299 const Instruction *Poison = Worklist.pop_back_val();
7300
7301 for (const Use &U : Poison->uses()) {
7302 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7303 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7304 DT.dominates(PoisonUser->getParent(), ExitingBB))
7305 return true;
7306
7307 if (propagatesPoison(U) && L->contains(PoisonUser))
7308 if (KnownPoison.insert(PoisonUser).second)
7309 Worklist.push_back(PoisonUser);
7310 }
7311 }
7312
7313 return false;
7314}
7315
7316ScalarEvolution::LoopProperties
7317ScalarEvolution::getLoopProperties(const Loop *L) {
7318 using LoopProperties = ScalarEvolution::LoopProperties;
7319
7320 auto Itr = LoopPropertiesCache.find(L);
7321 if (Itr == LoopPropertiesCache.end()) {
7322 auto HasSideEffects = [](Instruction *I) {
7323 if (auto *SI = dyn_cast<StoreInst>(I))
7324 return !SI->isSimple();
7325
7326 return I->mayThrow() || I->mayWriteToMemory();
7327 };
7328
7329 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7330 /*HasNoSideEffects*/ true};
7331
7332 for (auto *BB : L->getBlocks())
7333 for (auto &I : *BB) {
7334 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
7335 LP.HasNoAbnormalExits = false;
7336 if (HasSideEffects(&I))
7337 LP.HasNoSideEffects = false;
7338 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7339 break; // We're already as pessimistic as we can get.
7340 }
7341
7342 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7343 assert(InsertPair.second && "We just checked!")(static_cast <bool> (InsertPair.second && "We just checked!"
) ? void (0) : __assert_fail ("InsertPair.second && \"We just checked!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 7343, __extension__
__PRETTY_FUNCTION__))
;
7344 Itr = InsertPair.first;
7345 }
7346
7347 return Itr->second;
7348}
7349
7350bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
7351 // A mustprogress loop without side effects must be finite.
7352 // TODO: The check used here is very conservative. It's only *specific*
7353 // side effects which are well defined in infinite loops.
7354 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7355}
7356
7357const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7358 // Worklist item with a Value and a bool indicating whether all operands have
7359 // been visited already.
7360 using PointerTy = PointerIntPair<Value *, 1, bool>;
7361 SmallVector<PointerTy> Stack;
7362
7363 Stack.emplace_back(V, true);
7364 Stack.emplace_back(V, false);
7365 while (!Stack.empty()) {
7366 auto E = Stack.pop_back_val();
7367 Value *CurV = E.getPointer();
7368
7369 if (getExistingSCEV(CurV))
7370 continue;
7371
7372 SmallVector<Value *> Ops;
7373 const SCEV *CreatedSCEV = nullptr;
7374 // If all operands have been visited already, create the SCEV.
7375 if (E.getInt()) {
7376 CreatedSCEV = createSCEV(CurV);
7377 } else {
7378 // Otherwise get the operands we need to create SCEV's for before creating
7379 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7380 // just use it.
7381 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7382 }
7383
7384 if (CreatedSCEV) {
7385 insertValueToMap(CurV, CreatedSCEV);
7386 } else {
7387 // Queue CurV for SCEV creation, followed by its's operands which need to
7388 // be constructed first.
7389 Stack.emplace_back(CurV, true);
7390 for (Value *Op : Ops)
7391 Stack.emplace_back(Op, false);
7392 }
7393 }
7394
7395 return getExistingSCEV(V);
7396}
7397
7398const SCEV *
7399ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7400 if (!isSCEVable(V->getType()))
7401 return getUnknown(V);
7402
7403 if (Instruction *I = dyn_cast<Instruction>(V)) {
7404 // Don't attempt to analyze instructions in blocks that aren't
7405 // reachable. Such instructions don't matter, and they aren't required
7406 // to obey basic rules for definitions dominating uses which this
7407 // analysis depends on.
7408 if (!DT.isReachableFromEntry(I->getParent()))
7409 return getUnknown(PoisonValue::get(V->getType()));
7410 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7411 return getConstant(CI);
7412 else if (isa<GlobalAlias>(V))
7413 return getUnknown(V);
7414 else if (!isa<ConstantExpr>(V))
7415 return getUnknown(V);
7416
7417 Operator *U = cast<Operator>(V);
7418 if (auto BO =
7419 MatchBinaryOp(U, getDataLayout(), AC, DT, dyn_cast<Instruction>(V))) {
7420 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7421 switch (BO->Opcode) {
7422 case Instruction::Add:
7423 case Instruction::Mul: {
7424 // For additions and multiplications, traverse add/mul chains for which we
7425 // can potentially create a single SCEV, to reduce the number of
7426 // get{Add,Mul}Expr calls.
7427 do {
7428 if (BO->Op) {
7429 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7430 Ops.push_back(BO->Op);
7431 break;
7432 }
7433 }
7434 Ops.push_back(BO->RHS);
7435 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7436 dyn_cast<Instruction>(V));
7437 if (!NewBO ||
7438 (BO->Opcode == Instruction::Add &&
7439 (NewBO->Opcode != Instruction::Add &&
7440 NewBO->Opcode != Instruction::Sub)) ||
7441 (BO->Opcode == Instruction::Mul &&
7442 NewBO->Opcode != Instruction::Mul)) {
7443 Ops.push_back(BO->LHS);
7444 break;
7445 }
7446 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7447 // requires a SCEV for the LHS.
7448 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7449 auto *I = dyn_cast<Instruction>(BO->Op);
7450 if (I && programUndefinedIfPoison(I)) {
7451 Ops.push_back(BO->LHS);
7452 break;
7453 }
7454 }
7455 BO = NewBO;
7456 } while (true);
7457 return nullptr;
7458 }
7459 case Instruction::Sub:
7460 case Instruction::UDiv:
7461 case Instruction::URem:
7462 break;
7463 case Instruction::AShr:
7464 case Instruction::Shl:
7465 case Instruction::Xor:
7466 if (!IsConstArg)
7467 return nullptr;
7468 break;
7469 case Instruction::And:
7470 case Instruction::Or:
7471 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7472 return nullptr;
7473 break;
7474 case Instruction::LShr:
7475 return getUnknown(V);
7476 default:
7477 llvm_unreachable("Unhandled binop")::llvm::llvm_unreachable_internal("Unhandled binop", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 7477)
;
7478 break;
7479 }
7480
7481 Ops.push_back(BO->LHS);
7482 Ops.push_back(BO->RHS);
7483 return nullptr;
7484 }
7485
7486 switch (U->getOpcode()) {
7487 case Instruction::Trunc:
7488 case Instruction::ZExt:
7489 case Instruction::SExt:
7490 case Instruction::PtrToInt:
7491 Ops.push_back(U->getOperand(0));
7492 return nullptr;
7493
7494 case Instruction::BitCast:
7495 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7496 Ops.push_back(U->getOperand(0));
7497 return nullptr;
7498 }
7499 return getUnknown(V);
7500
7501 case Instruction::SDiv:
7502 case Instruction::SRem:
7503 Ops.push_back(U->getOperand(0));
7504 Ops.push_back(U->getOperand(1));
7505 return nullptr;
7506
7507 case Instruction::GetElementPtr:
7508 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&(static_cast <bool> (cast<GEPOperator>(U)->getSourceElementType
()->isSized() && "GEP source element type must be sized"
) ? void (0) : __assert_fail ("cast<GEPOperator>(U)->getSourceElementType()->isSized() && \"GEP source element type must be sized\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 7509, __extension__
__PRETTY_FUNCTION__))
7509 "GEP source element type must be sized")(static_cast <bool> (cast<GEPOperator>(U)->getSourceElementType
()->isSized() && "GEP source element type must be sized"
) ? void (0) : __assert_fail ("cast<GEPOperator>(U)->getSourceElementType()->isSized() && \"GEP source element type must be sized\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 7509, __extension__
__PRETTY_FUNCTION__))
;
7510 for (Value *Index : U->operands())
7511 Ops.push_back(Index);
7512 return nullptr;
7513
7514 case Instruction::IntToPtr:
7515 return getUnknown(V);
7516
7517 case Instruction::PHI:
7518 // Keep constructing SCEVs' for phis recursively for now.
7519 return nullptr;
7520
7521 case Instruction::Select: {
7522 // Check if U is a select that can be simplified to a SCEVUnknown.
7523 auto CanSimplifyToUnknown = [this, U]() {
7524 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7525 return false;
7526
7527 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7528 if (!ICI)
7529 return false;
7530 Value *LHS = ICI->getOperand(0);
7531 Value *RHS = ICI->getOperand(1);
7532 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7533 ICI->getPredicate() == CmpInst::ICMP_NE) {
7534 if (!(isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()))
7535 return true;
7536 } else if (getTypeSizeInBits(LHS->getType()) >
7537 getTypeSizeInBits(U->getType()))
7538 return true;
7539 return false;
7540 };
7541 if (CanSimplifyToUnknown())
7542 return getUnknown(U);
7543
7544 for (Value *Inc : U->operands())
7545 Ops.push_back(Inc);
7546 return nullptr;
7547 break;
7548 }
7549 case Instruction::Call:
7550 case Instruction::Invoke:
7551 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7552 Ops.push_back(RV);
7553 return nullptr;
7554 }
7555
7556 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7557 switch (II->getIntrinsicID()) {
7558 case Intrinsic::abs:
7559 Ops.push_back(II->getArgOperand(0));
7560 return nullptr;
7561 case Intrinsic::umax:
7562 case Intrinsic::umin:
7563 case Intrinsic::smax:
7564 case Intrinsic::smin:
7565 case Intrinsic::usub_sat:
7566 case Intrinsic::uadd_sat:
7567 Ops.push_back(II->getArgOperand(0));
7568 Ops.push_back(II->getArgOperand(1));
7569 return nullptr;
7570 case Intrinsic::start_loop_iterations:
7571 case Intrinsic::annotation:
7572 case Intrinsic::ptr_annotation:
7573 Ops.push_back(II->getArgOperand(0));
7574 return nullptr;
7575 default:
7576 break;
7577 }
7578 }
7579 break;
7580 }
7581
7582 return nullptr;
7583}
7584
7585const SCEV *ScalarEvolution::createSCEV(Value *V) {
7586 if (!isSCEVable(V->getType()))
7587 return getUnknown(V);
7588
7589 if (Instruction *I = dyn_cast<Instruction>(V)) {
7590 // Don't attempt to analyze instructions in blocks that aren't
7591 // reachable. Such instructions don't matter, and they aren't required
7592 // to obey basic rules for definitions dominating uses which this
7593 // analysis depends on.
7594 if (!DT.isReachableFromEntry(I->getParent()))
7595 return getUnknown(PoisonValue::get(V->getType()));
7596 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7597 return getConstant(CI);
7598 else if (isa<GlobalAlias>(V))
7599 return getUnknown(V);
7600 else if (!isa<ConstantExpr>(V))
7601 return getUnknown(V);
7602
7603 const SCEV *LHS;
7604 const SCEV *RHS;
7605
7606 Operator *U = cast<Operator>(V);
7607 if (auto BO =
7608 MatchBinaryOp(U, getDataLayout(), AC, DT, dyn_cast<Instruction>(V))) {
7609 switch (BO->Opcode) {
7610 case Instruction::Add: {
7611 // The simple thing to do would be to just call getSCEV on both operands
7612 // and call getAddExpr with the result. However if we're looking at a
7613 // bunch of things all added together, this can be quite inefficient,
7614 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7615 // Instead, gather up all the operands and make a single getAddExpr call.
7616 // LLVM IR canonical form means we need only traverse the left operands.
7617 SmallVector<const SCEV *, 4> AddOps;
7618 do {
7619 if (BO->Op) {
7620 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7621 AddOps.push_back(OpSCEV);
7622 break;
7623 }
7624
7625 // If a NUW or NSW flag can be applied to the SCEV for this
7626 // addition, then compute the SCEV for this addition by itself
7627 // with a separate call to getAddExpr. We need to do that
7628 // instead of pushing the operands of the addition onto AddOps,
7629 // since the flags are only known to apply to this particular
7630 // addition - they may not apply to other additions that can be
7631 // formed with operands from AddOps.
7632 const SCEV *RHS = getSCEV(BO->RHS);
7633 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7634 if (Flags != SCEV::FlagAnyWrap) {
7635 const SCEV *LHS = getSCEV(BO->LHS);
7636 if (BO->Opcode == Instruction::Sub)
7637 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7638 else
7639 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7640 break;
7641 }
7642 }
7643
7644 if (BO->Opcode == Instruction::Sub)
7645 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7646 else
7647 AddOps.push_back(getSCEV(BO->RHS));
7648
7649 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7650 dyn_cast<Instruction>(V));
7651 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7652 NewBO->Opcode != Instruction::Sub)) {
7653 AddOps.push_back(getSCEV(BO->LHS));
7654 break;
7655 }
7656 BO = NewBO;
7657 } while (true);
7658
7659 return getAddExpr(AddOps);
7660 }
7661
7662 case Instruction::Mul: {
7663 SmallVector<const SCEV *, 4> MulOps;
7664 do {
7665 if (BO->Op) {
7666 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7667 MulOps.push_back(OpSCEV);
7668 break;
7669 }
7670
7671 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7672 if (Flags != SCEV::FlagAnyWrap) {
7673 LHS = getSCEV(BO->LHS);
7674 RHS = getSCEV(BO->RHS);
7675 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7676 break;
7677 }
7678 }
7679
7680 MulOps.push_back(getSCEV(BO->RHS));
7681 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7682 dyn_cast<Instruction>(V));
7683 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7684 MulOps.push_back(getSCEV(BO->LHS));
7685 break;
7686 }
7687 BO = NewBO;
7688 } while (true);
7689
7690 return getMulExpr(MulOps);
7691 }
7692 case Instruction::UDiv:
7693 LHS = getSCEV(BO->LHS);
7694 RHS = getSCEV(BO->RHS);
7695 return getUDivExpr(LHS, RHS);
7696 case Instruction::URem:
7697 LHS = getSCEV(BO->LHS);
7698 RHS = getSCEV(BO->RHS);
7699 return getURemExpr(LHS, RHS);
7700 case Instruction::Sub: {
7701 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
7702 if (BO->Op)
7703 Flags = getNoWrapFlagsFromUB(BO->Op);
7704 LHS = getSCEV(BO->LHS);
7705 RHS = getSCEV(BO->RHS);
7706 return getMinusSCEV(LHS, RHS, Flags);
7707 }
7708 case Instruction::And:
7709 // For an expression like x&255 that merely masks off the high bits,
7710 // use zext(trunc(x)) as the SCEV expression.
7711 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7712 if (CI->isZero())
7713 return getSCEV(BO->RHS);
7714 if (CI->isMinusOne())
7715 return getSCEV(BO->LHS);
7716 const APInt &A = CI->getValue();
7717
7718 // Instcombine's ShrinkDemandedConstant may strip bits out of
7719 // constants, obscuring what would otherwise be a low-bits mask.
7720 // Use computeKnownBits to compute what ShrinkDemandedConstant
7721 // knew about to reconstruct a low-bits mask value.
7722 unsigned LZ = A.countl_zero();
7723 unsigned TZ = A.countr_zero();
7724 unsigned BitWidth = A.getBitWidth();
7725 KnownBits Known(BitWidth);
7726 computeKnownBits(BO->LHS, Known, getDataLayout(),
7727 0, &AC, nullptr, &DT);
7728
7729 APInt EffectiveMask =
7730 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7731 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7732 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7733 const SCEV *LHS = getSCEV(BO->LHS);
7734 const SCEV *ShiftedLHS = nullptr;
7735 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7736 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7737 // For an expression like (x * 8) & 8, simplify the multiply.
7738 unsigned MulZeros = OpC->getAPInt().countr_zero();
7739 unsigned GCD = std::min(MulZeros, TZ);
7740 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7741 SmallVector<const SCEV*, 4> MulOps;
7742 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
7743 append_range(MulOps, LHSMul->operands().drop_front());
7744 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7745 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
7746 }
7747 }
7748 if (!ShiftedLHS)
7749 ShiftedLHS = getUDivExpr(LHS, MulCount);
7750 return getMulExpr(
7751 getZeroExtendExpr(
7752 getTruncateExpr(ShiftedLHS,
7753 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
7754 BO->LHS->getType()),
7755 MulCount);
7756 }
7757 }
7758 // Binary `and` is a bit-wise `umin`.
7759 if (BO->LHS->getType()->isIntegerTy(1)) {
7760 LHS = getSCEV(BO->LHS);
7761 RHS = getSCEV(BO->RHS);
7762 return getUMinExpr(LHS, RHS);
7763 }
7764 break;
7765
7766 case Instruction::Or:
7767 // Binary `or` is a bit-wise `umax`.
7768 if (BO->LHS->getType()->isIntegerTy(1)) {
7769 LHS = getSCEV(BO->LHS);
7770 RHS = getSCEV(BO->RHS);
7771 return getUMaxExpr(LHS, RHS);
7772 }
7773 break;
7774
7775 case Instruction::Xor:
7776 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7777 // If the RHS of xor is -1, then this is a not operation.
7778 if (CI->isMinusOne())
7779 return getNotSCEV(getSCEV(BO->LHS));
7780
7781 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
7782 // This is a variant of the check for xor with -1, and it handles
7783 // the case where instcombine has trimmed non-demanded bits out
7784 // of an xor with -1.
7785 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
7786 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
7787 if (LBO->getOpcode() == Instruction::And &&
7788 LCI->getValue() == CI->getValue())
7789 if (const SCEVZeroExtendExpr *Z =
7790 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
7791 Type *UTy = BO->LHS->getType();
7792 const SCEV *Z0 = Z->getOperand();
7793 Type *Z0Ty = Z0->getType();
7794 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
7795
7796 // If C is a low-bits mask, the zero extend is serving to
7797 // mask off the high bits. Complement the operand and
7798 // re-apply the zext.
7799 if (CI->getValue().isMask(Z0TySize))
7800 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
7801
7802 // If C is a single bit, it may be in the sign-bit position
7803 // before the zero-extend. In this case, represent the xor
7804 // using an add, which is equivalent, and re-apply the zext.
7805 APInt Trunc = CI->getValue().trunc(Z0TySize);
7806 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
7807 Trunc.isSignMask())
7808 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
7809 UTy);
7810 }
7811 }
7812 break;
7813
7814 case Instruction::Shl:
7815 // Turn shift left of a constant amount into a multiply.
7816 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
7817 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
7818
7819 // If the shift count is not less than the bitwidth, the result of
7820 // the shift is undefined. Don't try to analyze it, because the
7821 // resolution chosen here may differ from the resolution chosen in
7822 // other parts of the compiler.
7823 if (SA->getValue().uge(BitWidth))
7824 break;
7825
7826 // We can safely preserve the nuw flag in all cases. It's also safe to
7827 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
7828 // requires special handling. It can be preserved as long as we're not
7829 // left shifting by bitwidth - 1.
7830 auto Flags = SCEV::FlagAnyWrap;
7831 if (BO->Op) {
7832 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
7833 if ((MulFlags & SCEV::FlagNSW) &&
7834 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
7835 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
7836 if (MulFlags & SCEV::FlagNUW)
7837 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
7838 }
7839
7840 ConstantInt *X = ConstantInt::get(
7841 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
7842 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
7843 }
7844 break;
7845
7846 case Instruction::AShr: {
7847 // AShr X, C, where C is a constant.
7848 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
7849 if (!CI)
7850 break;
7851
7852 Type *OuterTy = BO->LHS->getType();
7853 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
7854 // If the shift count is not less than the bitwidth, the result of
7855 // the shift is undefined. Don't try to analyze it, because the
7856 // resolution chosen here may differ from the resolution chosen in
7857 // other parts of the compiler.
7858 if (CI->getValue().uge(BitWidth))
7859 break;
7860
7861 if (CI->isZero())
7862 return getSCEV(BO->LHS); // shift by zero --> noop
7863
7864 uint64_t AShrAmt = CI->getZExtValue();
7865 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
7866
7867 Operator *L = dyn_cast<Operator>(BO->LHS);
7868 if (L && L->getOpcode() == Instruction::Shl) {
7869 // X = Shl A, n
7870 // Y = AShr X, m
7871 // Both n and m are constant.
7872
7873 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
7874 if (L->getOperand(1) == BO->RHS)
7875 // For a two-shift sext-inreg, i.e. n = m,
7876 // use sext(trunc(x)) as the SCEV expression.
7877 return getSignExtendExpr(
7878 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
7879
7880 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
7881 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
7882 uint64_t ShlAmt = ShlAmtCI->getZExtValue();
7883 if (ShlAmt > AShrAmt) {
7884 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
7885 // expression. We already checked that ShlAmt < BitWidth, so
7886 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
7887 // ShlAmt - AShrAmt < Amt.
7888 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
7889 ShlAmt - AShrAmt);
7890 return getSignExtendExpr(
7891 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
7892 getConstant(Mul)), OuterTy);
7893 }
7894 }
7895 }
7896 break;
7897 }
7898 }
7899 }
7900
7901 switch (U->getOpcode()) {
7902 case Instruction::Trunc:
7903 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
7904
7905 case Instruction::ZExt:
7906 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7907
7908 case Instruction::SExt:
7909 if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
7910 dyn_cast<Instruction>(V))) {
7911 // The NSW flag of a subtract does not always survive the conversion to
7912 // A + (-1)*B. By pushing sign extension onto its operands we are much
7913 // more likely to preserve NSW and allow later AddRec optimisations.
7914 //
7915 // NOTE: This is effectively duplicating this logic from getSignExtend:
7916 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
7917 // but by that point the NSW information has potentially been lost.
7918 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
7919 Type *Ty = U->getType();
7920 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
7921 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
7922 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
7923 }
7924 }
7925 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
7926
7927 case Instruction::BitCast:
7928 // BitCasts are no-op casts so we just eliminate the cast.
7929 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
7930 return getSCEV(U->getOperand(0));
7931 break;
7932
7933 case Instruction::PtrToInt: {
7934 // Pointer to integer cast is straight-forward, so do model it.
7935 const SCEV *Op = getSCEV(U->getOperand(0));
7936 Type *DstIntTy = U->getType();
7937 // But only if effective SCEV (integer) type is wide enough to represent
7938 // all possible pointer values.
7939 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
7940 if (isa<SCEVCouldNotCompute>(IntOp))
7941 return getUnknown(V);
7942 return IntOp;
7943 }
7944 case Instruction::IntToPtr:
7945 // Just don't deal with inttoptr casts.
7946 return getUnknown(V);
7947
7948 case Instruction::SDiv:
7949 // If both operands are non-negative, this is just an udiv.
7950 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7951 isKnownNonNegative(getSCEV(U->getOperand(1))))
7952 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7953 break;
7954
7955 case Instruction::SRem:
7956 // If both operands are non-negative, this is just an urem.
7957 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
7958 isKnownNonNegative(getSCEV(U->getOperand(1))))
7959 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
7960 break;
7961
7962 case Instruction::GetElementPtr:
7963 return createNodeForGEP(cast<GEPOperator>(U));
7964
7965 case Instruction::PHI:
7966 return createNodeForPHI(cast<PHINode>(U));
7967
7968 case Instruction::Select:
7969 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
7970 U->getOperand(2));
7971
7972 case Instruction::Call:
7973 case Instruction::Invoke:
7974 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
7975 return getSCEV(RV);
7976
7977 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7978 switch (II->getIntrinsicID()) {
7979 case Intrinsic::abs:
7980 return getAbsExpr(
7981 getSCEV(II->getArgOperand(0)),
7982 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
7983 case Intrinsic::umax:
7984 LHS = getSCEV(II->getArgOperand(0));
7985 RHS = getSCEV(II->getArgOperand(1));
7986 return getUMaxExpr(LHS, RHS);
7987 case Intrinsic::umin:
7988 LHS = getSCEV(II->getArgOperand(0));
7989 RHS = getSCEV(II->getArgOperand(1));
7990 return getUMinExpr(LHS, RHS);
7991 case Intrinsic::smax:
7992 LHS = getSCEV(II->getArgOperand(0));
7993 RHS = getSCEV(II->getArgOperand(1));
7994 return getSMaxExpr(LHS, RHS);
7995 case Intrinsic::smin:
7996 LHS = getSCEV(II->getArgOperand(0));
7997 RHS = getSCEV(II->getArgOperand(1));
7998 return getSMinExpr(LHS, RHS);
7999 case Intrinsic::usub_sat: {
8000 const SCEV *X = getSCEV(II->getArgOperand(0));
8001 const SCEV *Y = getSCEV(II->getArgOperand(1));
8002 const SCEV *ClampedY = getUMinExpr(X, Y);
8003 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8004 }
8005 case Intrinsic::uadd_sat: {
8006 const SCEV *X = getSCEV(II->getArgOperand(0));
8007 const SCEV *Y = getSCEV(II->getArgOperand(1));
8008 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8009 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8010 }
8011 case Intrinsic::start_loop_iterations:
8012 case Intrinsic::annotation:
8013 case Intrinsic::ptr_annotation:
8014 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8015 // just eqivalent to the first operand for SCEV purposes.
8016 return getSCEV(II->getArgOperand(0));
8017 case Intrinsic::vscale:
8018 return getVScale(II->getType());
8019 default:
8020 break;
8021 }
8022 }
8023 break;
8024 }
8025
8026 return getUnknown(V);
8027}
8028
8029//===----------------------------------------------------------------------===//
8030// Iteration Count Computation Code
8031//
8032
8033const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount) {
8034 if (isa<SCEVCouldNotCompute>(ExitCount))
8035 return getCouldNotCompute();
8036
8037 auto *ExitCountType = ExitCount->getType();
8038 assert(ExitCountType->isIntegerTy())(static_cast <bool> (ExitCountType->isIntegerTy()) ?
void (0) : __assert_fail ("ExitCountType->isIntegerTy()",
"llvm/lib/Analysis/ScalarEvolution.cpp", 8038, __extension__
__PRETTY_FUNCTION__))
;
8039 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8040 1 + ExitCountType->getScalarSizeInBits());
8041 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8042}
8043
8044const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount,
8045 Type *EvalTy,
8046 const Loop *L) {
8047 if (isa<SCEVCouldNotCompute>(ExitCount))
8048 return getCouldNotCompute();
8049
8050 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8051 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8052
8053 auto CanAddOneWithoutOverflow = [&]() {
8054 ConstantRange ExitCountRange =
8055 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8056 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8057 return true;
8058
8059 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8060 getMinusOne(ExitCount->getType()));
8061 };
8062
8063 // If we need to zero extend the backedge count, check if we can add one to
8064 // it prior to zero extending without overflow. Provided this is safe, it
8065 // allows better simplification of the +1.
8066 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8067 return getZeroExtendExpr(
8068 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8069
8070 // Get the total trip count from the count by adding 1. This may wrap.
8071 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8072}
8073
8074static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8075 if (!ExitCount)
8076 return 0;
8077
8078 ConstantInt *ExitConst = ExitCount->getValue();
8079
8080 // Guard against huge trip counts.
8081 if (ExitConst->getValue().getActiveBits() > 32)
8082 return 0;
8083
8084 // In case of integer overflow, this returns 0, which is correct.
8085 return ((unsigned)ExitConst->getZExtValue()) + 1;
8086}
8087
8088unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
8089 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8090 return getConstantTripCount(ExitCount);
8091}
8092
8093unsigned
8094ScalarEvolution::getSmallConstantTripCount(const Loop *L,
8095 const BasicBlock *ExitingBlock) {
8096 assert(ExitingBlock && "Must pass a non-null exiting block!")(static_cast <bool> (ExitingBlock && "Must pass a non-null exiting block!"
) ? void (0) : __assert_fail ("ExitingBlock && \"Must pass a non-null exiting block!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8096, __extension__
__PRETTY_FUNCTION__))
;
8097 assert(L->isLoopExiting(ExitingBlock) &&(static_cast <bool> (L->isLoopExiting(ExitingBlock) &&
"Exiting block must actually branch out of the loop!") ? void
(0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8098, __extension__
__PRETTY_FUNCTION__))
8098 "Exiting block must actually branch out of the loop!")(static_cast <bool> (L->isLoopExiting(ExitingBlock) &&
"Exiting block must actually branch out of the loop!") ? void
(0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8098, __extension__
__PRETTY_FUNCTION__))
;
8099 const SCEVConstant *ExitCount =
8100 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8101 return getConstantTripCount(ExitCount);
8102}
8103
8104unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
8105 const auto *MaxExitCount =
8106 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
8107 return getConstantTripCount(MaxExitCount);
8108}
8109
8110const SCEV *ScalarEvolution::getConstantMaxTripCountFromArray(const Loop *L) {
8111 // We can't infer from Array in Irregular Loop.
8112 // FIXME: It's hard to infer loop bound from array operated in Nested Loop.
8113 if (!L->isLoopSimplifyForm() || !L->isInnermost())
8114 return getCouldNotCompute();
8115
8116 // FIXME: To make the scene more typical, we only analysis loops that have
8117 // one exiting block and that block must be the latch. To make it easier to
8118 // capture loops that have memory access and memory access will be executed
8119 // in each iteration.
8120 const BasicBlock *LoopLatch = L->getLoopLatch();
8121 assert(LoopLatch && "See defination of simplify form loop.")(static_cast <bool> (LoopLatch && "See defination of simplify form loop."
) ? void (0) : __assert_fail ("LoopLatch && \"See defination of simplify form loop.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8121, __extension__
__PRETTY_FUNCTION__))
;
8122 if (L->getExitingBlock() != LoopLatch)
8123 return getCouldNotCompute();
8124
8125 const DataLayout &DL = getDataLayout();
8126 SmallVector<const SCEV *> InferCountColl;
8127 for (auto *BB : L->getBlocks()) {
8128 // Go here, we can know that Loop is a single exiting and simplified form
8129 // loop. Make sure that infer from Memory Operation in those BBs must be
8130 // executed in loop. First step, we can make sure that max execution time
8131 // of MemAccessBB in loop represents latch max excution time.
8132 // If MemAccessBB does not dom Latch, skip.
8133 // Entry
8134 // │
8135 // ┌─────▼─────┐
8136 // │Loop Header◄─────┐
8137 // └──┬──────┬─┘ │
8138 // │ │ │
8139 // ┌────────▼──┐ ┌─▼─────┐ │
8140 // │MemAccessBB│ │OtherBB│ │
8141 // └────────┬──┘ └─┬─────┘ │
8142 // │ │ │
8143 // ┌─▼──────▼─┐ │
8144 // │Loop Latch├─────┘
8145 // └────┬─────┘
8146 // ▼
8147 // Exit
8148 if (!DT.dominates(BB, LoopLatch))
8149 continue;
8150
8151 for (Instruction &Inst : *BB) {
8152 // Find Memory Operation Instruction.
8153 auto *GEP = getLoadStorePointerOperand(&Inst);
8154 if (!GEP)
8155 continue;
8156
8157 auto *ElemSize = dyn_cast<SCEVConstant>(getElementSize(&Inst));
8158 // Do not infer from scalar type, eg."ElemSize = sizeof()".
8159 if (!ElemSize)
8160 continue;
8161
8162 // Use a existing polynomial recurrence on the trip count.
8163 auto *AddRec = dyn_cast<SCEVAddRecExpr>(getSCEV(GEP));
8164 if (!AddRec)
8165 continue;
8166 auto *ArrBase = dyn_cast<SCEVUnknown>(getPointerBase(AddRec));
8167 auto *Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*this));
8168 if (!ArrBase || !Step)
8169 continue;
8170 assert(isLoopInvariant(ArrBase, L) && "See addrec definition")(static_cast <bool> (isLoopInvariant(ArrBase, L) &&
"See addrec definition") ? void (0) : __assert_fail ("isLoopInvariant(ArrBase, L) && \"See addrec definition\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8170, __extension__
__PRETTY_FUNCTION__))
;
8171
8172 // Only handle { %array + step },
8173 // FIXME: {(SCEVAddRecExpr) + step } could not be analysed here.
8174 if (AddRec->getStart() != ArrBase)
8175 continue;
8176
8177 // Memory operation pattern which have gaps.
8178 // Or repeat memory opreation.
8179 // And index of GEP wraps arround.
8180 if (Step->getAPInt().getActiveBits() > 32 ||
8181 Step->getAPInt().getZExtValue() !=
8182 ElemSize->getAPInt().getZExtValue() ||
8183 Step->isZero() || Step->getAPInt().isNegative())
8184 continue;
8185
8186 // Only infer from stack array which has certain size.
8187 // Make sure alloca instruction is not excuted in loop.
8188 AllocaInst *AllocateInst = dyn_cast<AllocaInst>(ArrBase->getValue());
8189 if (!AllocateInst || L->contains(AllocateInst->getParent()))
8190 continue;
8191
8192 // Make sure only handle normal array.
8193 auto *Ty = dyn_cast<ArrayType>(AllocateInst->getAllocatedType());
8194 auto *ArrSize = dyn_cast<ConstantInt>(AllocateInst->getArraySize());
8195 if (!Ty || !ArrSize || !ArrSize->isOne())
8196 continue;
8197
8198 // FIXME: Since gep indices are silently zext to the indexing type,
8199 // we will have a narrow gep index which wraps around rather than
8200 // increasing strictly, we shoule ensure that step is increasing
8201 // strictly by the loop iteration.
8202 // Now we can infer a max execution time by MemLength/StepLength.
8203 const SCEV *MemSize =
8204 getConstant(Step->getType(), DL.getTypeAllocSize(Ty));
8205 auto *MaxExeCount =
8206 dyn_cast<SCEVConstant>(getUDivCeilSCEV(MemSize, Step));
8207 if (!MaxExeCount || MaxExeCount->getAPInt().getActiveBits() > 32)
8208 continue;
8209
8210 // If the loop reaches the maximum number of executions, we can not
8211 // access bytes starting outside the statically allocated size without
8212 // being immediate UB. But it is allowed to enter loop header one more
8213 // time.
8214 auto *InferCount = dyn_cast<SCEVConstant>(
8215 getAddExpr(MaxExeCount, getOne(MaxExeCount->getType())));
8216 // Discard the maximum number of execution times under 32bits.
8217 if (!InferCount || InferCount->getAPInt().getActiveBits() > 32)
8218 continue;
8219
8220 InferCountColl.push_back(InferCount);
8221 }
8222 }
8223
8224 if (InferCountColl.size() == 0)
8225 return getCouldNotCompute();
8226
8227 return getUMinFromMismatchedTypes(InferCountColl);
8228}
8229
8230unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
8231 SmallVector<BasicBlock *, 8> ExitingBlocks;
8232 L->getExitingBlocks(ExitingBlocks);
8233
8234 std::optional<unsigned> Res;
8235 for (auto *ExitingBB : ExitingBlocks) {
8236 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
8237 if (!Res)
8238 Res = Multiple;
8239 Res = (unsigned)std::gcd(*Res, Multiple);
8240 }
8241 return Res.value_or(1);
8242}
8243
8244unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
8245 const SCEV *ExitCount) {
8246 if (ExitCount == getCouldNotCompute())
8247 return 1;
8248
8249 // Get the trip count
8250 const SCEV *TCExpr = getTripCountFromExitCount(applyLoopGuards(ExitCount, L));
8251
8252 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8253 // the greatest power of 2 divisor less than 2^32.
8254 auto GetSmallMultiple = [](unsigned TrailingZeros) {
8255 return 1U << std::min((uint32_t)31, TrailingZeros);
8256 };
8257
8258 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
8259 if (!TC) {
8260 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8261 return Multiple.getActiveBits() > 32
8262 ? 1
8263 : Multiple.zextOrTrunc(32).getZExtValue();
8264 }
8265
8266 ConstantInt *Result = TC->getValue();
8267 assert(Result && "SCEVConstant expected to have non-null ConstantInt")(static_cast <bool> (Result && "SCEVConstant expected to have non-null ConstantInt"
) ? void (0) : __assert_fail ("Result && \"SCEVConstant expected to have non-null ConstantInt\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8267, __extension__
__PRETTY_FUNCTION__))
;
8268 assert(Result->getValue() != 0 && "trip count should never be zero")(static_cast <bool> (Result->getValue() != 0 &&
"trip count should never be zero") ? void (0) : __assert_fail
("Result->getValue() != 0 && \"trip count should never be zero\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8268, __extension__
__PRETTY_FUNCTION__))
;
8269
8270 // Guard against huge trip multiples.
8271 if (Result->getValue().getActiveBits() > 32)
8272 return GetSmallMultiple(Result->getValue().countTrailingZeros());
8273
8274 return (unsigned)Result->getZExtValue();
8275}
8276
8277/// Returns the largest constant divisor of the trip count of this loop as a
8278/// normal unsigned value, if possible. This means that the actual trip count is
8279/// always a multiple of the returned value (don't forget the trip count could
8280/// very well be zero as well!).
8281///
8282/// Returns 1 if the trip count is unknown or not guaranteed to be the
8283/// multiple of a constant (which is also the case if the trip count is simply
8284/// constant, use getSmallConstantTripCount for that case), Will also return 1
8285/// if the trip count is very large (>= 2^32).
8286///
8287/// As explained in the comments for getSmallConstantTripCount, this assumes
8288/// that control exits the loop via ExitingBlock.
8289unsigned
8290ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
8291 const BasicBlock *ExitingBlock) {
8292 assert(ExitingBlock && "Must pass a non-null exiting block!")(static_cast <bool> (ExitingBlock && "Must pass a non-null exiting block!"
) ? void (0) : __assert_fail ("ExitingBlock && \"Must pass a non-null exiting block!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8292, __extension__
__PRETTY_FUNCTION__))
;
8293 assert(L->isLoopExiting(ExitingBlock) &&(static_cast <bool> (L->isLoopExiting(ExitingBlock) &&
"Exiting block must actually branch out of the loop!") ? void
(0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8294, __extension__
__PRETTY_FUNCTION__))
8294 "Exiting block must actually branch out of the loop!")(static_cast <bool> (L->isLoopExiting(ExitingBlock) &&
"Exiting block must actually branch out of the loop!") ? void
(0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8294, __extension__
__PRETTY_FUNCTION__))
;
8295 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8296 return getSmallConstantTripMultiple(L, ExitCount);
8297}
8298
8299const SCEV *ScalarEvolution::getExitCount(const Loop *L,
8300 const BasicBlock *ExitingBlock,
8301 ExitCountKind Kind) {
8302 switch (Kind) {
8303 case Exact:
8304 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8305 case SymbolicMaximum:
8306 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8307 case ConstantMaximum:
8308 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8309 };
8310 llvm_unreachable("Invalid ExitCountKind!")::llvm::llvm_unreachable_internal("Invalid ExitCountKind!", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 8310)
;
8311}
8312
8313const SCEV *
8314ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
8315 SmallVector<const SCEVPredicate *, 4> &Preds) {
8316 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8317}
8318
8319const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
8320 ExitCountKind Kind) {
8321 switch (Kind) {
8322 case Exact:
8323 return getBackedgeTakenInfo(L).getExact(L, this);
8324 case ConstantMaximum:
8325 return getBackedgeTakenInfo(L).getConstantMax(this);
8326 case SymbolicMaximum:
8327 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8328 };
8329 llvm_unreachable("Invalid ExitCountKind!")::llvm::llvm_unreachable_internal("Invalid ExitCountKind!", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 8329)
;
8330}
8331
8332bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
8333 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8334}
8335
8336/// Push PHI nodes in the header of the given loop onto the given Worklist.
8337static void PushLoopPHIs(const Loop *L,
8338 SmallVectorImpl<Instruction *> &Worklist,
8339 SmallPtrSetImpl<Instruction *> &Visited) {
8340 BasicBlock *Header = L->getHeader();
8341
8342 // Push all Loop-header PHIs onto the Worklist stack.
8343 for (PHINode &PN : Header->phis())
8344 if (Visited.insert(&PN).second)
8345 Worklist.push_back(&PN);
8346}
8347
8348const ScalarEvolution::BackedgeTakenInfo &
8349ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8350 auto &BTI = getBackedgeTakenInfo(L);
8351 if (BTI.hasFullInfo())
8352 return BTI;
8353
8354 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
8355
8356 if (!Pair.second)
8357 return Pair.first->second;
8358
8359 BackedgeTakenInfo Result =
8360 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8361
8362 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8363}
8364
8365ScalarEvolution::BackedgeTakenInfo &
8366ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8367 // Initially insert an invalid entry for this loop. If the insertion
8368 // succeeds, proceed to actually compute a backedge-taken count and
8369 // update the value. The temporary CouldNotCompute value tells SCEV
8370 // code elsewhere that it shouldn't attempt to request a new
8371 // backedge-taken count, which could result in infinite recursion.
8372 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8373 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
8374 if (!Pair.second)
8375 return Pair.first->second;
8376
8377 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8378 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8379 // must be cleared in this scope.
8380 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8381
8382 // In product build, there are no usage of statistic.
8383 (void)NumTripCountsComputed;
8384 (void)NumTripCountsNotComputed;
8385#if LLVM_ENABLE_STATS1 || !defined(NDEBUG)
8386 const SCEV *BEExact = Result.getExact(L, this);
8387 if (BEExact != getCouldNotCompute()) {
8388 assert(isLoopInvariant(BEExact, L) &&(static_cast <bool> (isLoopInvariant(BEExact, L) &&
isLoopInvariant(Result.getConstantMax(this), L) && "Computed backedge-taken count isn't loop invariant for loop!"
) ? void (0) : __assert_fail ("isLoopInvariant(BEExact, L) && isLoopInvariant(Result.getConstantMax(this), L) && \"Computed backedge-taken count isn't loop invariant for loop!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8390, __extension__
__PRETTY_FUNCTION__))
8389 isLoopInvariant(Result.getConstantMax(this), L) &&(static_cast <bool> (isLoopInvariant(BEExact, L) &&
isLoopInvariant(Result.getConstantMax(this), L) && "Computed backedge-taken count isn't loop invariant for loop!"
) ? void (0) : __assert_fail ("isLoopInvariant(BEExact, L) && isLoopInvariant(Result.getConstantMax(this), L) && \"Computed backedge-taken count isn't loop invariant for loop!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8390, __extension__
__PRETTY_FUNCTION__))
8390 "Computed backedge-taken count isn't loop invariant for loop!")(static_cast <bool> (isLoopInvariant(BEExact, L) &&
isLoopInvariant(Result.getConstantMax(this), L) && "Computed backedge-taken count isn't loop invariant for loop!"
) ? void (0) : __assert_fail ("isLoopInvariant(BEExact, L) && isLoopInvariant(Result.getConstantMax(this), L) && \"Computed backedge-taken count isn't loop invariant for loop!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8390, __extension__
__PRETTY_FUNCTION__))
;
8391 ++NumTripCountsComputed;
8392 } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
8393 isa<PHINode>(L->getHeader()->begin())) {
8394 // Only count loops that have phi nodes as not being computable.
8395 ++NumTripCountsNotComputed;
8396 }
8397#endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
8398
8399 // Now that we know more about the trip count for this loop, forget any
8400 // existing SCEV values for PHI nodes in this loop since they are only
8401 // conservative estimates made without the benefit of trip count
8402 // information. This invalidation is not necessary for correctness, and is
8403 // only done to produce more precise results.
8404 if (Result.hasAnyInfo()) {
8405 // Invalidate any expression using an addrec in this loop.
8406 SmallVector<const SCEV *, 8> ToForget;
8407 auto LoopUsersIt = LoopUsers.find(L);
8408 if (LoopUsersIt != LoopUsers.end())
8409 append_range(ToForget, LoopUsersIt->second);
8410 forgetMemoizedResults(ToForget);
8411
8412 // Invalidate constant-evolved loop header phis.
8413 for (PHINode &PN : L->getHeader()->phis())
8414 ConstantEvolutionLoopExitValue.erase(&PN);
8415 }
8416
8417 // Re-lookup the insert position, since the call to
8418 // computeBackedgeTakenCount above could result in a
8419 // recusive call to getBackedgeTakenInfo (on a different
8420 // loop), which would invalidate the iterator computed
8421 // earlier.
8422 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8423}
8424
8425void ScalarEvolution::forgetAllLoops() {
8426 // This method is intended to forget all info about loops. It should
8427 // invalidate caches as if the following happened:
8428 // - The trip counts of all loops have changed arbitrarily
8429 // - Every llvm::Value has been updated in place to produce a different
8430 // result.
8431 BackedgeTakenCounts.clear();
8432 PredicatedBackedgeTakenCounts.clear();
8433 BECountUsers.clear();
8434 LoopPropertiesCache.clear();
8435 ConstantEvolutionLoopExitValue.clear();
8436 ValueExprMap.clear();
8437 ValuesAtScopes.clear();
8438 ValuesAtScopesUsers.clear();
8439 LoopDispositions.clear();
8440 BlockDispositions.clear();
8441 UnsignedRanges.clear();
8442 SignedRanges.clear();
8443 ExprValueMap.clear();
8444 HasRecMap.clear();
8445 ConstantMultipleCache.clear();
8446 PredicatedSCEVRewrites.clear();
8447 FoldCache.clear();
8448 FoldCacheUser.clear();
8449}
8450void ScalarEvolution::visitAndClearUsers(
8451 SmallVectorImpl<Instruction *> &Worklist,
8452 SmallPtrSetImpl<Instruction *> &Visited,
8453 SmallVectorImpl<const SCEV *> &ToForget) {
8454 while (!Worklist.empty()) {
8455 Instruction *I = Worklist.pop_back_val();
8456 if (!isSCEVable(I->getType()))
8457 continue;
8458
8459 ValueExprMapType::iterator It =
8460 ValueExprMap.find_as(static_cast<Value *>(I));
8461 if (It != ValueExprMap.end()) {
8462 eraseValueFromMap(It->first);
8463 ToForget.push_back(It->second);
8464 if (PHINode *PN = dyn_cast<PHINode>(I))
8465 ConstantEvolutionLoopExitValue.erase(PN);
8466 }
8467
8468 PushDefUseChildren(I, Worklist, Visited);
8469 }
8470}
8471
8472void ScalarEvolution::forgetLoop(const Loop *L) {
8473 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8474 SmallVector<Instruction *, 32> Worklist;
8475 SmallPtrSet<Instruction *, 16> Visited;
8476 SmallVector<const SCEV *, 16> ToForget;
8477
8478 // Iterate over all the loops and sub-loops to drop SCEV information.
8479 while (!LoopWorklist.empty()) {
8480 auto *CurrL = LoopWorklist.pop_back_val();
8481
8482 // Drop any stored trip count value.
8483 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8484 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8485
8486 // Drop information about predicated SCEV rewrites for this loop.
8487 for (auto I = PredicatedSCEVRewrites.begin();
8488 I != PredicatedSCEVRewrites.end();) {
8489 std::pair<const SCEV *, const Loop *> Entry = I->first;
8490 if (Entry.second == CurrL)
8491 PredicatedSCEVRewrites.erase(I++);
8492 else
8493 ++I;
8494 }
8495
8496 auto LoopUsersItr = LoopUsers.find(CurrL);
8497 if (LoopUsersItr != LoopUsers.end()) {
8498 ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(),
8499 LoopUsersItr->second.end());
8500 }
8501
8502 // Drop information about expressions based on loop-header PHIs.
8503 PushLoopPHIs(CurrL, Worklist, Visited);
8504 visitAndClearUsers(Worklist, Visited, ToForget);
8505
8506 LoopPropertiesCache.erase(CurrL);
8507 // Forget all contained loops too, to avoid dangling entries in the
8508 // ValuesAtScopes map.
8509 LoopWorklist.append(CurrL->begin(), CurrL->end());
8510 }
8511 forgetMemoizedResults(ToForget);
8512}
8513
8514void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
8515 forgetLoop(L->getOutermostLoop());
8516}
8517
8518void ScalarEvolution::forgetValue(Value *V) {
8519 Instruction *I = dyn_cast<Instruction>(V);
8520 if (!I) return;
8521
8522 // Drop information about expressions based on loop-header PHIs.
8523 SmallVector<Instruction *, 16> Worklist;
8524 SmallPtrSet<Instruction *, 8> Visited;
8525 SmallVector<const SCEV *, 8> ToForget;
8526 Worklist.push_back(I);
8527 Visited.insert(I);
8528 visitAndClearUsers(Worklist, Visited, ToForget);
8529
8530 forgetMemoizedResults(ToForget);
8531}
8532
8533void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8534
8535void ScalarEvolution::forgetBlockAndLoopDispositions(Value *V) {
8536 // Unless a specific value is passed to invalidation, completely clear both
8537 // caches.
8538 if (!V) {
8539 BlockDispositions.clear();
8540 LoopDispositions.clear();
8541 return;
8542 }
8543
8544 if (!isSCEVable(V->getType()))
8545 return;
8546
8547 const SCEV *S = getExistingSCEV(V);
8548 if (!S)
8549 return;
8550
8551 // Invalidate the block and loop dispositions cached for S. Dispositions of
8552 // S's users may change if S's disposition changes (i.e. a user may change to
8553 // loop-invariant, if S changes to loop invariant), so also invalidate
8554 // dispositions of S's users recursively.
8555 SmallVector<const SCEV *, 8> Worklist = {S};
8556 SmallPtrSet<const SCEV *, 8> Seen = {S};
8557 while (!Worklist.empty()) {
8558 const SCEV *Curr = Worklist.pop_back_val();
8559 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8560 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8561 if (!LoopDispoRemoved && !BlockDispoRemoved)
8562 continue;
8563 auto Users = SCEVUsers.find(Curr);
8564 if (Users != SCEVUsers.end())
8565 for (const auto *User : Users->second)
8566 if (Seen.insert(User).second)
8567 Worklist.push_back(User);
8568 }
8569}
8570
8571/// Get the exact loop backedge taken count considering all loop exits. A
8572/// computable result can only be returned for loops with all exiting blocks
8573/// dominating the latch. howFarToZero assumes that the limit of each loop test
8574/// is never skipped. This is a valid assumption as long as the loop exits via
8575/// that test. For precise results, it is the caller's responsibility to specify
8576/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8577const SCEV *
8578ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
8579 SmallVector<const SCEVPredicate *, 4> *Preds) const {
8580 // If any exits were not computable, the loop is not computable.
8581 if (!isComplete() || ExitNotTaken.empty())
8582 return SE->getCouldNotCompute();
8583
8584 const BasicBlock *Latch = L->getLoopLatch();
8585 // All exiting blocks we have collected must dominate the only backedge.
8586 if (!Latch)
8587 return SE->getCouldNotCompute();
8588
8589 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8590 // count is simply a minimum out of all these calculated exit counts.
8591 SmallVector<const SCEV *, 2> Ops;
8592 for (const auto &ENT : ExitNotTaken) {
8593 const SCEV *BECount = ENT.ExactNotTaken;
8594 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!")(static_cast <bool> (BECount != SE->getCouldNotCompute
() && "Bad exit SCEV!") ? void (0) : __assert_fail ("BECount != SE->getCouldNotCompute() && \"Bad exit SCEV!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8594, __extension__
__PRETTY_FUNCTION__))
;
8595 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&(static_cast <bool> (SE->DT.dominates(ENT.ExitingBlock
, Latch) && "We should only have known counts for exiting blocks that dominate "
"latch!") ? void (0) : __assert_fail ("SE->DT.dominates(ENT.ExitingBlock, Latch) && \"We should only have known counts for exiting blocks that dominate \" \"latch!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8597, __extension__
__PRETTY_FUNCTION__))
8596 "We should only have known counts for exiting blocks that dominate "(static_cast <bool> (SE->DT.dominates(ENT.ExitingBlock
, Latch) && "We should only have known counts for exiting blocks that dominate "
"latch!") ? void (0) : __assert_fail ("SE->DT.dominates(ENT.ExitingBlock, Latch) && \"We should only have known counts for exiting blocks that dominate \" \"latch!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8597, __extension__
__PRETTY_FUNCTION__))
8597 "latch!")(static_cast <bool> (SE->DT.dominates(ENT.ExitingBlock
, Latch) && "We should only have known counts for exiting blocks that dominate "
"latch!") ? void (0) : __assert_fail ("SE->DT.dominates(ENT.ExitingBlock, Latch) && \"We should only have known counts for exiting blocks that dominate \" \"latch!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8597, __extension__
__PRETTY_FUNCTION__))
;
8598
8599 Ops.push_back(BECount);
8600
8601 if (Preds)
8602 for (const auto *P : ENT.Predicates)
8603 Preds->push_back(P);
8604
8605 assert((Preds || ENT.hasAlwaysTruePredicate()) &&(static_cast <bool> ((Preds || ENT.hasAlwaysTruePredicate
()) && "Predicate should be always true!") ? void (0)
: __assert_fail ("(Preds || ENT.hasAlwaysTruePredicate()) && \"Predicate should be always true!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8606, __extension__
__PRETTY_FUNCTION__))
8606 "Predicate should be always true!")(static_cast <bool> ((Preds || ENT.hasAlwaysTruePredicate
()) && "Predicate should be always true!") ? void (0)
: __assert_fail ("(Preds || ENT.hasAlwaysTruePredicate()) && \"Predicate should be always true!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8606, __extension__
__PRETTY_FUNCTION__))
;
8607 }
8608
8609 // If an earlier exit exits on the first iteration (exit count zero), then
8610 // a later poison exit count should not propagate into the result. This are
8611 // exactly the semantics provided by umin_seq.
8612 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8613}
8614
8615/// Get the exact not taken count for this loop exit.
8616const SCEV *
8617ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
8618 ScalarEvolution *SE) const {
8619 for (const auto &ENT : ExitNotTaken)
8620 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8621 return ENT.ExactNotTaken;
8622
8623 return SE->getCouldNotCompute();
8624}
8625
8626const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8627 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
8628 for (const auto &ENT : ExitNotTaken)
8629 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8630 return ENT.ConstantMaxNotTaken;
8631
8632 return SE->getCouldNotCompute();
8633}
8634
8635const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8636 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
8637 for (const auto &ENT : ExitNotTaken)
8638 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
8639 return ENT.SymbolicMaxNotTaken;
8640
8641 return SE->getCouldNotCompute();
8642}
8643
8644/// getConstantMax - Get the constant max backedge taken count for the loop.
8645const SCEV *
8646ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
8647 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8648 return !ENT.hasAlwaysTruePredicate();
8649 };
8650
8651 if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue))
8652 return SE->getCouldNotCompute();
8653
8654 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||(static_cast <bool> ((isa<SCEVCouldNotCompute>(getConstantMax
()) || isa<SCEVConstant>(getConstantMax())) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(getConstantMax()) || isa<SCEVConstant>(getConstantMax())) && \"No point in having a non-constant max backedge taken count!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8656, __extension__
__PRETTY_FUNCTION__))
8655 isa<SCEVConstant>(getConstantMax())) &&(static_cast <bool> ((isa<SCEVCouldNotCompute>(getConstantMax
()) || isa<SCEVConstant>(getConstantMax())) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(getConstantMax()) || isa<SCEVConstant>(getConstantMax())) && \"No point in having a non-constant max backedge taken count!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8656, __extension__
__PRETTY_FUNCTION__))
8656 "No point in having a non-constant max backedge taken count!")(static_cast <bool> ((isa<SCEVCouldNotCompute>(getConstantMax
()) || isa<SCEVConstant>(getConstantMax())) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(getConstantMax()) || isa<SCEVConstant>(getConstantMax())) && \"No point in having a non-constant max backedge taken count!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8656, __extension__
__PRETTY_FUNCTION__))
;
8657 return getConstantMax();
8658}
8659
8660const SCEV *
8661ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
8662 ScalarEvolution *SE) {
8663 if (!SymbolicMax)
8664 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
8665 return SymbolicMax;
8666}
8667
8668bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8669 ScalarEvolution *SE) const {
8670 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8671 return !ENT.hasAlwaysTruePredicate();
8672 };
8673 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8674}
8675
8676ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
8677 : ExitLimit(E, E, E, false, std::nullopt) {}
8678
8679ScalarEvolution::ExitLimit::ExitLimit(
8680 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8681 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8682 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
8683 : ExactNotTaken(E), ConstantMaxNotTaken(ConstantMaxNotTaken),
8684 SymbolicMaxNotTaken(SymbolicMaxNotTaken), MaxOrZero(MaxOrZero) {
8685 // If we prove the max count is zero, so is the symbolic bound. This happens
8686 // in practice due to differences in a) how context sensitive we've chosen
8687 // to be and b) how we reason about bounds implied by UB.
8688 if (ConstantMaxNotTaken->isZero()) {
8689 this->ExactNotTaken = E = ConstantMaxNotTaken;
8690 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8691 }
8692
8693 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||(static_cast <bool> ((isa<SCEVCouldNotCompute>(ExactNotTaken
) || !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
"Exact is not allowed to be less precise than Constant Max")
? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) && \"Exact is not allowed to be less precise than Constant Max\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8695, __extension__
__PRETTY_FUNCTION__))
8694 !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&(static_cast <bool> ((isa<SCEVCouldNotCompute>(ExactNotTaken
) || !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
"Exact is not allowed to be less precise than Constant Max")
? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) && \"Exact is not allowed to be less precise than Constant Max\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8695, __extension__
__PRETTY_FUNCTION__))
8695 "Exact is not allowed to be less precise than Constant Max")(static_cast <bool> ((isa<SCEVCouldNotCompute>(ExactNotTaken
) || !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
"Exact is not allowed to be less precise than Constant Max")
? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) && \"Exact is not allowed to be less precise than Constant Max\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8695, __extension__
__PRETTY_FUNCTION__))
;
8696 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||(static_cast <bool> ((isa<SCEVCouldNotCompute>(ExactNotTaken
) || !isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken)) &&
"Exact is not allowed to be less precise than Symbolic Max")
? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken)) && \"Exact is not allowed to be less precise than Symbolic Max\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8698, __extension__
__PRETTY_FUNCTION__))
8697 !isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken)) &&(static_cast <bool> ((isa<SCEVCouldNotCompute>(ExactNotTaken
) || !isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken)) &&
"Exact is not allowed to be less precise than Symbolic Max")
? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken)) && \"Exact is not allowed to be less precise than Symbolic Max\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8698, __extension__
__PRETTY_FUNCTION__))
8698 "Exact is not allowed to be less precise than Symbolic Max")(static_cast <bool> ((isa<SCEVCouldNotCompute>(ExactNotTaken
) || !isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken)) &&
"Exact is not allowed to be less precise than Symbolic Max")
? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken)) && \"Exact is not allowed to be less precise than Symbolic Max\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8698, __extension__
__PRETTY_FUNCTION__))
;
8699 assert((isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken) ||(static_cast <bool> ((isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken
) || !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
"Symbolic Max is not allowed to be less precise than Constant Max"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken) || !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) && \"Symbolic Max is not allowed to be less precise than Constant Max\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8701, __extension__
__PRETTY_FUNCTION__))
8700 !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&(static_cast <bool> ((isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken
) || !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
"Symbolic Max is not allowed to be less precise than Constant Max"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken) || !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) && \"Symbolic Max is not allowed to be less precise than Constant Max\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8701, __extension__
__PRETTY_FUNCTION__))
8701 "Symbolic Max is not allowed to be less precise than Constant Max")(static_cast <bool> ((isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken
) || !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
"Symbolic Max is not allowed to be less precise than Constant Max"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken) || !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) && \"Symbolic Max is not allowed to be less precise than Constant Max\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8701, __extension__
__PRETTY_FUNCTION__))
;
8702 assert((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) ||(static_cast <bool> ((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken
) || isa<SCEVConstant>(ConstantMaxNotTaken)) &&
"No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) || isa<SCEVConstant>(ConstantMaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8704, __extension__
__PRETTY_FUNCTION__))
8703 isa<SCEVConstant>(ConstantMaxNotTaken)) &&(static_cast <bool> ((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken
) || isa<SCEVConstant>(ConstantMaxNotTaken)) &&
"No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) || isa<SCEVConstant>(ConstantMaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8704, __extension__
__PRETTY_FUNCTION__))
8704 "No point in having a non-constant max backedge taken count!")(static_cast <bool> ((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken
) || isa<SCEVConstant>(ConstantMaxNotTaken)) &&
"No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) || isa<SCEVConstant>(ConstantMaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8704, __extension__
__PRETTY_FUNCTION__))
;
8705 for (const auto *PredSet : PredSetList)
8706 for (const auto *P : *PredSet)
8707 addPredicate(P);
8708 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&(static_cast <bool> ((isa<SCEVCouldNotCompute>(E)
|| !E->getType()->isPointerTy()) && "Backedge count should be int"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) && \"Backedge count should be int\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8709, __extension__
__PRETTY_FUNCTION__))
8709 "Backedge count should be int")(static_cast <bool> ((isa<SCEVCouldNotCompute>(E)
|| !E->getType()->isPointerTy()) && "Backedge count should be int"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) && \"Backedge count should be int\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8709, __extension__
__PRETTY_FUNCTION__))
;
8710 assert((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) ||(static_cast <bool> ((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken
) || !ConstantMaxNotTaken->getType()->isPointerTy()) &&
"Max backedge count should be int") ? void (0) : __assert_fail
("(isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) || !ConstantMaxNotTaken->getType()->isPointerTy()) && \"Max backedge count should be int\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8712, __extension__
__PRETTY_FUNCTION__))
8711 !ConstantMaxNotTaken->getType()->isPointerTy()) &&(static_cast <bool> ((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken
) || !ConstantMaxNotTaken->getType()->isPointerTy()) &&
"Max backedge count should be int") ? void (0) : __assert_fail
("(isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) || !ConstantMaxNotTaken->getType()->isPointerTy()) && \"Max backedge count should be int\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8712, __extension__
__PRETTY_FUNCTION__))
8712 "Max backedge count should be int")(static_cast <bool> ((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken
) || !ConstantMaxNotTaken->getType()->isPointerTy()) &&
"Max backedge count should be int") ? void (0) : __assert_fail
("(isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) || !ConstantMaxNotTaken->getType()->isPointerTy()) && \"Max backedge count should be int\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8712, __extension__
__PRETTY_FUNCTION__))
;
8713}
8714
8715ScalarEvolution::ExitLimit::ExitLimit(
8716 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8717 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8718 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
8719 : ExitLimit(E, ConstantMaxNotTaken, SymbolicMaxNotTaken, MaxOrZero,
8720 { &PredSet }) {}
8721
8722/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8723/// computable exit into a persistent ExitNotTakenInfo array.
8724ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8725 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
8726 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8727 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8728 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8729
8730 ExitNotTaken.reserve(ExitCounts.size());
8731 std::transform(ExitCounts.begin(), ExitCounts.end(),
8732 std::back_inserter(ExitNotTaken),
8733 [&](const EdgeExitInfo &EEI) {
8734 BasicBlock *ExitBB = EEI.first;
8735 const ExitLimit &EL = EEI.second;
8736 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
8737 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
8738 EL.Predicates);
8739 });
8740 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||(static_cast <bool> ((isa<SCEVCouldNotCompute>(ConstantMax
) || isa<SCEVConstant>(ConstantMax)) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ConstantMax) || isa<SCEVConstant>(ConstantMax)) && \"No point in having a non-constant max backedge taken count!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8742, __extension__
__PRETTY_FUNCTION__))
8741 isa<SCEVConstant>(ConstantMax)) &&(static_cast <bool> ((isa<SCEVCouldNotCompute>(ConstantMax
) || isa<SCEVConstant>(ConstantMax)) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ConstantMax) || isa<SCEVConstant>(ConstantMax)) && \"No point in having a non-constant max backedge taken count!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8742, __extension__
__PRETTY_FUNCTION__))
8742 "No point in having a non-constant max backedge taken count!")(static_cast <bool> ((isa<SCEVCouldNotCompute>(ConstantMax
) || isa<SCEVConstant>(ConstantMax)) && "No point in having a non-constant max backedge taken count!"
) ? void (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ConstantMax) || isa<SCEVConstant>(ConstantMax)) && \"No point in having a non-constant max backedge taken count!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8742, __extension__
__PRETTY_FUNCTION__))
;
8743}
8744
8745/// Compute the number of times the backedge of the specified loop will execute.
8746ScalarEvolution::BackedgeTakenInfo
8747ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8748 bool AllowPredicates) {
8749 SmallVector<BasicBlock *, 8> ExitingBlocks;
8750 L->getExitingBlocks(ExitingBlocks);
8751
8752 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8753
8754 SmallVector<EdgeExitInfo, 4> ExitCounts;
8755 bool CouldComputeBECount = true;
8756 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
8757 const SCEV *MustExitMaxBECount = nullptr;
8758 const SCEV *MayExitMaxBECount = nullptr;
8759 bool MustExitMaxOrZero = false;
8760
8761 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
8762 // and compute maxBECount.
8763 // Do a union of all the predicates here.
8764 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
8765 BasicBlock *ExitBB = ExitingBlocks[i];
8766
8767 // We canonicalize untaken exits to br (constant), ignore them so that
8768 // proving an exit untaken doesn't negatively impact our ability to reason
8769 // about the loop as whole.
8770 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
8771 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
8772 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8773 if (ExitIfTrue == CI->isZero())
8774 continue;
8775 }
8776
8777 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
8778
8779 assert((AllowPredicates || EL.Predicates.empty()) &&(static_cast <bool> ((AllowPredicates || EL.Predicates.
empty()) && "Predicated exit limit when predicates are not allowed!"
) ? void (0) : __assert_fail ("(AllowPredicates || EL.Predicates.empty()) && \"Predicated exit limit when predicates are not allowed!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8780, __extension__
__PRETTY_FUNCTION__))
8780 "Predicated exit limit when predicates are not allowed!")(static_cast <bool> ((AllowPredicates || EL.Predicates.
empty()) && "Predicated exit limit when predicates are not allowed!"
) ? void (0) : __assert_fail ("(AllowPredicates || EL.Predicates.empty()) && \"Predicated exit limit when predicates are not allowed!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8780, __extension__
__PRETTY_FUNCTION__))
;
8781
8782 // 1. For each exit that can be computed, add an entry to ExitCounts.
8783 // CouldComputeBECount is true only if all exits can be computed.
8784 if (EL.ExactNotTaken == getCouldNotCompute())
8785 // We couldn't compute an exact value for this exit, so
8786 // we won't be able to compute an exact value for the loop.
8787 CouldComputeBECount = false;
8788 // Remember exit count if either exact or symbolic is known. Because
8789 // Exact always implies symbolic, only check symbolic.
8790 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
8791 ExitCounts.emplace_back(ExitBB, EL);
8792 else
8793 assert(EL.ExactNotTaken == getCouldNotCompute() &&(static_cast <bool> (EL.ExactNotTaken == getCouldNotCompute
() && "Exact is known but symbolic isn't?") ? void (0
) : __assert_fail ("EL.ExactNotTaken == getCouldNotCompute() && \"Exact is known but symbolic isn't?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8794, __extension__
__PRETTY_FUNCTION__))
8794 "Exact is known but symbolic isn't?")(static_cast <bool> (EL.ExactNotTaken == getCouldNotCompute
() && "Exact is known but symbolic isn't?") ? void (0
) : __assert_fail ("EL.ExactNotTaken == getCouldNotCompute() && \"Exact is known but symbolic isn't?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8794, __extension__
__PRETTY_FUNCTION__))
;
8795
8796 // 2. Derive the loop's MaxBECount from each exit's max number of
8797 // non-exiting iterations. Partition the loop exits into two kinds:
8798 // LoopMustExits and LoopMayExits.
8799 //
8800 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
8801 // is a LoopMayExit. If any computable LoopMustExit is found, then
8802 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
8803 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
8804 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
8805 // any
8806 // computable EL.ConstantMaxNotTaken.
8807 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
8808 DT.dominates(ExitBB, Latch)) {
8809 if (!MustExitMaxBECount) {
8810 MustExitMaxBECount = EL.ConstantMaxNotTaken;
8811 MustExitMaxOrZero = EL.MaxOrZero;
8812 } else {
8813 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
8814 EL.ConstantMaxNotTaken);
8815 }
8816 } else if (MayExitMaxBECount != getCouldNotCompute()) {
8817 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
8818 MayExitMaxBECount = EL.ConstantMaxNotTaken;
8819 else {
8820 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
8821 EL.ConstantMaxNotTaken);
8822 }
8823 }
8824 }
8825 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
8826 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
8827 // The loop backedge will be taken the maximum or zero times if there's
8828 // a single exit that must be taken the maximum or zero times.
8829 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
8830
8831 // Remember which SCEVs are used in exit limits for invalidation purposes.
8832 // We only care about non-constant SCEVs here, so we can ignore
8833 // EL.ConstantMaxNotTaken
8834 // and MaxBECount, which must be SCEVConstant.
8835 for (const auto &Pair : ExitCounts) {
8836 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
8837 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
8838 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
8839 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
8840 {L, AllowPredicates});
8841 }
8842 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
8843 MaxBECount, MaxOrZero);
8844}
8845
8846ScalarEvolution::ExitLimit
8847ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
8848 bool AllowPredicates) {
8849 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?")(static_cast <bool> (L->contains(ExitingBlock) &&
"Exit count for non-loop block?") ? void (0) : __assert_fail
("L->contains(ExitingBlock) && \"Exit count for non-loop block?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8849, __extension__
__PRETTY_FUNCTION__))
;
8850 // If our exiting block does not dominate the latch, then its connection with
8851 // loop's exit limit may be far from trivial.
8852 const BasicBlock *Latch = L->getLoopLatch();
8853 if (!Latch || !DT.dominates(ExitingBlock, Latch))
8854 return getCouldNotCompute();
8855
8856 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
8857 Instruction *Term = ExitingBlock->getTerminator();
8858 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
8859 assert(BI->isConditional() && "If unconditional, it can't be in loop!")(static_cast <bool> (BI->isConditional() && "If unconditional, it can't be in loop!"
) ? void (0) : __assert_fail ("BI->isConditional() && \"If unconditional, it can't be in loop!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8859, __extension__
__PRETTY_FUNCTION__))
;
8860 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
8861 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&(static_cast <bool> (ExitIfTrue == L->contains(BI->
getSuccessor(1)) && "It should have one successor in loop and one exit block!"
) ? void (0) : __assert_fail ("ExitIfTrue == L->contains(BI->getSuccessor(1)) && \"It should have one successor in loop and one exit block!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8862, __extension__
__PRETTY_FUNCTION__))
8862 "It should have one successor in loop and one exit block!")(static_cast <bool> (ExitIfTrue == L->contains(BI->
getSuccessor(1)) && "It should have one successor in loop and one exit block!"
) ? void (0) : __assert_fail ("ExitIfTrue == L->contains(BI->getSuccessor(1)) && \"It should have one successor in loop and one exit block!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8862, __extension__
__PRETTY_FUNCTION__))
;
8863 // Proceed to the next level to examine the exit condition expression.
8864 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
8865 /*ControlsOnlyExit=*/IsOnlyExit,
8866 AllowPredicates);
8867 }
8868
8869 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
8870 // For switch, make sure that there is a single exit from the loop.
8871 BasicBlock *Exit = nullptr;
8872 for (auto *SBB : successors(ExitingBlock))
8873 if (!L->contains(SBB)) {
8874 if (Exit) // Multiple exit successors.
8875 return getCouldNotCompute();
8876 Exit = SBB;
8877 }
8878 assert(Exit && "Exiting block must have at least one exit")(static_cast <bool> (Exit && "Exiting block must have at least one exit"
) ? void (0) : __assert_fail ("Exit && \"Exiting block must have at least one exit\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8878, __extension__
__PRETTY_FUNCTION__))
;
8879 return computeExitLimitFromSingleExitSwitch(
8880 L, SI, Exit,
8881 /*ControlsOnlyExit=*/IsOnlyExit);
8882 }
8883
8884 return getCouldNotCompute();
8885}
8886
8887ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
8888 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
8889 bool AllowPredicates) {
8890 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
8891 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
8892 ControlsOnlyExit, AllowPredicates);
8893}
8894
8895std::optional<ScalarEvolution::ExitLimit>
8896ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
8897 bool ExitIfTrue, bool ControlsOnlyExit,
8898 bool AllowPredicates) {
8899 (void)this->L;
8900 (void)this->ExitIfTrue;
8901 (void)this->AllowPredicates;
8902
8903 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&(static_cast <bool> (this->L == L && this->
ExitIfTrue == ExitIfTrue && this->AllowPredicates ==
AllowPredicates && "Variance in assumed invariant key components!"
) ? void (0) : __assert_fail ("this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8905, __extension__
__PRETTY_FUNCTION__))
8904 this->AllowPredicates == AllowPredicates &&(static_cast <bool> (this->L == L && this->
ExitIfTrue == ExitIfTrue && this->AllowPredicates ==
AllowPredicates && "Variance in assumed invariant key components!"
) ? void (0) : __assert_fail ("this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8905, __extension__
__PRETTY_FUNCTION__))
8905 "Variance in assumed invariant key components!")(static_cast <bool> (this->L == L && this->
ExitIfTrue == ExitIfTrue && this->AllowPredicates ==
AllowPredicates && "Variance in assumed invariant key components!"
) ? void (0) : __assert_fail ("this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8905, __extension__
__PRETTY_FUNCTION__))
;
8906 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
8907 if (Itr == TripCountMap.end())
8908 return std::nullopt;
8909 return Itr->second;
8910}
8911
8912void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
8913 bool ExitIfTrue,
8914 bool ControlsOnlyExit,
8915 bool AllowPredicates,
8916 const ExitLimit &EL) {
8917 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&(static_cast <bool> (this->L == L && this->
ExitIfTrue == ExitIfTrue && this->AllowPredicates ==
AllowPredicates && "Variance in assumed invariant key components!"
) ? void (0) : __assert_fail ("this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8919, __extension__
__PRETTY_FUNCTION__))
8918 this->AllowPredicates == AllowPredicates &&(static_cast <bool> (this->L == L && this->
ExitIfTrue == ExitIfTrue && this->AllowPredicates ==
AllowPredicates && "Variance in assumed invariant key components!"
) ? void (0) : __assert_fail ("this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8919, __extension__
__PRETTY_FUNCTION__))
8919 "Variance in assumed invariant key components!")(static_cast <bool> (this->L == L && this->
ExitIfTrue == ExitIfTrue && this->AllowPredicates ==
AllowPredicates && "Variance in assumed invariant key components!"
) ? void (0) : __assert_fail ("this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8919, __extension__
__PRETTY_FUNCTION__))
;
8920
8921 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
8922 assert(InsertResult.second && "Expected successful insertion!")(static_cast <bool> (InsertResult.second && "Expected successful insertion!"
) ? void (0) : __assert_fail ("InsertResult.second && \"Expected successful insertion!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 8922, __extension__
__PRETTY_FUNCTION__))
;
8923 (void)InsertResult;
8924 (void)ExitIfTrue;
8925}
8926
8927ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
8928 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8929 bool ControlsOnlyExit, bool AllowPredicates) {
8930
8931 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
8932 AllowPredicates))
8933 return *MaybeEL;
8934
8935 ExitLimit EL = computeExitLimitFromCondImpl(
8936 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
8937 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
8938 return EL;
8939}
8940
8941ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
8942 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
8943 bool ControlsOnlyExit, bool AllowPredicates) {
8944 // Handle BinOp conditions (And, Or).
8945 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
8946 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates))
8947 return *LimitFromBinOp;
8948
8949 // With an icmp, it may be feasible to compute an exact backedge-taken count.
8950 // Proceed to the next level to examine the icmp.
8951 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
8952 ExitLimit EL =
8953 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
8954 if (EL.hasFullInfo() || !AllowPredicates)
8955 return EL;
8956
8957 // Try again, but use SCEV predicates this time.
8958 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
8959 ControlsOnlyExit,
8960 /*AllowPredicates=*/true);
8961 }
8962
8963 // Check for a constant condition. These are normally stripped out by
8964 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
8965 // preserve the CFG and is temporarily leaving constant conditions
8966 // in place.
8967 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
8968 if (ExitIfTrue == !CI->getZExtValue())
8969 // The backedge is always taken.
8970 return getCouldNotCompute();
8971 // The backedge is never taken.
8972 return getZero(CI->getType());
8973 }
8974
8975 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
8976 // with a constant step, we can form an equivalent icmp predicate and figure
8977 // out how many iterations will be taken before we exit.
8978 const WithOverflowInst *WO;
8979 const APInt *C;
8980 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
8981 match(WO->getRHS(), m_APInt(C))) {
8982 ConstantRange NWR =
8983 ConstantRange::makeExactNoWrapRegion(WO->getBinaryOp(), *C,
8984 WO->getNoWrapKind());
8985 CmpInst::Predicate Pred;
8986 APInt NewRHSC, Offset;
8987 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
8988 if (!ExitIfTrue)
8989 Pred = ICmpInst::getInversePredicate(Pred);
8990 auto *LHS = getSCEV(WO->getLHS());
8991 if (Offset != 0)
8992 LHS = getAddExpr(LHS, getConstant(Offset));
8993 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
8994 ControlsOnlyExit, AllowPredicates);
8995 if (EL.hasAnyInfo())
8996 return EL;
8997 }
8998
8999 // If it's not an integer or pointer comparison then compute it the hard way.
9000 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9001}
9002
9003std::optional<ScalarEvolution::ExitLimit>
9004ScalarEvolution::computeExitLimitFromCondFromBinOp(
9005 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9006 bool ControlsOnlyExit, bool AllowPredicates) {
9007 // Check if the controlling expression for this loop is an And or Or.
9008 Value *Op0, *Op1;
9009 bool IsAnd = false;
9010 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9011 IsAnd = true;
9012 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9013 IsAnd = false;
9014 else
9015 return std::nullopt;
9016
9017 // EitherMayExit is true in these two cases:
9018 // br (and Op0 Op1), loop, exit
9019 // br (or Op0 Op1), exit, loop
9020 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9021 ExitLimit EL0 = computeExitLimitFromCondCached(
9022 Cache, L, Op0, ExitIfTrue, ControlsOnlyExit && !EitherMayExit,
9023 AllowPredicates);
9024 ExitLimit EL1 = computeExitLimitFromCondCached(
9025 Cache, L, Op1, ExitIfTrue, ControlsOnlyExit && !EitherMayExit,
9026 AllowPredicates);
9027
9028 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
9029 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
9030 if (isa<ConstantInt>(Op1))
9031 return Op1 == NeutralElement ? EL0 : EL1;
9032 if (isa<ConstantInt>(Op0))
9033 return Op0 == NeutralElement ? EL1 : EL0;
9034
9035 const SCEV *BECount = getCouldNotCompute();
9036 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9037 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9038 if (EitherMayExit) {
9039 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9040 // Both conditions must be same for the loop to continue executing.
9041 // Choose the less conservative count.
9042 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9043 EL1.ExactNotTaken != getCouldNotCompute()) {
9044 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9045 UseSequentialUMin);
9046 }
9047 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9048 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9049 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9050 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9051 else
9052 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9053 EL1.ConstantMaxNotTaken);
9054 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9055 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9056 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9057 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9058 else
9059 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9060 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9061 } else {
9062 // Both conditions must be same at the same time for the loop to exit.
9063 // For now, be conservative.
9064 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9065 BECount = EL0.ExactNotTaken;
9066 }
9067
9068 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9069 // to be more aggressive when computing BECount than when computing
9070 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9071 // and
9072 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9073 // EL1.ConstantMaxNotTaken to not.
9074 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9075 !isa<SCEVCouldNotCompute>(BECount))
9076 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9077 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9078 SymbolicMaxBECount =
9079 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9080 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9081 { &EL0.Predicates, &EL1.Predicates });
9082}
9083
9084ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9085 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9086 bool AllowPredicates) {
9087 // If the condition was exit on true, convert the condition to exit on false
9088 ICmpInst::Predicate Pred;
9089 if (!ExitIfTrue)
9090 Pred = ExitCond->getPredicate();
9091 else
9092 Pred = ExitCond->getInversePredicate();
9093 const ICmpInst::Predicate OriginalPred = Pred;
9094
9095 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9096 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9097
9098 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9099 AllowPredicates);
9100 if (EL.hasAnyInfo())
9101 return EL;
9102
9103 auto *ExhaustiveCount =
9104 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9105
9106 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9107 return ExhaustiveCount;
9108
9109 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9110 ExitCond->getOperand(1), L, OriginalPred);
9111}
9112ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9113 const Loop *L, ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9114 bool ControlsOnlyExit, bool AllowPredicates) {
9115
9116 // Try to evaluate any dependencies out of the loop.
9117 LHS = getSCEVAtScope(LHS, L);
9118 RHS = getSCEVAtScope(RHS, L);
9119
9120 // At this point, we would like to compute how many iterations of the
9121 // loop the predicate will return true for these inputs.
9122 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9123 // If there is a loop-invariant, force it into the RHS.
9124 std::swap(LHS, RHS);
9125 Pred = ICmpInst::getSwappedPredicate(Pred);
9126 }
9127
9128 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9129 loopIsFiniteByAssumption(L);
9130 // Simplify the operands before analyzing them.
9131 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9132
9133 // If we have a comparison of a chrec against a constant, try to use value
9134 // ranges to answer this query.
9135 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9136 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9137 if (AddRec->getLoop() == L) {
9138 // Form the constant range.
9139 ConstantRange CompRange =
9140 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9141
9142 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9143 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9144 }
9145
9146 // If this loop must exit based on this condition (or execute undefined
9147 // behaviour), and we can prove the test sequence produced must repeat
9148 // the same values on self-wrap of the IV, then we can infer that IV
9149 // doesn't self wrap because if it did, we'd have an infinite (undefined)
9150 // loop.
9151 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9152 // TODO: We can peel off any functions which are invertible *in L*. Loop
9153 // invariant terms are effectively constants for our purposes here.
9154 auto *InnerLHS = LHS;
9155 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9156 InnerLHS = ZExt->getOperand();
9157 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) {
9158 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
9159 if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9160 StrideC && StrideC->getAPInt().isPowerOf2()) {
9161 auto Flags = AR->getNoWrapFlags();
9162 Flags = setFlags(Flags, SCEV::FlagNW);
9163 SmallVector<const SCEV*> Operands{AR->operands()};
9164 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
9165 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9166 }
9167 }
9168 }
9169
9170 switch (Pred) {
9171 case ICmpInst::ICMP_NE: { // while (X != Y)
9172 // Convert to: while (X-Y != 0)
9173 if (LHS->getType()->isPointerTy()) {
9174 LHS = getLosslessPtrToIntExpr(LHS);
9175 if (isa<SCEVCouldNotCompute>(LHS))
9176 return LHS;
9177 }
9178 if (RHS->getType()->isPointerTy()) {
9179 RHS = getLosslessPtrToIntExpr(RHS);
9180 if (isa<SCEVCouldNotCompute>(RHS))
9181 return RHS;
9182 }
9183 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9184 AllowPredicates);
9185 if (EL.hasAnyInfo())
9186 return EL;
9187 break;
9188 }
9189 case ICmpInst::ICMP_EQ: { // while (X == Y)
9190 // Convert to: while (X-Y == 0)
9191 if (LHS->getType()->isPointerTy()) {
9192 LHS = getLosslessPtrToIntExpr(LHS);
9193 if (isa<SCEVCouldNotCompute>(LHS))
9194 return LHS;
9195 }
9196 if (RHS->getType()->isPointerTy()) {
9197 RHS = getLosslessPtrToIntExpr(RHS);
9198 if (isa<SCEVCouldNotCompute>(RHS))
9199 return RHS;
9200 }
9201 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9202 if (EL.hasAnyInfo()) return EL;
9203 break;
9204 }
9205 case ICmpInst::ICMP_SLE:
9206 case ICmpInst::ICMP_ULE:
9207 // Since the loop is finite, an invariant RHS cannot include the boundary
9208 // value, otherwise it would loop forever.
9209 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9210 !isLoopInvariant(RHS, L))
9211 break;
9212 RHS = getAddExpr(getOne(RHS->getType()), RHS);
9213 [[fallthrough]];
9214 case ICmpInst::ICMP_SLT:
9215 case ICmpInst::ICMP_ULT: { // while (X < Y)
9216 bool IsSigned = ICmpInst::isSigned(Pred);
9217 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9218 AllowPredicates);
9219 if (EL.hasAnyInfo())
9220 return EL;
9221 break;
9222 }
9223 case ICmpInst::ICMP_SGE:
9224 case ICmpInst::ICMP_UGE:
9225 // Since the loop is finite, an invariant RHS cannot include the boundary
9226 // value, otherwise it would loop forever.
9227 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9228 !isLoopInvariant(RHS, L))
9229 break;
9230 RHS = getAddExpr(getMinusOne(RHS->getType()), RHS);
9231 [[fallthrough]];
9232 case ICmpInst::ICMP_SGT:
9233 case ICmpInst::ICMP_UGT: { // while (X > Y)
9234 bool IsSigned = ICmpInst::isSigned(Pred);
9235 ExitLimit EL = howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9236 AllowPredicates);
9237 if (EL.hasAnyInfo())
9238 return EL;
9239 break;
9240 }
9241 default:
9242 break;
9243 }
9244
9245 return getCouldNotCompute();
9246}
9247
9248ScalarEvolution::ExitLimit
9249ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9250 SwitchInst *Switch,
9251 BasicBlock *ExitingBlock,
9252 bool ControlsOnlyExit) {
9253 assert(!L->contains(ExitingBlock) && "Not an exiting block!")(static_cast <bool> (!L->contains(ExitingBlock) &&
"Not an exiting block!") ? void (0) : __assert_fail ("!L->contains(ExitingBlock) && \"Not an exiting block!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 9253, __extension__
__PRETTY_FUNCTION__))
;
9254
9255 // Give up if the exit is the default dest of a switch.
9256 if (Switch->getDefaultDest() == ExitingBlock)
9257 return getCouldNotCompute();
9258
9259 assert(L->contains(Switch->getDefaultDest()) &&(static_cast <bool> (L->contains(Switch->getDefaultDest
()) && "Default case must not exit the loop!") ? void
(0) : __assert_fail ("L->contains(Switch->getDefaultDest()) && \"Default case must not exit the loop!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 9260, __extension__
__PRETTY_FUNCTION__))
9260 "Default case must not exit the loop!")(static_cast <bool> (L->contains(Switch->getDefaultDest
()) && "Default case must not exit the loop!") ? void
(0) : __assert_fail ("L->contains(Switch->getDefaultDest()) && \"Default case must not exit the loop!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 9260, __extension__
__PRETTY_FUNCTION__))
;
9261 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9262 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9263
9264 // while (X != Y) --> while (X-Y != 0)
9265 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9266 if (EL.hasAnyInfo())
9267 return EL;
9268
9269 return getCouldNotCompute();
9270}
9271
9272static ConstantInt *
9273EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
9274 ScalarEvolution &SE) {
9275 const SCEV *InVal = SE.getConstant(C);
9276 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9277 assert(isa<SCEVConstant>(Val) &&(static_cast <bool> (isa<SCEVConstant>(Val) &&
"Evaluation of SCEV at constant didn't fold correctly?") ? void
(0) : __assert_fail ("isa<SCEVConstant>(Val) && \"Evaluation of SCEV at constant didn't fold correctly?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 9278, __extension__
__PRETTY_FUNCTION__))
9278 "Evaluation of SCEV at constant didn't fold correctly?")(static_cast <bool> (isa<SCEVConstant>(Val) &&
"Evaluation of SCEV at constant didn't fold correctly?") ? void
(0) : __assert_fail ("isa<SCEVConstant>(Val) && \"Evaluation of SCEV at constant didn't fold correctly?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 9278, __extension__
__PRETTY_FUNCTION__))
;
9279 return cast<SCEVConstant>(Val)->getValue();
9280}
9281
9282ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9283 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9284 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9285 if (!RHS)
9286 return getCouldNotCompute();
9287
9288 const BasicBlock *Latch = L->getLoopLatch();
9289 if (!Latch)
9290 return getCouldNotCompute();
9291
9292 const BasicBlock *Predecessor = L->getLoopPredecessor();
9293 if (!Predecessor)
9294 return getCouldNotCompute();
9295
9296 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9297 // Return LHS in OutLHS and shift_opt in OutOpCode.
9298 auto MatchPositiveShift =
9299 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
9300
9301 using namespace PatternMatch;
9302
9303 ConstantInt *ShiftAmt;
9304 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9305 OutOpCode = Instruction::LShr;
9306 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9307 OutOpCode = Instruction::AShr;
9308 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9309 OutOpCode = Instruction::Shl;
9310 else
9311 return false;
9312
9313 return ShiftAmt->getValue().isStrictlyPositive();
9314 };
9315
9316 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9317 //
9318 // loop:
9319 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9320 // %iv.shifted = lshr i32 %iv, <positive constant>
9321 //
9322 // Return true on a successful match. Return the corresponding PHI node (%iv
9323 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
9324 auto MatchShiftRecurrence =
9325 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
9326 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9327
9328 {
9329 Instruction::BinaryOps OpC;
9330 Value *V;
9331
9332 // If we encounter a shift instruction, "peel off" the shift operation,
9333 // and remember that we did so. Later when we inspect %iv's backedge
9334 // value, we will make sure that the backedge value uses the same
9335 // operation.
9336 //
9337 // Note: the peeled shift operation does not have to be the same
9338 // instruction as the one feeding into the PHI's backedge value. We only
9339 // really care about it being the same *kind* of shift instruction --
9340 // that's all that is required for our later inferences to hold.
9341 if (MatchPositiveShift(LHS, V, OpC)) {
9342 PostShiftOpCode = OpC;
9343 LHS = V;
9344 }
9345 }
9346
9347 PNOut = dyn_cast<PHINode>(LHS);
9348 if (!PNOut || PNOut->getParent() != L->getHeader())
9349 return false;
9350
9351 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9352 Value *OpLHS;
9353
9354 return
9355 // The backedge value for the PHI node must be a shift by a positive
9356 // amount
9357 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
9358
9359 // of the PHI node itself
9360 OpLHS == PNOut &&
9361
9362 // and the kind of shift should be match the kind of shift we peeled
9363 // off, if any.
9364 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9365 };
9366
9367 PHINode *PN;
9368 Instruction::BinaryOps OpCode;
9369 if (!MatchShiftRecurrence(LHS, PN, OpCode))
9370 return getCouldNotCompute();
9371
9372 const DataLayout &DL = getDataLayout();
9373
9374 // The key rationale for this optimization is that for some kinds of shift
9375 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9376 // within a finite number of iterations. If the condition guarding the
9377 // backedge (in the sense that the backedge is taken if the condition is true)
9378 // is false for the value the shift recurrence stabilizes to, then we know
9379 // that the backedge is taken only a finite number of times.
9380
9381 ConstantInt *StableValue = nullptr;
9382 switch (OpCode) {
9383 default:
9384 llvm_unreachable("Impossible case!")::llvm::llvm_unreachable_internal("Impossible case!", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 9384)
;
9385
9386 case Instruction::AShr: {
9387 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9388 // bitwidth(K) iterations.
9389 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9390 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
9391 Predecessor->getTerminator(), &DT);
9392 auto *Ty = cast<IntegerType>(RHS->getType());
9393 if (Known.isNonNegative())
9394 StableValue = ConstantInt::get(Ty, 0);
9395 else if (Known.isNegative())
9396 StableValue = ConstantInt::get(Ty, -1, true);
9397 else
9398 return getCouldNotCompute();
9399
9400 break;
9401 }
9402 case Instruction::LShr:
9403 case Instruction::Shl:
9404 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9405 // stabilize to 0 in at most bitwidth(K) iterations.
9406 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9407 break;
9408 }
9409
9410 auto *Result =
9411 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9412 assert(Result->getType()->isIntegerTy(1) &&(static_cast <bool> (Result->getType()->isIntegerTy
(1) && "Otherwise cannot be an operand to a branch instruction"
) ? void (0) : __assert_fail ("Result->getType()->isIntegerTy(1) && \"Otherwise cannot be an operand to a branch instruction\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 9413, __extension__
__PRETTY_FUNCTION__))
9413 "Otherwise cannot be an operand to a branch instruction")(static_cast <bool> (Result->getType()->isIntegerTy
(1) && "Otherwise cannot be an operand to a branch instruction"
) ? void (0) : __assert_fail ("Result->getType()->isIntegerTy(1) && \"Otherwise cannot be an operand to a branch instruction\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 9413, __extension__
__PRETTY_FUNCTION__))
;
9414
9415 if (Result->isZeroValue()) {
9416 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9417 const SCEV *UpperBound =
9418 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
9419 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9420 }
9421
9422 return getCouldNotCompute();
9423}
9424
9425/// Return true if we can constant fold an instruction of the specified type,
9426/// assuming that all operands were constants.
9427static bool CanConstantFold(const Instruction *I) {
9428 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
9429 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
9430 isa<LoadInst>(I) || isa<ExtractValueInst>(I))
9431 return true;
9432
9433 if (const CallInst *CI = dyn_cast<CallInst>(I))
9434 if (const Function *F = CI->getCalledFunction())
9435 return canConstantFoldCallTo(CI, F);
9436 return false;
9437}
9438
9439/// Determine whether this instruction can constant evolve within this loop
9440/// assuming its operands can all constant evolve.
9441static bool canConstantEvolve(Instruction *I, const Loop *L) {
9442 // An instruction outside of the loop can't be derived from a loop PHI.
9443 if (!L->contains(I)) return false;
9444
9445 if (isa<PHINode>(I)) {
9446 // We don't currently keep track of the control flow needed to evaluate
9447 // PHIs, so we cannot handle PHIs inside of loops.
9448 return L->getHeader() == I->getParent();
9449 }
9450
9451 // If we won't be able to constant fold this expression even if the operands
9452 // are constants, bail early.
9453 return CanConstantFold(I);
9454}
9455
9456/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9457/// recursing through each instruction operand until reaching a loop header phi.
9458static PHINode *
9459getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
9460 DenseMap<Instruction *, PHINode *> &PHIMap,
9461 unsigned Depth) {
9462 if (Depth > MaxConstantEvolvingDepth)
9463 return nullptr;
9464
9465 // Otherwise, we can evaluate this instruction if all of its operands are
9466 // constant or derived from a PHI node themselves.
9467 PHINode *PHI = nullptr;
9468 for (Value *Op : UseInst->operands()) {
9469 if (isa<Constant>(Op)) continue;
9470
9471 Instruction *OpInst = dyn_cast<Instruction>(Op);
9472 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
9473
9474 PHINode *P = dyn_cast<PHINode>(OpInst);
9475 if (!P)
9476 // If this operand is already visited, reuse the prior result.
9477 // We may have P != PHI if this is the deepest point at which the
9478 // inconsistent paths meet.
9479 P = PHIMap.lookup(OpInst);
9480 if (!P) {
9481 // Recurse and memoize the results, whether a phi is found or not.
9482 // This recursive call invalidates pointers into PHIMap.
9483 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
9484 PHIMap[OpInst] = P;
9485 }
9486 if (!P)
9487 return nullptr; // Not evolving from PHI
9488 if (PHI && PHI != P)
9489 return nullptr; // Evolving from multiple different PHIs.
9490 PHI = P;
9491 }
9492 // This is a expression evolving from a constant PHI!
9493 return PHI;
9494}
9495
9496/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9497/// in the loop that V is derived from. We allow arbitrary operations along the
9498/// way, but the operands of an operation must either be constants or a value
9499/// derived from a constant PHI. If this expression does not fit with these
9500/// constraints, return null.
9501static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
9502 Instruction *I = dyn_cast<Instruction>(V);
9503 if (!I || !canConstantEvolve(I, L)) return nullptr;
9504
9505 if (PHINode *PN = dyn_cast<PHINode>(I))
9506 return PN;
9507
9508 // Record non-constant instructions contained by the loop.
9509 DenseMap<Instruction *, PHINode *> PHIMap;
9510 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
9511}
9512
9513/// EvaluateExpression - Given an expression that passes the
9514/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9515/// in the loop has the value PHIVal. If we can't fold this expression for some
9516/// reason, return null.
9517static Constant *EvaluateExpression(Value *V, const Loop *L,
9518 DenseMap<Instruction *, Constant *> &Vals,
9519 const DataLayout &DL,
9520 const TargetLibraryInfo *TLI) {
9521 // Convenient constant check, but redundant for recursive calls.
9522 if (Constant *C = dyn_cast<Constant>(V)) return C;
9523 Instruction *I = dyn_cast<Instruction>(V);
9524 if (!I) return nullptr;
9525
9526 if (Constant *C = Vals.lookup(I)) return C;
9527
9528 // An instruction inside the loop depends on a value outside the loop that we
9529 // weren't given a mapping for, or a value such as a call inside the loop.
9530 if (!canConstantEvolve(I, L)) return nullptr;
9531
9532 // An unmapped PHI can be due to a branch or another loop inside this loop,
9533 // or due to this not being the initial iteration through a loop where we
9534 // couldn't compute the evolution of this particular PHI last time.
9535 if (isa<PHINode>(I)) return nullptr;
9536
9537 std::vector<Constant*> Operands(I->getNumOperands());
9538
9539 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9540 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9541 if (!Operand) {
9542 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9543 if (!Operands[i]) return nullptr;
9544 continue;
9545 }
9546 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9547 Vals[Operand] = C;
9548 if (!C) return nullptr;
9549 Operands[i] = C;
9550 }
9551
9552 return ConstantFoldInstOperands(I, Operands, DL, TLI);
9553}
9554
9555
9556// If every incoming value to PN except the one for BB is a specific Constant,
9557// return that, else return nullptr.
9558static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
9559 Constant *IncomingVal = nullptr;
9560
9561 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9562 if (PN->getIncomingBlock(i) == BB)
9563 continue;
9564
9565 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9566 if (!CurrentVal)
9567 return nullptr;
9568
9569 if (IncomingVal != CurrentVal) {
9570 if (IncomingVal)
9571 return nullptr;
9572 IncomingVal = CurrentVal;
9573 }
9574 }
9575
9576 return IncomingVal;
9577}
9578
9579/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9580/// in the header of its containing loop, we know the loop executes a
9581/// constant number of times, and the PHI node is just a recurrence
9582/// involving constants, fold it.
9583Constant *
9584ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9585 const APInt &BEs,
9586 const Loop *L) {
9587 auto I = ConstantEvolutionLoopExitValue.find(PN);
9588 if (I != ConstantEvolutionLoopExitValue.end())
9589 return I->second;
9590
9591 if (BEs.ugt(MaxBruteForceIterations))
9592 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
9593
9594 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
9595
9596 DenseMap<Instruction *, Constant *> CurrentIterVals;
9597 BasicBlock *Header = L->getHeader();
9598 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!")(static_cast <bool> (PN->getParent() == Header &&
"Can't evaluate PHI not in loop header!") ? void (0) : __assert_fail
("PN->getParent() == Header && \"Can't evaluate PHI not in loop header!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 9598, __extension__
__PRETTY_FUNCTION__))
;
9599
9600 BasicBlock *Latch = L->getLoopLatch();
9601 if (!Latch)
9602 return nullptr;
9603
9604 for (PHINode &PHI : Header->phis()) {
9605 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9606 CurrentIterVals[&PHI] = StartCST;
9607 }
9608 if (!CurrentIterVals.count(PN))
9609 return RetVal = nullptr;
9610
9611 Value *BEValue = PN->getIncomingValueForBlock(Latch);
9612
9613 // Execute the loop symbolically to determine the exit value.
9614 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&(static_cast <bool> (BEs.getActiveBits() < 8 * sizeof
(unsigned) && "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"
) ? void (0) : __assert_fail ("BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && \"BEs is <= MaxBruteForceIterations which is an 'unsigned'!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 9615, __extension__
__PRETTY_FUNCTION__))
9615 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!")(static_cast <bool> (BEs.getActiveBits() < 8 * sizeof
(unsigned) && "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"
) ? void (0) : __assert_fail ("BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && \"BEs is <= MaxBruteForceIterations which is an 'unsigned'!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 9615, __extension__
__PRETTY_FUNCTION__))
;
9616
9617 unsigned NumIterations = BEs.getZExtValue(); // must be in range
9618 unsigned IterationNum = 0;
9619 const DataLayout &DL = getDataLayout();
9620 for (; ; ++IterationNum) {
9621 if (IterationNum == NumIterations)
9622 return RetVal = CurrentIterVals[PN]; // Got exit value!
9623
9624 // Compute the value of the PHIs for the next iteration.
9625 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9626 DenseMap<Instruction *, Constant *> NextIterVals;
9627 Constant *NextPHI =
9628 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9629 if (!NextPHI)
9630 return nullptr; // Couldn't evaluate!
9631 NextIterVals[PN] = NextPHI;
9632
9633 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9634
9635 // Also evaluate the other PHI nodes. However, we don't get to stop if we
9636 // cease to be able to evaluate one of them or if they stop evolving,
9637 // because that doesn't necessarily prevent us from computing PN.
9638 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
9639 for (const auto &I : CurrentIterVals) {
9640 PHINode *PHI = dyn_cast<PHINode>(I.first);
9641 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9642 PHIsToCompute.emplace_back(PHI, I.second);
9643 }
9644 // We use two distinct loops because EvaluateExpression may invalidate any
9645 // iterators into CurrentIterVals.
9646 for (const auto &I : PHIsToCompute) {
9647 PHINode *PHI = I.first;
9648 Constant *&NextPHI = NextIterVals[PHI];
9649 if (!NextPHI) { // Not already computed.
9650 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9651 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9652 }
9653 if (NextPHI != I.second)
9654 StoppedEvolving = false;
9655 }
9656
9657 // If all entries in CurrentIterVals == NextIterVals then we can stop
9658 // iterating, the loop can't continue to change.
9659 if (StoppedEvolving)
9660 return RetVal = CurrentIterVals[PN];
9661
9662 CurrentIterVals.swap(NextIterVals);
9663 }
9664}
9665
9666const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9667 Value *Cond,
9668 bool ExitWhen) {
9669 PHINode *PN = getConstantEvolvingPHI(Cond, L);
9670 if (!PN) return getCouldNotCompute();
9671
9672 // If the loop is canonicalized, the PHI will have exactly two entries.
9673 // That's the only form we support here.
9674 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9675
9676 DenseMap<Instruction *, Constant *> CurrentIterVals;
9677 BasicBlock *Header = L->getHeader();
9678 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!")(static_cast <bool> (PN->getParent() == Header &&
"Can't evaluate PHI not in loop header!") ? void (0) : __assert_fail
("PN->getParent() == Header && \"Can't evaluate PHI not in loop header!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 9678, __extension__
__PRETTY_FUNCTION__))
;
9679
9680 BasicBlock *Latch = L->getLoopLatch();
9681 assert(Latch && "Should follow from NumIncomingValues == 2!")(static_cast <bool> (Latch && "Should follow from NumIncomingValues == 2!"
) ? void (0) : __assert_fail ("Latch && \"Should follow from NumIncomingValues == 2!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 9681, __extension__
__PRETTY_FUNCTION__))
;
9682
9683 for (PHINode &PHI : Header->phis()) {
9684 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9685 CurrentIterVals[&PHI] = StartCST;
9686 }
9687 if (!CurrentIterVals.count(PN))
9688 return getCouldNotCompute();
9689
9690 // Okay, we find a PHI node that defines the trip count of this loop. Execute
9691 // the loop symbolically to determine when the condition gets a value of
9692 // "ExitWhen".
9693 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
9694 const DataLayout &DL = getDataLayout();
9695 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
9696 auto *CondVal = dyn_cast_or_null<ConstantInt>(
9697 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
9698
9699 // Couldn't symbolically evaluate.
9700 if (!CondVal) return getCouldNotCompute();
9701
9702 if (CondVal->getValue() == uint64_t(ExitWhen)) {
9703 ++NumBruteForceTripCountsComputed;
9704 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
9705 }
9706
9707 // Update all the PHI nodes for the next iteration.
9708 DenseMap<Instruction *, Constant *> NextIterVals;
9709
9710 // Create a list of which PHIs we need to compute. We want to do this before
9711 // calling EvaluateExpression on them because that may invalidate iterators
9712 // into CurrentIterVals.
9713 SmallVector<PHINode *, 8> PHIsToCompute;
9714 for (const auto &I : CurrentIterVals) {
9715 PHINode *PHI = dyn_cast<PHINode>(I.first);
9716 if (!PHI || PHI->getParent() != Header) continue;
9717 PHIsToCompute.push_back(PHI);
9718 }
9719 for (PHINode *PHI : PHIsToCompute) {
9720 Constant *&NextPHI = NextIterVals[PHI];
9721 if (NextPHI) continue; // Already computed!
9722
9723 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9724 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9725 }
9726 CurrentIterVals.swap(NextIterVals);
9727 }
9728
9729 // Too many iterations were needed to evaluate.
9730 return getCouldNotCompute();
9731}
9732
9733const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
9734 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
9735 ValuesAtScopes[V];
9736 // Check to see if we've folded this expression at this loop before.
9737 for (auto &LS : Values)
9738 if (LS.first == L)
9739 return LS.second ? LS.second : V;
9740
9741 Values.emplace_back(L, nullptr);
9742
9743 // Otherwise compute it.
9744 const SCEV *C = computeSCEVAtScope(V, L);
9745 for (auto &LS : reverse(ValuesAtScopes[V]))
9746 if (LS.first == L) {
9747 LS.second = C;
9748 if (!isa<SCEVConstant>(C))
9749 ValuesAtScopesUsers[C].push_back({L, V});
9750 break;
9751 }
9752 return C;
9753}
9754
9755/// This builds up a Constant using the ConstantExpr interface. That way, we
9756/// will return Constants for objects which aren't represented by a
9757/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
9758/// Returns NULL if the SCEV isn't representable as a Constant.
9759static Constant *BuildConstantFromSCEV(const SCEV *V) {
9760 switch (V->getSCEVType()) {
9761 case scCouldNotCompute:
9762 case scAddRecExpr:
9763 case scVScale:
9764 return nullptr;
9765 case scConstant:
9766 return cast<SCEVConstant>(V)->getValue();
9767 case scUnknown:
9768 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
9769 case scSignExtend: {
9770 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
9771 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
9772 return ConstantExpr::getSExt(CastOp, SS->getType());
9773 return nullptr;
9774 }
9775 case scZeroExtend: {
9776 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
9777 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
9778 return ConstantExpr::getZExt(CastOp, SZ->getType());
9779 return nullptr;
9780 }
9781 case scPtrToInt: {
9782 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
9783 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
9784 return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
9785
9786 return nullptr;
9787 }
9788 case scTruncate: {
9789 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
9790 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
9791 return ConstantExpr::getTrunc(CastOp, ST->getType());
9792 return nullptr;
9793 }
9794 case scAddExpr: {
9795 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
9796 Constant *C = nullptr;
9797 for (const SCEV *Op : SA->operands()) {
9798 Constant *OpC = BuildConstantFromSCEV(Op);
9799 if (!OpC)
9800 return nullptr;
9801 if (!C) {
9802 C = OpC;
9803 continue;
9804 }
9805 assert(!C->getType()->isPointerTy() &&(static_cast <bool> (!C->getType()->isPointerTy()
&& "Can only have one pointer, and it must be last")
? void (0) : __assert_fail ("!C->getType()->isPointerTy() && \"Can only have one pointer, and it must be last\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 9806, __extension__
__PRETTY_FUNCTION__))
9806 "Can only have one pointer, and it must be last")(static_cast <bool> (!C->getType()->isPointerTy()
&& "Can only have one pointer, and it must be last")
? void (0) : __assert_fail ("!C->getType()->isPointerTy() && \"Can only have one pointer, and it must be last\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 9806, __extension__
__PRETTY_FUNCTION__))
;
9807 if (auto *PT = dyn_cast<PointerType>(OpC->getType())) {
9808 // The offsets have been converted to bytes. We can add bytes to an
9809 // i8* by GEP with the byte count in the first index.
9810 Type *DestPtrTy =
9811 Type::getInt8PtrTy(PT->getContext(), PT->getAddressSpace());
9812 OpC = ConstantExpr::getBitCast(OpC, DestPtrTy);
9813 C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()),
9814 OpC, C);
9815 } else {
9816 C = ConstantExpr::getAdd(C, OpC);
9817 }
9818 }
9819 return C;
9820 }
9821 case scMulExpr: {
9822 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
9823 Constant *C = nullptr;
9824 for (const SCEV *Op : SM->operands()) {
9825 assert(!Op->getType()->isPointerTy() && "Can't multiply pointers")(static_cast <bool> (!Op->getType()->isPointerTy(
) && "Can't multiply pointers") ? void (0) : __assert_fail
("!Op->getType()->isPointerTy() && \"Can't multiply pointers\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 9825, __extension__
__PRETTY_FUNCTION__))
;
9826 Constant *OpC = BuildConstantFromSCEV(Op);
9827 if (!OpC)
9828 return nullptr;
9829 C = C ? ConstantExpr::getMul(C, OpC) : OpC;
9830 }
9831 return C;
9832 }
9833 case scUDivExpr:
9834 case scSMaxExpr:
9835 case scUMaxExpr:
9836 case scSMinExpr:
9837 case scUMinExpr:
9838 case scSequentialUMinExpr:
9839 return nullptr; // TODO: smax, umax, smin, umax, umin_seq.
9840 }
9841 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 9841)
;
9842}
9843
9844const SCEV *
9845ScalarEvolution::getWithOperands(const SCEV *S,
9846 SmallVectorImpl<const SCEV *> &NewOps) {
9847 switch (S->getSCEVType()) {
9848 case scTruncate:
9849 case scZeroExtend:
9850 case scSignExtend:
9851 case scPtrToInt:
9852 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
9853 case scAddRecExpr: {
9854 auto *AddRec = cast<SCEVAddRecExpr>(S);
9855 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
9856 }
9857 case scAddExpr:
9858 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
9859 case scMulExpr:
9860 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
9861 case scUDivExpr:
9862 return getUDivExpr(NewOps[0], NewOps[1]);
9863 case scUMaxExpr:
9864 case scSMaxExpr:
9865 case scUMinExpr:
9866 case scSMinExpr:
9867 return getMinMaxExpr(S->getSCEVType(), NewOps);
9868 case scSequentialUMinExpr:
9869 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
9870 case scConstant:
9871 case scVScale:
9872 case scUnknown:
9873 return S;
9874 case scCouldNotCompute:
9875 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 9875)
;
9876 }
9877 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 9877)
;
9878}
9879
9880const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
9881 switch (V->getSCEVType()) {
9882 case scConstant:
9883 case scVScale:
9884 return V;
9885 case scAddRecExpr: {
9886 // If this is a loop recurrence for a loop that does not contain L, then we
9887 // are dealing with the final value computed by the loop.
9888 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
9889 // First, attempt to evaluate each operand.
9890 // Avoid performing the look-up in the common case where the specified
9891 // expression has no loop-variant portions.
9892 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
9893 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
9894 if (OpAtScope == AddRec->getOperand(i))
9895 continue;
9896
9897 // Okay, at least one of these operands is loop variant but might be
9898 // foldable. Build a new instance of the folded commutative expression.
9899 SmallVector<const SCEV *, 8> NewOps;
9900 NewOps.reserve(AddRec->getNumOperands());
9901 append_range(NewOps, AddRec->operands().take_front(i));
9902 NewOps.push_back(OpAtScope);
9903 for (++i; i != e; ++i)
9904 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
9905
9906 const SCEV *FoldedRec = getAddRecExpr(
9907 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
9908 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
9909 // The addrec may be folded to a nonrecurrence, for example, if the
9910 // induction variable is multiplied by zero after constant folding. Go
9911 // ahead and return the folded value.
9912 if (!AddRec)
9913 return FoldedRec;
9914 break;
9915 }
9916
9917 // If the scope is outside the addrec's loop, evaluate it by using the
9918 // loop exit value of the addrec.
9919 if (!AddRec->getLoop()->contains(L)) {
9920 // To evaluate this recurrence, we need to know how many times the AddRec
9921 // loop iterates. Compute this now.
9922 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
9923 if (BackedgeTakenCount == getCouldNotCompute())
9924 return AddRec;
9925
9926 // Then, evaluate the AddRec.
9927 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
9928 }
9929
9930 return AddRec;
9931 }
9932 case scTruncate:
9933 case scZeroExtend:
9934 case scSignExtend:
9935 case scPtrToInt:
9936 case scAddExpr:
9937 case scMulExpr:
9938 case scUDivExpr:
9939 case scUMaxExpr:
9940 case scSMaxExpr:
9941 case scUMinExpr:
9942 case scSMinExpr:
9943 case scSequentialUMinExpr: {
9944 ArrayRef<const SCEV *> Ops = V->operands();
9945 // Avoid performing the look-up in the common case where the specified
9946 // expression has no loop-variant portions.
9947 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
9948 const SCEV *OpAtScope = getSCEVAtScope(Ops[i], L);
9949 if (OpAtScope != Ops[i]) {
9950 // Okay, at least one of these operands is loop variant but might be
9951 // foldable. Build a new instance of the folded commutative expression.
9952 SmallVector<const SCEV *, 8> NewOps;
9953 NewOps.reserve(Ops.size());
9954 append_range(NewOps, Ops.take_front(i));
9955 NewOps.push_back(OpAtScope);
9956
9957 for (++i; i != e; ++i) {
9958 OpAtScope = getSCEVAtScope(Ops[i], L);
9959 NewOps.push_back(OpAtScope);
9960 }
9961
9962 return getWithOperands(V, NewOps);
9963 }
9964 }
9965 // If we got here, all operands are loop invariant.
9966 return V;
9967 }
9968 case scUnknown: {
9969 // If this instruction is evolved from a constant-evolving PHI, compute the
9970 // exit value from the loop without using SCEVs.
9971 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
9972 Instruction *I = dyn_cast<Instruction>(SU->getValue());
9973 if (!I)
9974 return V; // This is some other type of SCEVUnknown, just return it.
9975
9976 if (PHINode *PN = dyn_cast<PHINode>(I)) {
9977 const Loop *CurrLoop = this->LI[I->getParent()];
9978 // Looking for loop exit value.
9979 if (CurrLoop && CurrLoop->getParentLoop() == L &&
9980 PN->getParent() == CurrLoop->getHeader()) {
9981 // Okay, there is no closed form solution for the PHI node. Check
9982 // to see if the loop that contains it has a known backedge-taken
9983 // count. If so, we may be able to force computation of the exit
9984 // value.
9985 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
9986 // This trivial case can show up in some degenerate cases where
9987 // the incoming IR has not yet been fully simplified.
9988 if (BackedgeTakenCount->isZero()) {
9989 Value *InitValue = nullptr;
9990 bool MultipleInitValues = false;
9991 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
9992 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
9993 if (!InitValue)
9994 InitValue = PN->getIncomingValue(i);
9995 else if (InitValue != PN->getIncomingValue(i)) {
9996 MultipleInitValues = true;
9997 break;
9998 }
9999 }
10000 }
10001 if (!MultipleInitValues && InitValue)
10002 return getSCEV(InitValue);
10003 }
10004 // Do we have a loop invariant value flowing around the backedge
10005 // for a loop which must execute the backedge?
10006 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10007 isKnownPositive(BackedgeTakenCount) &&
10008 PN->getNumIncomingValues() == 2) {
10009
10010 unsigned InLoopPred =
10011 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10012 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10013 if (CurrLoop->isLoopInvariant(BackedgeVal))
10014 return getSCEV(BackedgeVal);
10015 }
10016 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10017 // Okay, we know how many times the containing loop executes. If
10018 // this is a constant evolving PHI node, get the final value at
10019 // the specified iteration number.
10020 Constant *RV =
10021 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10022 if (RV)
10023 return getSCEV(RV);
10024 }
10025 }
10026 }
10027
10028 // Okay, this is an expression that we cannot symbolically evaluate
10029 // into a SCEV. Check to see if it's possible to symbolically evaluate
10030 // the arguments into constants, and if so, try to constant propagate the
10031 // result. This is particularly useful for computing loop exit values.
10032 if (!CanConstantFold(I))
10033 return V; // This is some other type of SCEVUnknown, just return it.
10034
10035 SmallVector<Constant *, 4> Operands;
10036 Operands.reserve(I->getNumOperands());
10037 bool MadeImprovement = false;
10038 for (Value *Op : I->operands()) {
10039 if (Constant *C = dyn_cast<Constant>(Op)) {
10040 Operands.push_back(C);
10041 continue;
10042 }
10043
10044 // If any of the operands is non-constant and if they are
10045 // non-integer and non-pointer, don't even try to analyze them
10046 // with scev techniques.
10047 if (!isSCEVable(Op->getType()))
10048 return V;
10049
10050 const SCEV *OrigV = getSCEV(Op);
10051 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10052 MadeImprovement |= OrigV != OpV;
10053
10054 Constant *C = BuildConstantFromSCEV(OpV);
10055 if (!C)
10056 return V;
10057 if (C->getType() != Op->getType())
10058 C = ConstantExpr::getCast(
10059 CastInst::getCastOpcode(C, false, Op->getType(), false), C,
10060 Op->getType());
10061 Operands.push_back(C);
10062 }
10063
10064 // Check to see if getSCEVAtScope actually made an improvement.
10065 if (!MadeImprovement)
10066 return V; // This is some other type of SCEVUnknown, just return it.
10067
10068 Constant *C = nullptr;
10069 const DataLayout &DL = getDataLayout();
10070 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
10071 if (!C)
10072 return V;
10073 return getSCEV(C);
10074 }
10075 case scCouldNotCompute:
10076 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10076)
;
10077 }
10078 llvm_unreachable("Unknown SCEV type!")::llvm::llvm_unreachable_internal("Unknown SCEV type!", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 10078)
;
10079}
10080
10081const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
10082 return getSCEVAtScope(getSCEV(V), L);
10083}
10084
10085const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10086 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
10087 return stripInjectiveFunctions(ZExt->getOperand());
10088 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
10089 return stripInjectiveFunctions(SExt->getOperand());
10090 return S;
10091}
10092
10093/// Finds the minimum unsigned root of the following equation:
10094///
10095/// A * X = B (mod N)
10096///
10097/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10098/// A and B isn't important.
10099///
10100/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10101static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
10102 ScalarEvolution &SE) {
10103 uint32_t BW = A.getBitWidth();
10104 assert(BW == SE.getTypeSizeInBits(B->getType()))(static_cast <bool> (BW == SE.getTypeSizeInBits(B->getType
())) ? void (0) : __assert_fail ("BW == SE.getTypeSizeInBits(B->getType())"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10104, __extension__
__PRETTY_FUNCTION__))
;
10105 assert(A != 0 && "A must be non-zero.")(static_cast <bool> (A != 0 && "A must be non-zero."
) ? void (0) : __assert_fail ("A != 0 && \"A must be non-zero.\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10105, __extension__
__PRETTY_FUNCTION__))
;
10106
10107 // 1. D = gcd(A, N)
10108 //
10109 // The gcd of A and N may have only one prime factor: 2. The number of
10110 // trailing zeros in A is its multiplicity
10111 uint32_t Mult2 = A.countr_zero();
10112 // D = 2^Mult2
10113
10114 // 2. Check if B is divisible by D.
10115 //
10116 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10117 // is not less than multiplicity of this prime factor for D.
10118 if (SE.getMinTrailingZeros(B) < Mult2)
10119 return SE.getCouldNotCompute();
10120
10121 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10122 // modulo (N / D).
10123 //
10124 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10125 // (N / D) in general. The inverse itself always fits into BW bits, though,
10126 // so we immediately truncate it.
10127 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
10128 APInt Mod(BW + 1, 0);
10129 Mod.setBit(BW - Mult2); // Mod = N / D
10130 APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
10131
10132 // 4. Compute the minimum unsigned root of the equation:
10133 // I * (B / D) mod (N / D)
10134 // To simplify the computation, we factor out the divide by D:
10135 // (I * B mod N) / D
10136 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10137 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10138}
10139
10140/// For a given quadratic addrec, generate coefficients of the corresponding
10141/// quadratic equation, multiplied by a common value to ensure that they are
10142/// integers.
10143/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10144/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10145/// were multiplied by, and BitWidth is the bit width of the original addrec
10146/// coefficients.
10147/// This function returns std::nullopt if the addrec coefficients are not
10148/// compile- time constants.
10149static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10150GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
10151 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!")(static_cast <bool> (AddRec->getNumOperands() == 3 &&
"This is not a quadratic chrec!") ? void (0) : __assert_fail
("AddRec->getNumOperands() == 3 && \"This is not a quadratic chrec!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10151, __extension__
__PRETTY_FUNCTION__))
;
10152 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10153 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10154 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10155 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << __func__ << ": analyzing quadratic addrec: "
<< *AddRec << '\n'; } } while (false)
10156 << *AddRec << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << __func__ << ": analyzing quadratic addrec: "
<< *AddRec << '\n'; } } while (false)
;
10157
10158 // We currently can only solve this if the coefficients are constants.
10159 if (!LC || !MC || !NC) {
10160 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << __func__ << ": coefficients are not constant\n"
; } } while (false)
;
10161 return std::nullopt;
10162 }
10163
10164 APInt L = LC->getAPInt();
10165 APInt M = MC->getAPInt();
10166 APInt N = NC->getAPInt();
10167 assert(!N.isZero() && "This is not a quadratic addrec")(static_cast <bool> (!N.isZero() && "This is not a quadratic addrec"
) ? void (0) : __assert_fail ("!N.isZero() && \"This is not a quadratic addrec\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10167, __extension__
__PRETTY_FUNCTION__))
;
10168
10169 unsigned BitWidth = LC->getAPInt().getBitWidth();
10170 unsigned NewWidth = BitWidth + 1;
10171 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << __func__ << ": addrec coeff bw: "
<< BitWidth << '\n'; } } while (false)
10172 << BitWidth << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << __func__ << ": addrec coeff bw: "
<< BitWidth << '\n'; } } while (false)
;
10173 // The sign-extension (as opposed to a zero-extension) here matches the
10174 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10175 N = N.sext(NewWidth);
10176 M = M.sext(NewWidth);
10177 L = L.sext(NewWidth);
10178
10179 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10180 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10181 // L+M, L+2M+N, L+3M+3N, ...
10182 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10183 //
10184 // The equation Acc = 0 is then
10185 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10186 // In a quadratic form it becomes:
10187 // N n^2 + (2M-N) n + 2L = 0.
10188
10189 APInt A = N;
10190 APInt B = 2 * M - A;
10191 APInt C = 2 * L;
10192 APInt T = APInt(NewWidth, 2);
10193 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << Bdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << __func__ << ": equation "
<< A << "x^2 + " << B << "x + " <<
C << ", coeff bw: " << NewWidth << ", multiplied by "
<< T << '\n'; } } while (false)
10194 << "x + " << C << ", coeff bw: " << NewWidthdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << __func__ << ": equation "
<< A << "x^2 + " << B << "x + " <<
C << ", coeff bw: " << NewWidth << ", multiplied by "
<< T << '\n'; } } while (false)
10195 << ", multiplied by " << T << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << __func__ << ": equation "
<< A << "x^2 + " << B << "x + " <<
C << ", coeff bw: " << NewWidth << ", multiplied by "
<< T << '\n'; } } while (false)
;
10196 return std::make_tuple(A, B, C, T, BitWidth);
10197}
10198
10199/// Helper function to compare optional APInts:
10200/// (a) if X and Y both exist, return min(X, Y),
10201/// (b) if neither X nor Y exist, return std::nullopt,
10202/// (c) if exactly one of X and Y exists, return that value.
10203static std::optional<APInt> MinOptional(std::optional<APInt> X,
10204 std::optional<APInt> Y) {
10205 if (X && Y) {
10206 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10207 APInt XW = X->sext(W);
10208 APInt YW = Y->sext(W);
10209 return XW.slt(YW) ? *X : *Y;
10210 }
10211 if (!X && !Y)
10212 return std::nullopt;
10213 return X ? *X : *Y;
10214}
10215
10216/// Helper function to truncate an optional APInt to a given BitWidth.
10217/// When solving addrec-related equations, it is preferable to return a value
10218/// that has the same bit width as the original addrec's coefficients. If the
10219/// solution fits in the original bit width, truncate it (except for i1).
10220/// Returning a value of a different bit width may inhibit some optimizations.
10221///
10222/// In general, a solution to a quadratic equation generated from an addrec
10223/// may require BW+1 bits, where BW is the bit width of the addrec's
10224/// coefficients. The reason is that the coefficients of the quadratic
10225/// equation are BW+1 bits wide (to avoid truncation when converting from
10226/// the addrec to the equation).
10227static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10228 unsigned BitWidth) {
10229 if (!X)
10230 return std::nullopt;
10231 unsigned W = X->getBitWidth();
10232 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
10233 return X->trunc(BitWidth);
10234 return X;
10235}
10236
10237/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10238/// iterations. The values L, M, N are assumed to be signed, and they
10239/// should all have the same bit widths.
10240/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10241/// where BW is the bit width of the addrec's coefficients.
10242/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10243/// returned as such, otherwise the bit width of the returned value may
10244/// be greater than BW.
10245///
10246/// This function returns std::nullopt if
10247/// (a) the addrec coefficients are not constant, or
10248/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10249/// like x^2 = 5, no integer solutions exist, in other cases an integer
10250/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10251static std::optional<APInt>
10252SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
10253 APInt A, B, C, M;
10254 unsigned BitWidth;
10255 auto T = GetQuadraticEquation(AddRec);
10256 if (!T)
10257 return std::nullopt;
10258
10259 std::tie(A, B, C, M, BitWidth) = *T;
10260 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << __func__ << ": solving for unsigned overflow\n"
; } } while (false)
;
10261 std::optional<APInt> X =
10262 APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth + 1);
10263 if (!X)
10264 return std::nullopt;
10265
10266 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10267 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10268 if (!V->isZero())
10269 return std::nullopt;
10270
10271 return TruncIfPossible(X, BitWidth);
10272}
10273
10274/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10275/// iterations. The values M, N are assumed to be signed, and they
10276/// should all have the same bit widths.
10277/// Find the least n such that c(n) does not belong to the given range,
10278/// while c(n-1) does.
10279///
10280/// This function returns std::nullopt if
10281/// (a) the addrec coefficients are not constant, or
10282/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10283/// bounds of the range.
10284static std::optional<APInt>
10285SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
10286 const ConstantRange &Range, ScalarEvolution &SE) {
10287 assert(AddRec->getOperand(0)->isZero() &&(static_cast <bool> (AddRec->getOperand(0)->isZero
() && "Starting value of addrec should be 0") ? void (
0) : __assert_fail ("AddRec->getOperand(0)->isZero() && \"Starting value of addrec should be 0\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10288, __extension__
__PRETTY_FUNCTION__))
10288 "Starting value of addrec should be 0")(static_cast <bool> (AddRec->getOperand(0)->isZero
() && "Starting value of addrec should be 0") ? void (
0) : __assert_fail ("AddRec->getOperand(0)->isZero() && \"Starting value of addrec should be 0\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10288, __extension__
__PRETTY_FUNCTION__))
;
10289 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << __func__ << ": solving boundary crossing for range "
<< Range << ", addrec " << *AddRec <<
'\n'; } } while (false)
10290 << Range << ", addrec " << *AddRec << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << __func__ << ": solving boundary crossing for range "
<< Range << ", addrec " << *AddRec <<
'\n'; } } while (false)
;
10291 // This case is handled in getNumIterationsInRange. Here we can assume that
10292 // we start in the range.
10293 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&(static_cast <bool> (Range.contains(APInt(SE.getTypeSizeInBits
(AddRec->getType()), 0)) && "Addrec's initial value should be in range"
) ? void (0) : __assert_fail ("Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && \"Addrec's initial value should be in range\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10294, __extension__
__PRETTY_FUNCTION__))
10294 "Addrec's initial value should be in range")(static_cast <bool> (Range.contains(APInt(SE.getTypeSizeInBits
(AddRec->getType()), 0)) && "Addrec's initial value should be in range"
) ? void (0) : __assert_fail ("Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && \"Addrec's initial value should be in range\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10294, __extension__
__PRETTY_FUNCTION__))
;
10295
10296 APInt A, B, C, M;
10297 unsigned BitWidth;
10298 auto T = GetQuadraticEquation(AddRec);
10299 if (!T)
10300 return std::nullopt;
10301
10302 // Be careful about the return value: there can be two reasons for not
10303 // returning an actual number. First, if no solutions to the equations
10304 // were found, and second, if the solutions don't leave the given range.
10305 // The first case means that the actual solution is "unknown", the second
10306 // means that it's known, but not valid. If the solution is unknown, we
10307 // cannot make any conclusions.
10308 // Return a pair: the optional solution and a flag indicating if the
10309 // solution was found.
10310 auto SolveForBoundary =
10311 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10312 // Solve for signed overflow and unsigned overflow, pick the lower
10313 // solution.
10314 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "SolveQuadraticAddRecRange: checking boundary "
<< Bound << " (before multiplying by " << M
<< ")\n"; } } while (false)
10315 << Bound << " (before multiplying by " << M << ")\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "SolveQuadraticAddRecRange: checking boundary "
<< Bound << " (before multiplying by " << M
<< ")\n"; } } while (false)
;
10316 Bound *= M; // The quadratic equation multiplier.
10317
10318 std::optional<APInt> SO;
10319 if (BitWidth > 1) {
10320 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "SolveQuadraticAddRecRange: solving for "
"signed overflow\n"; } } while (false)
10321 "signed overflow\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "SolveQuadraticAddRecRange: solving for "
"signed overflow\n"; } } while (false)
;
10322 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
10323 }
10324 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "SolveQuadraticAddRecRange: solving for "
"unsigned overflow\n"; } } while (false)
10325 "unsigned overflow\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "SolveQuadraticAddRecRange: solving for "
"unsigned overflow\n"; } } while (false)
;
10326 std::optional<APInt> UO =
10327 APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth + 1);
10328
10329 auto LeavesRange = [&] (const APInt &X) {
10330 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10331 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10332 if (Range.contains(V0->getValue()))
10333 return false;
10334 // X should be at least 1, so X-1 is non-negative.
10335 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10336 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
10337 if (Range.contains(V1->getValue()))
10338 return true;
10339 return false;
10340 };
10341
10342 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10343 // can be a solution, but the function failed to find it. We cannot treat it
10344 // as "no solution".
10345 if (!SO || !UO)
10346 return {std::nullopt, false};
10347
10348 // Check the smaller value first to see if it leaves the range.
10349 // At this point, both SO and UO must have values.
10350 std::optional<APInt> Min = MinOptional(SO, UO);
10351 if (LeavesRange(*Min))
10352 return { Min, true };
10353 std::optional<APInt> Max = Min == SO ? UO : SO;
10354 if (LeavesRange(*Max))
10355 return { Max, true };
10356
10357 // Solutions were found, but were eliminated, hence the "true".
10358 return {std::nullopt, true};
10359 };
10360
10361 std::tie(A, B, C, M, BitWidth) = *T;
10362 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10363 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10364 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10365 auto SL = SolveForBoundary(Lower);
10366 auto SU = SolveForBoundary(Upper);
10367 // If any of the solutions was unknown, no meaninigful conclusions can
10368 // be made.
10369 if (!SL.second || !SU.second)
10370 return std::nullopt;
10371
10372 // Claim: The correct solution is not some value between Min and Max.
10373 //
10374 // Justification: Assuming that Min and Max are different values, one of
10375 // them is when the first signed overflow happens, the other is when the
10376 // first unsigned overflow happens. Crossing the range boundary is only
10377 // possible via an overflow (treating 0 as a special case of it, modeling
10378 // an overflow as crossing k*2^W for some k).
10379 //
10380 // The interesting case here is when Min was eliminated as an invalid
10381 // solution, but Max was not. The argument is that if there was another
10382 // overflow between Min and Max, it would also have been eliminated if
10383 // it was considered.
10384 //
10385 // For a given boundary, it is possible to have two overflows of the same
10386 // type (signed/unsigned) without having the other type in between: this
10387 // can happen when the vertex of the parabola is between the iterations
10388 // corresponding to the overflows. This is only possible when the two
10389 // overflows cross k*2^W for the same k. In such case, if the second one
10390 // left the range (and was the first one to do so), the first overflow
10391 // would have to enter the range, which would mean that either we had left
10392 // the range before or that we started outside of it. Both of these cases
10393 // are contradictions.
10394 //
10395 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10396 // solution is not some value between the Max for this boundary and the
10397 // Min of the other boundary.
10398 //
10399 // Justification: Assume that we had such Max_A and Min_B corresponding
10400 // to range boundaries A and B and such that Max_A < Min_B. If there was
10401 // a solution between Max_A and Min_B, it would have to be caused by an
10402 // overflow corresponding to either A or B. It cannot correspond to B,
10403 // since Min_B is the first occurrence of such an overflow. If it
10404 // corresponded to A, it would have to be either a signed or an unsigned
10405 // overflow that is larger than both eliminated overflows for A. But
10406 // between the eliminated overflows and this overflow, the values would
10407 // cover the entire value space, thus crossing the other boundary, which
10408 // is a contradiction.
10409
10410 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10411}
10412
10413ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10414 const Loop *L,
10415 bool ControlsOnlyExit,
10416 bool AllowPredicates) {
10417
10418 // This is only used for loops with a "x != y" exit test. The exit condition
10419 // is now expressed as a single expression, V = x-y. So the exit test is
10420 // effectively V != 0. We know and take advantage of the fact that this
10421 // expression only being used in a comparison by zero context.
10422
10423 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10424 // If the value is a constant
10425 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10426 // If the value is already zero, the branch will execute zero times.
10427 if (C->getValue()->isZero()) return C;
10428 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10429 }
10430
10431 const SCEVAddRecExpr *AddRec =
10432 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10433
10434 if (!AddRec && AllowPredicates)
10435 // Try to make this an AddRec using runtime tests, in the first X
10436 // iterations of this loop, where X is the SCEV expression found by the
10437 // algorithm below.
10438 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10439
10440 if (!AddRec || AddRec->getLoop() != L)
10441 return getCouldNotCompute();
10442
10443 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10444 // the quadratic equation to solve it.
10445 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10446 // We can only use this value if the chrec ends up with an exact zero
10447 // value at this index. When solving for "X*X != 5", for example, we
10448 // should not accept a root of 2.
10449 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10450 const auto *R = cast<SCEVConstant>(getConstant(*S));
10451 return ExitLimit(R, R, R, false, Predicates);
10452 }
10453 return getCouldNotCompute();
10454 }
10455
10456 // Otherwise we can only handle this if it is affine.
10457 if (!AddRec->isAffine())
10458 return getCouldNotCompute();
10459
10460 // If this is an affine expression, the execution count of this branch is
10461 // the minimum unsigned root of the following equation:
10462 //
10463 // Start + Step*N = 0 (mod 2^BW)
10464 //
10465 // equivalent to:
10466 //
10467 // Step*N = -Start (mod 2^BW)
10468 //
10469 // where BW is the common bit width of Start and Step.
10470
10471 // Get the initial value for the loop.
10472 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10473 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10474
10475 // For now we handle only constant steps.
10476 //
10477 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
10478 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
10479 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
10480 // We have not yet seen any such cases.
10481 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10482 if (!StepC || StepC->getValue()->isZero())
10483 return getCouldNotCompute();
10484
10485 // For positive steps (counting up until unsigned overflow):
10486 // N = -Start/Step (as unsigned)
10487 // For negative steps (counting down to zero):
10488 // N = Start/-Step
10489 // First compute the unsigned distance from zero in the direction of Step.
10490 bool CountDown = StepC->getAPInt().isNegative();
10491 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10492
10493 // Handle unitary steps, which cannot wraparound.
10494 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10495 // N = Distance (as unsigned)
10496 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
10497 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
10498 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10499
10500 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10501 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10502 // case, and see if we can improve the bound.
10503 //
10504 // Explicitly handling this here is necessary because getUnsignedRange
10505 // isn't context-sensitive; it doesn't know that we only care about the
10506 // range inside the loop.
10507 const SCEV *Zero = getZero(Distance->getType());
10508 const SCEV *One = getOne(Distance->getType());
10509 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10510 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10511 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10512 // as "unsigned_max(Distance + 1) - 1".
10513 ConstantRange CR = getUnsignedRange(DistancePlusOne);
10514 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
10515 }
10516 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10517 Predicates);
10518 }
10519
10520 // If the condition controls loop exit (the loop exits only if the expression
10521 // is true) and the addition is no-wrap we can use unsigned divide to
10522 // compute the backedge count. In this case, the step may not divide the
10523 // distance, but we don't care because if the condition is "missed" the loop
10524 // will have undefined behavior due to wrapping.
10525 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10526 loopHasNoAbnormalExits(AddRec->getLoop())) {
10527 const SCEV *Exact =
10528 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10529 const SCEV *ConstantMax = getCouldNotCompute();
10530 if (Exact != getCouldNotCompute()) {
10531 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L));
10532 ConstantMax =
10533 getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact)));
10534 }
10535 const SCEV *SymbolicMax =
10536 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10537 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10538 }
10539
10540 // Solve the general equation.
10541 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
10542 getNegativeSCEV(Start), *this);
10543
10544 const SCEV *M = E;
10545 if (E != getCouldNotCompute()) {
10546 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L));
10547 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10548 }
10549 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10550 return ExitLimit(E, M, S, false, Predicates);
10551}
10552
10553ScalarEvolution::ExitLimit
10554ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10555 // Loops that look like: while (X == 0) are very strange indeed. We don't
10556 // handle them yet except for the trivial case. This could be expanded in the
10557 // future as needed.
10558
10559 // If the value is a constant, check to see if it is known to be non-zero
10560 // already. If so, the backedge will execute zero times.
10561 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10562 if (!C->getValue()->isZero())
10563 return getZero(C->getType());
10564 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10565 }
10566
10567 // We could implement others, but I really doubt anyone writes loops like
10568 // this, and if they did, they would already be constant folded.
10569 return getCouldNotCompute();
10570}
10571
10572std::pair<const BasicBlock *, const BasicBlock *>
10573ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10574 const {
10575 // If the block has a unique predecessor, then there is no path from the
10576 // predecessor to the block that does not go through the direct edge
10577 // from the predecessor to the block.
10578 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10579 return {Pred, BB};
10580
10581 // A loop's header is defined to be a block that dominates the loop.
10582 // If the header has a unique predecessor outside the loop, it must be
10583 // a block that has exactly one successor that can reach the loop.
10584 if (const Loop *L = LI.getLoopFor(BB))
10585 return {L->getLoopPredecessor(), L->getHeader()};
10586
10587 return {nullptr, nullptr};
10588}
10589
10590/// SCEV structural equivalence is usually sufficient for testing whether two
10591/// expressions are equal, however for the purposes of looking for a condition
10592/// guarding a loop, it can be useful to be a little more general, since a
10593/// front-end may have replicated the controlling expression.
10594static bool HasSameValue(const SCEV *A, const SCEV *B) {
10595 // Quick check to see if they are the same SCEV.
10596 if (A == B) return true;
10597
10598 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10599 // Not all instructions that are "identical" compute the same value. For
10600 // instance, two distinct alloca instructions allocating the same type are
10601 // identical and do not read memory; but compute distinct values.
10602 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10603 };
10604
10605 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10606 // two different instructions with the same value. Check for this case.
10607 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10608 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10609 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10610 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10611 if (ComputesEqualValues(AI, BI))
10612 return true;
10613
10614 // Otherwise assume they may have a different value.
10615 return false;
10616}
10617
10618bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
10619 const SCEV *&LHS, const SCEV *&RHS,
10620 unsigned Depth) {
10621 bool Changed = false;
10622 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10623 // '0 != 0'.
10624 auto TrivialCase = [&](bool TriviallyTrue) {
10625 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
10626 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10627 return true;
10628 };
10629 // If we hit the max recursion limit bail out.
10630 if (Depth >= 3)
10631 return false;
10632
10633 // Canonicalize a constant to the right side.
10634 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
10635 // Check for both operands constant.
10636 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
10637 if (ConstantExpr::getICmp(Pred,
10638 LHSC->getValue(),
10639 RHSC->getValue())->isNullValue())
10640 return TrivialCase(false);
10641 return TrivialCase(true);
10642 }
10643 // Otherwise swap the operands to put the constant on the right.
10644 std::swap(LHS, RHS);
10645 Pred = ICmpInst::getSwappedPredicate(Pred);
10646 Changed = true;
10647 }
10648
10649 // If we're comparing an addrec with a value which is loop-invariant in the
10650 // addrec's loop, put the addrec on the left. Also make a dominance check,
10651 // as both operands could be addrecs loop-invariant in each other's loop.
10652 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
10653 const Loop *L = AR->getLoop();
10654 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
10655 std::swap(LHS, RHS);
10656 Pred = ICmpInst::getSwappedPredicate(Pred);
10657 Changed = true;
10658 }
10659 }
10660
10661 // If there's a constant operand, canonicalize comparisons with boundary
10662 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
10663 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
10664 const APInt &RA = RC->getAPInt();
10665
10666 bool SimplifiedByConstantRange = false;
10667
10668 if (!ICmpInst::isEquality(Pred)) {
10669 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
10670 if (ExactCR.isFullSet())
10671 return TrivialCase(true);
10672 if (ExactCR.isEmptySet())
10673 return TrivialCase(false);
10674
10675 APInt NewRHS;
10676 CmpInst::Predicate NewPred;
10677 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
10678 ICmpInst::isEquality(NewPred)) {
10679 // We were able to convert an inequality to an equality.
10680 Pred = NewPred;
10681 RHS = getConstant(NewRHS);
10682 Changed = SimplifiedByConstantRange = true;
10683 }
10684 }
10685
10686 if (!SimplifiedByConstantRange) {
10687 switch (Pred) {
10688 default:
10689 break;
10690 case ICmpInst::ICMP_EQ:
10691 case ICmpInst::ICMP_NE:
10692 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
10693 if (!RA)
10694 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
10695 if (const SCEVMulExpr *ME =
10696 dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
10697 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
10698 ME->getOperand(0)->isAllOnesValue()) {
10699 RHS = AE->getOperand(1);
10700 LHS = ME->getOperand(1);
10701 Changed = true;
10702 }
10703 break;
10704
10705
10706 // The "Should have been caught earlier!" messages refer to the fact
10707 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
10708 // should have fired on the corresponding cases, and canonicalized the
10709 // check to trivial case.
10710
10711 case ICmpInst::ICMP_UGE:
10712 assert(!RA.isMinValue() && "Should have been caught earlier!")(static_cast <bool> (!RA.isMinValue() && "Should have been caught earlier!"
) ? void (0) : __assert_fail ("!RA.isMinValue() && \"Should have been caught earlier!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10712, __extension__
__PRETTY_FUNCTION__))
;
10713 Pred = ICmpInst::ICMP_UGT;
10714 RHS = getConstant(RA - 1);
10715 Changed = true;
10716 break;
10717 case ICmpInst::ICMP_ULE:
10718 assert(!RA.isMaxValue() && "Should have been caught earlier!")(static_cast <bool> (!RA.isMaxValue() && "Should have been caught earlier!"
) ? void (0) : __assert_fail ("!RA.isMaxValue() && \"Should have been caught earlier!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10718, __extension__
__PRETTY_FUNCTION__))
;
10719 Pred = ICmpInst::ICMP_ULT;
10720 RHS = getConstant(RA + 1);
10721 Changed = true;
10722 break;
10723 case ICmpInst::ICMP_SGE:
10724 assert(!RA.isMinSignedValue() && "Should have been caught earlier!")(static_cast <bool> (!RA.isMinSignedValue() && "Should have been caught earlier!"
) ? void (0) : __assert_fail ("!RA.isMinSignedValue() && \"Should have been caught earlier!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10724, __extension__
__PRETTY_FUNCTION__))
;
10725 Pred = ICmpInst::ICMP_SGT;
10726 RHS = getConstant(RA - 1);
10727 Changed = true;
10728 break;
10729 case ICmpInst::ICMP_SLE:
10730 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!")(static_cast <bool> (!RA.isMaxSignedValue() && "Should have been caught earlier!"
) ? void (0) : __assert_fail ("!RA.isMaxSignedValue() && \"Should have been caught earlier!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10730, __extension__
__PRETTY_FUNCTION__))
;
10731 Pred = ICmpInst::ICMP_SLT;
10732 RHS = getConstant(RA + 1);
10733 Changed = true;
10734 break;
10735 }
10736 }
10737 }
10738
10739 // Check for obvious equality.
10740 if (HasSameValue(LHS, RHS)) {
10741 if (ICmpInst::isTrueWhenEqual(Pred))
10742 return TrivialCase(true);
10743 if (ICmpInst::isFalseWhenEqual(Pred))
10744 return TrivialCase(false);
10745 }
10746
10747 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
10748 // adding or subtracting 1 from one of the operands.
10749 switch (Pred) {
10750 case ICmpInst::ICMP_SLE:
10751 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
10752 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10753 SCEV::FlagNSW);
10754 Pred = ICmpInst::ICMP_SLT;
10755 Changed = true;
10756 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
10757 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
10758 SCEV::FlagNSW);
10759 Pred = ICmpInst::ICMP_SLT;
10760 Changed = true;
10761 }
10762 break;
10763 case ICmpInst::ICMP_SGE:
10764 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
10765 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
10766 SCEV::FlagNSW);
10767 Pred = ICmpInst::ICMP_SGT;
10768 Changed = true;
10769 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
10770 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10771 SCEV::FlagNSW);
10772 Pred = ICmpInst::ICMP_SGT;
10773 Changed = true;
10774 }
10775 break;
10776 case ICmpInst::ICMP_ULE:
10777 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
10778 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
10779 SCEV::FlagNUW);
10780 Pred = ICmpInst::ICMP_ULT;
10781 Changed = true;
10782 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
10783 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
10784 Pred = ICmpInst::ICMP_ULT;
10785 Changed = true;
10786 }
10787 break;
10788 case ICmpInst::ICMP_UGE:
10789 if (!getUnsignedRangeMin(RHS).isMinValue()) {
10790 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
10791 Pred = ICmpInst::ICMP_UGT;
10792 Changed = true;
10793 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
10794 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
10795 SCEV::FlagNUW);
10796 Pred = ICmpInst::ICMP_UGT;
10797 Changed = true;
10798 }
10799 break;
10800 default:
10801 break;
10802 }
10803
10804 // TODO: More simplifications are possible here.
10805
10806 // Recursively simplify until we either hit a recursion limit or nothing
10807 // changes.
10808 if (Changed)
10809 return SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
10810
10811 return Changed;
10812}
10813
10814bool ScalarEvolution::isKnownNegative(const SCEV *S) {
10815 return getSignedRangeMax(S).isNegative();
10816}
10817
10818bool ScalarEvolution::isKnownPositive(const SCEV *S) {
10819 return getSignedRangeMin(S).isStrictlyPositive();
10820}
10821
10822bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
10823 return !getSignedRangeMin(S).isNegative();
10824}
10825
10826bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
10827 return !getSignedRangeMax(S).isStrictlyPositive();
10828}
10829
10830bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
10831 return getUnsignedRangeMin(S) != 0;
10832}
10833
10834std::pair<const SCEV *, const SCEV *>
10835ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
10836 // Compute SCEV on entry of loop L.
10837 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
10838 if (Start == getCouldNotCompute())
10839 return { Start, Start };
10840 // Compute post increment SCEV for loop L.
10841 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
10842 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute")(static_cast <bool> (PostInc != getCouldNotCompute() &&
"Unexpected could not compute") ? void (0) : __assert_fail (
"PostInc != getCouldNotCompute() && \"Unexpected could not compute\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10842, __extension__
__PRETTY_FUNCTION__))
;
10843 return { Start, PostInc };
10844}
10845
10846bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
10847 const SCEV *LHS, const SCEV *RHS) {
10848 // First collect all loops.
10849 SmallPtrSet<const Loop *, 8> LoopsUsed;
10850 getUsedLoops(LHS, LoopsUsed);
10851 getUsedLoops(RHS, LoopsUsed);
10852
10853 if (LoopsUsed.empty())
10854 return false;
10855
10856 // Domination relationship must be a linear order on collected loops.
10857#ifndef NDEBUG
10858 for (const auto *L1 : LoopsUsed)
10859 for (const auto *L2 : LoopsUsed)
10860 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||(static_cast <bool> ((DT.dominates(L1->getHeader(), L2
->getHeader()) || DT.dominates(L2->getHeader(), L1->
getHeader())) && "Domination relationship is not a linear order"
) ? void (0) : __assert_fail ("(DT.dominates(L1->getHeader(), L2->getHeader()) || DT.dominates(L2->getHeader(), L1->getHeader())) && \"Domination relationship is not a linear order\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10862, __extension__
__PRETTY_FUNCTION__))
10861 DT.dominates(L2->getHeader(), L1->getHeader())) &&(static_cast <bool> ((DT.dominates(L1->getHeader(), L2
->getHeader()) || DT.dominates(L2->getHeader(), L1->
getHeader())) && "Domination relationship is not a linear order"
) ? void (0) : __assert_fail ("(DT.dominates(L1->getHeader(), L2->getHeader()) || DT.dominates(L2->getHeader(), L1->getHeader())) && \"Domination relationship is not a linear order\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10862, __extension__
__PRETTY_FUNCTION__))
10862 "Domination relationship is not a linear order")(static_cast <bool> ((DT.dominates(L1->getHeader(), L2
->getHeader()) || DT.dominates(L2->getHeader(), L1->
getHeader())) && "Domination relationship is not a linear order"
) ? void (0) : __assert_fail ("(DT.dominates(L1->getHeader(), L2->getHeader()) || DT.dominates(L2->getHeader(), L1->getHeader())) && \"Domination relationship is not a linear order\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10862, __extension__
__PRETTY_FUNCTION__))
;
10863#endif
10864
10865 const Loop *MDL =
10866 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
10867 [&](const Loop *L1, const Loop *L2) {
10868 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
10869 });
10870
10871 // Get init and post increment value for LHS.
10872 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
10873 // if LHS contains unknown non-invariant SCEV then bail out.
10874 if (SplitLHS.first == getCouldNotCompute())
10875 return false;
10876 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC")(static_cast <bool> (SplitLHS.second != getCouldNotCompute
() && "Unexpected CNC") ? void (0) : __assert_fail ("SplitLHS.second != getCouldNotCompute() && \"Unexpected CNC\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10876, __extension__
__PRETTY_FUNCTION__))
;
10877 // Get init and post increment value for RHS.
10878 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
10879 // if RHS contains unknown non-invariant SCEV then bail out.
10880 if (SplitRHS.first == getCouldNotCompute())
10881 return false;
10882 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC")(static_cast <bool> (SplitRHS.second != getCouldNotCompute
() && "Unexpected CNC") ? void (0) : __assert_fail ("SplitRHS.second != getCouldNotCompute() && \"Unexpected CNC\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10882, __extension__
__PRETTY_FUNCTION__))
;
10883 // It is possible that init SCEV contains an invariant load but it does
10884 // not dominate MDL and is not available at MDL loop entry, so we should
10885 // check it here.
10886 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
10887 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
10888 return false;
10889
10890 // It seems backedge guard check is faster than entry one so in some cases
10891 // it can speed up whole estimation by short circuit
10892 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
10893 SplitRHS.second) &&
10894 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
10895}
10896
10897bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
10898 const SCEV *LHS, const SCEV *RHS) {
10899 // Canonicalize the inputs first.
10900 (void)SimplifyICmpOperands(Pred, LHS, RHS);
10901
10902 if (isKnownViaInduction(Pred, LHS, RHS))
10903 return true;
10904
10905 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
10906 return true;
10907
10908 // Otherwise see what can be done with some simple reasoning.
10909 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
10910}
10911
10912std::optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
10913 const SCEV *LHS,
10914 const SCEV *RHS) {
10915 if (isKnownPredicate(Pred, LHS, RHS))
10916 return true;
10917 if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
10918 return false;
10919 return std::nullopt;
10920}
10921
10922bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
10923 const SCEV *LHS, const SCEV *RHS,
10924 const Instruction *CtxI) {
10925 // TODO: Analyze guards and assumes from Context's block.
10926 return isKnownPredicate(Pred, LHS, RHS) ||
10927 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
10928}
10929
10930std::optional<bool>
10931ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS,
10932 const SCEV *RHS, const Instruction *CtxI) {
10933 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
10934 if (KnownWithoutContext)
10935 return KnownWithoutContext;
10936
10937 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
10938 return true;
10939 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(),
10940 ICmpInst::getInversePredicate(Pred),
10941 LHS, RHS))
10942 return false;
10943 return std::nullopt;
10944}
10945
10946bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
10947 const SCEVAddRecExpr *LHS,
10948 const SCEV *RHS) {
10949 const Loop *L = LHS->getLoop();
10950 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
10951 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
10952}
10953
10954std::optional<ScalarEvolution::MonotonicPredicateType>
10955ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
10956 ICmpInst::Predicate Pred) {
10957 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
10958
10959#ifndef NDEBUG
10960 // Verify an invariant: inverting the predicate should turn a monotonically
10961 // increasing change to a monotonically decreasing one, and vice versa.
10962 if (Result) {
10963 auto ResultSwapped =
10964 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
10965
10966 assert(*ResultSwapped != *Result &&(static_cast <bool> (*ResultSwapped != *Result &&
"monotonicity should flip as we flip the predicate") ? void (
0) : __assert_fail ("*ResultSwapped != *Result && \"monotonicity should flip as we flip the predicate\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10967, __extension__
__PRETTY_FUNCTION__))
10967 "monotonicity should flip as we flip the predicate")(static_cast <bool> (*ResultSwapped != *Result &&
"monotonicity should flip as we flip the predicate") ? void (
0) : __assert_fail ("*ResultSwapped != *Result && \"monotonicity should flip as we flip the predicate\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10967, __extension__
__PRETTY_FUNCTION__))
;
10968 }
10969#endif
10970
10971 return Result;
10972}
10973
10974std::optional<ScalarEvolution::MonotonicPredicateType>
10975ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
10976 ICmpInst::Predicate Pred) {
10977 // A zero step value for LHS means the induction variable is essentially a
10978 // loop invariant value. We don't really depend on the predicate actually
10979 // flipping from false to true (for increasing predicates, and the other way
10980 // around for decreasing predicates), all we care about is that *if* the
10981 // predicate changes then it only changes from false to true.
10982 //
10983 // A zero step value in itself is not very useful, but there may be places
10984 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
10985 // as general as possible.
10986
10987 // Only handle LE/LT/GE/GT predicates.
10988 if (!ICmpInst::isRelational(Pred))
10989 return std::nullopt;
10990
10991 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
10992 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&(static_cast <bool> ((IsGreater || ICmpInst::isLE(Pred)
|| ICmpInst::isLT(Pred)) && "Should be greater or less!"
) ? void (0) : __assert_fail ("(IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && \"Should be greater or less!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10993, __extension__
__PRETTY_FUNCTION__))
10993 "Should be greater or less!")(static_cast <bool> ((IsGreater || ICmpInst::isLE(Pred)
|| ICmpInst::isLT(Pred)) && "Should be greater or less!"
) ? void (0) : __assert_fail ("(IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && \"Should be greater or less!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 10993, __extension__
__PRETTY_FUNCTION__))
;
10994
10995 // Check that AR does not wrap.
10996 if (ICmpInst::isUnsigned(Pred)) {
10997 if (!LHS->hasNoUnsignedWrap())
10998 return std::nullopt;
10999 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
11000 }
11001 assert(ICmpInst::isSigned(Pred) &&(static_cast <bool> (ICmpInst::isSigned(Pred) &&
"Relational predicate is either signed or unsigned!") ? void
(0) : __assert_fail ("ICmpInst::isSigned(Pred) && \"Relational predicate is either signed or unsigned!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11002, __extension__
__PRETTY_FUNCTION__))
11002 "Relational predicate is either signed or unsigned!")(static_cast <bool> (ICmpInst::isSigned(Pred) &&
"Relational predicate is either signed or unsigned!") ? void
(0) : __assert_fail ("ICmpInst::isSigned(Pred) && \"Relational predicate is either signed or unsigned!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11002, __extension__
__PRETTY_FUNCTION__))
;
11003 if (!LHS->hasNoSignedWrap())
11004 return std::nullopt;
11005
11006 const SCEV *Step = LHS->getStepRecurrence(*this);
11007
11008 if (isKnownNonNegative(Step))
11009 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
11010
11011 if (isKnownNonPositive(Step))
11012 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
11013
11014 return std::nullopt;
11015}
11016
11017std::optional<ScalarEvolution::LoopInvariantPredicate>
11018ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
11019 const SCEV *LHS, const SCEV *RHS,
11020 const Loop *L,
11021 const Instruction *CtxI) {
11022 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11023 if (!isLoopInvariant(RHS, L)) {
11024 if (!isLoopInvariant(LHS, L))
11025 return std::nullopt;
11026
11027 std::swap(LHS, RHS);
11028 Pred = ICmpInst::getSwappedPredicate(Pred);
11029 }
11030
11031 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11032 if (!ArLHS || ArLHS->getLoop() != L)
11033 return std::nullopt;
11034
11035 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11036 if (!MonotonicType)
11037 return std::nullopt;
11038 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11039 // true as the loop iterates, and the backedge is control dependent on
11040 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11041 //
11042 // * if the predicate was false in the first iteration then the predicate
11043 // is never evaluated again, since the loop exits without taking the
11044 // backedge.
11045 // * if the predicate was true in the first iteration then it will
11046 // continue to be true for all future iterations since it is
11047 // monotonically increasing.
11048 //
11049 // For both the above possibilities, we can replace the loop varying
11050 // predicate with its value on the first iteration of the loop (which is
11051 // loop invariant).
11052 //
11053 // A similar reasoning applies for a monotonically decreasing predicate, by
11054 // replacing true with false and false with true in the above two bullets.
11055 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
11056 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
11057
11058 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11059 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(),
11060 RHS);
11061
11062 if (!CtxI)
11063 return std::nullopt;
11064 // Try to prove via context.
11065 // TODO: Support other cases.
11066 switch (Pred) {
11067 default:
11068 break;
11069 case ICmpInst::ICMP_ULE:
11070 case ICmpInst::ICMP_ULT: {
11071 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!")(static_cast <bool> (ArLHS->hasNoUnsignedWrap() &&
"Is a requirement of monotonicity!") ? void (0) : __assert_fail
("ArLHS->hasNoUnsignedWrap() && \"Is a requirement of monotonicity!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11071, __extension__
__PRETTY_FUNCTION__))
;
11072 // Given preconditions
11073 // (1) ArLHS does not cross the border of positive and negative parts of
11074 // range because of:
11075 // - Positive step; (TODO: lift this limitation)
11076 // - nuw - does not cross zero boundary;
11077 // - nsw - does not cross SINT_MAX boundary;
11078 // (2) ArLHS <s RHS
11079 // (3) RHS >=s 0
11080 // we can replace the loop variant ArLHS <u RHS condition with loop
11081 // invariant Start(ArLHS) <u RHS.
11082 //
11083 // Because of (1) there are two options:
11084 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11085 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11086 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11087 // Because of (2) ArLHS <u RHS is trivially true.
11088 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11089 // We can strengthen this to Start(ArLHS) <u RHS.
11090 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11091 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11092 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11093 isKnownNonNegative(RHS) &&
11094 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11095 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(),
11096 RHS);
11097 }
11098 }
11099
11100 return std::nullopt;
11101}
11102
11103std::optional<ScalarEvolution::LoopInvariantPredicate>
11104ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
11105 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11106 const Instruction *CtxI, const SCEV *MaxIter) {
11107 if (auto LIP = getLoopInvariantExitCondDuringFirstIterationsImpl(
11108 Pred, LHS, RHS, L, CtxI, MaxIter))
11109 return LIP;
11110 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11111 // Number of iterations expressed as UMIN isn't always great for expressing
11112 // the value on the last iteration. If the straightforward approach didn't
11113 // work, try the following trick: if the a predicate is invariant for X, it
11114 // is also invariant for umin(X, ...). So try to find something that works
11115 // among subexpressions of MaxIter expressed as umin.
11116 for (auto *Op : UMin->operands())
11117 if (auto LIP = getLoopInvariantExitCondDuringFirstIterationsImpl(
11118 Pred, LHS, RHS, L, CtxI, Op))
11119 return LIP;
11120 return std::nullopt;
11121}
11122
11123std::optional<ScalarEvolution::LoopInvariantPredicate>
11124ScalarEvolution::getLoopInvariantExitCondDuringFirstIterationsImpl(
11125 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11126 const Instruction *CtxI, const SCEV *MaxIter) {
11127 // Try to prove the following set of facts:
11128 // - The predicate is monotonic in the iteration space.
11129 // - If the check does not fail on the 1st iteration:
11130 // - No overflow will happen during first MaxIter iterations;
11131 // - It will not fail on the MaxIter'th iteration.
11132 // If the check does fail on the 1st iteration, we leave the loop and no
11133 // other checks matter.
11134
11135 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11136 if (!isLoopInvariant(RHS, L)) {
11137 if (!isLoopInvariant(LHS, L))
11138 return std::nullopt;
11139
11140 std::swap(LHS, RHS);
11141 Pred = ICmpInst::getSwappedPredicate(Pred);
11142 }
11143
11144 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11145 if (!AR || AR->getLoop() != L)
11146 return std::nullopt;
11147
11148 // The predicate must be relational (i.e. <, <=, >=, >).
11149 if (!ICmpInst::isRelational(Pred))
11150 return std::nullopt;
11151
11152 // TODO: Support steps other than +/- 1.
11153 const SCEV *Step = AR->getStepRecurrence(*this);
11154 auto *One = getOne(Step->getType());
11155 auto *MinusOne = getNegativeSCEV(One);
11156 if (Step != One && Step != MinusOne)
11157 return std::nullopt;
11158
11159 // Type mismatch here means that MaxIter is potentially larger than max
11160 // unsigned value in start type, which mean we cannot prove no wrap for the
11161 // indvar.
11162 if (AR->getType() != MaxIter->getType())
11163 return std::nullopt;
11164
11165 // Value of IV on suggested last iteration.
11166 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11167 // Does it still meet the requirement?
11168 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11169 return std::nullopt;
11170 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11171 // not exceed max unsigned value of this type), this effectively proves
11172 // that there is no wrap during the iteration. To prove that there is no
11173 // signed/unsigned wrap, we need to check that
11174 // Start <= Last for step = 1 or Start >= Last for step = -1.
11175 ICmpInst::Predicate NoOverflowPred =
11176 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
11177 if (Step == MinusOne)
11178 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
11179 const SCEV *Start = AR->getStart();
11180 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11181 return std::nullopt;
11182
11183 // Everything is fine.
11184 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11185}
11186
11187bool ScalarEvolution::isKnownPredicateViaConstantRanges(
11188 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
11189 if (HasSameValue(LHS, RHS))
11190 return ICmpInst::isTrueWhenEqual(Pred);
11191
11192 // This code is split out from isKnownPredicate because it is called from
11193 // within isLoopEntryGuardedByCond.
11194
11195 auto CheckRanges = [&](const ConstantRange &RangeLHS,
11196 const ConstantRange &RangeRHS) {
11197 return RangeLHS.icmp(Pred, RangeRHS);
11198 };
11199
11200 // The check at the top of the function catches the case where the values are
11201 // known to be equal.
11202 if (Pred == CmpInst::ICMP_EQ)
11203 return false;
11204
11205 if (Pred == CmpInst::ICMP_NE) {
11206 auto SL = getSignedRange(LHS);
11207 auto SR = getSignedRange(RHS);
11208 if (CheckRanges(SL, SR))
11209 return true;
11210 auto UL = getUnsignedRange(LHS);
11211 auto UR = getUnsignedRange(RHS);
11212 if (CheckRanges(UL, UR))
11213 return true;
11214 auto *Diff = getMinusSCEV(LHS, RHS);
11215 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11216 }
11217
11218 if (CmpInst::isSigned(Pred)) {
11219 auto SL = getSignedRange(LHS);
11220 auto SR = getSignedRange(RHS);
11221 return CheckRanges(SL, SR);
11222 }
11223
11224 auto UL = getUnsignedRange(LHS);
11225 auto UR = getUnsignedRange(RHS);
11226 return CheckRanges(UL, UR);
11227}
11228
11229bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
11230 const SCEV *LHS,
11231 const SCEV *RHS) {
11232 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11233 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11234 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11235 // OutC1 and OutC2.
11236 auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y,
11237 APInt &OutC1, APInt &OutC2,
11238 SCEV::NoWrapFlags ExpectedFlags) {
11239 const SCEV *XNonConstOp, *XConstOp;
11240 const SCEV *YNonConstOp, *YConstOp;
11241 SCEV::NoWrapFlags XFlagsPresent;
11242 SCEV::NoWrapFlags YFlagsPresent;
11243
11244 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11245 XConstOp = getZero(X->getType());
11246 XNonConstOp = X;
11247 XFlagsPresent = ExpectedFlags;
11248 }
11249 if (!isa<SCEVConstant>(XConstOp) ||
11250 (XFlagsPresent & ExpectedFlags) != ExpectedFlags)
11251 return false;
11252
11253 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11254 YConstOp = getZero(Y->getType());
11255 YNonConstOp = Y;
11256 YFlagsPresent = ExpectedFlags;
11257 }
11258
11259 if (!isa<SCEVConstant>(YConstOp) ||
11260 (YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11261 return false;
11262
11263 if (YNonConstOp != XNonConstOp)
11264 return false;
11265
11266 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11267 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11268
11269 return true;
11270 };
11271
11272 APInt C1;
11273 APInt C2;
11274
11275 switch (Pred) {
11276 default:
11277 break;
11278
11279 case ICmpInst::ICMP_SGE:
11280 std::swap(LHS, RHS);
11281 [[fallthrough]];
11282 case ICmpInst::ICMP_SLE:
11283 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11284 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11285 return true;
11286
11287 break;
11288
11289 case ICmpInst::ICMP_SGT:
11290 std::swap(LHS, RHS);
11291 [[fallthrough]];
11292 case ICmpInst::ICMP_SLT:
11293 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11294 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11295 return true;
11296
11297 break;
11298
11299 case ICmpInst::ICMP_UGE:
11300 std::swap(LHS, RHS);
11301 [[fallthrough]];
11302 case ICmpInst::ICMP_ULE:
11303 // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2.
11304 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2))
11305 return true;
11306
11307 break;
11308
11309 case ICmpInst::ICMP_UGT:
11310 std::swap(LHS, RHS);
11311 [[fallthrough]];
11312 case ICmpInst::ICMP_ULT:
11313 // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2.
11314 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2))
11315 return true;
11316 break;
11317 }
11318
11319 return false;
11320}
11321
11322bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
11323 const SCEV *LHS,
11324 const SCEV *RHS) {
11325 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11326 return false;
11327
11328 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11329 // the stack can result in exponential time complexity.
11330 SaveAndRestore Restore(ProvingSplitPredicate, true);
11331
11332 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11333 //
11334 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11335 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11336 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11337 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11338 // use isKnownPredicate later if needed.
11339 return isKnownNonNegative(RHS) &&
11340 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
11341 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
11342}
11343
11344bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
11345 ICmpInst::Predicate Pred,
11346 const SCEV *LHS, const SCEV *RHS) {
11347 // No need to even try if we know the module has no guards.
11348 if (!HasGuards)
11349 return false;
11350
11351 return any_of(*BB, [&](const Instruction &I) {
11352 using namespace llvm::PatternMatch;
11353
11354 Value *Condition;
11355 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
11356 m_Value(Condition))) &&
11357 isImpliedCond(Pred, LHS, RHS, Condition, false);
11358 });
11359}
11360
11361/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11362/// protected by a conditional between LHS and RHS. This is used to
11363/// to eliminate casts.
11364bool
11365ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
11366 ICmpInst::Predicate Pred,
11367 const SCEV *LHS, const SCEV *RHS) {
11368 // Interpret a null as meaning no loop, where there is obviously no guard
11369 // (interprocedural conditions notwithstanding). Do not bother about
11370 // unreachable loops.
11371 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11372 return true;
11373
11374 if (VerifyIR)
11375 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&(static_cast <bool> (!verifyFunction(*L->getHeader()
->getParent(), &dbgs()) && "This cannot be done on broken IR!"
) ? void (0) : __assert_fail ("!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && \"This cannot be done on broken IR!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11376, __extension__
__PRETTY_FUNCTION__))
11376 "This cannot be done on broken IR!")(static_cast <bool> (!verifyFunction(*L->getHeader()
->getParent(), &dbgs()) && "This cannot be done on broken IR!"
) ? void (0) : __assert_fail ("!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && \"This cannot be done on broken IR!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11376, __extension__
__PRETTY_FUNCTION__))
;
11377
11378
11379 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11380 return true;
11381
11382 BasicBlock *Latch = L->getLoopLatch();
11383 if (!Latch)
11384 return false;
11385
11386 BranchInst *LoopContinuePredicate =
11387 dyn_cast<BranchInst>(Latch->getTerminator());
11388 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
11389 isImpliedCond(Pred, LHS, RHS,
11390 LoopContinuePredicate->getCondition(),
11391 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11392 return true;
11393
11394 // We don't want more than one activation of the following loops on the stack
11395 // -- that can lead to O(n!) time complexity.
11396 if (WalkingBEDominatingConds)
11397 return false;
11398
11399 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11400
11401 // See if we can exploit a trip count to prove the predicate.
11402 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11403 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11404 if (LatchBECount != getCouldNotCompute()) {
11405 // We know that Latch branches back to the loop header exactly
11406 // LatchBECount times. This means the backdege condition at Latch is
11407 // equivalent to "{0,+,1} u< LatchBECount".
11408 Type *Ty = LatchBECount->getType();
11409 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
11410 const SCEV *LoopCounter =
11411 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11412 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11413 LatchBECount))
11414 return true;
11415 }
11416
11417 // Check conditions due to any @llvm.assume intrinsics.
11418 for (auto &AssumeVH : AC.assumptions()) {
11419 if (!AssumeVH)
11420 continue;
11421 auto *CI = cast<CallInst>(AssumeVH);
11422 if (!DT.dominates(CI, Latch->getTerminator()))
11423 continue;
11424
11425 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11426 return true;
11427 }
11428
11429 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11430 return true;
11431
11432 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11433 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11434 assert(DTN && "should reach the loop header before reaching the root!")(static_cast <bool> (DTN && "should reach the loop header before reaching the root!"
) ? void (0) : __assert_fail ("DTN && \"should reach the loop header before reaching the root!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11434, __extension__
__PRETTY_FUNCTION__))
;
11435
11436 BasicBlock *BB = DTN->getBlock();
11437 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11438 return true;
11439
11440 BasicBlock *PBB = BB->getSinglePredecessor();
11441 if (!PBB)
11442 continue;
11443
11444 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
11445 if (!ContinuePredicate || !ContinuePredicate->isConditional())
11446 continue;
11447
11448 Value *Condition = ContinuePredicate->getCondition();
11449
11450 // If we have an edge `E` within the loop body that dominates the only
11451 // latch, the condition guarding `E` also guards the backedge. This
11452 // reasoning works only for loops with a single latch.
11453
11454 BasicBlockEdge DominatingEdge(PBB, BB);
11455 if (DominatingEdge.isSingleEdge()) {
11456 // We're constructively (and conservatively) enumerating edges within the
11457 // loop body that dominate the latch. The dominator tree better agree
11458 // with us on this:
11459 assert(DT.dominates(DominatingEdge, Latch) && "should be!")(static_cast <bool> (DT.dominates(DominatingEdge, Latch
) && "should be!") ? void (0) : __assert_fail ("DT.dominates(DominatingEdge, Latch) && \"should be!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11459, __extension__
__PRETTY_FUNCTION__))
;
11460
11461 if (isImpliedCond(Pred, LHS, RHS, Condition,
11462 BB != ContinuePredicate->getSuccessor(0)))
11463 return true;
11464 }
11465 }
11466
11467 return false;
11468}
11469
11470bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
11471 ICmpInst::Predicate Pred,
11472 const SCEV *LHS,
11473 const SCEV *RHS) {
11474 // Do not bother proving facts for unreachable code.
11475 if (!DT.isReachableFromEntry(BB))
11476 return true;
11477 if (VerifyIR)
11478 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&(static_cast <bool> (!verifyFunction(*BB->getParent(
), &dbgs()) && "This cannot be done on broken IR!"
) ? void (0) : __assert_fail ("!verifyFunction(*BB->getParent(), &dbgs()) && \"This cannot be done on broken IR!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11479, __extension__
__PRETTY_FUNCTION__))
11479 "This cannot be done on broken IR!")(static_cast <bool> (!verifyFunction(*BB->getParent(
), &dbgs()) && "This cannot be done on broken IR!"
) ? void (0) : __assert_fail ("!verifyFunction(*BB->getParent(), &dbgs()) && \"This cannot be done on broken IR!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11479, __extension__
__PRETTY_FUNCTION__))
;
11480
11481 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
11482 // the facts (a >= b && a != b) separately. A typical situation is when the
11483 // non-strict comparison is known from ranges and non-equality is known from
11484 // dominating predicates. If we are proving strict comparison, we always try
11485 // to prove non-equality and non-strict comparison separately.
11486 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
11487 const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
11488 bool ProvedNonStrictComparison = false;
11489 bool ProvedNonEquality = false;
11490
11491 auto SplitAndProve =
11492 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
11493 if (!ProvedNonStrictComparison)
11494 ProvedNonStrictComparison = Fn(NonStrictPredicate);
11495 if (!ProvedNonEquality)
11496 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
11497 if (ProvedNonStrictComparison && ProvedNonEquality)
11498 return true;
11499 return false;
11500 };
11501
11502 if (ProvingStrictComparison) {
11503 auto ProofFn = [&](ICmpInst::Predicate P) {
11504 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
11505 };
11506 if (SplitAndProve(ProofFn))
11507 return true;
11508 }
11509
11510 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
11511 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
11512 const Instruction *CtxI = &BB->front();
11513 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
11514 return true;
11515 if (ProvingStrictComparison) {
11516 auto ProofFn = [&](ICmpInst::Predicate P) {
11517 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
11518 };
11519 if (SplitAndProve(ProofFn))
11520 return true;
11521 }
11522 return false;
11523 };
11524
11525 // Starting at the block's predecessor, climb up the predecessor chain, as long
11526 // as there are predecessors that can be found that have unique successors
11527 // leading to the original block.
11528 const Loop *ContainingLoop = LI.getLoopFor(BB);
11529 const BasicBlock *PredBB;
11530 if (ContainingLoop && ContainingLoop->getHeader() == BB)
11531 PredBB = ContainingLoop->getLoopPredecessor();
11532 else
11533 PredBB = BB->getSinglePredecessor();
11534 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
11535 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
11536 const BranchInst *BlockEntryPredicate =
11537 dyn_cast<BranchInst>(Pair.first->getTerminator());
11538 if (!BlockEntryPredicate || BlockEntryPredicate->isUnconditional())
11539 continue;
11540
11541 if (ProveViaCond(BlockEntryPredicate->getCondition(),
11542 BlockEntryPredicate->getSuccessor(0) != Pair.second))
11543 return true;
11544 }
11545
11546 // Check conditions due to any @llvm.assume intrinsics.
11547 for (auto &AssumeVH : AC.assumptions()) {
11548 if (!AssumeVH)
11549 continue;
11550 auto *CI = cast<CallInst>(AssumeVH);
11551 if (!DT.dominates(CI, BB))
11552 continue;
11553
11554 if (ProveViaCond(CI->getArgOperand(0), false))
11555 return true;
11556 }
11557
11558 // Check conditions due to any @llvm.experimental.guard intrinsics.
11559 auto *GuardDecl = F.getParent()->getFunction(
11560 Intrinsic::getName(Intrinsic::experimental_guard));
11561 if (GuardDecl)
11562 for (const auto *GU : GuardDecl->users())
11563 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
11564 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
11565 if (ProveViaCond(Guard->getArgOperand(0), false))
11566 return true;
11567 return false;
11568}
11569
11570bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
11571 ICmpInst::Predicate Pred,
11572 const SCEV *LHS,
11573 const SCEV *RHS) {
11574 // Interpret a null as meaning no loop, where there is obviously no guard
11575 // (interprocedural conditions notwithstanding).
11576 if (!L)
11577 return false;
11578
11579 // Both LHS and RHS must be available at loop entry.
11580 assert(isAvailableAtLoopEntry(LHS, L) &&(static_cast <bool> (isAvailableAtLoopEntry(LHS, L) &&
"LHS is not available at Loop Entry") ? void (0) : __assert_fail
("isAvailableAtLoopEntry(LHS, L) && \"LHS is not available at Loop Entry\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11581, __extension__
__PRETTY_FUNCTION__))
11581 "LHS is not available at Loop Entry")(static_cast <bool> (isAvailableAtLoopEntry(LHS, L) &&
"LHS is not available at Loop Entry") ? void (0) : __assert_fail
("isAvailableAtLoopEntry(LHS, L) && \"LHS is not available at Loop Entry\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11581, __extension__
__PRETTY_FUNCTION__))
;
11582 assert(isAvailableAtLoopEntry(RHS, L) &&(static_cast <bool> (isAvailableAtLoopEntry(RHS, L) &&
"RHS is not available at Loop Entry") ? void (0) : __assert_fail
("isAvailableAtLoopEntry(RHS, L) && \"RHS is not available at Loop Entry\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11583, __extension__
__PRETTY_FUNCTION__))
11583 "RHS is not available at Loop Entry")(static_cast <bool> (isAvailableAtLoopEntry(RHS, L) &&
"RHS is not available at Loop Entry") ? void (0) : __assert_fail
("isAvailableAtLoopEntry(RHS, L) && \"RHS is not available at Loop Entry\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11583, __extension__
__PRETTY_FUNCTION__))
;
11584
11585 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11586 return true;
11587
11588 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
11589}
11590
11591bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11592 const SCEV *RHS,
11593 const Value *FoundCondValue, bool Inverse,
11594 const Instruction *CtxI) {
11595 // False conditions implies anything. Do not bother analyzing it further.
11596 if (FoundCondValue ==
11597 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
11598 return true;
11599
11600 if (!PendingLoopPredicates.insert(FoundCondValue).second)
11601 return false;
11602
11603 auto ClearOnExit =
11604 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
11605
11606 // Recursively handle And and Or conditions.
11607 const Value *Op0, *Op1;
11608 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
11609 if (!Inverse)
11610 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11611 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11612 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
11613 if (Inverse)
11614 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
11615 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
11616 }
11617
11618 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
11619 if (!ICI) return false;
11620
11621 // Now that we found a conditional branch that dominates the loop or controls
11622 // the loop latch. Check to see if it is the comparison we are looking for.
11623 ICmpInst::Predicate FoundPred;
11624 if (Inverse)
11625 FoundPred = ICI->getInversePredicate();
11626 else
11627 FoundPred = ICI->getPredicate();
11628
11629 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
11630 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
11631
11632 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
11633}
11634
11635bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
11636 const SCEV *RHS,
11637 ICmpInst::Predicate FoundPred,
11638 const SCEV *FoundLHS, const SCEV *FoundRHS,
11639 const Instruction *CtxI) {
11640 // Balance the types.
11641 if (getTypeSizeInBits(LHS->getType()) <
11642 getTypeSizeInBits(FoundLHS->getType())) {
11643 // For unsigned and equality predicates, try to prove that both found
11644 // operands fit into narrow unsigned range. If so, try to prove facts in
11645 // narrow types.
11646 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
11647 !FoundRHS->getType()->isPointerTy()) {
11648 auto *NarrowType = LHS->getType();
11649 auto *WideType = FoundLHS->getType();
11650 auto BitWidth = getTypeSizeInBits(NarrowType);
11651 const SCEV *MaxValue = getZeroExtendExpr(
11652 getConstant(APInt::getMaxValue(BitWidth)), WideType);
11653 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
11654 MaxValue) &&
11655 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
11656 MaxValue)) {
11657 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
11658 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
11659 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
11660 TruncFoundRHS, CtxI))
11661 return true;
11662 }
11663 }
11664
11665 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
11666 return false;
11667 if (CmpInst::isSigned(Pred)) {
11668 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
11669 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
11670 } else {
11671 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
11672 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
11673 }
11674 } else if (getTypeSizeInBits(LHS->getType()) >
11675 getTypeSizeInBits(FoundLHS->getType())) {
11676 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
11677 return false;
11678 if (CmpInst::isSigned(FoundPred)) {
11679 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
11680 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
11681 } else {
11682 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
11683 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
11684 }
11685 }
11686 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
11687 FoundRHS, CtxI);
11688}
11689
11690bool ScalarEvolution::isImpliedCondBalancedTypes(
11691 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11692 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
11693 const Instruction *CtxI) {
11694 assert(getTypeSizeInBits(LHS->getType()) ==(static_cast <bool> (getTypeSizeInBits(LHS->getType(
)) == getTypeSizeInBits(FoundLHS->getType()) && "Types should be balanced!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(FoundLHS->getType()) && \"Types should be balanced!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11696, __extension__
__PRETTY_FUNCTION__))
11695 getTypeSizeInBits(FoundLHS->getType()) &&(static_cast <bool> (getTypeSizeInBits(LHS->getType(
)) == getTypeSizeInBits(FoundLHS->getType()) && "Types should be balanced!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(FoundLHS->getType()) && \"Types should be balanced!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11696, __extension__
__PRETTY_FUNCTION__))
11696 "Types should be balanced!")(static_cast <bool> (getTypeSizeInBits(LHS->getType(
)) == getTypeSizeInBits(FoundLHS->getType()) && "Types should be balanced!"
) ? void (0) : __assert_fail ("getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(FoundLHS->getType()) && \"Types should be balanced!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11696, __extension__
__PRETTY_FUNCTION__))
;
11697 // Canonicalize the query to match the way instcombine will have
11698 // canonicalized the comparison.
11699 if (SimplifyICmpOperands(Pred, LHS, RHS))
11700 if (LHS == RHS)
11701 return CmpInst::isTrueWhenEqual(Pred);
11702 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
11703 if (FoundLHS == FoundRHS)
11704 return CmpInst::isFalseWhenEqual(FoundPred);
11705
11706 // Check to see if we can make the LHS or RHS match.
11707 if (LHS == FoundRHS || RHS == FoundLHS) {
11708 if (isa<SCEVConstant>(RHS)) {
11709 std::swap(FoundLHS, FoundRHS);
11710 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
11711 } else {
11712 std::swap(LHS, RHS);
11713 Pred = ICmpInst::getSwappedPredicate(Pred);
11714 }
11715 }
11716
11717 // Check whether the found predicate is the same as the desired predicate.
11718 if (FoundPred == Pred)
11719 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11720
11721 // Check whether swapping the found predicate makes it the same as the
11722 // desired predicate.
11723 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
11724 // We can write the implication
11725 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
11726 // using one of the following ways:
11727 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
11728 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
11729 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS
11730 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS
11731 // Forms 1. and 2. require swapping the operands of one condition. Don't
11732 // do this if it would break canonical constant/addrec ordering.
11733 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
11734 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
11735 CtxI);
11736 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
11737 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI);
11738
11739 // There's no clear preference between forms 3. and 4., try both. Avoid
11740 // forming getNotSCEV of pointer values as the resulting subtract is
11741 // not legal.
11742 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
11743 isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
11744 FoundLHS, FoundRHS, CtxI))
11745 return true;
11746
11747 if (!FoundLHS->getType()->isPointerTy() &&
11748 !FoundRHS->getType()->isPointerTy() &&
11749 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
11750 getNotSCEV(FoundRHS), CtxI))
11751 return true;
11752
11753 return false;
11754 }
11755
11756 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
11757 CmpInst::Predicate P2) {
11758 assert(P1 != P2 && "Handled earlier!")(static_cast <bool> (P1 != P2 && "Handled earlier!"
) ? void (0) : __assert_fail ("P1 != P2 && \"Handled earlier!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11758, __extension__
__PRETTY_FUNCTION__))
;
11759 return CmpInst::isRelational(P2) &&
11760 P1 == CmpInst::getFlippedSignednessPredicate(P2);
11761 };
11762 if (IsSignFlippedPredicate(Pred, FoundPred)) {
11763 // Unsigned comparison is the same as signed comparison when both the
11764 // operands are non-negative or negative.
11765 if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) ||
11766 (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS)))
11767 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
11768 // Create local copies that we can freely swap and canonicalize our
11769 // conditions to "le/lt".
11770 ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
11771 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
11772 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
11773 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
11774 CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred);
11775 CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred);
11776 std::swap(CanonicalLHS, CanonicalRHS);
11777 std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
11778 }
11779 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&(static_cast <bool> ((ICmpInst::isLT(CanonicalPred) || ICmpInst
::isLE(CanonicalPred)) && "Must be!") ? void (0) : __assert_fail
("(ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) && \"Must be!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11780, __extension__
__PRETTY_FUNCTION__))
11780 "Must be!")(static_cast <bool> ((ICmpInst::isLT(CanonicalPred) || ICmpInst
::isLE(CanonicalPred)) && "Must be!") ? void (0) : __assert_fail
("(ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) && \"Must be!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11780, __extension__
__PRETTY_FUNCTION__))
;
11781 assert((ICmpInst::isLT(CanonicalFoundPred) ||(static_cast <bool> ((ICmpInst::isLT(CanonicalFoundPred
) || ICmpInst::isLE(CanonicalFoundPred)) && "Must be!"
) ? void (0) : __assert_fail ("(ICmpInst::isLT(CanonicalFoundPred) || ICmpInst::isLE(CanonicalFoundPred)) && \"Must be!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11783, __extension__
__PRETTY_FUNCTION__))
11782 ICmpInst::isLE(CanonicalFoundPred)) &&(static_cast <bool> ((ICmpInst::isLT(CanonicalFoundPred
) || ICmpInst::isLE(CanonicalFoundPred)) && "Must be!"
) ? void (0) : __assert_fail ("(ICmpInst::isLT(CanonicalFoundPred) || ICmpInst::isLE(CanonicalFoundPred)) && \"Must be!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11783, __extension__
__PRETTY_FUNCTION__))
11783 "Must be!")(static_cast <bool> ((ICmpInst::isLT(CanonicalFoundPred
) || ICmpInst::isLE(CanonicalFoundPred)) && "Must be!"
) ? void (0) : __assert_fail ("(ICmpInst::isLT(CanonicalFoundPred) || ICmpInst::isLE(CanonicalFoundPred)) && \"Must be!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 11783, __extension__
__PRETTY_FUNCTION__))
;
11784 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
11785 // Use implication:
11786 // x <u y && y >=s 0 --> x <s y.
11787 // If we can prove the left part, the right part is also proven.
11788 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11789 CanonicalRHS, CanonicalFoundLHS,
11790 CanonicalFoundRHS);
11791 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
11792 // Use implication:
11793 // x <s y && y <s 0 --> x <u y.
11794 // If we can prove the left part, the right part is also proven.
11795 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
11796 CanonicalRHS, CanonicalFoundLHS,
11797 CanonicalFoundRHS);
11798 }
11799
11800 // Check if we can make progress by sharpening ranges.
11801 if (FoundPred == ICmpInst::ICMP_NE &&
11802 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
11803
11804 const SCEVConstant *C = nullptr;
11805 const SCEV *V = nullptr;
11806
11807 if (isa<SCEVConstant>(FoundLHS)) {
11808 C = cast<SCEVConstant>(FoundLHS);
11809 V = FoundRHS;
11810 } else {
11811 C = cast<SCEVConstant>(FoundRHS);
11812 V = FoundLHS;
11813 }
11814
11815 // The guarding predicate tells us that C != V. If the known range
11816 // of V is [C, t), we can sharpen the range to [C + 1, t). The
11817 // range we consider has to correspond to same signedness as the
11818 // predicate we're interested in folding.
11819
11820 APInt Min = ICmpInst::isSigned(Pred) ?
11821 getSignedRangeMin(V) : getUnsignedRangeMin(V);
11822
11823 if (Min == C->getAPInt()) {
11824 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
11825 // This is true even if (Min + 1) wraps around -- in case of
11826 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
11827
11828 APInt SharperMin = Min + 1;
11829
11830 switch (Pred) {
11831 case ICmpInst::ICMP_SGE:
11832 case ICmpInst::ICMP_UGE:
11833 // We know V `Pred` SharperMin. If this implies LHS `Pred`
11834 // RHS, we're done.
11835 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
11836 CtxI))
11837 return true;
11838 [[fallthrough]];
11839
11840 case ICmpInst::ICMP_SGT:
11841 case ICmpInst::ICMP_UGT:
11842 // We know from the range information that (V `Pred` Min ||
11843 // V == Min). We know from the guarding condition that !(V
11844 // == Min). This gives us
11845 //
11846 // V `Pred` Min || V == Min && !(V == Min)
11847 // => V `Pred` Min
11848 //
11849 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
11850
11851 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
11852 return true;
11853 break;
11854
11855 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
11856 case ICmpInst::ICMP_SLE:
11857 case ICmpInst::ICMP_ULE:
11858 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11859 LHS, V, getConstant(SharperMin), CtxI))
11860 return true;
11861 [[fallthrough]];
11862
11863 case ICmpInst::ICMP_SLT:
11864 case ICmpInst::ICMP_ULT:
11865 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
11866 LHS, V, getConstant(Min), CtxI))
11867 return true;
11868 break;
11869
11870 default:
11871 // No change
11872 break;
11873 }
11874 }
11875 }
11876
11877 // Check whether the actual condition is beyond sufficient.
11878 if (FoundPred == ICmpInst::ICMP_EQ)
11879 if (ICmpInst::isTrueWhenEqual(Pred))
11880 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11881 return true;
11882 if (Pred == ICmpInst::ICMP_NE)
11883 if (!ICmpInst::isTrueWhenEqual(FoundPred))
11884 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
11885 return true;
11886
11887 // Otherwise assume the worst.
11888 return false;
11889}
11890
11891bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
11892 const SCEV *&L, const SCEV *&R,
11893 SCEV::NoWrapFlags &Flags) {
11894 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
11895 if (!AE || AE->getNumOperands() != 2)
11896 return false;
11897
11898 L = AE->getOperand(0);
11899 R = AE->getOperand(1);
11900 Flags = AE->getNoWrapFlags();
11901 return true;
11902}
11903
11904std::optional<APInt>
11905ScalarEvolution::computeConstantDifference(const SCEV *More, const SCEV *Less) {
11906 // We avoid subtracting expressions here because this function is usually
11907 // fairly deep in the call stack (i.e. is called many times).
11908
11909 // X - X = 0.
11910 if (More == Less)
11911 return APInt(getTypeSizeInBits(More->getType()), 0);
11912
11913 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
11914 const auto *LAR = cast<SCEVAddRecExpr>(Less);
11915 const auto *MAR = cast<SCEVAddRecExpr>(More);
11916
11917 if (LAR->getLoop() != MAR->getLoop())
11918 return std::nullopt;
11919
11920 // We look at affine expressions only; not for correctness but to keep
11921 // getStepRecurrence cheap.
11922 if (!LAR->isAffine() || !MAR->isAffine())
11923 return std::nullopt;
11924
11925 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
11926 return std::nullopt;
11927
11928 Less = LAR->getStart();
11929 More = MAR->getStart();
11930
11931 // fall through
11932 }
11933
11934 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
11935 const auto &M = cast<SCEVConstant>(More)->getAPInt();
11936 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
11937 return M - L;
11938 }
11939
11940 SCEV::NoWrapFlags Flags;
11941 const SCEV *LLess = nullptr, *RLess = nullptr;
11942 const SCEV *LMore = nullptr, *RMore = nullptr;
11943 const SCEVConstant *C1 = nullptr, *C2 = nullptr;
11944 // Compare (X + C1) vs X.
11945 if (splitBinaryAdd(Less, LLess, RLess, Flags))
11946 if ((C1 = dyn_cast<SCEVConstant>(LLess)))
11947 if (RLess == More)
11948 return -(C1->getAPInt());
11949
11950 // Compare X vs (X + C2).
11951 if (splitBinaryAdd(More, LMore, RMore, Flags))
11952 if ((C2 = dyn_cast<SCEVConstant>(LMore)))
11953 if (RMore == Less)
11954 return C2->getAPInt();
11955
11956 // Compare (X + C1) vs (X + C2).
11957 if (C1 && C2 && RLess == RMore)
11958 return C2->getAPInt() - C1->getAPInt();
11959
11960 return std::nullopt;
11961}
11962
11963bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
11964 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
11965 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) {
11966 // Try to recognize the following pattern:
11967 //
11968 // FoundRHS = ...
11969 // ...
11970 // loop:
11971 // FoundLHS = {Start,+,W}
11972 // context_bb: // Basic block from the same loop
11973 // known(Pred, FoundLHS, FoundRHS)
11974 //
11975 // If some predicate is known in the context of a loop, it is also known on
11976 // each iteration of this loop, including the first iteration. Therefore, in
11977 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
11978 // prove the original pred using this fact.
11979 if (!CtxI)
11980 return false;
11981 const BasicBlock *ContextBB = CtxI->getParent();
11982 // Make sure AR varies in the context block.
11983 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
11984 const Loop *L = AR->getLoop();
11985 // Make sure that context belongs to the loop and executes on 1st iteration
11986 // (if it ever executes at all).
11987 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11988 return false;
11989 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
11990 return false;
11991 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
11992 }
11993
11994 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
11995 const Loop *L = AR->getLoop();
11996 // Make sure that context belongs to the loop and executes on 1st iteration
11997 // (if it ever executes at all).
11998 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
11999 return false;
12000 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12001 return false;
12002 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12003 }
12004
12005 return false;
12006}
12007
12008bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
12009 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
12010 const SCEV *FoundLHS, const SCEV *FoundRHS) {
12011 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12012 return false;
12013
12014 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12015 if (!AddRecLHS)
12016 return false;
12017
12018 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12019 if (!AddRecFoundLHS)
12020 return false;
12021
12022 // We'd like to let SCEV reason about control dependencies, so we constrain
12023 // both the inequalities to be about add recurrences on the same loop. This
12024 // way we can use isLoopEntryGuardedByCond later.
12025
12026 const Loop *L = AddRecFoundLHS->getLoop();
12027 if (L != AddRecLHS->getLoop())
12028 return false;
12029
12030 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12031 //
12032 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12033 // ... (2)
12034 //
12035 // Informal proof for (2), assuming (1) [*]:
12036 //
12037 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12038 //
12039 // Then
12040 //
12041 // FoundLHS s< FoundRHS s< INT_MIN - C
12042 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12043 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12044 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12045 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12046 // <=> FoundLHS + C s< FoundRHS + C
12047 //
12048 // [*]: (1) can be proved by ruling out overflow.
12049 //
12050 // [**]: This can be proved by analyzing all the four possibilities:
12051 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12052 // (A s>= 0, B s>= 0).
12053 //
12054 // Note:
12055 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12056 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12057 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12058 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12059 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12060 // C)".
12061
12062 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12063 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12064 if (!LDiff || !RDiff || *LDiff != *RDiff)
12065 return false;
12066
12067 if (LDiff->isMinValue())
12068 return true;
12069
12070 APInt FoundRHSLimit;
12071
12072 if (Pred == CmpInst::ICMP_ULT) {
12073 FoundRHSLimit = -(*RDiff);
12074 } else {
12075 assert(Pred == CmpInst::ICMP_SLT && "Checked above!")(static_cast <bool> (Pred == CmpInst::ICMP_SLT &&
"Checked above!") ? void (0) : __assert_fail ("Pred == CmpInst::ICMP_SLT && \"Checked above!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 12075, __extension__
__PRETTY_FUNCTION__))
;
12076 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12077 }
12078
12079 // Try to prove (1) or (2), as needed.
12080 return isAvailableAtLoopEntry(FoundRHS, L) &&
12081 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12082 getConstant(FoundRHSLimit));
12083}
12084
12085bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
12086 const SCEV *LHS, const SCEV *RHS,
12087 const SCEV *FoundLHS,
12088 const SCEV *FoundRHS, unsigned Depth) {
12089 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12090
12091 auto ClearOnExit = make_scope_exit([&]() {
12092 if (LPhi) {
12093 bool Erased = PendingMerges.erase(LPhi);
12094 assert(Erased && "Failed to erase LPhi!")(static_cast <bool> (Erased && "Failed to erase LPhi!"
) ? void (0) : __assert_fail ("Erased && \"Failed to erase LPhi!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 12094, __extension__
__PRETTY_FUNCTION__))
;
12095 (void)Erased;
12096 }
12097 if (RPhi) {
12098 bool Erased = PendingMerges.erase(RPhi);
12099 assert(Erased && "Failed to erase RPhi!")(static_cast <bool> (Erased && "Failed to erase RPhi!"
) ? void (0) : __assert_fail ("Erased && \"Failed to erase RPhi!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 12099, __extension__
__PRETTY_FUNCTION__))
;
12100 (void)Erased;
12101 }
12102 });
12103
12104 // Find respective Phis and check that they are not being pending.
12105 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12106 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12107 if (!PendingMerges.insert(Phi).second)
12108 return false;
12109 LPhi = Phi;
12110 }
12111 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12112 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12113 // If we detect a loop of Phi nodes being processed by this method, for
12114 // example:
12115 //
12116 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12117 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12118 //
12119 // we don't want to deal with a case that complex, so return conservative
12120 // answer false.
12121 if (!PendingMerges.insert(Phi).second)
12122 return false;
12123 RPhi = Phi;
12124 }
12125
12126 // If none of LHS, RHS is a Phi, nothing to do here.
12127 if (!LPhi && !RPhi)
12128 return false;
12129
12130 // If there is a SCEVUnknown Phi we are interested in, make it left.
12131 if (!LPhi) {
12132 std::swap(LHS, RHS);
12133 std::swap(FoundLHS, FoundRHS);
12134 std::swap(LPhi, RPhi);
12135 Pred = ICmpInst::getSwappedPredicate(Pred);
12136 }
12137
12138 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!")(static_cast <bool> (LPhi && "LPhi should definitely be a SCEVUnknown Phi!"
) ? void (0) : __assert_fail ("LPhi && \"LPhi should definitely be a SCEVUnknown Phi!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 12138, __extension__
__PRETTY_FUNCTION__))
;
12139 const BasicBlock *LBB = LPhi->getParent();
12140 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12141
12142 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12143 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12144 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
12145 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12146 };
12147
12148 if (RPhi && RPhi->getParent() == LBB) {
12149 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12150 // If we compare two Phis from the same block, and for each entry block
12151 // the predicate is true for incoming values from this block, then the
12152 // predicate is also true for the Phis.
12153 for (const BasicBlock *IncBB : predecessors(LBB)) {
12154 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12155 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12156 if (!ProvedEasily(L, R))
12157 return false;
12158 }
12159 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12160 // Case two: RHS is also a Phi from the same basic block, and it is an
12161 // AddRec. It means that there is a loop which has both AddRec and Unknown
12162 // PHIs, for it we can compare incoming values of AddRec from above the loop
12163 // and latch with their respective incoming values of LPhi.
12164 // TODO: Generalize to handle loops with many inputs in a header.
12165 if (LPhi->getNumIncomingValues() != 2) return false;
12166
12167 auto *RLoop = RAR->getLoop();
12168 auto *Predecessor = RLoop->getLoopPredecessor();
12169 assert(Predecessor && "Loop with AddRec with no predecessor?")(static_cast <bool> (Predecessor && "Loop with AddRec with no predecessor?"
) ? void (0) : __assert_fail ("Predecessor && \"Loop with AddRec with no predecessor?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 12169, __extension__
__PRETTY_FUNCTION__))
;
12170 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12171 if (!ProvedEasily(L1, RAR->getStart()))
12172 return false;
12173 auto *Latch = RLoop->getLoopLatch();
12174 assert(Latch && "Loop with AddRec with no latch?")(static_cast <bool> (Latch && "Loop with AddRec with no latch?"
) ? void (0) : __assert_fail ("Latch && \"Loop with AddRec with no latch?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 12174, __extension__
__PRETTY_FUNCTION__))
;
12175 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12176 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12177 return false;
12178 } else {
12179 // In all other cases go over inputs of LHS and compare each of them to RHS,
12180 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12181 // At this point RHS is either a non-Phi, or it is a Phi from some block
12182 // different from LBB.
12183 for (const BasicBlock *IncBB : predecessors(LBB)) {
12184 // Check that RHS is available in this block.
12185 if (!dominates(RHS, IncBB))
12186 return false;
12187 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12188 // Make sure L does not refer to a value from a potentially previous
12189 // iteration of a loop.
12190 if (!properlyDominates(L, LBB))
12191 return false;
12192 if (!ProvedEasily(L, RHS))
12193 return false;
12194 }
12195 }
12196 return true;
12197}
12198
12199bool ScalarEvolution::isImpliedCondOperandsViaShift(ICmpInst::Predicate Pred,
12200 const SCEV *LHS,
12201 const SCEV *RHS,
12202 const SCEV *FoundLHS,
12203 const SCEV *FoundRHS) {
12204 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12205 // sure that we are dealing with same LHS.
12206 if (RHS == FoundRHS) {
12207 std::swap(LHS, RHS);
12208 std::swap(FoundLHS, FoundRHS);
12209 Pred = ICmpInst::getSwappedPredicate(Pred);
12210 }
12211 if (LHS != FoundLHS)
12212 return false;
12213
12214 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12215 if (!SUFoundRHS)
12216 return false;
12217
12218 Value *Shiftee, *ShiftValue;
12219
12220 using namespace PatternMatch;
12221 if (match(SUFoundRHS->getValue(),
12222 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12223 auto *ShifteeS = getSCEV(Shiftee);
12224 // Prove one of the following:
12225 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12226 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12227 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12228 // ---> LHS <s RHS
12229 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12230 // ---> LHS <=s RHS
12231 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12232 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12233 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12234 if (isKnownNonNegative(ShifteeS))
12235 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12236 }
12237
12238 return false;
12239}
12240
12241bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
12242 const SCEV *LHS, const SCEV *RHS,
12243 const SCEV *FoundLHS,
12244 const SCEV *FoundRHS,
12245 const Instruction *CtxI) {
12246 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
12247 return true;
12248
12249 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
12250 return true;
12251
12252 if (isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS))
12253 return true;
12254
12255 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12256 CtxI))
12257 return true;
12258
12259 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
12260 FoundLHS, FoundRHS);
12261}
12262
12263/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12264template <typename MinMaxExprType>
12265static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12266 const SCEV *Candidate) {
12267 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12268 if (!MinMaxExpr)
12269 return false;
12270
12271 return is_contained(MinMaxExpr->operands(), Candidate);
12272}
12273
12274static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
12275 ICmpInst::Predicate Pred,
12276 const SCEV *LHS, const SCEV *RHS) {
12277 // If both sides are affine addrecs for the same loop, with equal
12278 // steps, and we know the recurrences don't wrap, then we only
12279 // need to check the predicate on the starting values.
12280
12281 if (!ICmpInst::isRelational(Pred))
12282 return false;
12283
12284 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
12285 if (!LAR)
12286 return false;
12287 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12288 if (!RAR)
12289 return false;
12290 if (LAR->getLoop() != RAR->getLoop())
12291 return false;
12292 if (!LAR->isAffine() || !RAR->isAffine())
12293 return false;
12294
12295 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
12296 return false;
12297
12298 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
12299 SCEV::FlagNSW : SCEV::FlagNUW;
12300 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12301 return false;
12302
12303 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
12304}
12305
12306/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12307/// expression?
12308static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
12309 ICmpInst::Predicate Pred,
12310 const SCEV *LHS, const SCEV *RHS) {
12311 switch (Pred) {
12312 default:
12313 return false;
12314
12315 case ICmpInst::ICMP_SGE:
12316 std::swap(LHS, RHS);
12317 [[fallthrough]];
12318 case ICmpInst::ICMP_SLE:
12319 return
12320 // min(A, ...) <= A
12321 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
12322 // A <= max(A, ...)
12323 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
12324
12325 case ICmpInst::ICMP_UGE:
12326 std::swap(LHS, RHS);
12327 [[fallthrough]];
12328 case ICmpInst::ICMP_ULE:
12329 return
12330 // min(A, ...) <= A
12331 // FIXME: what about umin_seq?
12332 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
12333 // A <= max(A, ...)
12334 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
12335 }
12336
12337 llvm_unreachable("covered switch fell through?!")::llvm::llvm_unreachable_internal("covered switch fell through?!"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 12337)
;
12338}
12339
12340bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
12341 const SCEV *LHS, const SCEV *RHS,
12342 const SCEV *FoundLHS,
12343 const SCEV *FoundRHS,
12344 unsigned Depth) {
12345 assert(getTypeSizeInBits(LHS->getType()) ==(static_cast <bool> (getTypeSizeInBits(LHS->getType(
)) == getTypeSizeInBits(RHS->getType()) && "LHS and RHS have different sizes?"
) ? void (0) : __assert_fail ("getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(RHS->getType()) && \"LHS and RHS have different sizes?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 12347, __extension__
__PRETTY_FUNCTION__))
12346 getTypeSizeInBits(RHS->getType()) &&(static_cast <bool> (getTypeSizeInBits(LHS->getType(
)) == getTypeSizeInBits(RHS->getType()) && "LHS and RHS have different sizes?"
) ? void (0) : __assert_fail ("getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(RHS->getType()) && \"LHS and RHS have different sizes?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 12347, __extension__
__PRETTY_FUNCTION__))
12347 "LHS and RHS have different sizes?")(static_cast <bool> (getTypeSizeInBits(LHS->getType(
)) == getTypeSizeInBits(RHS->getType()) && "LHS and RHS have different sizes?"
) ? void (0) : __assert_fail ("getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(RHS->getType()) && \"LHS and RHS have different sizes?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 12347, __extension__
__PRETTY_FUNCTION__))
;
12348 assert(getTypeSizeInBits(FoundLHS->getType()) ==(static_cast <bool> (getTypeSizeInBits(FoundLHS->getType
()) == getTypeSizeInBits(FoundRHS->getType()) && "FoundLHS and FoundRHS have different sizes?"
) ? void (0) : __assert_fail ("getTypeSizeInBits(FoundLHS->getType()) == getTypeSizeInBits(FoundRHS->getType()) && \"FoundLHS and FoundRHS have different sizes?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 12350, __extension__
__PRETTY_FUNCTION__))
12349 getTypeSizeInBits(FoundRHS->getType()) &&(static_cast <bool> (getTypeSizeInBits(FoundLHS->getType
()) == getTypeSizeInBits(FoundRHS->getType()) && "FoundLHS and FoundRHS have different sizes?"
) ? void (0) : __assert_fail ("getTypeSizeInBits(FoundLHS->getType()) == getTypeSizeInBits(FoundRHS->getType()) && \"FoundLHS and FoundRHS have different sizes?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 12350, __extension__
__PRETTY_FUNCTION__))
12350 "FoundLHS and FoundRHS have different sizes?")(static_cast <bool> (getTypeSizeInBits(FoundLHS->getType
()) == getTypeSizeInBits(FoundRHS->getType()) && "FoundLHS and FoundRHS have different sizes?"
) ? void (0) : __assert_fail ("getTypeSizeInBits(FoundLHS->getType()) == getTypeSizeInBits(FoundRHS->getType()) && \"FoundLHS and FoundRHS have different sizes?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 12350, __extension__
__PRETTY_FUNCTION__))
;
12351 // We want to avoid hurting the compile time with analysis of too big trees.
12352 if (Depth > MaxSCEVOperationsImplicationDepth)
12353 return false;
12354
12355 // We only want to work with GT comparison so far.
12356 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
12357 Pred = CmpInst::getSwappedPredicate(Pred);
12358 std::swap(LHS, RHS);
12359 std::swap(FoundLHS, FoundRHS);
12360 }
12361
12362 // For unsigned, try to reduce it to corresponding signed comparison.
12363 if (Pred == ICmpInst::ICMP_UGT)
12364 // We can replace unsigned predicate with its signed counterpart if all
12365 // involved values are non-negative.
12366 // TODO: We could have better support for unsigned.
12367 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
12368 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
12369 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
12370 // use this fact to prove that LHS and RHS are non-negative.
12371 const SCEV *MinusOne = getMinusOne(LHS->getType());
12372 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
12373 FoundRHS) &&
12374 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
12375 FoundRHS))
12376 Pred = ICmpInst::ICMP_SGT;
12377 }
12378
12379 if (Pred != ICmpInst::ICMP_SGT)
12380 return false;
12381
12382 auto GetOpFromSExt = [&](const SCEV *S) {
12383 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
12384 return Ext->getOperand();
12385 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
12386 // the constant in some cases.
12387 return S;
12388 };
12389
12390 // Acquire values from extensions.
12391 auto *OrigLHS = LHS;
12392 auto *OrigFoundLHS = FoundLHS;
12393 LHS = GetOpFromSExt(LHS);
12394 FoundLHS = GetOpFromSExt(FoundLHS);
12395
12396 // Is the SGT predicate can be proved trivially or using the found context.
12397 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
12398 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
12399 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
12400 FoundRHS, Depth + 1);
12401 };
12402
12403 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
12404 // We want to avoid creation of any new non-constant SCEV. Since we are
12405 // going to compare the operands to RHS, we should be certain that we don't
12406 // need any size extensions for this. So let's decline all cases when the
12407 // sizes of types of LHS and RHS do not match.
12408 // TODO: Maybe try to get RHS from sext to catch more cases?
12409 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
12410 return false;
12411
12412 // Should not overflow.
12413 if (!LHSAddExpr->hasNoSignedWrap())
12414 return false;
12415
12416 auto *LL = LHSAddExpr->getOperand(0);
12417 auto *LR = LHSAddExpr->getOperand(1);
12418 auto *MinusOne = getMinusOne(RHS->getType());
12419
12420 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
12421 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
12422 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
12423 };
12424 // Try to prove the following rule:
12425 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
12426 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
12427 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
12428 return true;
12429 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
12430 Value *LL, *LR;
12431 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
12432
12433 using namespace llvm::PatternMatch;
12434
12435 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
12436 // Rules for division.
12437 // We are going to perform some comparisons with Denominator and its
12438 // derivative expressions. In general case, creating a SCEV for it may
12439 // lead to a complex analysis of the entire graph, and in particular it
12440 // can request trip count recalculation for the same loop. This would
12441 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
12442 // this, we only want to create SCEVs that are constants in this section.
12443 // So we bail if Denominator is not a constant.
12444 if (!isa<ConstantInt>(LR))
12445 return false;
12446
12447 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
12448
12449 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
12450 // then a SCEV for the numerator already exists and matches with FoundLHS.
12451 auto *Numerator = getExistingSCEV(LL);
12452 if (!Numerator || Numerator->getType() != FoundLHS->getType())
12453 return false;
12454
12455 // Make sure that the numerator matches with FoundLHS and the denominator
12456 // is positive.
12457 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
12458 return false;
12459
12460 auto *DTy = Denominator->getType();
12461 auto *FRHSTy = FoundRHS->getType();
12462 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
12463 // One of types is a pointer and another one is not. We cannot extend
12464 // them properly to a wider type, so let us just reject this case.
12465 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
12466 // to avoid this check.
12467 return false;
12468
12469 // Given that:
12470 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
12471 auto *WTy = getWiderType(DTy, FRHSTy);
12472 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
12473 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
12474
12475 // Try to prove the following rule:
12476 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
12477 // For example, given that FoundLHS > 2. It means that FoundLHS is at
12478 // least 3. If we divide it by Denominator < 4, we will have at least 1.
12479 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
12480 if (isKnownNonPositive(RHS) &&
12481 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
12482 return true;
12483
12484 // Try to prove the following rule:
12485 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
12486 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
12487 // If we divide it by Denominator > 2, then:
12488 // 1. If FoundLHS is negative, then the result is 0.
12489 // 2. If FoundLHS is non-negative, then the result is non-negative.
12490 // Anyways, the result is non-negative.
12491 auto *MinusOne = getMinusOne(WTy);
12492 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
12493 if (isKnownNegative(RHS) &&
12494 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
12495 return true;
12496 }
12497 }
12498
12499 // If our expression contained SCEVUnknown Phis, and we split it down and now
12500 // need to prove something for them, try to prove the predicate for every
12501 // possible incoming values of those Phis.
12502 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
12503 return true;
12504
12505 return false;
12506}
12507
12508static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
12509 const SCEV *LHS, const SCEV *RHS) {
12510 // zext x u<= sext x, sext x s<= zext x
12511 switch (Pred) {
12512 case ICmpInst::ICMP_SGE:
12513 std::swap(LHS, RHS);
12514 [[fallthrough]];
12515 case ICmpInst::ICMP_SLE: {
12516 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
12517 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
12518 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
12519 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
12520 return true;
12521 break;
12522 }
12523 case ICmpInst::ICMP_UGE:
12524 std::swap(LHS, RHS);
12525 [[fallthrough]];
12526 case ICmpInst::ICMP_ULE: {
12527 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt.
12528 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
12529 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
12530 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
12531 return true;
12532 break;
12533 }
12534 default:
12535 break;
12536 };
12537 return false;
12538}
12539
12540bool
12541ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
12542 const SCEV *LHS, const SCEV *RHS) {
12543 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
12544 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
12545 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
12546 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
12547 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
12548}
12549
12550bool
12551ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
12552 const SCEV *LHS, const SCEV *RHS,
12553 const SCEV *FoundLHS,
12554 const SCEV *FoundRHS) {
12555 switch (Pred) {
12556 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!")::llvm::llvm_unreachable_internal("Unexpected ICmpInst::Predicate value!"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 12556)
;
12557 case ICmpInst::ICMP_EQ:
12558 case ICmpInst::ICMP_NE:
12559 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
12560 return true;
12561 break;
12562 case ICmpInst::ICMP_SLT:
12563 case ICmpInst::ICMP_SLE:
12564 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
12565 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
12566 return true;
12567 break;
12568 case ICmpInst::ICMP_SGT:
12569 case ICmpInst::ICMP_SGE:
12570 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
12571 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
12572 return true;
12573 break;
12574 case ICmpInst::ICMP_ULT:
12575 case ICmpInst::ICMP_ULE:
12576 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
12577 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
12578 return true;
12579 break;
12580 case ICmpInst::ICMP_UGT:
12581 case ICmpInst::ICMP_UGE:
12582 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
12583 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
12584 return true;
12585 break;
12586 }
12587
12588 // Maybe it can be proved via operations?
12589 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
12590 return true;
12591
12592 return false;
12593}
12594
12595bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
12596 const SCEV *LHS,
12597 const SCEV *RHS,
12598 const SCEV *FoundLHS,
12599 const SCEV *FoundRHS) {
12600 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
12601 // The restriction on `FoundRHS` be lifted easily -- it exists only to
12602 // reduce the compile time impact of this optimization.
12603 return false;
12604
12605 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
12606 if (!Addend)
12607 return false;
12608
12609 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
12610
12611 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
12612 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
12613 ConstantRange FoundLHSRange =
12614 ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS);
12615
12616 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
12617 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
12618
12619 // We can also compute the range of values for `LHS` that satisfy the
12620 // consequent, "`LHS` `Pred` `RHS`":
12621 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
12622 // The antecedent implies the consequent if every value of `LHS` that
12623 // satisfies the antecedent also satisfies the consequent.
12624 return LHSRange.icmp(Pred, ConstRHS);
12625}
12626
12627bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
12628 bool IsSigned) {
12629 assert(isKnownPositive(Stride) && "Positive stride expected!")(static_cast <bool> (isKnownPositive(Stride) &&
"Positive stride expected!") ? void (0) : __assert_fail ("isKnownPositive(Stride) && \"Positive stride expected!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 12629, __extension__
__PRETTY_FUNCTION__))
;
12630
12631 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12632 const SCEV *One = getOne(Stride->getType());
12633
12634 if (IsSigned) {
12635 APInt MaxRHS = getSignedRangeMax(RHS);
12636 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
12637 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12638
12639 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
12640 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
12641 }
12642
12643 APInt MaxRHS = getUnsignedRangeMax(RHS);
12644 APInt MaxValue = APInt::getMaxValue(BitWidth);
12645 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12646
12647 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
12648 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
12649}
12650
12651bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
12652 bool IsSigned) {
12653
12654 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
12655 const SCEV *One = getOne(Stride->getType());
12656
12657 if (IsSigned) {
12658 APInt MinRHS = getSignedRangeMin(RHS);
12659 APInt MinValue = APInt::getSignedMinValue(BitWidth);
12660 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
12661
12662 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
12663 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
12664 }
12665
12666 APInt MinRHS = getUnsignedRangeMin(RHS);
12667 APInt MinValue = APInt::getMinValue(BitWidth);
12668 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
12669
12670 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
12671 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
12672}
12673
12674const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) {
12675 // umin(N, 1) + floor((N - umin(N, 1)) / D)
12676 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
12677 // expression fixes the case of N=0.
12678 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
12679 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
12680 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
12681}
12682
12683const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
12684 const SCEV *Stride,
12685 const SCEV *End,
12686 unsigned BitWidth,
12687 bool IsSigned) {
12688 // The logic in this function assumes we can represent a positive stride.
12689 // If we can't, the backedge-taken count must be zero.
12690 if (IsSigned && BitWidth == 1)
12691 return getZero(Stride->getType());
12692
12693 // This code below only been closely audited for negative strides in the
12694 // unsigned comparison case, it may be correct for signed comparison, but
12695 // that needs to be established.
12696 if (IsSigned && isKnownNegative(Stride))
12697 return getCouldNotCompute();
12698
12699 // Calculate the maximum backedge count based on the range of values
12700 // permitted by Start, End, and Stride.
12701 APInt MinStart =
12702 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
12703
12704 APInt MinStride =
12705 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
12706
12707 // We assume either the stride is positive, or the backedge-taken count
12708 // is zero. So force StrideForMaxBECount to be at least one.
12709 APInt One(BitWidth, 1);
12710 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
12711 : APIntOps::umax(One, MinStride);
12712
12713 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
12714 : APInt::getMaxValue(BitWidth);
12715 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
12716
12717 // Although End can be a MAX expression we estimate MaxEnd considering only
12718 // the case End = RHS of the loop termination condition. This is safe because
12719 // in the other case (End - Start) is zero, leading to a zero maximum backedge
12720 // taken count.
12721 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
12722 : APIntOps::umin(getUnsignedRangeMax(End), Limit);
12723
12724 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
12725 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
12726 : APIntOps::umax(MaxEnd, MinStart);
12727
12728 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
12729 getConstant(StrideForMaxBECount) /* Step */);
12730}
12731
12732ScalarEvolution::ExitLimit
12733ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
12734 const Loop *L, bool IsSigned,
12735 bool ControlsOnlyExit, bool AllowPredicates) {
12736 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
12737
12738 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
12739 bool PredicatedIV = false;
12740
12741 auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) {
12742 // Can we prove this loop *must* be UB if overflow of IV occurs?
12743 // Reasoning goes as follows:
12744 // * Suppose the IV did self wrap.
12745 // * If Stride evenly divides the iteration space, then once wrap
12746 // occurs, the loop must revisit the same values.
12747 // * We know that RHS is invariant, and that none of those values
12748 // caused this exit to be taken previously. Thus, this exit is
12749 // dynamically dead.
12750 // * If this is the sole exit, then a dead exit implies the loop
12751 // must be infinite if there are no abnormal exits.
12752 // * If the loop were infinite, then it must either not be mustprogress
12753 // or have side effects. Otherwise, it must be UB.
12754 // * It can't (by assumption), be UB so we have contradicted our
12755 // premise and can conclude the IV did not in fact self-wrap.
12756 if (!isLoopInvariant(RHS, L))
12757 return false;
12758
12759 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
12760 if (!StrideC || !StrideC->getAPInt().isPowerOf2())
12761 return false;
12762
12763 if (!ControlsOnlyExit || !loopHasNoAbnormalExits(L))
12764 return false;
12765
12766 return loopIsFiniteByAssumption(L);
12767 };
12768
12769 if (!IV) {
12770 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
12771 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
12772 if (AR && AR->getLoop() == L && AR->isAffine()) {
12773 auto canProveNUW = [&]() {
12774 if (!isLoopInvariant(RHS, L))
12775 return false;
12776
12777 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
12778 // We need the sequence defined by AR to strictly increase in the
12779 // unsigned integer domain for the logic below to hold.
12780 return false;
12781
12782 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
12783 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
12784 // If RHS <=u Limit, then there must exist a value V in the sequence
12785 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
12786 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
12787 // overflow occurs. This limit also implies that a signed comparison
12788 // (in the wide bitwidth) is equivalent to an unsigned comparison as
12789 // the high bits on both sides must be zero.
12790 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
12791 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
12792 Limit = Limit.zext(OuterBitWidth);
12793 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
12794 };
12795 auto Flags = AR->getNoWrapFlags();
12796 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
12797 Flags = setFlags(Flags, SCEV::FlagNUW);
12798
12799 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
12800 if (AR->hasNoUnsignedWrap()) {
12801 // Emulate what getZeroExtendExpr would have done during construction
12802 // if we'd been able to infer the fact just above at that time.
12803 const SCEV *Step = AR->getStepRecurrence(*this);
12804 Type *Ty = ZExt->getType();
12805 auto *S = getAddRecExpr(
12806 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0),
12807 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
12808 IV = dyn_cast<SCEVAddRecExpr>(S);
12809 }
12810 }
12811 }
12812 }
12813
12814
12815 if (!IV && AllowPredicates) {
12816 // Try to make this an AddRec using runtime tests, in the first X
12817 // iterations of this loop, where X is the SCEV expression found by the
12818 // algorithm below.
12819 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
12820 PredicatedIV = true;
12821 }
12822
12823 // Avoid weird loops
12824 if (!IV || IV->getLoop() != L || !IV->isAffine())
12825 return getCouldNotCompute();
12826
12827 // A precondition of this method is that the condition being analyzed
12828 // reaches an exiting branch which dominates the latch. Given that, we can
12829 // assume that an increment which violates the nowrap specification and
12830 // produces poison must cause undefined behavior when the resulting poison
12831 // value is branched upon and thus we can conclude that the backedge is
12832 // taken no more often than would be required to produce that poison value.
12833 // Note that a well defined loop can exit on the iteration which violates
12834 // the nowrap specification if there is another exit (either explicit or
12835 // implicit/exceptional) which causes the loop to execute before the
12836 // exiting instruction we're analyzing would trigger UB.
12837 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
12838 bool NoWrap = ControlsOnlyExit && IV->getNoWrapFlags(WrapType);
12839 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
12840
12841 const SCEV *Stride = IV->getStepRecurrence(*this);
12842
12843 bool PositiveStride = isKnownPositive(Stride);
12844
12845 // Avoid negative or zero stride values.
12846 if (!PositiveStride) {
12847 // We can compute the correct backedge taken count for loops with unknown
12848 // strides if we can prove that the loop is not an infinite loop with side
12849 // effects. Here's the loop structure we are trying to handle -
12850 //
12851 // i = start
12852 // do {
12853 // A[i] = i;
12854 // i += s;
12855 // } while (i < end);
12856 //
12857 // The backedge taken count for such loops is evaluated as -
12858 // (max(end, start + stride) - start - 1) /u stride
12859 //
12860 // The additional preconditions that we need to check to prove correctness
12861 // of the above formula is as follows -
12862 //
12863 // a) IV is either nuw or nsw depending upon signedness (indicated by the
12864 // NoWrap flag).
12865 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
12866 // no side effects within the loop)
12867 // c) loop has a single static exit (with no abnormal exits)
12868 //
12869 // Precondition a) implies that if the stride is negative, this is a single
12870 // trip loop. The backedge taken count formula reduces to zero in this case.
12871 //
12872 // Precondition b) and c) combine to imply that if rhs is invariant in L,
12873 // then a zero stride means the backedge can't be taken without executing
12874 // undefined behavior.
12875 //
12876 // The positive stride case is the same as isKnownPositive(Stride) returning
12877 // true (original behavior of the function).
12878 //
12879 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
12880 !loopHasNoAbnormalExits(L))
12881 return getCouldNotCompute();
12882
12883 if (!isKnownNonZero(Stride)) {
12884 // If we have a step of zero, and RHS isn't invariant in L, we don't know
12885 // if it might eventually be greater than start and if so, on which
12886 // iteration. We can't even produce a useful upper bound.
12887 if (!isLoopInvariant(RHS, L))
12888 return getCouldNotCompute();
12889
12890 // We allow a potentially zero stride, but we need to divide by stride
12891 // below. Since the loop can't be infinite and this check must control
12892 // the sole exit, we can infer the exit must be taken on the first
12893 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
12894 // we know the numerator in the divides below must be zero, so we can
12895 // pick an arbitrary non-zero value for the denominator (e.g. stride)
12896 // and produce the right result.
12897 // FIXME: Handle the case where Stride is poison?
12898 auto wouldZeroStrideBeUB = [&]() {
12899 // Proof by contradiction. Suppose the stride were zero. If we can
12900 // prove that the backedge *is* taken on the first iteration, then since
12901 // we know this condition controls the sole exit, we must have an
12902 // infinite loop. We can't have a (well defined) infinite loop per
12903 // check just above.
12904 // Note: The (Start - Stride) term is used to get the start' term from
12905 // (start' + stride,+,stride). Remember that we only care about the
12906 // result of this expression when stride == 0 at runtime.
12907 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
12908 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
12909 };
12910 if (!wouldZeroStrideBeUB()) {
12911 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
12912 }
12913 }
12914 } else if (!Stride->isOne() && !NoWrap) {
12915 auto isUBOnWrap = [&]() {
12916 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This
12917 // follows trivially from the fact that every (un)signed-wrapped, but
12918 // not self-wrapped value must be LT than the last value before
12919 // (un)signed wrap. Since we know that last value didn't exit, nor
12920 // will any smaller one.
12921 return canAssumeNoSelfWrap(IV);
12922 };
12923
12924 // Avoid proven overflow cases: this will ensure that the backedge taken
12925 // count will not generate any unsigned overflow. Relaxed no-overflow
12926 // conditions exploit NoWrapFlags, allowing to optimize in presence of
12927 // undefined behaviors like the case of C language.
12928 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
12929 return getCouldNotCompute();
12930 }
12931
12932 // On all paths just preceeding, we established the following invariant:
12933 // IV can be assumed not to overflow up to and including the exiting
12934 // iteration. We proved this in one of two ways:
12935 // 1) We can show overflow doesn't occur before the exiting iteration
12936 // 1a) canIVOverflowOnLT, and b) step of one
12937 // 2) We can show that if overflow occurs, the loop must execute UB
12938 // before any possible exit.
12939 // Note that we have not yet proved RHS invariant (in general).
12940
12941 const SCEV *Start = IV->getStart();
12942
12943 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
12944 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
12945 // Use integer-typed versions for actual computation; we can't subtract
12946 // pointers in general.
12947 const SCEV *OrigStart = Start;
12948 const SCEV *OrigRHS = RHS;
12949 if (Start->getType()->isPointerTy()) {
12950 Start = getLosslessPtrToIntExpr(Start);
12951 if (isa<SCEVCouldNotCompute>(Start))
12952 return Start;
12953 }
12954 if (RHS->getType()->isPointerTy()) {
12955 RHS = getLosslessPtrToIntExpr(RHS);
12956 if (isa<SCEVCouldNotCompute>(RHS))
12957 return RHS;
12958 }
12959
12960 // When the RHS is not invariant, we do not know the end bound of the loop and
12961 // cannot calculate the ExactBECount needed by ExitLimit. However, we can
12962 // calculate the MaxBECount, given the start, stride and max value for the end
12963 // bound of the loop (RHS), and the fact that IV does not overflow (which is
12964 // checked above).
12965 if (!isLoopInvariant(RHS, L)) {
12966 const SCEV *MaxBECount = computeMaxBECountForLT(
12967 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
12968 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
12969 MaxBECount, false /*MaxOrZero*/, Predicates);
12970 }
12971
12972 // We use the expression (max(End,Start)-Start)/Stride to describe the
12973 // backedge count, as if the backedge is taken at least once max(End,Start)
12974 // is End and so the result is as above, and if not max(End,Start) is Start
12975 // so we get a backedge count of zero.
12976 const SCEV *BECount = nullptr;
12977 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
12978 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!")(static_cast <bool> (isAvailableAtLoopEntry(OrigStartMinusStride
, L) && "Must be!") ? void (0) : __assert_fail ("isAvailableAtLoopEntry(OrigStartMinusStride, L) && \"Must be!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 12978, __extension__
__PRETTY_FUNCTION__))
;
12979 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!")(static_cast <bool> (isAvailableAtLoopEntry(OrigStart, L
) && "Must be!") ? void (0) : __assert_fail ("isAvailableAtLoopEntry(OrigStart, L) && \"Must be!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 12979, __extension__
__PRETTY_FUNCTION__))
;
12980 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!")(static_cast <bool> (isAvailableAtLoopEntry(OrigRHS, L)
&& "Must be!") ? void (0) : __assert_fail ("isAvailableAtLoopEntry(OrigRHS, L) && \"Must be!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 12980, __extension__
__PRETTY_FUNCTION__))
;
12981 // Can we prove (max(RHS,Start) > Start - Stride?
12982 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
12983 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
12984 // In this case, we can use a refined formula for computing backedge taken
12985 // count. The general formula remains:
12986 // "End-Start /uceiling Stride" where "End = max(RHS,Start)"
12987 // We want to use the alternate formula:
12988 // "((End - 1) - (Start - Stride)) /u Stride"
12989 // Let's do a quick case analysis to show these are equivalent under
12990 // our precondition that max(RHS,Start) > Start - Stride.
12991 // * For RHS <= Start, the backedge-taken count must be zero.
12992 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
12993 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
12994 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values
12995 // of Stride. For 0 stride, we've use umin(1,Stride) above, reducing
12996 // this to the stride of 1 case.
12997 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride".
12998 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
12999 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
13000 // "((RHS - (Start - Stride) - 1) /u Stride".
13001 // Our preconditions trivially imply no overflow in that form.
13002 const SCEV *MinusOne = getMinusOne(Stride->getType());
13003 const SCEV *Numerator =
13004 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
13005 BECount = getUDivExpr(Numerator, Stride);
13006 }
13007
13008 const SCEV *BECountIfBackedgeTaken = nullptr;
13009 if (!BECount) {
13010 auto canProveRHSGreaterThanEqualStart = [&]() {
13011 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13012 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart))
13013 return true;
13014
13015 // (RHS > Start - 1) implies RHS >= Start.
13016 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13017 // "Start - 1" doesn't overflow.
13018 // * For signed comparison, if Start - 1 does overflow, it's equal
13019 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13020 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13021 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13022 //
13023 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13024 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13025 auto *StartMinusOne = getAddExpr(OrigStart,
13026 getMinusOne(OrigStart->getType()));
13027 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
13028 };
13029
13030 // If we know that RHS >= Start in the context of loop, then we know that
13031 // max(RHS, Start) = RHS at this point.
13032 const SCEV *End;
13033 if (canProveRHSGreaterThanEqualStart()) {
13034 End = RHS;
13035 } else {
13036 // If RHS < Start, the backedge will be taken zero times. So in
13037 // general, we can write the backedge-taken count as:
13038 //
13039 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13040 //
13041 // We convert it to the following to make it more convenient for SCEV:
13042 //
13043 // ceil(max(RHS, Start) - Start) / Stride
13044 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13045
13046 // See what would happen if we assume the backedge is taken. This is
13047 // used to compute MaxBECount.
13048 BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
13049 }
13050
13051 // At this point, we know:
13052 //
13053 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
13054 // 2. The index variable doesn't overflow.
13055 //
13056 // Therefore, we know N exists such that
13057 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13058 // doesn't overflow.
13059 //
13060 // Using this information, try to prove whether the addition in
13061 // "(Start - End) + (Stride - 1)" has unsigned overflow.
13062 const SCEV *One = getOne(Stride->getType());
13063 bool MayAddOverflow = [&] {
13064 if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) {
13065 if (StrideC->getAPInt().isPowerOf2()) {
13066 // Suppose Stride is a power of two, and Start/End are unsigned
13067 // integers. Let UMAX be the largest representable unsigned
13068 // integer.
13069 //
13070 // By the preconditions of this function, we know
13071 // "(Start + Stride * N) >= End", and this doesn't overflow.
13072 // As a formula:
13073 //
13074 // End <= (Start + Stride * N) <= UMAX
13075 //
13076 // Subtracting Start from all the terms:
13077 //
13078 // End - Start <= Stride * N <= UMAX - Start
13079 //
13080 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13081 //
13082 // End - Start <= Stride * N <= UMAX
13083 //
13084 // Stride * N is a multiple of Stride. Therefore,
13085 //
13086 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13087 //
13088 // Since Stride is a power of two, UMAX + 1 is divisible by Stride.
13089 // Therefore, UMAX mod Stride == Stride - 1. So we can write:
13090 //
13091 // End - Start <= Stride * N <= UMAX - Stride - 1
13092 //
13093 // Dropping the middle term:
13094 //
13095 // End - Start <= UMAX - Stride - 1
13096 //
13097 // Adding Stride - 1 to both sides:
13098 //
13099 // (End - Start) + (Stride - 1) <= UMAX
13100 //
13101 // In other words, the addition doesn't have unsigned overflow.
13102 //
13103 // A similar proof works if we treat Start/End as signed values.
13104 // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to
13105 // use signed max instead of unsigned max. Note that we're trying
13106 // to prove a lack of unsigned overflow in either case.
13107 return false;
13108 }
13109 }
13110 if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
13111 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1.
13112 // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End.
13113 // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End.
13114 //
13115 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End.
13116 return false;
13117 }
13118 return true;
13119 }();
13120
13121 const SCEV *Delta = getMinusSCEV(End, Start);
13122 if (!MayAddOverflow) {
13123 // floor((D + (S - 1)) / S)
13124 // We prefer this formulation if it's legal because it's fewer operations.
13125 BECount =
13126 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13127 } else {
13128 BECount = getUDivCeilSCEV(Delta, Stride);
13129 }
13130 }
13131
13132 const SCEV *ConstantMaxBECount;
13133 bool MaxOrZero = false;
13134 if (isa<SCEVConstant>(BECount)) {
13135 ConstantMaxBECount = BECount;
13136 } else if (BECountIfBackedgeTaken &&
13137 isa<SCEVConstant>(BECountIfBackedgeTaken)) {
13138 // If we know exactly how many times the backedge will be taken if it's
13139 // taken at least once, then the backedge count will either be that or
13140 // zero.
13141 ConstantMaxBECount = BECountIfBackedgeTaken;
13142 MaxOrZero = true;
13143 } else {
13144 ConstantMaxBECount = computeMaxBECountForLT(
13145 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13146 }
13147
13148 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13149 !isa<SCEVCouldNotCompute>(BECount))
13150 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13151
13152 const SCEV *SymbolicMaxBECount =
13153 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13154 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13155 Predicates);
13156}
13157
13158ScalarEvolution::ExitLimit ScalarEvolution::howManyGreaterThans(
13159 const SCEV *LHS, const SCEV *RHS, const Loop *L, bool IsSigned,
13160 bool ControlsOnlyExit, bool AllowPredicates) {
13161 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
13162 // We handle only IV > Invariant
13163 if (!isLoopInvariant(RHS, L))
13164 return getCouldNotCompute();
13165
13166 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
13167 if (!IV && AllowPredicates)
13168 // Try to make this an AddRec using runtime tests, in the first X
13169 // iterations of this loop, where X is the SCEV expression found by the
13170 // algorithm below.
13171 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13172
13173 // Avoid weird loops
13174 if (!IV || IV->getLoop() != L || !IV->isAffine())
13175 return getCouldNotCompute();
13176
13177 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13178 bool NoWrap = ControlsOnlyExit && IV->getNoWrapFlags(WrapType);
13179 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13180
13181 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
13182
13183 // Avoid negative or zero stride values
13184 if (!isKnownPositive(Stride))
13185 return getCouldNotCompute();
13186
13187 // Avoid proven overflow cases: this will ensure that the backedge taken count
13188 // will not generate any unsigned overflow. Relaxed no-overflow conditions
13189 // exploit NoWrapFlags, allowing to optimize in presence of undefined
13190 // behaviors like the case of C language.
13191 if (!Stride->isOne() && !NoWrap)
13192 if (canIVOverflowOnGT(RHS, Stride, IsSigned))
13193 return getCouldNotCompute();
13194
13195 const SCEV *Start = IV->getStart();
13196 const SCEV *End = RHS;
13197 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
13198 // If we know that Start >= RHS in the context of loop, then we know that
13199 // min(RHS, Start) = RHS at this point.
13200 if (isLoopEntryGuardedByCond(
13201 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
13202 End = RHS;
13203 else
13204 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13205 }
13206
13207 if (Start->getType()->isPointerTy()) {
13208 Start = getLosslessPtrToIntExpr(Start);
13209 if (isa<SCEVCouldNotCompute>(Start))
13210 return Start;
13211 }
13212 if (End->getType()->isPointerTy()) {
13213 End = getLosslessPtrToIntExpr(End);
13214 if (isa<SCEVCouldNotCompute>(End))
13215 return End;
13216 }
13217
13218 // Compute ((Start - End) + (Stride - 1)) / Stride.
13219 // FIXME: This can overflow. Holding off on fixing this for now;
13220 // howManyGreaterThans will hopefully be gone soon.
13221 const SCEV *One = getOne(Stride->getType());
13222 const SCEV *BECount = getUDivExpr(
13223 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
13224
13225 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
13226 : getUnsignedRangeMax(Start);
13227
13228 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
13229 : getUnsignedRangeMin(Stride);
13230
13231 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
13232 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
13233 : APInt::getMinValue(BitWidth) + (MinStride - 1);
13234
13235 // Although End can be a MIN expression we estimate MinEnd considering only
13236 // the case End = RHS. This is safe because in the other case (Start - End)
13237 // is zero, leading to a zero maximum backedge taken count.
13238 APInt MinEnd =
13239 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
13240 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
13241
13242 const SCEV *ConstantMaxBECount =
13243 isa<SCEVConstant>(BECount)
13244 ? BECount
13245 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
13246 getConstant(MinStride));
13247
13248 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount))
13249 ConstantMaxBECount = BECount;
13250 const SCEV *SymbolicMaxBECount =
13251 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13252
13253 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
13254 Predicates);
13255}
13256
13257const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
13258 ScalarEvolution &SE) const {
13259 if (Range.isFullSet()) // Infinite loop.
13260 return SE.getCouldNotCompute();
13261
13262 // If the start is a non-zero constant, shift the range to simplify things.
13263 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13264 if (!SC->getValue()->isZero()) {
13265 SmallVector<const SCEV *, 4> Operands(operands());
13266 Operands[0] = SE.getZero(SC->getType());
13267 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13268 getNoWrapFlags(FlagNW));
13269 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13270 return ShiftedAddRec->getNumIterationsInRange(
13271 Range.subtract(SC->getAPInt()), SE);
13272 // This is strange and shouldn't happen.
13273 return SE.getCouldNotCompute();
13274 }
13275
13276 // The only time we can solve this is when we have all constant indices.
13277 // Otherwise, we cannot determine the overflow conditions.
13278 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
13279 return SE.getCouldNotCompute();
13280
13281 // Okay at this point we know that all elements of the chrec are constants and
13282 // that the start element is zero.
13283
13284 // First check to see if the range contains zero. If not, the first
13285 // iteration exits.
13286 unsigned BitWidth = SE.getTypeSizeInBits(getType());
13287 if (!Range.contains(APInt(BitWidth, 0)))
13288 return SE.getZero(getType());
13289
13290 if (isAffine()) {
13291 // If this is an affine expression then we have this situation:
13292 // Solve {0,+,A} in Range === Ax in Range
13293
13294 // We know that zero is in the range. If A is positive then we know that
13295 // the upper value of the range must be the first possible exit value.
13296 // If A is negative then the lower of the range is the last possible loop
13297 // value. Also note that we already checked for a full range.
13298 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13299 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13300
13301 // The exit value should be (End+A)/A.
13302 APInt ExitVal = (End + A).udiv(A);
13303 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13304
13305 // Evaluate at the exit value. If we really did fall out of the valid
13306 // range, then we computed our trip count, otherwise wrap around or other
13307 // things must have happened.
13308 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
13309 if (Range.contains(Val->getValue()))
13310 return SE.getCouldNotCompute(); // Something strange happened
13311
13312 // Ensure that the previous value is in the range.
13313 assert(Range.contains((static_cast <bool> (Range.contains( EvaluateConstantChrecAtConstant
(this, ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->
getValue()) && "Linear scev computation is off in a bad way!"
) ? void (0) : __assert_fail ("Range.contains( EvaluateConstantChrecAtConstant(this, ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && \"Linear scev computation is off in a bad way!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 13316, __extension__
__PRETTY_FUNCTION__))
13314 EvaluateConstantChrecAtConstant(this,(static_cast <bool> (Range.contains( EvaluateConstantChrecAtConstant
(this, ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->
getValue()) && "Linear scev computation is off in a bad way!"
) ? void (0) : __assert_fail ("Range.contains( EvaluateConstantChrecAtConstant(this, ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && \"Linear scev computation is off in a bad way!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 13316, __extension__
__PRETTY_FUNCTION__))
13315 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&(static_cast <bool> (Range.contains( EvaluateConstantChrecAtConstant
(this, ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->
getValue()) && "Linear scev computation is off in a bad way!"
) ? void (0) : __assert_fail ("Range.contains( EvaluateConstantChrecAtConstant(this, ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && \"Linear scev computation is off in a bad way!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 13316, __extension__
__PRETTY_FUNCTION__))
13316 "Linear scev computation is off in a bad way!")(static_cast <bool> (Range.contains( EvaluateConstantChrecAtConstant
(this, ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->
getValue()) && "Linear scev computation is off in a bad way!"
) ? void (0) : __assert_fail ("Range.contains( EvaluateConstantChrecAtConstant(this, ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && \"Linear scev computation is off in a bad way!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 13316, __extension__
__PRETTY_FUNCTION__))
;
13317 return SE.getConstant(ExitValue);
13318 }
13319
13320 if (isQuadratic()) {
13321 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
13322 return SE.getConstant(*S);
13323 }
13324
13325 return SE.getCouldNotCompute();
13326}
13327
13328const SCEVAddRecExpr *
13329SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
13330 assert(getNumOperands() > 1 && "AddRec with zero step?")(static_cast <bool> (getNumOperands() > 1 &&
"AddRec with zero step?") ? void (0) : __assert_fail ("getNumOperands() > 1 && \"AddRec with zero step?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 13330, __extension__
__PRETTY_FUNCTION__))
;
13331 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
13332 // but in this case we cannot guarantee that the value returned will be an
13333 // AddRec because SCEV does not have a fixed point where it stops
13334 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
13335 // may happen if we reach arithmetic depth limit while simplifying. So we
13336 // construct the returned value explicitly.
13337 SmallVector<const SCEV *, 3> Ops;
13338 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
13339 // (this + Step) is {A+B,+,B+C,+...,+,N}.
13340 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
13341 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
13342 // We know that the last operand is not a constant zero (otherwise it would
13343 // have been popped out earlier). This guarantees us that if the result has
13344 // the same last operand, then it will also not be popped out, meaning that
13345 // the returned value will be an AddRec.
13346 const SCEV *Last = getOperand(getNumOperands() - 1);
13347 assert(!Last->isZero() && "Recurrency with zero step?")(static_cast <bool> (!Last->isZero() && "Recurrency with zero step?"
) ? void (0) : __assert_fail ("!Last->isZero() && \"Recurrency with zero step?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 13347, __extension__
__PRETTY_FUNCTION__))
;
13348 Ops.push_back(Last);
13349 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
13350 SCEV::FlagAnyWrap));
13351}
13352
13353// Return true when S contains at least an undef value.
13354bool ScalarEvolution::containsUndefs(const SCEV *S) const {
13355 return SCEVExprContains(S, [](const SCEV *S) {
13356 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
13357 return isa<UndefValue>(SU->getValue());
13358 return false;
13359 });
13360}
13361
13362// Return true when S contains a value that is a nullptr.
13363bool ScalarEvolution::containsErasedValue(const SCEV *S) const {
13364 return SCEVExprContains(S, [](const SCEV *S) {
13365 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
13366 return SU->getValue() == nullptr;
13367 return false;
13368 });
13369}
13370
13371/// Return the size of an element read or written by Inst.
13372const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
13373 Type *Ty;
13374 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
13375 Ty = Store->getValueOperand()->getType();
13376 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
13377 Ty = Load->getType();
13378 else
13379 return nullptr;
13380
13381 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
13382 return getSizeOfExpr(ETy, Ty);
13383}
13384
13385//===----------------------------------------------------------------------===//
13386// SCEVCallbackVH Class Implementation
13387//===----------------------------------------------------------------------===//
13388
13389void ScalarEvolution::SCEVCallbackVH::deleted() {
13390 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!")(static_cast <bool> (SE && "SCEVCallbackVH called with a null ScalarEvolution!"
) ? void (0) : __assert_fail ("SE && \"SCEVCallbackVH called with a null ScalarEvolution!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 13390, __extension__
__PRETTY_FUNCTION__))
;
13391 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
13392 SE->ConstantEvolutionLoopExitValue.erase(PN);
13393 SE->eraseValueFromMap(getValPtr());
13394 // this now dangles!
13395}
13396
13397void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
13398 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!")(static_cast <bool> (SE && "SCEVCallbackVH called with a null ScalarEvolution!"
) ? void (0) : __assert_fail ("SE && \"SCEVCallbackVH called with a null ScalarEvolution!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 13398, __extension__
__PRETTY_FUNCTION__))
;
13399
13400 // Forget all the expressions associated with users of the old value,
13401 // so that future queries will recompute the expressions using the new
13402 // value.
13403 Value *Old = getValPtr();
13404 SmallVector<User *, 16> Worklist(Old->users());
13405 SmallPtrSet<User *, 8> Visited;
13406 while (!Worklist.empty()) {
13407 User *U = Worklist.pop_back_val();
13408 // Deleting the Old value will cause this to dangle. Postpone
13409 // that until everything else is done.
13410 if (U == Old)
13411 continue;
13412 if (!Visited.insert(U).second)
13413 continue;
13414 if (PHINode *PN = dyn_cast<PHINode>(U))
13415 SE->ConstantEvolutionLoopExitValue.erase(PN);
13416 SE->eraseValueFromMap(U);
13417 llvm::append_range(Worklist, U->users());
13418 }
13419 // Delete the Old value.
13420 if (PHINode *PN = dyn_cast<PHINode>(Old))
13421 SE->ConstantEvolutionLoopExitValue.erase(PN);
13422 SE->eraseValueFromMap(Old);
13423 // this now dangles!
13424}
13425
13426ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
13427 : CallbackVH(V), SE(se) {}
13428
13429//===----------------------------------------------------------------------===//
13430// ScalarEvolution Class Implementation
13431//===----------------------------------------------------------------------===//
13432
13433ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
13434 AssumptionCache &AC, DominatorTree &DT,
13435 LoopInfo &LI)
13436 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
13437 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
13438 LoopDispositions(64), BlockDispositions(64) {
13439 // To use guards for proving predicates, we need to scan every instruction in
13440 // relevant basic blocks, and not just terminators. Doing this is a waste of
13441 // time if the IR does not actually contain any calls to
13442 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
13443 //
13444 // This pessimizes the case where a pass that preserves ScalarEvolution wants
13445 // to _add_ guards to the module when there weren't any before, and wants
13446 // ScalarEvolution to optimize based on those guards. For now we prefer to be
13447 // efficient in lieu of being smart in that rather obscure case.
13448
13449 auto *GuardDecl = F.getParent()->getFunction(
13450 Intrinsic::getName(Intrinsic::experimental_guard));
13451 HasGuards = GuardDecl && !GuardDecl->use_empty();
13452}
13453
13454ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
13455 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
13456 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
13457 ValueExprMap(std::move(Arg.ValueExprMap)),
13458 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
13459 PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
13460 PendingMerges(std::move(Arg.PendingMerges)),
13461 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
13462 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
13463 PredicatedBackedgeTakenCounts(
13464 std::move(Arg.PredicatedBackedgeTakenCounts)),
13465 BECountUsers(std::move(Arg.BECountUsers)),
13466 ConstantEvolutionLoopExitValue(
13467 std::move(Arg.ConstantEvolutionLoopExitValue)),
13468 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
13469 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
13470 LoopDispositions(std::move(Arg.LoopDispositions)),
13471 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
13472 BlockDispositions(std::move(Arg.BlockDispositions)),
13473 SCEVUsers(std::move(Arg.SCEVUsers)),
13474 UnsignedRanges(std::move(Arg.UnsignedRanges)),
13475 SignedRanges(std::move(Arg.SignedRanges)),
13476 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
13477 UniquePreds(std::move(Arg.UniquePreds)),
13478 SCEVAllocator(std::move(Arg.SCEVAllocator)),
13479 LoopUsers(std::move(Arg.LoopUsers)),
13480 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
13481 FirstUnknown(Arg.FirstUnknown) {
13482 Arg.FirstUnknown = nullptr;
13483}
13484
13485ScalarEvolution::~ScalarEvolution() {
13486 // Iterate through all the SCEVUnknown instances and call their
13487 // destructors, so that they release their references to their values.
13488 for (SCEVUnknown *U = FirstUnknown; U;) {
13489 SCEVUnknown *Tmp = U;
13490 U = U->Next;
13491 Tmp->~SCEVUnknown();
13492 }
13493 FirstUnknown = nullptr;
13494
13495 ExprValueMap.clear();
13496 ValueExprMap.clear();
13497 HasRecMap.clear();
13498 BackedgeTakenCounts.clear();
13499 PredicatedBackedgeTakenCounts.clear();
13500
13501 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage")(static_cast <bool> (PendingLoopPredicates.empty() &&
"isImpliedCond garbage") ? void (0) : __assert_fail ("PendingLoopPredicates.empty() && \"isImpliedCond garbage\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 13501, __extension__
__PRETTY_FUNCTION__))
;
13502 assert(PendingPhiRanges.empty() && "getRangeRef garbage")(static_cast <bool> (PendingPhiRanges.empty() &&
"getRangeRef garbage") ? void (0) : __assert_fail ("PendingPhiRanges.empty() && \"getRangeRef garbage\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 13502, __extension__
__PRETTY_FUNCTION__))
;
13503 assert(PendingMerges.empty() && "isImpliedViaMerge garbage")(static_cast <bool> (PendingMerges.empty() && "isImpliedViaMerge garbage"
) ? void (0) : __assert_fail ("PendingMerges.empty() && \"isImpliedViaMerge garbage\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 13503, __extension__
__PRETTY_FUNCTION__))
;
13504 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!")(static_cast <bool> (!WalkingBEDominatingConds &&
"isLoopBackedgeGuardedByCond garbage!") ? void (0) : __assert_fail
("!WalkingBEDominatingConds && \"isLoopBackedgeGuardedByCond garbage!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 13504, __extension__
__PRETTY_FUNCTION__))
;
13505 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!")(static_cast <bool> (!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"
) ? void (0) : __assert_fail ("!ProvingSplitPredicate && \"ProvingSplitPredicate garbage!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 13505, __extension__
__PRETTY_FUNCTION__))
;
13506}
13507
13508bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
13509 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
13510}
13511
13512static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
13513 const Loop *L) {
13514 // Print all inner loops first
13515 for (Loop *I : *L)
13516 PrintLoopInfo(OS, SE, I);
13517
13518 OS << "Loop ";
13519 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13520 OS << ": ";
13521
13522 SmallVector<BasicBlock *, 8> ExitingBlocks;
13523 L->getExitingBlocks(ExitingBlocks);
13524 if (ExitingBlocks.size() != 1)
13525 OS << "<multiple exits> ";
13526
13527 if (SE->hasLoopInvariantBackedgeTakenCount(L))
13528 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
13529 else
13530 OS << "Unpredictable backedge-taken count.\n";
13531
13532 if (ExitingBlocks.size() > 1)
13533 for (BasicBlock *ExitingBlock : ExitingBlocks) {
13534 OS << " exit count for " << ExitingBlock->getName() << ": "
13535 << *SE->getExitCount(L, ExitingBlock) << "\n";
13536 }
13537
13538 OS << "Loop ";
13539 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13540 OS << ": ";
13541
13542 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
13543 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
13544 OS << "constant max backedge-taken count is " << *ConstantBTC;
13545 if (SE->isBackedgeTakenCountMaxOrZero(L))
13546 OS << ", actual taken count either this or zero.";
13547 } else {
13548 OS << "Unpredictable constant max backedge-taken count. ";
13549 }
13550
13551 OS << "\n"
13552 "Loop ";
13553 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13554 OS << ": ";
13555
13556 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
13557 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
13558 OS << "symbolic max backedge-taken count is " << *SymbolicBTC;
13559 if (SE->isBackedgeTakenCountMaxOrZero(L))
13560 OS << ", actual taken count either this or zero.";
13561 } else {
13562 OS << "Unpredictable symbolic max backedge-taken count. ";
13563 }
13564
13565 OS << "\n";
13566 if (ExitingBlocks.size() > 1)
13567 for (BasicBlock *ExitingBlock : ExitingBlocks) {
13568 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": "
13569 << *SE->getExitCount(L, ExitingBlock, ScalarEvolution::SymbolicMaximum)
13570 << "\n";
13571 }
13572
13573 OS << "Loop ";
13574 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13575 OS << ": ";
13576
13577 SmallVector<const SCEVPredicate *, 4> Preds;
13578 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
13579 if (!isa<SCEVCouldNotCompute>(PBT)) {
13580 OS << "Predicated backedge-taken count is " << *PBT << "\n";
13581 OS << " Predicates:\n";
13582 for (const auto *P : Preds)
13583 P->print(OS, 4);
13584 } else {
13585 OS << "Unpredictable predicated backedge-taken count. ";
13586 }
13587 OS << "\n";
13588
13589 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
13590 OS << "Loop ";
13591 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13592 OS << ": ";
13593 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
13594 }
13595}
13596
13597static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
13598 switch (LD) {
13599 case ScalarEvolution::LoopVariant:
13600 return "Variant";
13601 case ScalarEvolution::LoopInvariant:
13602 return "Invariant";
13603 case ScalarEvolution::LoopComputable:
13604 return "Computable";
13605 }
13606 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!")::llvm::llvm_unreachable_internal("Unknown ScalarEvolution::LoopDisposition kind!"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 13606)
;
13607}
13608
13609void ScalarEvolution::print(raw_ostream &OS) const {
13610 // ScalarEvolution's implementation of the print method is to print
13611 // out SCEV values of all instructions that are interesting. Doing
13612 // this potentially causes it to create new SCEV objects though,
13613 // which technically conflicts with the const qualifier. This isn't
13614 // observable from outside the class though, so casting away the
13615 // const isn't dangerous.
13616 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
13617
13618 if (ClassifyExpressions) {
13619 OS << "Classifying expressions for: ";
13620 F.printAsOperand(OS, /*PrintType=*/false);
13621 OS << "\n";
13622 for (Instruction &I : instructions(F))
13623 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
13624 OS << I << '\n';
13625 OS << " --> ";
13626 const SCEV *SV = SE.getSCEV(&I);
13627 SV->print(OS);
13628 if (!isa<SCEVCouldNotCompute>(SV)) {
13629 OS << " U: ";
13630 SE.getUnsignedRange(SV).print(OS);
13631 OS << " S: ";
13632 SE.getSignedRange(SV).print(OS);
13633 }
13634
13635 const Loop *L = LI.getLoopFor(I.getParent());
13636
13637 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
13638 if (AtUse != SV) {
13639 OS << " --> ";
13640 AtUse->print(OS);
13641 if (!isa<SCEVCouldNotCompute>(AtUse)) {
13642 OS << " U: ";
13643 SE.getUnsignedRange(AtUse).print(OS);
13644 OS << " S: ";
13645 SE.getSignedRange(AtUse).print(OS);
13646 }
13647 }
13648
13649 if (L) {
13650 OS << "\t\t" "Exits: ";
13651 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
13652 if (!SE.isLoopInvariant(ExitValue, L)) {
13653 OS << "<<Unknown>>";
13654 } else {
13655 OS << *ExitValue;
13656 }
13657
13658 bool First = true;
13659 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
13660 if (First) {
13661 OS << "\t\t" "LoopDispositions: { ";
13662 First = false;
13663 } else {
13664 OS << ", ";
13665 }
13666
13667 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13668 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
13669 }
13670
13671 for (const auto *InnerL : depth_first(L)) {
13672 if (InnerL == L)
13673 continue;
13674 if (First) {
13675 OS << "\t\t" "LoopDispositions: { ";
13676 First = false;
13677 } else {
13678 OS << ", ";
13679 }
13680
13681 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
13682 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
13683 }
13684
13685 OS << " }";
13686 }
13687
13688 OS << "\n";
13689 }
13690 }
13691
13692 OS << "Determining loop execution counts for: ";
13693 F.printAsOperand(OS, /*PrintType=*/false);
13694 OS << "\n";
13695 for (Loop *I : LI)
13696 PrintLoopInfo(OS, &SE, I);
13697}
13698
13699ScalarEvolution::LoopDisposition
13700ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
13701 auto &Values = LoopDispositions[S];
13702 for (auto &V : Values) {
13703 if (V.getPointer() == L)
13704 return V.getInt();
13705 }
13706 Values.emplace_back(L, LoopVariant);
13707 LoopDisposition D = computeLoopDisposition(S, L);
13708 auto &Values2 = LoopDispositions[S];
13709 for (auto &V : llvm::reverse(Values2)) {
13710 if (V.getPointer() == L) {
13711 V.setInt(D);
13712 break;
13713 }
13714 }
13715 return D;
13716}
13717
13718ScalarEvolution::LoopDisposition
13719ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
13720 switch (S->getSCEVType()) {
13721 case scConstant:
13722 case scVScale:
13723 return LoopInvariant;
13724 case scAddRecExpr: {
13725 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13726
13727 // If L is the addrec's loop, it's computable.
13728 if (AR->getLoop() == L)
13729 return LoopComputable;
13730
13731 // Add recurrences are never invariant in the function-body (null loop).
13732 if (!L)
13733 return LoopVariant;
13734
13735 // Everything that is not defined at loop entry is variant.
13736 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
13737 return LoopVariant;
13738 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"(static_cast <bool> (!L->contains(AR->getLoop()) &&
"Containing loop's header does not" " dominate the contained loop's header?"
) ? void (0) : __assert_fail ("!L->contains(AR->getLoop()) && \"Containing loop's header does not\" \" dominate the contained loop's header?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 13739, __extension__
__PRETTY_FUNCTION__))
13739 " dominate the contained loop's header?")(static_cast <bool> (!L->contains(AR->getLoop()) &&
"Containing loop's header does not" " dominate the contained loop's header?"
) ? void (0) : __assert_fail ("!L->contains(AR->getLoop()) && \"Containing loop's header does not\" \" dominate the contained loop's header?\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 13739, __extension__
__PRETTY_FUNCTION__))
;
13740
13741 // This recurrence is invariant w.r.t. L if AR's loop contains L.
13742 if (AR->getLoop()->contains(L))
13743 return LoopInvariant;
13744
13745 // This recurrence is variant w.r.t. L if any of its operands
13746 // are variant.
13747 for (const auto *Op : AR->operands())
13748 if (!isLoopInvariant(Op, L))
13749 return LoopVariant;
13750
13751 // Otherwise it's loop-invariant.
13752 return LoopInvariant;
13753 }
13754 case scTruncate:
13755 case scZeroExtend:
13756 case scSignExtend:
13757 case scPtrToInt:
13758 case scAddExpr:
13759 case scMulExpr:
13760 case scUDivExpr:
13761 case scUMaxExpr:
13762 case scSMaxExpr:
13763 case scUMinExpr:
13764 case scSMinExpr:
13765 case scSequentialUMinExpr: {
13766 bool HasVarying = false;
13767 for (const auto *Op : S->operands()) {
13768 LoopDisposition D = getLoopDisposition(Op, L);
13769 if (D == LoopVariant)
13770 return LoopVariant;
13771 if (D == LoopComputable)
13772 HasVarying = true;
13773 }
13774 return HasVarying ? LoopComputable : LoopInvariant;
13775 }
13776 case scUnknown:
13777 // All non-instruction values are loop invariant. All instructions are loop
13778 // invariant if they are not contained in the specified loop.
13779 // Instructions are never considered invariant in the function body
13780 // (null loop) because they are defined within the "loop".
13781 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
13782 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
13783 return LoopInvariant;
13784 case scCouldNotCompute:
13785 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 13785)
;
13786 }
13787 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 13787)
;
13788}
13789
13790bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
13791 return getLoopDisposition(S, L) == LoopInvariant;
13792}
13793
13794bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
13795 return getLoopDisposition(S, L) == LoopComputable;
13796}
13797
13798ScalarEvolution::BlockDisposition
13799ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13800 auto &Values = BlockDispositions[S];
13801 for (auto &V : Values) {
13802 if (V.getPointer() == BB)
13803 return V.getInt();
13804 }
13805 Values.emplace_back(BB, DoesNotDominateBlock);
13806 BlockDisposition D = computeBlockDisposition(S, BB);
13807 auto &Values2 = BlockDispositions[S];
13808 for (auto &V : llvm::reverse(Values2)) {
13809 if (V.getPointer() == BB) {
13810 V.setInt(D);
13811 break;
13812 }
13813 }
13814 return D;
13815}
13816
13817ScalarEvolution::BlockDisposition
13818ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
13819 switch (S->getSCEVType()) {
13820 case scConstant:
13821 case scVScale:
13822 return ProperlyDominatesBlock;
13823 case scAddRecExpr: {
13824 // This uses a "dominates" query instead of "properly dominates" query
13825 // to test for proper dominance too, because the instruction which
13826 // produces the addrec's value is a PHI, and a PHI effectively properly
13827 // dominates its entire containing block.
13828 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
13829 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
13830 return DoesNotDominateBlock;
13831
13832 // Fall through into SCEVNAryExpr handling.
13833 [[fallthrough]];
13834 }
13835 case scTruncate:
13836 case scZeroExtend:
13837 case scSignExtend:
13838 case scPtrToInt:
13839 case scAddExpr:
13840 case scMulExpr:
13841 case scUDivExpr:
13842 case scUMaxExpr:
13843 case scSMaxExpr:
13844 case scUMinExpr:
13845 case scSMinExpr:
13846 case scSequentialUMinExpr: {
13847 bool Proper = true;
13848 for (const SCEV *NAryOp : S->operands()) {
13849 BlockDisposition D = getBlockDisposition(NAryOp, BB);
13850 if (D == DoesNotDominateBlock)
13851 return DoesNotDominateBlock;
13852 if (D == DominatesBlock)
13853 Proper = false;
13854 }
13855 return Proper ? ProperlyDominatesBlock : DominatesBlock;
13856 }
13857 case scUnknown:
13858 if (Instruction *I =
13859 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
13860 if (I->getParent() == BB)
13861 return DominatesBlock;
13862 if (DT.properlyDominates(I->getParent(), BB))
13863 return ProperlyDominatesBlock;
13864 return DoesNotDominateBlock;
13865 }
13866 return ProperlyDominatesBlock;
13867 case scCouldNotCompute:
13868 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "llvm/lib/Analysis/ScalarEvolution.cpp", 13868)
;
13869 }
13870 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 13870)
;
13871}
13872
13873bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
13874 return getBlockDisposition(S, BB) >= DominatesBlock;
13875}
13876
13877bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
13878 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
13879}
13880
13881bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
13882 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
13883}
13884
13885void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
13886 bool Predicated) {
13887 auto &BECounts =
13888 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
13889 auto It = BECounts.find(L);
13890 if (It != BECounts.end()) {
13891 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
13892 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
13893 if (!isa<SCEVConstant>(S)) {
13894 auto UserIt = BECountUsers.find(S);
13895 assert(UserIt != BECountUsers.end())(static_cast <bool> (UserIt != BECountUsers.end()) ? void
(0) : __assert_fail ("UserIt != BECountUsers.end()", "llvm/lib/Analysis/ScalarEvolution.cpp"
, 13895, __extension__ __PRETTY_FUNCTION__))
;
13896 UserIt->second.erase({L, Predicated});
13897 }
13898 }
13899 }
13900 BECounts.erase(It);
13901 }
13902}
13903
13904void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) {
13905 SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end());
13906 SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end());
13907
13908 while (!Worklist.empty()) {
13909 const SCEV *Curr = Worklist.pop_back_val();
13910 auto Users = SCEVUsers.find(Curr);
13911 if (Users != SCEVUsers.end())
13912 for (const auto *User : Users->second)
13913 if (ToForget.insert(User).second)
13914 Worklist.push_back(User);
13915 }
13916
13917 for (const auto *S : ToForget)
13918 forgetMemoizedResultsImpl(S);
13919
13920 for (auto I = PredicatedSCEVRewrites.begin();
13921 I != PredicatedSCEVRewrites.end();) {
13922 std::pair<const SCEV *, const Loop *> Entry = I->first;
13923 if (ToForget.count(Entry.first))
13924 PredicatedSCEVRewrites.erase(I++);
13925 else
13926 ++I;
13927 }
13928}
13929
13930void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
13931 LoopDispositions.erase(S);
13932 BlockDispositions.erase(S);
13933 UnsignedRanges.erase(S);
13934 SignedRanges.erase(S);
13935 HasRecMap.erase(S);
13936 ConstantMultipleCache.erase(S);
13937
13938 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
13939 UnsignedWrapViaInductionTried.erase(AR);
13940 SignedWrapViaInductionTried.erase(AR);
13941 }
13942
13943 auto ExprIt = ExprValueMap.find(S);
13944 if (ExprIt != ExprValueMap.end()) {
13945 for (Value *V : ExprIt->second) {
13946 auto ValueIt = ValueExprMap.find_as(V);
13947 if (ValueIt != ValueExprMap.end())
13948 ValueExprMap.erase(ValueIt);
13949 }
13950 ExprValueMap.erase(ExprIt);
13951 }
13952
13953 auto ScopeIt = ValuesAtScopes.find(S);
13954 if (ScopeIt != ValuesAtScopes.end()) {
13955 for (const auto &Pair : ScopeIt->second)
13956 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
13957 erase_value(ValuesAtScopesUsers[Pair.second],
13958 std::make_pair(Pair.first, S));
13959 ValuesAtScopes.erase(ScopeIt);
13960 }
13961
13962 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
13963 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
13964 for (const auto &Pair : ScopeUserIt->second)
13965 erase_value(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
13966 ValuesAtScopesUsers.erase(ScopeUserIt);
13967 }
13968
13969 auto BEUsersIt = BECountUsers.find(S);
13970 if (BEUsersIt != BECountUsers.end()) {
13971 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
13972 auto Copy = BEUsersIt->second;
13973 for (const auto &Pair : Copy)
13974 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
13975 BECountUsers.erase(BEUsersIt);
13976 }
13977
13978 auto FoldUser = FoldCacheUser.find(S);
13979 if (FoldUser != FoldCacheUser.end())
13980 for (auto &KV : FoldUser->second)
13981 FoldCache.erase(KV);
13982 FoldCacheUser.erase(S);
13983}
13984
13985void
13986ScalarEvolution::getUsedLoops(const SCEV *S,
13987 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
13988 struct FindUsedLoops {
13989 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
13990 : LoopsUsed(LoopsUsed) {}
13991 SmallPtrSetImpl<const Loop *> &LoopsUsed;
13992 bool follow(const SCEV *S) {
13993 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
13994 LoopsUsed.insert(AR->getLoop());
13995 return true;
13996 }
13997
13998 bool isDone() const { return false; }
13999 };
14000
14001 FindUsedLoops F(LoopsUsed);
14002 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14003}
14004
14005void ScalarEvolution::getReachableBlocks(
14006 SmallPtrSetImpl<BasicBlock *> &Reachable, Function &F) {
14007 SmallVector<BasicBlock *> Worklist;
14008 Worklist.push_back(&F.getEntryBlock());
14009 while (!Worklist.empty()) {
14010 BasicBlock *BB = Worklist.pop_back_val();
14011 if (!Reachable.insert(BB).second)
14012 continue;
14013
14014 Value *Cond;
14015 BasicBlock *TrueBB, *FalseBB;
14016 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14017 m_BasicBlock(FalseBB)))) {
14018 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14019 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14020 continue;
14021 }
14022
14023 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14024 const SCEV *L = getSCEV(Cmp->getOperand(0));
14025 const SCEV *R = getSCEV(Cmp->getOperand(1));
14026 if (isKnownPredicateViaConstantRanges(Cmp->getPredicate(), L, R)) {
14027 Worklist.push_back(TrueBB);
14028 continue;
14029 }
14030 if (isKnownPredicateViaConstantRanges(Cmp->getInversePredicate(), L,
14031 R)) {
14032 Worklist.push_back(FalseBB);
14033 continue;
14034 }
14035 }
14036 }
14037
14038 append_range(Worklist, successors(BB));
14039 }
14040}
14041
14042void ScalarEvolution::verify() const {
14043 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14044 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14045
14046 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14047
14048 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14049 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14050 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14051
14052 const SCEV *visitConstant(const SCEVConstant *Constant) {
14053 return SE.getConstant(Constant->getAPInt());
14054 }
14055
14056 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14057 return SE.getUnknown(Expr->getValue());
14058 }
14059
14060 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14061 return SE.getCouldNotCompute();
14062 }
14063 };
14064
14065 SCEVMapper SCM(SE2);
14066 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14067 SE2.getReachableBlocks(ReachableBlocks, F);
14068
14069 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14070 if (containsUndefs(Old) || containsUndefs(New)) {
1
Assuming the condition is false
2
Assuming the condition is false
3
Taking false branch
14071 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14072 // not propagate undef aggressively). This means we can (and do) fail
14073 // verification in cases where a transform makes a value go from "undef"
14074 // to "undef+1" (say). The transform is fine, since in both cases the
14075 // result is "undef", but SCEV thinks the value increased by 1.
14076 return nullptr;
14077 }
14078
14079 // Unless VerifySCEVStrict is set, we only compare constant deltas.
14080 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
4
Calling 'ScalarEvolution::getMinusSCEV'
14081 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
14082 return nullptr;
14083
14084 return Delta;
14085 };
14086
14087 while (!LoopStack.empty()) {
14088 auto *L = LoopStack.pop_back_val();
14089 llvm::append_range(LoopStack, *L);
14090
14091 // Only verify BECounts in reachable loops. For an unreachable loop,
14092 // any BECount is legal.
14093 if (!ReachableBlocks.contains(L->getHeader()))
14094 continue;
14095
14096 // Only verify cached BECounts. Computing new BECounts may change the
14097 // results of subsequent SCEV uses.
14098 auto It = BackedgeTakenCounts.find(L);
14099 if (It == BackedgeTakenCounts.end())
14100 continue;
14101
14102 auto *CurBECount =
14103 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14104 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14105
14106 if (CurBECount == SE2.getCouldNotCompute() ||
14107 NewBECount == SE2.getCouldNotCompute()) {
14108 // NB! This situation is legal, but is very suspicious -- whatever pass
14109 // change the loop to make a trip count go from could not compute to
14110 // computable or vice-versa *should have* invalidated SCEV. However, we
14111 // choose not to assert here (for now) since we don't want false
14112 // positives.
14113 continue;
14114 }
14115
14116 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14117 SE.getTypeSizeInBits(NewBECount->getType()))
14118 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14119 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14120 SE.getTypeSizeInBits(NewBECount->getType()))
14121 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14122
14123 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14124 if (Delta && !Delta->isZero()) {
14125 dbgs() << "Trip Count for " << *L << " Changed!\n";
14126 dbgs() << "Old: " << *CurBECount << "\n";
14127 dbgs() << "New: " << *NewBECount << "\n";
14128 dbgs() << "Delta: " << *Delta << "\n";
14129 std::abort();
14130 }
14131 }
14132
14133 // Collect all valid loops currently in LoopInfo.
14134 SmallPtrSet<Loop *, 32> ValidLoops;
14135 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14136 while (!Worklist.empty()) {
14137 Loop *L = Worklist.pop_back_val();
14138 if (ValidLoops.insert(L).second)
14139 Worklist.append(L->begin(), L->end());
14140 }
14141 for (const auto &KV : ValueExprMap) {
14142#ifndef NDEBUG
14143 // Check for SCEV expressions referencing invalid/deleted loops.
14144 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14145 assert(ValidLoops.contains(AR->getLoop()) &&(static_cast <bool> (ValidLoops.contains(AR->getLoop
()) && "AddRec references invalid loop") ? void (0) :
__assert_fail ("ValidLoops.contains(AR->getLoop()) && \"AddRec references invalid loop\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 14146, __extension__
__PRETTY_FUNCTION__))
14146 "AddRec references invalid loop")(static_cast <bool> (ValidLoops.contains(AR->getLoop
()) && "AddRec references invalid loop") ? void (0) :
__assert_fail ("ValidLoops.contains(AR->getLoop()) && \"AddRec references invalid loop\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 14146, __extension__
__PRETTY_FUNCTION__))
;
14147 }
14148#endif
14149
14150 // Check that the value is also part of the reverse map.
14151 auto It = ExprValueMap.find(KV.second);
14152 if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
14153 dbgs() << "Value " << *KV.first
14154 << " is in ValueExprMap but not in ExprValueMap\n";
14155 std::abort();
14156 }
14157
14158 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14159 if (!ReachableBlocks.contains(I->getParent()))
14160 continue;
14161 const SCEV *OldSCEV = SCM.visit(KV.second);
14162 const SCEV *NewSCEV = SE2.getSCEV(I);
14163 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14164 if (Delta && !Delta->isZero()) {
14165 dbgs() << "SCEV for value " << *I << " changed!\n"
14166 << "Old: " << *OldSCEV << "\n"
14167 << "New: " << *NewSCEV << "\n"
14168 << "Delta: " << *Delta << "\n";
14169 std::abort();
14170 }
14171 }
14172 }
14173
14174 for (const auto &KV : ExprValueMap) {
14175 for (Value *V : KV.second) {
14176 auto It = ValueExprMap.find_as(V);
14177 if (It == ValueExprMap.end()) {
14178 dbgs() << "Value " << *V
14179 << " is in ExprValueMap but not in ValueExprMap\n";
14180 std::abort();
14181 }
14182 if (It->second != KV.first) {
14183 dbgs() << "Value " << *V << " mapped to " << *It->second
14184 << " rather than " << *KV.first << "\n";
14185 std::abort();
14186 }
14187 }
14188 }
14189
14190 // Verify integrity of SCEV users.
14191 for (const auto &S : UniqueSCEVs) {
14192 for (const auto *Op : S.operands()) {
14193 // We do not store dependencies of constants.
14194 if (isa<SCEVConstant>(Op))
14195 continue;
14196 auto It = SCEVUsers.find(Op);
14197 if (It != SCEVUsers.end() && It->second.count(&S))
14198 continue;
14199 dbgs() << "Use of operand " << *Op << " by user " << S
14200 << " is not being tracked!\n";
14201 std::abort();
14202 }
14203 }
14204
14205 // Verify integrity of ValuesAtScopes users.
14206 for (const auto &ValueAndVec : ValuesAtScopes) {
14207 const SCEV *Value = ValueAndVec.first;
14208 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14209 const Loop *L = LoopAndValueAtScope.first;
14210 const SCEV *ValueAtScope = LoopAndValueAtScope.second;
14211 if (!isa<SCEVConstant>(ValueAtScope)) {
14212 auto It = ValuesAtScopesUsers.find(ValueAtScope);
14213 if (It != ValuesAtScopesUsers.end() &&
14214 is_contained(It->second, std::make_pair(L, Value)))
14215 continue;
14216 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14217 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14218 std::abort();
14219 }
14220 }
14221 }
14222
14223 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14224 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14225 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14226 const Loop *L = LoopAndValue.first;
14227 const SCEV *Value = LoopAndValue.second;
14228 assert(!isa<SCEVConstant>(Value))(static_cast <bool> (!isa<SCEVConstant>(Value)) ?
void (0) : __assert_fail ("!isa<SCEVConstant>(Value)",
"llvm/lib/Analysis/ScalarEvolution.cpp", 14228, __extension__
__PRETTY_FUNCTION__))
;
14229 auto It = ValuesAtScopes.find(Value);
14230 if (It != ValuesAtScopes.end() &&
14231 is_contained(It->second, std::make_pair(L, ValueAtScope)))
14232 continue;
14233 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14234 << *ValueAtScope << " missing in ValuesAtScopes\n";
14235 std::abort();
14236 }
14237 }
14238
14239 // Verify integrity of BECountUsers.
14240 auto VerifyBECountUsers = [&](bool Predicated) {
14241 auto &BECounts =
14242 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14243 for (const auto &LoopAndBEInfo : BECounts) {
14244 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
14245 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14246 if (!isa<SCEVConstant>(S)) {
14247 auto UserIt = BECountUsers.find(S);
14248 if (UserIt != BECountUsers.end() &&
14249 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
14250 continue;
14251 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
14252 << " missing from BECountUsers\n";
14253 std::abort();
14254 }
14255 }
14256 }
14257 }
14258 };
14259 VerifyBECountUsers(/* Predicated */ false);
14260 VerifyBECountUsers(/* Predicated */ true);
14261
14262 // Verify intergity of loop disposition cache.
14263 for (auto &[S, Values] : LoopDispositions) {
14264 for (auto [Loop, CachedDisposition] : Values) {
14265 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
14266 if (CachedDisposition != RecomputedDisposition) {
14267 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
14268 << " is incorrect: cached "
14269 << loopDispositionToStr(CachedDisposition) << ", actual "
14270 << loopDispositionToStr(RecomputedDisposition) << "\n";
14271 std::abort();
14272 }
14273 }
14274 }
14275
14276 // Verify integrity of the block disposition cache.
14277 for (auto &[S, Values] : BlockDispositions) {
14278 for (auto [BB, CachedDisposition] : Values) {
14279 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
14280 if (CachedDisposition != RecomputedDisposition) {
14281 dbgs() << "Cached disposition of " << *S << " for block %"
14282 << BB->getName() << " is incorrect! \n";
14283 std::abort();
14284 }
14285 }
14286 }
14287
14288 // Verify FoldCache/FoldCacheUser caches.
14289 for (auto [FoldID, Expr] : FoldCache) {
14290 auto I = FoldCacheUser.find(Expr);
14291 if (I == FoldCacheUser.end()) {
14292 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
14293 << "!\n";
14294 std::abort();
14295 }
14296 if (!is_contained(I->second, FoldID)) {
14297 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
14298 std::abort();
14299 }
14300 }
14301 for (auto [Expr, IDs] : FoldCacheUser) {
14302 for (auto &FoldID : IDs) {
14303 auto I = FoldCache.find(FoldID);
14304 if (I == FoldCache.end()) {
14305 dbgs() << "Missing entry in FoldCache for expression " << *Expr
14306 << "!\n";
14307 std::abort();
14308 }
14309 if (I->second != Expr) {
14310 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: "
14311 << *I->second << " != " << *Expr << "!\n";
14312 std::abort();
14313 }
14314 }
14315 }
14316
14317 // Verify that ConstantMultipleCache computations are correct. It is possible
14318 // that a recomputed multiple has a higher multiple than the cached multiple
14319 // due to strengthened wrap flags. In this case, the cached multiple is a
14320 // conservative, but still correct if it divides the recomputed multiple. As
14321 // a special case, if if one multiple is zero, the other must also be zero.
14322 for (auto [S, Multiple] : ConstantMultipleCache) {
14323 APInt RecomputedMultiple = SE2.getConstantMultipleImpl(S);
14324 if ((Multiple != RecomputedMultiple &&
14325 (Multiple == 0 || RecomputedMultiple == 0)) &&
14326 RecomputedMultiple.urem(Multiple) != 0) {
14327 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
14328 << *S << " : Computed " << RecomputedMultiple
14329 << " but cache contains " << Multiple << "!\n";
14330 std::abort();
14331 }
14332 }
14333}
14334
14335bool ScalarEvolution::invalidate(
14336 Function &F, const PreservedAnalyses &PA,
14337 FunctionAnalysisManager::Invalidator &Inv) {
14338 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
14339 // of its dependencies is invalidated.
14340 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
14341 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
14342 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
14343 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
14344 Inv.invalidate<LoopAnalysis>(F, PA);
14345}
14346
14347AnalysisKey ScalarEvolutionAnalysis::Key;
14348
14349ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
14350 FunctionAnalysisManager &AM) {
14351 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
14352 auto &AC = AM.getResult<AssumptionAnalysis>(F);
14353 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
14354 auto &LI = AM.getResult<LoopAnalysis>(F);
14355 return ScalarEvolution(F, TLI, AC, DT, LI);
14356}
14357
14358PreservedAnalyses
14359ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
14360 AM.getResult<ScalarEvolutionAnalysis>(F).verify();
14361 return PreservedAnalyses::all();
14362}
14363
14364PreservedAnalyses
14365ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
14366 // For compatibility with opt's -analyze feature under legacy pass manager
14367 // which was not ported to NPM. This keeps tests using
14368 // update_analyze_test_checks.py working.
14369 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
14370 << F.getName() << "':\n";
14371 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
14372 return PreservedAnalyses::all();
14373}
14374
14375INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",static void *initializeScalarEvolutionWrapperPassPassOnce(PassRegistry
&Registry) {
14376 "Scalar Evolution Analysis", false, true)static void *initializeScalarEvolutionWrapperPassPassOnce(PassRegistry
&Registry) {
14377INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry);
14378INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)initializeLoopInfoWrapperPassPass(Registry);
14379INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)initializeDominatorTreeWrapperPassPass(Registry);
14380INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
14381INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",PassInfo *PI = new PassInfo( "Scalar Evolution Analysis", "scalar-evolution"
, &ScalarEvolutionWrapperPass::ID, PassInfo::NormalCtor_t
(callDefaultCtor<ScalarEvolutionWrapperPass>), false, true
); Registry.registerPass(*PI, true); return PI; } static llvm
::once_flag InitializeScalarEvolutionWrapperPassPassFlag; void
llvm::initializeScalarEvolutionWrapperPassPass(PassRegistry &
Registry) { llvm::call_once(InitializeScalarEvolutionWrapperPassPassFlag
, initializeScalarEvolutionWrapperPassPassOnce, std::ref(Registry
)); }
14382 "Scalar Evolution Analysis", false, true)PassInfo *PI = new PassInfo( "Scalar Evolution Analysis", "scalar-evolution"
, &ScalarEvolutionWrapperPass::ID, PassInfo::NormalCtor_t
(callDefaultCtor<ScalarEvolutionWrapperPass>), false, true
); Registry.registerPass(*PI, true); return PI; } static llvm
::once_flag InitializeScalarEvolutionWrapperPassPassFlag; void
llvm::initializeScalarEvolutionWrapperPassPass(PassRegistry &
Registry) { llvm::call_once(InitializeScalarEvolutionWrapperPassPassFlag
, initializeScalarEvolutionWrapperPassPassOnce, std::ref(Registry
)); }
14383
14384char ScalarEvolutionWrapperPass::ID = 0;
14385
14386ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
14387 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
14388}
14389
14390bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
14391 SE.reset(new ScalarEvolution(
14392 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
14393 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
14394 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
14395 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
14396 return false;
14397}
14398
14399void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
14400
14401void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
14402 SE->print(OS);
14403}
14404
14405void ScalarEvolutionWrapperPass::verifyAnalysis() const {
14406 if (!VerifySCEV)
14407 return;
14408
14409 SE->verify();
14410}
14411
14412void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
14413 AU.setPreservesAll();
14414 AU.addRequiredTransitive<AssumptionCacheTracker>();
14415 AU.addRequiredTransitive<LoopInfoWrapperPass>();
14416 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
14417 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
14418}
14419
14420const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
14421 const SCEV *RHS) {
14422 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
14423}
14424
14425const SCEVPredicate *
14426ScalarEvolution::getComparePredicate(const ICmpInst::Predicate Pred,
14427 const SCEV *LHS, const SCEV *RHS) {
14428 FoldingSetNodeID ID;
14429 assert(LHS->getType() == RHS->getType() &&(static_cast <bool> (LHS->getType() == RHS->getType
() && "Type mismatch between LHS and RHS") ? void (0)
: __assert_fail ("LHS->getType() == RHS->getType() && \"Type mismatch between LHS and RHS\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 14430, __extension__
__PRETTY_FUNCTION__))
14430 "Type mismatch between LHS and RHS")(static_cast <bool> (LHS->getType() == RHS->getType
() && "Type mismatch between LHS and RHS") ? void (0)
: __assert_fail ("LHS->getType() == RHS->getType() && \"Type mismatch between LHS and RHS\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 14430, __extension__
__PRETTY_FUNCTION__))
;
14431 // Unique this node based on the arguments
14432 ID.AddInteger(SCEVPredicate::P_Compare);
14433 ID.AddInteger(Pred);
14434 ID.AddPointer(LHS);
14435 ID.AddPointer(RHS);
14436 void *IP = nullptr;
14437 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
14438 return S;
14439 SCEVComparePredicate *Eq = new (SCEVAllocator)
14440 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
14441 UniquePreds.InsertNode(Eq, IP);
14442 return Eq;
14443}
14444
14445const SCEVPredicate *ScalarEvolution::getWrapPredicate(
14446 const SCEVAddRecExpr *AR,
14447 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
14448 FoldingSetNodeID ID;
14449 // Unique this node based on the arguments
14450 ID.AddInteger(SCEVPredicate::P_Wrap);
14451 ID.AddPointer(AR);
14452 ID.AddInteger(AddedFlags);
14453 void *IP = nullptr;
14454 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
14455 return S;
14456 auto *OF = new (SCEVAllocator)
14457 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
14458 UniquePreds.InsertNode(OF, IP);
14459 return OF;
14460}
14461
14462namespace {
14463
14464class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
14465public:
14466
14467 /// Rewrites \p S in the context of a loop L and the SCEV predication
14468 /// infrastructure.
14469 ///
14470 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
14471 /// equivalences present in \p Pred.
14472 ///
14473 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
14474 /// \p NewPreds such that the result will be an AddRecExpr.
14475 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
14476 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
14477 const SCEVPredicate *Pred) {
14478 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
14479 return Rewriter.visit(S);
14480 }
14481
14482 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14483 if (Pred) {
14484 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
14485 for (const auto *Pred : U->getPredicates())
14486 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
14487 if (IPred->getLHS() == Expr &&
14488 IPred->getPredicate() == ICmpInst::ICMP_EQ)
14489 return IPred->getRHS();
14490 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
14491 if (IPred->getLHS() == Expr &&
14492 IPred->getPredicate() == ICmpInst::ICMP_EQ)
14493 return IPred->getRHS();
14494 }
14495 }
14496 return convertToAddRecWithPreds(Expr);
14497 }
14498
14499 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
14500 const SCEV *Operand = visit(Expr->getOperand());
14501 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
14502 if (AR && AR->getLoop() == L && AR->isAffine()) {
14503 // This couldn't be folded because the operand didn't have the nuw
14504 // flag. Add the nusw flag as an assumption that we could make.
14505 const SCEV *Step = AR->getStepRecurrence(SE);
14506 Type *Ty = Expr->getType();
14507 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
14508 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
14509 SE.getSignExtendExpr(Step, Ty), L,
14510 AR->getNoWrapFlags());
14511 }
14512 return SE.getZeroExtendExpr(Operand, Expr->getType());
14513 }
14514
14515 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
14516 const SCEV *Operand = visit(Expr->getOperand());
14517 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
14518 if (AR && AR->getLoop() == L && AR->isAffine()) {
14519 // This couldn't be folded because the operand didn't have the nsw
14520 // flag. Add the nssw flag as an assumption that we could make.
14521 const SCEV *Step = AR->getStepRecurrence(SE);
14522 Type *Ty = Expr->getType();
14523 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
14524 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
14525 SE.getSignExtendExpr(Step, Ty), L,
14526 AR->getNoWrapFlags());
14527 }
14528 return SE.getSignExtendExpr(Operand, Expr->getType());
14529 }
14530
14531private:
14532 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
14533 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
14534 const SCEVPredicate *Pred)
14535 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
14536
14537 bool addOverflowAssumption(const SCEVPredicate *P) {
14538 if (!NewPreds) {
14539 // Check if we've already made this assumption.
14540 return Pred && Pred->implies(P);
14541 }
14542 NewPreds->insert(P);
14543 return true;
14544 }
14545
14546 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
14547 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
14548 auto *A = SE.getWrapPredicate(AR, AddedFlags);
14549 return addOverflowAssumption(A);
14550 }
14551
14552 // If \p Expr represents a PHINode, we try to see if it can be represented
14553 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
14554 // to add this predicate as a runtime overflow check, we return the AddRec.
14555 // If \p Expr does not meet these conditions (is not a PHI node, or we
14556 // couldn't create an AddRec for it, or couldn't add the predicate), we just
14557 // return \p Expr.
14558 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
14559 if (!isa<PHINode>(Expr->getValue()))
14560 return Expr;
14561 std::optional<
14562 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
14563 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
14564 if (!PredicatedRewrite)
14565 return Expr;
14566 for (const auto *P : PredicatedRewrite->second){
14567 // Wrap predicates from outer loops are not supported.
14568 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
14569 if (L != WP->getExpr()->getLoop())
14570 return Expr;
14571 }
14572 if (!addOverflowAssumption(P))
14573 return Expr;
14574 }
14575 return PredicatedRewrite->first;
14576 }
14577
14578 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
14579 const SCEVPredicate *Pred;
14580 const Loop *L;
14581};
14582
14583} // end anonymous namespace
14584
14585const SCEV *
14586ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
14587 const SCEVPredicate &Preds) {
14588 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
14589}
14590
14591const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
14592 const SCEV *S, const Loop *L,
14593 SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
14594 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
14595 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
14596 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
14597
14598 if (!AddRec)
14599 return nullptr;
14600
14601 // Since the transformation was successful, we can now transfer the SCEV
14602 // predicates.
14603 for (const auto *P : TransformPreds)
14604 Preds.insert(P);
14605
14606 return AddRec;
14607}
14608
14609/// SCEV predicates
14610SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
14611 SCEVPredicateKind Kind)
14612 : FastID(ID), Kind(Kind) {}
14613
14614SCEVComparePredicate::SCEVComparePredicate(const FoldingSetNodeIDRef ID,
14615 const ICmpInst::Predicate Pred,
14616 const SCEV *LHS, const SCEV *RHS)
14617 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
14618 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match")(static_cast <bool> (LHS->getType() == RHS->getType
() && "LHS and RHS types don't match") ? void (0) : __assert_fail
("LHS->getType() == RHS->getType() && \"LHS and RHS types don't match\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 14618, __extension__
__PRETTY_FUNCTION__))
;
14619 assert(LHS != RHS && "LHS and RHS are the same SCEV")(static_cast <bool> (LHS != RHS && "LHS and RHS are the same SCEV"
) ? void (0) : __assert_fail ("LHS != RHS && \"LHS and RHS are the same SCEV\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 14619, __extension__
__PRETTY_FUNCTION__))
;
14620}
14621
14622bool SCEVComparePredicate::implies(const SCEVPredicate *N) const {
14623 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
14624
14625 if (!Op)
14626 return false;
14627
14628 if (Pred != ICmpInst::ICMP_EQ)
14629 return false;
14630
14631 return Op->LHS == LHS && Op->RHS == RHS;
14632}
14633
14634bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
14635
14636void SCEVComparePredicate::print(raw_ostream &OS, unsigned Depth) const {
14637 if (Pred == ICmpInst::ICMP_EQ)
14638 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
14639 else
14640 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
14641 << *RHS << "\n";
14642
14643}
14644
14645SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
14646 const SCEVAddRecExpr *AR,
14647 IncrementWrapFlags Flags)
14648 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
14649
14650const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
14651
14652bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
14653 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
14654
14655 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
14656}
14657
14658bool SCEVWrapPredicate::isAlwaysTrue() const {
14659 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
14660 IncrementWrapFlags IFlags = Flags;
14661
14662 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
14663 IFlags = clearFlags(IFlags, IncrementNSSW);
14664
14665 return IFlags == IncrementAnyWrap;
14666}
14667
14668void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
14669 OS.indent(Depth) << *getExpr() << " Added Flags: ";
14670 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
14671 OS << "<nusw>";
14672 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
14673 OS << "<nssw>";
14674 OS << "\n";
14675}
14676
14677SCEVWrapPredicate::IncrementWrapFlags
14678SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
14679 ScalarEvolution &SE) {
14680 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
14681 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
14682
14683 // We can safely transfer the NSW flag as NSSW.
14684 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
14685 ImpliedFlags = IncrementNSSW;
14686
14687 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
14688 // If the increment is positive, the SCEV NUW flag will also imply the
14689 // WrapPredicate NUSW flag.
14690 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
14691 if (Step->getValue()->getValue().isNonNegative())
14692 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
14693 }
14694
14695 return ImpliedFlags;
14696}
14697
14698/// Union predicates don't get cached so create a dummy set ID for it.
14699SCEVUnionPredicate::SCEVUnionPredicate(ArrayRef<const SCEVPredicate *> Preds)
14700 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {
14701 for (const auto *P : Preds)
14702 add(P);
14703}
14704
14705bool SCEVUnionPredicate::isAlwaysTrue() const {
14706 return all_of(Preds,
14707 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
14708}
14709
14710bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
14711 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
14712 return all_of(Set->Preds,
14713 [this](const SCEVPredicate *I) { return this->implies(I); });
14714
14715 return any_of(Preds,
14716 [N](const SCEVPredicate *I) { return I->implies(N); });
14717}
14718
14719void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
14720 for (const auto *Pred : Preds)
14721 Pred->print(OS, Depth);
14722}
14723
14724void SCEVUnionPredicate::add(const SCEVPredicate *N) {
14725 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
14726 for (const auto *Pred : Set->Preds)
14727 add(Pred);
14728 return;
14729 }
14730
14731 Preds.push_back(N);
14732}
14733
14734PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
14735 Loop &L)
14736 : SE(SE), L(L) {
14737 SmallVector<const SCEVPredicate*, 4> Empty;
14738 Preds = std::make_unique<SCEVUnionPredicate>(Empty);
14739}
14740
14741void ScalarEvolution::registerUser(const SCEV *User,
14742 ArrayRef<const SCEV *> Ops) {
14743 for (const auto *Op : Ops)
14744 // We do not expect that forgetting cached data for SCEVConstants will ever
14745 // open any prospects for sharpening or introduce any correctness issues,
14746 // so we don't bother storing their dependencies.
14747 if (!isa<SCEVConstant>(Op))
14748 SCEVUsers[Op].insert(User);
14749}
14750
14751const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
14752 const SCEV *Expr = SE.getSCEV(V);
14753 RewriteEntry &Entry = RewriteMap[Expr];
14754
14755 // If we already have an entry and the version matches, return it.
14756 if (Entry.second && Generation == Entry.first)
14757 return Entry.second;
14758
14759 // We found an entry but it's stale. Rewrite the stale entry
14760 // according to the current predicate.
14761 if (Entry.second)
14762 Expr = Entry.second;
14763
14764 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
14765 Entry = {Generation, NewSCEV};
14766
14767 return NewSCEV;
14768}
14769
14770const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
14771 if (!BackedgeCount) {
14772 SmallVector<const SCEVPredicate *, 4> Preds;
14773 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
14774 for (const auto *P : Preds)
14775 addPredicate(*P);
14776 }
14777 return BackedgeCount;
14778}
14779
14780void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
14781 if (Preds->implies(&Pred))
14782 return;
14783
14784 auto &OldPreds = Preds->getPredicates();
14785 SmallVector<const SCEVPredicate*, 4> NewPreds(OldPreds.begin(), OldPreds.end());
14786 NewPreds.push_back(&Pred);
14787 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds);
14788 updateGeneration();
14789}
14790
14791const SCEVPredicate &PredicatedScalarEvolution::getPredicate() const {
14792 return *Preds;
14793}
14794
14795void PredicatedScalarEvolution::updateGeneration() {
14796 // If the generation number wrapped recompute everything.
14797 if (++Generation == 0) {
14798 for (auto &II : RewriteMap) {
14799 const SCEV *Rewritten = II.second.second;
14800 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
14801 }
14802 }
14803}
14804
14805void PredicatedScalarEvolution::setNoOverflow(
14806 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14807 const SCEV *Expr = getSCEV(V);
14808 const auto *AR = cast<SCEVAddRecExpr>(Expr);
14809
14810 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
14811
14812 // Clear the statically implied flags.
14813 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
14814 addPredicate(*SE.getWrapPredicate(AR, Flags));
14815
14816 auto II = FlagsMap.insert({V, Flags});
14817 if (!II.second)
14818 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
14819}
14820
14821bool PredicatedScalarEvolution::hasNoOverflow(
14822 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
14823 const SCEV *Expr = getSCEV(V);
14824 const auto *AR = cast<SCEVAddRecExpr>(Expr);
14825
14826 Flags = SCEVWrapPredicate::clearFlags(
14827 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
14828
14829 auto II = FlagsMap.find(V);
14830
14831 if (II != FlagsMap.end())
14832 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
14833
14834 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
14835}
14836
14837const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
14838 const SCEV *Expr = this->getSCEV(V);
14839 SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
14840 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
14841
14842 if (!New)
14843 return nullptr;
14844
14845 for (const auto *P : NewPreds)
14846 addPredicate(*P);
14847
14848 RewriteMap[SE.getSCEV(V)] = {Generation, New};
14849 return New;
14850}
14851
14852PredicatedScalarEvolution::PredicatedScalarEvolution(
14853 const PredicatedScalarEvolution &Init)
14854 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
14855 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates())),
14856 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
14857 for (auto I : Init.FlagsMap)
14858 FlagsMap.insert(I);
14859}
14860
14861void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
14862 // For each block.
14863 for (auto *BB : L.getBlocks())
14864 for (auto &I : *BB) {
14865 if (!SE.isSCEVable(I.getType()))
14866 continue;
14867
14868 auto *Expr = SE.getSCEV(&I);
14869 auto II = RewriteMap.find(Expr);
14870
14871 if (II == RewriteMap.end())
14872 continue;
14873
14874 // Don't print things that are not interesting.
14875 if (II->second.second == Expr)
14876 continue;
14877
14878 OS.indent(Depth) << "[PSE]" << I << ":\n";
14879 OS.indent(Depth + 2) << *Expr << "\n";
14880 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
14881 }
14882}
14883
14884// Match the mathematical pattern A - (A / B) * B, where A and B can be
14885// arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
14886// for URem with constant power-of-2 second operands.
14887// It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
14888// 4, A / B becomes X / 8).
14889bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
14890 const SCEV *&RHS) {
14891 // Try to match 'zext (trunc A to iB) to iY', which is used
14892 // for URem with constant power-of-2 second operands. Make sure the size of
14893 // the operand A matches the size of the whole expressions.
14894 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
14895 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
14896 LHS = Trunc->getOperand();
14897 // Bail out if the type of the LHS is larger than the type of the
14898 // expression for now.
14899 if (getTypeSizeInBits(LHS->getType()) >
14900 getTypeSizeInBits(Expr->getType()))
14901 return false;
14902 if (LHS->getType() != Expr->getType())
14903 LHS = getZeroExtendExpr(LHS, Expr->getType());
14904 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
14905 << getTypeSizeInBits(Trunc->getType()));
14906 return true;
14907 }
14908 const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
14909 if (Add == nullptr || Add->getNumOperands() != 2)
14910 return false;
14911
14912 const SCEV *A = Add->getOperand(1);
14913 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
14914
14915 if (Mul == nullptr)
14916 return false;
14917
14918 const auto MatchURemWithDivisor = [&](const SCEV *B) {
14919 // (SomeExpr + (-(SomeExpr / B) * B)).
14920 if (Expr == getURemExpr(A, B)) {
14921 LHS = A;
14922 RHS = B;
14923 return true;
14924 }
14925 return false;
14926 };
14927
14928 // (SomeExpr + (-1 * (SomeExpr / B) * B)).
14929 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
14930 return MatchURemWithDivisor(Mul->getOperand(1)) ||
14931 MatchURemWithDivisor(Mul->getOperand(2));
14932
14933 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
14934 if (Mul->getNumOperands() == 2)
14935 return MatchURemWithDivisor(Mul->getOperand(1)) ||
14936 MatchURemWithDivisor(Mul->getOperand(0)) ||
14937 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
14938 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
14939 return false;
14940}
14941
14942const SCEV *
14943ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
14944 SmallVector<BasicBlock*, 16> ExitingBlocks;
14945 L->getExitingBlocks(ExitingBlocks);
14946
14947 // Form an expression for the maximum exit count possible for this loop. We
14948 // merge the max and exact information to approximate a version of
14949 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
14950 SmallVector<const SCEV*, 4> ExitCounts;
14951 for (BasicBlock *ExitingBB : ExitingBlocks) {
14952 const SCEV *ExitCount =
14953 getExitCount(L, ExitingBB, ScalarEvolution::SymbolicMaximum);
14954 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
14955 assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&(static_cast <bool> (DT.dominates(ExitingBB, L->getLoopLatch
()) && "We should only have known counts for exiting blocks that "
"dominate latch!") ? void (0) : __assert_fail ("DT.dominates(ExitingBB, L->getLoopLatch()) && \"We should only have known counts for exiting blocks that \" \"dominate latch!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 14957, __extension__
__PRETTY_FUNCTION__))
14956 "We should only have known counts for exiting blocks that "(static_cast <bool> (DT.dominates(ExitingBB, L->getLoopLatch
()) && "We should only have known counts for exiting blocks that "
"dominate latch!") ? void (0) : __assert_fail ("DT.dominates(ExitingBB, L->getLoopLatch()) && \"We should only have known counts for exiting blocks that \" \"dominate latch!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 14957, __extension__
__PRETTY_FUNCTION__))
14957 "dominate latch!")(static_cast <bool> (DT.dominates(ExitingBB, L->getLoopLatch
()) && "We should only have known counts for exiting blocks that "
"dominate latch!") ? void (0) : __assert_fail ("DT.dominates(ExitingBB, L->getLoopLatch()) && \"We should only have known counts for exiting blocks that \" \"dominate latch!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 14957, __extension__
__PRETTY_FUNCTION__))
;
14958 ExitCounts.push_back(ExitCount);
14959 }
14960 }
14961 if (ExitCounts.empty())
14962 return getCouldNotCompute();
14963 return getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
14964}
14965
14966/// A rewriter to replace SCEV expressions in Map with the corresponding entry
14967/// in the map. It skips AddRecExpr because we cannot guarantee that the
14968/// replacement is loop invariant in the loop of the AddRec.
14969class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
14970 const DenseMap<const SCEV *, const SCEV *> &Map;
14971
14972public:
14973 SCEVLoopGuardRewriter(ScalarEvolution &SE,
14974 DenseMap<const SCEV *, const SCEV *> &M)
14975 : SCEVRewriteVisitor(SE), Map(M) {}
14976
14977 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
14978
14979 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14980 auto I = Map.find(Expr);
14981 if (I == Map.end())
14982 return Expr;
14983 return I->second;
14984 }
14985
14986 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
14987 auto I = Map.find(Expr);
14988 if (I == Map.end())
14989 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr(
14990 Expr);
14991 return I->second;
14992 }
14993
14994 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
14995 auto I = Map.find(Expr);
14996 if (I == Map.end())
14997 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitSignExtendExpr(
14998 Expr);
14999 return I->second;
15000 }
15001
15002 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
15003 auto I = Map.find(Expr);
15004 if (I == Map.end())
15005 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitUMinExpr(Expr);
15006 return I->second;
15007 }
15008
15009 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
15010 auto I = Map.find(Expr);
15011 if (I == Map.end())
15012 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitSMinExpr(Expr);
15013 return I->second;
15014 }
15015};
15016
15017const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
15018 SmallVector<const SCEV *> ExprsToRewrite;
15019 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
15020 const SCEV *RHS,
15021 DenseMap<const SCEV *, const SCEV *>
15022 &RewriteMap) {
15023 // WARNING: It is generally unsound to apply any wrap flags to the proposed
15024 // replacement SCEV which isn't directly implied by the structure of that
15025 // SCEV. In particular, using contextual facts to imply flags is *NOT*
15026 // legal. See the scoping rules for flags in the header to understand why.
15027
15028 // If LHS is a constant, apply information to the other expression.
15029 if (isa<SCEVConstant>(LHS)) {
15030 std::swap(LHS, RHS);
15031 Predicate = CmpInst::getSwappedPredicate(Predicate);
15032 }
15033
15034 // Check for a condition of the form (-C1 + X < C2). InstCombine will
15035 // create this form when combining two checks of the form (X u< C2 + C1) and
15036 // (X >=u C1).
15037 auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap,
15038 &ExprsToRewrite]() {
15039 auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS);
15040 if (!AddExpr || AddExpr->getNumOperands() != 2)
15041 return false;
15042
15043 auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0));
15044 auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1));
15045 auto *C2 = dyn_cast<SCEVConstant>(RHS);
15046 if (!C1 || !C2 || !LHSUnknown)
15047 return false;
15048
15049 auto ExactRegion =
15050 ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt())
15051 .sub(C1->getAPInt());
15052
15053 // Bail out, unless we have a non-wrapping, monotonic range.
15054 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
15055 return false;
15056 auto I = RewriteMap.find(LHSUnknown);
15057 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown;
15058 RewriteMap[LHSUnknown] = getUMaxExpr(
15059 getConstant(ExactRegion.getUnsignedMin()),
15060 getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax())));
15061 ExprsToRewrite.push_back(LHSUnknown);
15062 return true;
15063 };
15064 if (MatchRangeCheckIdiom())
15065 return;
15066
15067 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
15068 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
15069 // the non-constant operand and in \p LHS the constant operand.
15070 auto IsMinMaxSCEVWithNonNegativeConstant =
15071 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
15072 const SCEV *&RHS) {
15073 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15074 if (MinMax->getNumOperands() != 2)
15075 return false;
15076 if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
15077 if (C->getAPInt().isNegative())
15078 return false;
15079 SCTy = MinMax->getSCEVType();
15080 LHS = MinMax->getOperand(0);
15081 RHS = MinMax->getOperand(1);
15082 return true;
15083 }
15084 }
15085 return false;
15086 };
15087
15088 // Checks whether Expr is a non-negative constant, and Divisor is a positive
15089 // constant, and returns their APInt in ExprVal and in DivisorVal.
15090 auto GetNonNegExprAndPosDivisor = [&](const SCEV *Expr, const SCEV *Divisor,
15091 APInt &ExprVal, APInt &DivisorVal) {
15092 auto *ConstExpr = dyn_cast<SCEVConstant>(Expr);
15093 auto *ConstDivisor = dyn_cast<SCEVConstant>(Divisor);
15094 if (!ConstExpr || !ConstDivisor)
15095 return false;
15096 ExprVal = ConstExpr->getAPInt();
15097 DivisorVal = ConstDivisor->getAPInt();
15098 return ExprVal.isNonNegative() && !DivisorVal.isNonPositive();
15099 };
15100
15101 // Return a new SCEV that modifies \p Expr to the closest number divides by
15102 // \p Divisor and greater or equal than Expr.
15103 // For now, only handle constant Expr and Divisor.
15104 auto GetNextSCEVDividesByDivisor = [&](const SCEV *Expr,
15105 const SCEV *Divisor) {
15106 APInt ExprVal;
15107 APInt DivisorVal;
15108 if (!GetNonNegExprAndPosDivisor(Expr, Divisor, ExprVal, DivisorVal))
15109 return Expr;
15110 APInt Rem = ExprVal.urem(DivisorVal);
15111 if (!Rem.isZero())
15112 // return the SCEV: Expr + Divisor - Expr % Divisor
15113 return getConstant(ExprVal + DivisorVal - Rem);
15114 return Expr;
15115 };
15116
15117 // Return a new SCEV that modifies \p Expr to the closest number divides by
15118 // \p Divisor and less or equal than Expr.
15119 // For now, only handle constant Expr and Divisor.
15120 auto GetPreviousSCEVDividesByDivisor = [&](const SCEV *Expr,
15121 const SCEV *Divisor) {
15122 APInt ExprVal;
15123 APInt DivisorVal;
15124 if (!GetNonNegExprAndPosDivisor(Expr, Divisor, ExprVal, DivisorVal))
15125 return Expr;
15126 APInt Rem = ExprVal.urem(DivisorVal);
15127 // return the SCEV: Expr - Expr % Divisor
15128 return getConstant(ExprVal - Rem);
15129 };
15130
15131 // Apply divisibilty by \p Divisor on MinMaxExpr with constant values,
15132 // recursively. This is done by aligning up/down the constant value to the
15133 // Divisor.
15134 std::function<const SCEV *(const SCEV *, const SCEV *)>
15135 ApplyDivisibiltyOnMinMaxExpr = [&](const SCEV *MinMaxExpr,
15136 const SCEV *Divisor) {
15137 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15138 SCEVTypes SCTy;
15139 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15140 MinMaxRHS))
15141 return MinMaxExpr;
15142 auto IsMin =
15143 isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
15144 assert(isKnownNonNegative(MinMaxLHS) &&(static_cast <bool> (isKnownNonNegative(MinMaxLHS) &&
"Expected non-negative operand!") ? void (0) : __assert_fail
("isKnownNonNegative(MinMaxLHS) && \"Expected non-negative operand!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 15145, __extension__
__PRETTY_FUNCTION__))
15145 "Expected non-negative operand!")(static_cast <bool> (isKnownNonNegative(MinMaxLHS) &&
"Expected non-negative operand!") ? void (0) : __assert_fail
("isKnownNonNegative(MinMaxLHS) && \"Expected non-negative operand!\""
, "llvm/lib/Analysis/ScalarEvolution.cpp", 15145, __extension__
__PRETTY_FUNCTION__))
;
15146 auto *DivisibleExpr =
15147 IsMin ? GetPreviousSCEVDividesByDivisor(MinMaxLHS, Divisor)
15148 : GetNextSCEVDividesByDivisor(MinMaxLHS, Divisor);
15149 SmallVector<const SCEV *> Ops = {
15150 ApplyDivisibiltyOnMinMaxExpr(MinMaxRHS, Divisor), DivisibleExpr};
15151 return getMinMaxExpr(SCTy, Ops);
15152 };
15153
15154 // If we have LHS == 0, check if LHS is computing a property of some unknown
15155 // SCEV %v which we can rewrite %v to express explicitly.
15156 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
15157 if (Predicate == CmpInst::ICMP_EQ && RHSC &&
15158 RHSC->getValue()->isNullValue()) {
15159 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15160 // explicitly express that.
15161 const SCEV *URemLHS = nullptr;
15162 const SCEV *URemRHS = nullptr;
15163 if (matchURem(LHS, URemLHS, URemRHS)) {
15164 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
15165 auto I = RewriteMap.find(LHSUnknown);
15166 const SCEV *RewrittenLHS =
15167 I != RewriteMap.end() ? I->second : LHSUnknown;
15168 RewrittenLHS = ApplyDivisibiltyOnMinMaxExpr(RewrittenLHS, URemRHS);
15169 const auto *Multiple =
15170 getMulExpr(getUDivExpr(RewrittenLHS, URemRHS), URemRHS);
15171 RewriteMap[LHSUnknown] = Multiple;
15172 ExprsToRewrite.push_back(LHSUnknown);
15173 return;
15174 }
15175 }
15176 }
15177
15178 // Do not apply information for constants or if RHS contains an AddRec.
15179 if (isa<SCEVConstant>(LHS) || containsAddRecurrence(RHS))
15180 return;
15181
15182 // If RHS is SCEVUnknown, make sure the information is applied to it.
15183 if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) {
15184 std::swap(LHS, RHS);
15185 Predicate = CmpInst::getSwappedPredicate(Predicate);
15186 }
15187
15188 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15189 // and \p FromRewritten are the same (i.e. there has been no rewrite
15190 // registered for \p From), then puts this value in the list of rewritten
15191 // expressions.
15192 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15193 const SCEV *To) {
15194 if (From == FromRewritten)
15195 ExprsToRewrite.push_back(From);
15196 RewriteMap[From] = To;
15197 };
15198
15199 // Checks whether \p S has already been rewritten. In that case returns the
15200 // existing rewrite because we want to chain further rewrites onto the
15201 // already rewritten value. Otherwise returns \p S.
15202 auto GetMaybeRewritten = [&](const SCEV *S) {
15203 auto I = RewriteMap.find(S);
15204 return I != RewriteMap.end() ? I->second : S;
15205 };
15206
15207 // Check for the SCEV expression (A /u B) * B while B is a constant, inside
15208 // \p Expr. The check is done recuresively on \p Expr, which is assumed to
15209 // be a composition of Min/Max SCEVs. Return whether the SCEV expression (A
15210 // /u B) * B was found, and return the divisor B in \p DividesBy. For
15211 // example, if Expr = umin (umax ((A /u 8) * 8, 16), 64), return true since
15212 // (A /u 8) * 8 matched the pattern, and return the constant SCEV 8 in \p
15213 // DividesBy.
15214 std::function<bool(const SCEV *, const SCEV *&)> HasDivisibiltyInfo =
15215 [&](const SCEV *Expr, const SCEV *&DividesBy) {
15216 if (auto *Mul = dyn_cast<SCEVMulExpr>(Expr)) {
15217 if (Mul->getNumOperands() != 2)
15218 return false;
15219 auto *MulLHS = Mul->getOperand(0);
15220 auto *MulRHS = Mul->getOperand(1);
15221 if (isa<SCEVConstant>(MulLHS))
15222 std::swap(MulLHS, MulRHS);
15223 if (auto *Div = dyn_cast<SCEVUDivExpr>(MulLHS))
15224 if (Div->getOperand(1) == MulRHS) {
15225 DividesBy = MulRHS;
15226 return true;
15227 }
15228 }
15229 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr))
15230 return HasDivisibiltyInfo(MinMax->getOperand(0), DividesBy) ||
15231 HasDivisibiltyInfo(MinMax->getOperand(1), DividesBy);
15232 return false;
15233 };
15234
15235 // Return true if Expr known to divide by \p DividesBy.
15236 std::function<bool(const SCEV *, const SCEV *&)> IsKnownToDivideBy =
15237 [&](const SCEV *Expr, const SCEV *DividesBy) {
15238 if (getURemExpr(Expr, DividesBy)->isZero())
15239 return true;
15240 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr))
15241 return IsKnownToDivideBy(MinMax->getOperand(0), DividesBy) &&
15242 IsKnownToDivideBy(MinMax->getOperand(1), DividesBy);
15243 return false;
15244 };
15245
15246 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
15247 const SCEV *DividesBy = nullptr;
15248 if (HasDivisibiltyInfo(RewrittenLHS, DividesBy))
15249 // Check that the whole expression is divided by DividesBy
15250 DividesBy =
15251 IsKnownToDivideBy(RewrittenLHS, DividesBy) ? DividesBy : nullptr;
15252
15253 // Collect rewrites for LHS and its transitive operands based on the
15254 // condition.
15255 // For min/max expressions, also apply the guard to its operands:
15256 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
15257 // 'min(a, b) > c' -> '(a > c) and (b > c)',
15258 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
15259 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
15260
15261 // We cannot express strict predicates in SCEV, so instead we replace them
15262 // with non-strict ones against plus or minus one of RHS depending on the
15263 // predicate.
15264 const SCEV *One = getOne(RHS->getType());
15265 switch (Predicate) {
15266 case CmpInst::ICMP_ULT:
15267 if (RHS->getType()->isPointerTy())
15268 return;
15269 RHS = getUMaxExpr(RHS, One);
15270 LLVM_FALLTHROUGH[[fallthrough]];
15271 case CmpInst::ICMP_SLT: {
15272 RHS = getMinusSCEV(RHS, One);
15273 RHS = DividesBy ? GetPreviousSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15274 break;
15275 }
15276 case CmpInst::ICMP_UGT:
15277 case CmpInst::ICMP_SGT:
15278 RHS = getAddExpr(RHS, One);
15279 RHS = DividesBy ? GetNextSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15280 break;
15281 case CmpInst::ICMP_ULE:
15282 case CmpInst::ICMP_SLE:
15283 RHS = DividesBy ? GetPreviousSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15284 break;
15285 case CmpInst::ICMP_UGE:
15286 case CmpInst::ICMP_SGE:
15287 RHS = DividesBy ? GetNextSCEVDividesByDivisor(RHS, DividesBy) : RHS;
15288 break;
15289 default:
15290 break;
15291 }
15292
15293 SmallVector<const SCEV *, 16> Worklist(1, LHS);
15294 SmallPtrSet<const SCEV *, 16> Visited;
15295
15296 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
15297 append_range(Worklist, S->operands());
15298 };
15299
15300 while (!Worklist.empty()) {
15301 const SCEV *From = Worklist.pop_back_val();
15302 if (isa<SCEVConstant>(From))
15303 continue;
15304 if (!Visited.insert(From).second)
15305 continue;
15306 const SCEV *FromRewritten = GetMaybeRewritten(From);
15307 const SCEV *To = nullptr;
15308
15309 switch (Predicate) {
15310 case CmpInst::ICMP_ULT:
15311 case CmpInst::ICMP_ULE:
15312 To = getUMinExpr(FromRewritten, RHS);
15313 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
15314 EnqueueOperands(UMax);
15315 break;
15316 case CmpInst::ICMP_SLT:
15317 case CmpInst::ICMP_SLE:
15318 To = getSMinExpr(FromRewritten, RHS);
15319 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
15320 EnqueueOperands(SMax);
15321 break;
15322 case CmpInst::ICMP_UGT:
15323 case CmpInst::ICMP_UGE:
15324 To = getUMaxExpr(FromRewritten, RHS);
15325 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
15326 EnqueueOperands(UMin);
15327 break;
15328 case CmpInst::ICMP_SGT:
15329 case CmpInst::ICMP_SGE:
15330 To = getSMaxExpr(FromRewritten, RHS);
15331 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
15332 EnqueueOperands(SMin);
15333 break;
15334 case CmpInst::ICMP_EQ:
15335 if (isa<SCEVConstant>(RHS))
15336 To = RHS;
15337 break;
15338 case CmpInst::ICMP_NE:
15339 if (isa<SCEVConstant>(RHS) &&
15340 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) {
15341 const SCEV *OneAlignedUp =
15342 DividesBy ? GetNextSCEVDividesByDivisor(One, DividesBy) : One;
15343 To = getUMaxExpr(FromRewritten, OneAlignedUp);
15344 }
15345 break;
15346 default:
15347 break;
15348 }
15349
15350 if (To)
15351 AddRewrite(From, FromRewritten, To);
15352 }
15353 };
15354
15355 BasicBlock *Header = L->getHeader();
15356 SmallVector<PointerIntPair<Value *, 1, bool>> Terms;
15357 // First, collect information from assumptions dominating the loop.
15358 for (auto &AssumeVH : AC.assumptions()) {
15359 if (!AssumeVH)
15360 continue;
15361 auto *AssumeI = cast<CallInst>(AssumeVH);
15362 if (!DT.dominates(AssumeI, Header))
15363 continue;
15364 Terms.emplace_back(AssumeI->getOperand(0), true);
15365 }
15366
15367 // Second, collect information from llvm.experimental.guards dominating the loop.
15368 auto *GuardDecl = F.getParent()->getFunction(
15369 Intrinsic::getName(Intrinsic::experimental_guard));
15370 if (GuardDecl)
15371 for (const auto *GU : GuardDecl->users())
15372 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
15373 if (Guard->getFunction() == Header->getParent() && DT.dominates(Guard, Header))
15374 Terms.emplace_back(Guard->getArgOperand(0), true);
15375
15376 // Third, collect conditions from dominating branches. Starting at the loop
15377 // predecessor, climb up the predecessor chain, as long as there are
15378 // predecessors that can be found that have unique successors leading to the
15379 // original header.
15380 // TODO: share this logic with isLoopEntryGuardedByCond.
15381 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
15382 L->getLoopPredecessor(), Header);
15383 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
15384
15385 const BranchInst *LoopEntryPredicate =
15386 dyn_cast<BranchInst>(Pair.first->getTerminator());
15387 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
15388 continue;
15389
15390 Terms.emplace_back(LoopEntryPredicate->getCondition(),
15391 LoopEntryPredicate->getSuccessor(0) == Pair.second);
15392 }
15393
15394 // Now apply the information from the collected conditions to RewriteMap.
15395 // Conditions are processed in reverse order, so the earliest conditions is
15396 // processed first. This ensures the SCEVs with the shortest dependency chains
15397 // are constructed first.
15398 DenseMap<const SCEV *, const SCEV *> RewriteMap;
15399 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
15400 SmallVector<Value *, 8> Worklist;
15401 SmallPtrSet<Value *, 8> Visited;
15402 Worklist.push_back(Term);
15403 while (!Worklist.empty()) {
15404 Value *Cond = Worklist.pop_back_val();
15405 if (!Visited.insert(Cond).second)
15406 continue;
15407
15408 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
15409 auto Predicate =
15410 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
15411 const auto *LHS = getSCEV(Cmp->getOperand(0));
15412 const auto *RHS = getSCEV(Cmp->getOperand(1));
15413 CollectCondition(Predicate, LHS, RHS, RewriteMap);
15414 continue;
15415 }
15416
15417 Value *L, *R;
15418 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
15419 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
15420 Worklist.push_back(L);
15421 Worklist.push_back(R);
15422 }
15423 }
15424 }
15425
15426 if (RewriteMap.empty())
15427 return Expr;
15428
15429 // Now that all rewrite information is collect, rewrite the collected
15430 // expressions with the information in the map. This applies information to
15431 // sub-expressions.
15432 if (ExprsToRewrite.size() > 1) {
15433 for (const SCEV *Expr : ExprsToRewrite) {
15434 const SCEV *RewriteTo = RewriteMap[Expr];
15435 RewriteMap.erase(Expr);
15436 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
15437 RewriteMap.insert({Expr, Rewriter.visit(RewriteTo)});
15438 }
15439 }
15440
15441 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
15442 return Rewriter.visit(Expr);
15443}