Bug Summary

File:llvm/lib/Analysis/ScalarEvolution.cpp
Warning:line 9494, column 41
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ScalarEvolution.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/build-llvm/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-11-24-172238-38865-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp

/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp

1//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the implementation of the scalar evolution analysis
10// engine, which is used primarily to analyze expressions involving induction
11// variables in loops.
12//
13// There are several aspects to this library. First is the representation of
14// scalar expressions, which are represented as subclasses of the SCEV class.
15// These classes are used to represent certain types of subexpressions that we
16// can handle. We only create one SCEV of a particular shape, so
17// pointer-comparisons for equality are legal.
18//
19// One important aspect of the SCEV objects is that they are never cyclic, even
20// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
21// the PHI node is one of the idioms that we can represent (e.g., a polynomial
22// recurrence) then we represent it directly as a recurrence node, otherwise we
23// represent it as a SCEVUnknown node.
24//
25// In addition to being able to represent expressions of various types, we also
26// have folders that are used to build the *canonical* representation for a
27// particular expression. These folders are capable of using a variety of
28// rewrite rules to simplify the expressions.
29//
30// Once the folders are defined, we can implement the more interesting
31// higher-level code, such as the code that recognizes PHI nodes of various
32// types, computes the execution count of a loop, etc.
33//
34// TODO: We should use these routines and value representations to implement
35// dependence analysis!
36//
37//===----------------------------------------------------------------------===//
38//
39// There are several good references for the techniques used in this analysis.
40//
41// Chains of recurrences -- a method to expedite the evaluation
42// of closed-form functions
43// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44//
45// On computational properties of chains of recurrences
46// Eugene V. Zima
47//
48// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49// Robert A. van Engelen
50//
51// Efficient Symbolic Analysis for Optimizing Compilers
52// Robert A. van Engelen
53//
54// Using the chains of recurrences algebra for data dependence testing and
55// induction variable substitution
56// MS Thesis, Johnie Birch
57//
58//===----------------------------------------------------------------------===//
59
60#include "llvm/Analysis/ScalarEvolution.h"
61#include "llvm/ADT/APInt.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/DenseMap.h"
64#include "llvm/ADT/DepthFirstIterator.h"
65#include "llvm/ADT/EquivalenceClasses.h"
66#include "llvm/ADT/FoldingSet.h"
67#include "llvm/ADT/None.h"
68#include "llvm/ADT/Optional.h"
69#include "llvm/ADT/STLExtras.h"
70#include "llvm/ADT/ScopeExit.h"
71#include "llvm/ADT/Sequence.h"
72#include "llvm/ADT/SetVector.h"
73#include "llvm/ADT/SmallPtrSet.h"
74#include "llvm/ADT/SmallSet.h"
75#include "llvm/ADT/SmallVector.h"
76#include "llvm/ADT/Statistic.h"
77#include "llvm/ADT/StringRef.h"
78#include "llvm/Analysis/AssumptionCache.h"
79#include "llvm/Analysis/ConstantFolding.h"
80#include "llvm/Analysis/InstructionSimplify.h"
81#include "llvm/Analysis/LoopInfo.h"
82#include "llvm/Analysis/ScalarEvolutionDivision.h"
83#include "llvm/Analysis/ScalarEvolutionExpressions.h"
84#include "llvm/Analysis/TargetLibraryInfo.h"
85#include "llvm/Analysis/ValueTracking.h"
86#include "llvm/Config/llvm-config.h"
87#include "llvm/IR/Argument.h"
88#include "llvm/IR/BasicBlock.h"
89#include "llvm/IR/CFG.h"
90#include "llvm/IR/Constant.h"
91#include "llvm/IR/ConstantRange.h"
92#include "llvm/IR/Constants.h"
93#include "llvm/IR/DataLayout.h"
94#include "llvm/IR/DerivedTypes.h"
95#include "llvm/IR/Dominators.h"
96#include "llvm/IR/Function.h"
97#include "llvm/IR/GlobalAlias.h"
98#include "llvm/IR/GlobalValue.h"
99#include "llvm/IR/GlobalVariable.h"
100#include "llvm/IR/InstIterator.h"
101#include "llvm/IR/InstrTypes.h"
102#include "llvm/IR/Instruction.h"
103#include "llvm/IR/Instructions.h"
104#include "llvm/IR/IntrinsicInst.h"
105#include "llvm/IR/Intrinsics.h"
106#include "llvm/IR/LLVMContext.h"
107#include "llvm/IR/Metadata.h"
108#include "llvm/IR/Operator.h"
109#include "llvm/IR/PatternMatch.h"
110#include "llvm/IR/Type.h"
111#include "llvm/IR/Use.h"
112#include "llvm/IR/User.h"
113#include "llvm/IR/Value.h"
114#include "llvm/IR/Verifier.h"
115#include "llvm/InitializePasses.h"
116#include "llvm/Pass.h"
117#include "llvm/Support/Casting.h"
118#include "llvm/Support/CommandLine.h"
119#include "llvm/Support/Compiler.h"
120#include "llvm/Support/Debug.h"
121#include "llvm/Support/ErrorHandling.h"
122#include "llvm/Support/KnownBits.h"
123#include "llvm/Support/SaveAndRestore.h"
124#include "llvm/Support/raw_ostream.h"
125#include <algorithm>
126#include <cassert>
127#include <climits>
128#include <cstddef>
129#include <cstdint>
130#include <cstdlib>
131#include <map>
132#include <memory>
133#include <tuple>
134#include <utility>
135#include <vector>
136
137using namespace llvm;
138
139#define DEBUG_TYPE"scalar-evolution" "scalar-evolution"
140
141STATISTIC(NumArrayLenItCounts,static llvm::Statistic NumArrayLenItCounts = {"scalar-evolution"
, "NumArrayLenItCounts", "Number of trip counts computed with array length"
}
142 "Number of trip counts computed with array length")static llvm::Statistic NumArrayLenItCounts = {"scalar-evolution"
, "NumArrayLenItCounts", "Number of trip counts computed with array length"
}
;
143STATISTIC(NumTripCountsComputed,static llvm::Statistic NumTripCountsComputed = {"scalar-evolution"
, "NumTripCountsComputed", "Number of loops with predictable loop counts"
}
144 "Number of loops with predictable loop counts")static llvm::Statistic NumTripCountsComputed = {"scalar-evolution"
, "NumTripCountsComputed", "Number of loops with predictable loop counts"
}
;
145STATISTIC(NumTripCountsNotComputed,static llvm::Statistic NumTripCountsNotComputed = {"scalar-evolution"
, "NumTripCountsNotComputed", "Number of loops without predictable loop counts"
}
146 "Number of loops without predictable loop counts")static llvm::Statistic NumTripCountsNotComputed = {"scalar-evolution"
, "NumTripCountsNotComputed", "Number of loops without predictable loop counts"
}
;
147STATISTIC(NumBruteForceTripCountsComputed,static llvm::Statistic NumBruteForceTripCountsComputed = {"scalar-evolution"
, "NumBruteForceTripCountsComputed", "Number of loops with trip counts computed by force"
}
148 "Number of loops with trip counts computed by force")static llvm::Statistic NumBruteForceTripCountsComputed = {"scalar-evolution"
, "NumBruteForceTripCountsComputed", "Number of loops with trip counts computed by force"
}
;
149
150static cl::opt<unsigned>
151MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
152 cl::ZeroOrMore,
153 cl::desc("Maximum number of iterations SCEV will "
154 "symbolically execute a constant "
155 "derived loop"),
156 cl::init(100));
157
158// FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
159static cl::opt<bool> VerifySCEV(
160 "verify-scev", cl::Hidden,
161 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
162static cl::opt<bool> VerifySCEVStrict(
163 "verify-scev-strict", cl::Hidden,
164 cl::desc("Enable stricter verification with -verify-scev is passed"));
165static cl::opt<bool>
166 VerifySCEVMap("verify-scev-maps", cl::Hidden,
167 cl::desc("Verify no dangling value in ScalarEvolution's "
168 "ExprValueMap (slow)"));
169
170static cl::opt<bool> VerifyIR(
171 "scev-verify-ir", cl::Hidden,
172 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
173 cl::init(false));
174
175static cl::opt<unsigned> MulOpsInlineThreshold(
176 "scev-mulops-inline-threshold", cl::Hidden,
177 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
178 cl::init(32));
179
180static cl::opt<unsigned> AddOpsInlineThreshold(
181 "scev-addops-inline-threshold", cl::Hidden,
182 cl::desc("Threshold for inlining addition operands into a SCEV"),
183 cl::init(500));
184
185static cl::opt<unsigned> MaxSCEVCompareDepth(
186 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
187 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
188 cl::init(32));
189
190static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
191 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
192 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
193 cl::init(2));
194
195static cl::opt<unsigned> MaxValueCompareDepth(
196 "scalar-evolution-max-value-compare-depth", cl::Hidden,
197 cl::desc("Maximum depth of recursive value complexity comparisons"),
198 cl::init(2));
199
200static cl::opt<unsigned>
201 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
202 cl::desc("Maximum depth of recursive arithmetics"),
203 cl::init(32));
204
205static cl::opt<unsigned> MaxConstantEvolvingDepth(
206 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
207 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
208
209static cl::opt<unsigned>
210 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
211 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
212 cl::init(8));
213
214static cl::opt<unsigned>
215 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
216 cl::desc("Max coefficients in AddRec during evolving"),
217 cl::init(8));
218
219static cl::opt<unsigned>
220 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
221 cl::desc("Size of the expression which is considered huge"),
222 cl::init(4096));
223
224static cl::opt<bool>
225ClassifyExpressions("scalar-evolution-classify-expressions",
226 cl::Hidden, cl::init(true),
227 cl::desc("When printing analysis, include information on every instruction"));
228
229static cl::opt<bool> UseExpensiveRangeSharpening(
230 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
231 cl::init(false),
232 cl::desc("Use more powerful methods of sharpening expression ranges. May "
233 "be costly in terms of compile time"));
234
235//===----------------------------------------------------------------------===//
236// SCEV class definitions
237//===----------------------------------------------------------------------===//
238
239//===----------------------------------------------------------------------===//
240// Implementation of the SCEV class.
241//
242
243#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
244LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void SCEV::dump() const {
245 print(dbgs());
246 dbgs() << '\n';
247}
248#endif
249
250void SCEV::print(raw_ostream &OS) const {
251 switch (getSCEVType()) {
252 case scConstant:
253 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
254 return;
255 case scPtrToInt: {
256 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
257 const SCEV *Op = PtrToInt->getOperand();
258 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
259 << *PtrToInt->getType() << ")";
260 return;
261 }
262 case scTruncate: {
263 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
264 const SCEV *Op = Trunc->getOperand();
265 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
266 << *Trunc->getType() << ")";
267 return;
268 }
269 case scZeroExtend: {
270 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
271 const SCEV *Op = ZExt->getOperand();
272 OS << "(zext " << *Op->getType() << " " << *Op << " to "
273 << *ZExt->getType() << ")";
274 return;
275 }
276 case scSignExtend: {
277 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
278 const SCEV *Op = SExt->getOperand();
279 OS << "(sext " << *Op->getType() << " " << *Op << " to "
280 << *SExt->getType() << ")";
281 return;
282 }
283 case scAddRecExpr: {
284 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
285 OS << "{" << *AR->getOperand(0);
286 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
287 OS << ",+," << *AR->getOperand(i);
288 OS << "}<";
289 if (AR->hasNoUnsignedWrap())
290 OS << "nuw><";
291 if (AR->hasNoSignedWrap())
292 OS << "nsw><";
293 if (AR->hasNoSelfWrap() &&
294 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
295 OS << "nw><";
296 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
297 OS << ">";
298 return;
299 }
300 case scAddExpr:
301 case scMulExpr:
302 case scUMaxExpr:
303 case scSMaxExpr:
304 case scUMinExpr:
305 case scSMinExpr: {
306 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
307 const char *OpStr = nullptr;
308 switch (NAry->getSCEVType()) {
309 case scAddExpr: OpStr = " + "; break;
310 case scMulExpr: OpStr = " * "; break;
311 case scUMaxExpr: OpStr = " umax "; break;
312 case scSMaxExpr: OpStr = " smax "; break;
313 case scUMinExpr:
314 OpStr = " umin ";
315 break;
316 case scSMinExpr:
317 OpStr = " smin ";
318 break;
319 default:
320 llvm_unreachable("There are no other nary expression types.")::llvm::llvm_unreachable_internal("There are no other nary expression types."
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 320)
;
321 }
322 OS << "(";
323 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
324 I != E; ++I) {
325 OS << **I;
326 if (std::next(I) != E)
327 OS << OpStr;
328 }
329 OS << ")";
330 switch (NAry->getSCEVType()) {
331 case scAddExpr:
332 case scMulExpr:
333 if (NAry->hasNoUnsignedWrap())
334 OS << "<nuw>";
335 if (NAry->hasNoSignedWrap())
336 OS << "<nsw>";
337 break;
338 default:
339 // Nothing to print for other nary expressions.
340 break;
341 }
342 return;
343 }
344 case scUDivExpr: {
345 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
346 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
347 return;
348 }
349 case scUnknown: {
350 const SCEVUnknown *U = cast<SCEVUnknown>(this);
351 Type *AllocTy;
352 if (U->isSizeOf(AllocTy)) {
353 OS << "sizeof(" << *AllocTy << ")";
354 return;
355 }
356 if (U->isAlignOf(AllocTy)) {
357 OS << "alignof(" << *AllocTy << ")";
358 return;
359 }
360
361 Type *CTy;
362 Constant *FieldNo;
363 if (U->isOffsetOf(CTy, FieldNo)) {
364 OS << "offsetof(" << *CTy << ", ";
365 FieldNo->printAsOperand(OS, false);
366 OS << ")";
367 return;
368 }
369
370 // Otherwise just print it normally.
371 U->getValue()->printAsOperand(OS, false);
372 return;
373 }
374 case scCouldNotCompute:
375 OS << "***COULDNOTCOMPUTE***";
376 return;
377 }
378 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 378)
;
379}
380
381Type *SCEV::getType() const {
382 switch (getSCEVType()) {
383 case scConstant:
384 return cast<SCEVConstant>(this)->getType();
385 case scPtrToInt:
386 case scTruncate:
387 case scZeroExtend:
388 case scSignExtend:
389 return cast<SCEVCastExpr>(this)->getType();
390 case scAddRecExpr:
391 case scMulExpr:
392 case scUMaxExpr:
393 case scSMaxExpr:
394 case scUMinExpr:
395 case scSMinExpr:
396 return cast<SCEVNAryExpr>(this)->getType();
397 case scAddExpr:
398 return cast<SCEVAddExpr>(this)->getType();
399 case scUDivExpr:
400 return cast<SCEVUDivExpr>(this)->getType();
401 case scUnknown:
402 return cast<SCEVUnknown>(this)->getType();
403 case scCouldNotCompute:
404 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 404)
;
405 }
406 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 406)
;
407}
408
409bool SCEV::isZero() const {
410 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
411 return SC->getValue()->isZero();
412 return false;
413}
414
415bool SCEV::isOne() const {
416 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
417 return SC->getValue()->isOne();
418 return false;
419}
420
421bool SCEV::isAllOnesValue() const {
422 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
423 return SC->getValue()->isMinusOne();
424 return false;
425}
426
427bool SCEV::isNonConstantNegative() const {
428 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
429 if (!Mul) return false;
430
431 // If there is a constant factor, it will be first.
432 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
433 if (!SC) return false;
434
435 // Return true if the value is negative, this matches things like (-42 * V).
436 return SC->getAPInt().isNegative();
437}
438
439SCEVCouldNotCompute::SCEVCouldNotCompute() :
440 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
441
442bool SCEVCouldNotCompute::classof(const SCEV *S) {
443 return S->getSCEVType() == scCouldNotCompute;
444}
445
446const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
447 FoldingSetNodeID ID;
448 ID.AddInteger(scConstant);
449 ID.AddPointer(V);
450 void *IP = nullptr;
451 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
452 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
453 UniqueSCEVs.InsertNode(S, IP);
454 return S;
455}
456
457const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
458 return getConstant(ConstantInt::get(getContext(), Val));
459}
460
461const SCEV *
462ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
463 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
464 return getConstant(ConstantInt::get(ITy, V, isSigned));
465}
466
467SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
468 const SCEV *op, Type *ty)
469 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) {
470 Operands[0] = op;
471}
472
473SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
474 Type *ITy)
475 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
476 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&((getOperand()->getType()->isPointerTy() && Ty->
isIntegerTy() && "Must be a non-bit-width-changing pointer-to-integer cast!"
) ? static_cast<void> (0) : __assert_fail ("getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() && \"Must be a non-bit-width-changing pointer-to-integer cast!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 477, __PRETTY_FUNCTION__))
477 "Must be a non-bit-width-changing pointer-to-integer cast!")((getOperand()->getType()->isPointerTy() && Ty->
isIntegerTy() && "Must be a non-bit-width-changing pointer-to-integer cast!"
) ? static_cast<void> (0) : __assert_fail ("getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() && \"Must be a non-bit-width-changing pointer-to-integer cast!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 477, __PRETTY_FUNCTION__))
;
478}
479
480SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
481 SCEVTypes SCEVTy, const SCEV *op,
482 Type *ty)
483 : SCEVCastExpr(ID, SCEVTy, op, ty) {}
484
485SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
486 Type *ty)
487 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
488 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((getOperand()->getType()->isIntOrPtrTy() && Ty
->isIntOrPtrTy() && "Cannot truncate non-integer value!"
) ? static_cast<void> (0) : __assert_fail ("getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate non-integer value!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 489, __PRETTY_FUNCTION__))
489 "Cannot truncate non-integer value!")((getOperand()->getType()->isIntOrPtrTy() && Ty
->isIntOrPtrTy() && "Cannot truncate non-integer value!"
) ? static_cast<void> (0) : __assert_fail ("getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate non-integer value!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 489, __PRETTY_FUNCTION__))
;
490}
491
492SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
493 const SCEV *op, Type *ty)
494 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
495 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((getOperand()->getType()->isIntOrPtrTy() && Ty
->isIntOrPtrTy() && "Cannot zero extend non-integer value!"
) ? static_cast<void> (0) : __assert_fail ("getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot zero extend non-integer value!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 496, __PRETTY_FUNCTION__))
496 "Cannot zero extend non-integer value!")((getOperand()->getType()->isIntOrPtrTy() && Ty
->isIntOrPtrTy() && "Cannot zero extend non-integer value!"
) ? static_cast<void> (0) : __assert_fail ("getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot zero extend non-integer value!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 496, __PRETTY_FUNCTION__))
;
497}
498
499SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
500 const SCEV *op, Type *ty)
501 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
502 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((getOperand()->getType()->isIntOrPtrTy() && Ty
->isIntOrPtrTy() && "Cannot sign extend non-integer value!"
) ? static_cast<void> (0) : __assert_fail ("getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot sign extend non-integer value!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 503, __PRETTY_FUNCTION__))
503 "Cannot sign extend non-integer value!")((getOperand()->getType()->isIntOrPtrTy() && Ty
->isIntOrPtrTy() && "Cannot sign extend non-integer value!"
) ? static_cast<void> (0) : __assert_fail ("getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot sign extend non-integer value!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 503, __PRETTY_FUNCTION__))
;
504}
505
506void SCEVUnknown::deleted() {
507 // Clear this SCEVUnknown from various maps.
508 SE->forgetMemoizedResults(this);
509
510 // Remove this SCEVUnknown from the uniquing map.
511 SE->UniqueSCEVs.RemoveNode(this);
512
513 // Release the value.
514 setValPtr(nullptr);
515}
516
517void SCEVUnknown::allUsesReplacedWith(Value *New) {
518 // Remove this SCEVUnknown from the uniquing map.
519 SE->UniqueSCEVs.RemoveNode(this);
520
521 // Update this SCEVUnknown to point to the new value. This is needed
522 // because there may still be outstanding SCEVs which still point to
523 // this SCEVUnknown.
524 setValPtr(New);
525}
526
527bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
528 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
529 if (VCE->getOpcode() == Instruction::PtrToInt)
530 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
531 if (CE->getOpcode() == Instruction::GetElementPtr &&
532 CE->getOperand(0)->isNullValue() &&
533 CE->getNumOperands() == 2)
534 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
535 if (CI->isOne()) {
536 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
537 ->getElementType();
538 return true;
539 }
540
541 return false;
542}
543
544bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
545 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
546 if (VCE->getOpcode() == Instruction::PtrToInt)
547 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
548 if (CE->getOpcode() == Instruction::GetElementPtr &&
549 CE->getOperand(0)->isNullValue()) {
550 Type *Ty =
551 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
552 if (StructType *STy = dyn_cast<StructType>(Ty))
553 if (!STy->isPacked() &&
554 CE->getNumOperands() == 3 &&
555 CE->getOperand(1)->isNullValue()) {
556 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
557 if (CI->isOne() &&
558 STy->getNumElements() == 2 &&
559 STy->getElementType(0)->isIntegerTy(1)) {
560 AllocTy = STy->getElementType(1);
561 return true;
562 }
563 }
564 }
565
566 return false;
567}
568
569bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
570 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
571 if (VCE->getOpcode() == Instruction::PtrToInt)
572 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
573 if (CE->getOpcode() == Instruction::GetElementPtr &&
574 CE->getNumOperands() == 3 &&
575 CE->getOperand(0)->isNullValue() &&
576 CE->getOperand(1)->isNullValue()) {
577 Type *Ty =
578 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
579 // Ignore vector types here so that ScalarEvolutionExpander doesn't
580 // emit getelementptrs that index into vectors.
581 if (Ty->isStructTy() || Ty->isArrayTy()) {
582 CTy = Ty;
583 FieldNo = CE->getOperand(2);
584 return true;
585 }
586 }
587
588 return false;
589}
590
591//===----------------------------------------------------------------------===//
592// SCEV Utilities
593//===----------------------------------------------------------------------===//
594
595/// Compare the two values \p LV and \p RV in terms of their "complexity" where
596/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
597/// operands in SCEV expressions. \p EqCache is a set of pairs of values that
598/// have been previously deemed to be "equally complex" by this routine. It is
599/// intended to avoid exponential time complexity in cases like:
600///
601/// %a = f(%x, %y)
602/// %b = f(%a, %a)
603/// %c = f(%b, %b)
604///
605/// %d = f(%x, %y)
606/// %e = f(%d, %d)
607/// %f = f(%e, %e)
608///
609/// CompareValueComplexity(%f, %c)
610///
611/// Since we do not continue running this routine on expression trees once we
612/// have seen unequal values, there is no need to track them in the cache.
613static int
614CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
615 const LoopInfo *const LI, Value *LV, Value *RV,
616 unsigned Depth) {
617 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
618 return 0;
619
620 // Order pointer values after integer values. This helps SCEVExpander form
621 // GEPs.
622 bool LIsPointer = LV->getType()->isPointerTy(),
623 RIsPointer = RV->getType()->isPointerTy();
624 if (LIsPointer != RIsPointer)
625 return (int)LIsPointer - (int)RIsPointer;
626
627 // Compare getValueID values.
628 unsigned LID = LV->getValueID(), RID = RV->getValueID();
629 if (LID != RID)
630 return (int)LID - (int)RID;
631
632 // Sort arguments by their position.
633 if (const auto *LA = dyn_cast<Argument>(LV)) {
634 const auto *RA = cast<Argument>(RV);
635 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
636 return (int)LArgNo - (int)RArgNo;
637 }
638
639 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
640 const auto *RGV = cast<GlobalValue>(RV);
641
642 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
643 auto LT = GV->getLinkage();
644 return !(GlobalValue::isPrivateLinkage(LT) ||
645 GlobalValue::isInternalLinkage(LT));
646 };
647
648 // Use the names to distinguish the two values, but only if the
649 // names are semantically important.
650 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
651 return LGV->getName().compare(RGV->getName());
652 }
653
654 // For instructions, compare their loop depth, and their operand count. This
655 // is pretty loose.
656 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
657 const auto *RInst = cast<Instruction>(RV);
658
659 // Compare loop depths.
660 const BasicBlock *LParent = LInst->getParent(),
661 *RParent = RInst->getParent();
662 if (LParent != RParent) {
663 unsigned LDepth = LI->getLoopDepth(LParent),
664 RDepth = LI->getLoopDepth(RParent);
665 if (LDepth != RDepth)
666 return (int)LDepth - (int)RDepth;
667 }
668
669 // Compare the number of operands.
670 unsigned LNumOps = LInst->getNumOperands(),
671 RNumOps = RInst->getNumOperands();
672 if (LNumOps != RNumOps)
673 return (int)LNumOps - (int)RNumOps;
674
675 for (unsigned Idx : seq(0u, LNumOps)) {
676 int Result =
677 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
678 RInst->getOperand(Idx), Depth + 1);
679 if (Result != 0)
680 return Result;
681 }
682 }
683
684 EqCacheValue.unionSets(LV, RV);
685 return 0;
686}
687
688// Return negative, zero, or positive, if LHS is less than, equal to, or greater
689// than RHS, respectively. A three-way result allows recursive comparisons to be
690// more efficient.
691static int CompareSCEVComplexity(
692 EquivalenceClasses<const SCEV *> &EqCacheSCEV,
693 EquivalenceClasses<const Value *> &EqCacheValue,
694 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
695 DominatorTree &DT, unsigned Depth = 0) {
696 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
697 if (LHS == RHS)
698 return 0;
699
700 // Primarily, sort the SCEVs by their getSCEVType().
701 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
702 if (LType != RType)
703 return (int)LType - (int)RType;
704
705 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
706 return 0;
707 // Aside from the getSCEVType() ordering, the particular ordering
708 // isn't very important except that it's beneficial to be consistent,
709 // so that (a + b) and (b + a) don't end up as different expressions.
710 switch (LType) {
711 case scUnknown: {
712 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
713 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
714
715 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
716 RU->getValue(), Depth + 1);
717 if (X == 0)
718 EqCacheSCEV.unionSets(LHS, RHS);
719 return X;
720 }
721
722 case scConstant: {
723 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
724 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
725
726 // Compare constant values.
727 const APInt &LA = LC->getAPInt();
728 const APInt &RA = RC->getAPInt();
729 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
730 if (LBitWidth != RBitWidth)
731 return (int)LBitWidth - (int)RBitWidth;
732 return LA.ult(RA) ? -1 : 1;
733 }
734
735 case scAddRecExpr: {
736 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
737 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
738
739 // There is always a dominance between two recs that are used by one SCEV,
740 // so we can safely sort recs by loop header dominance. We require such
741 // order in getAddExpr.
742 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
743 if (LLoop != RLoop) {
744 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
745 assert(LHead != RHead && "Two loops share the same header?")((LHead != RHead && "Two loops share the same header?"
) ? static_cast<void> (0) : __assert_fail ("LHead != RHead && \"Two loops share the same header?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 745, __PRETTY_FUNCTION__))
;
746 if (DT.dominates(LHead, RHead))
747 return 1;
748 else
749 assert(DT.dominates(RHead, LHead) &&((DT.dominates(RHead, LHead) && "No dominance between recurrences used by one SCEV?"
) ? static_cast<void> (0) : __assert_fail ("DT.dominates(RHead, LHead) && \"No dominance between recurrences used by one SCEV?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 750, __PRETTY_FUNCTION__))
750 "No dominance between recurrences used by one SCEV?")((DT.dominates(RHead, LHead) && "No dominance between recurrences used by one SCEV?"
) ? static_cast<void> (0) : __assert_fail ("DT.dominates(RHead, LHead) && \"No dominance between recurrences used by one SCEV?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 750, __PRETTY_FUNCTION__))
;
751 return -1;
752 }
753
754 // Addrec complexity grows with operand count.
755 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
756 if (LNumOps != RNumOps)
757 return (int)LNumOps - (int)RNumOps;
758
759 // Lexicographically compare.
760 for (unsigned i = 0; i != LNumOps; ++i) {
761 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
762 LA->getOperand(i), RA->getOperand(i), DT,
763 Depth + 1);
764 if (X != 0)
765 return X;
766 }
767 EqCacheSCEV.unionSets(LHS, RHS);
768 return 0;
769 }
770
771 case scAddExpr:
772 case scMulExpr:
773 case scSMaxExpr:
774 case scUMaxExpr:
775 case scSMinExpr:
776 case scUMinExpr: {
777 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
778 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
779
780 // Lexicographically compare n-ary expressions.
781 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
782 if (LNumOps != RNumOps)
783 return (int)LNumOps - (int)RNumOps;
784
785 for (unsigned i = 0; i != LNumOps; ++i) {
786 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
787 LC->getOperand(i), RC->getOperand(i), DT,
788 Depth + 1);
789 if (X != 0)
790 return X;
791 }
792 EqCacheSCEV.unionSets(LHS, RHS);
793 return 0;
794 }
795
796 case scUDivExpr: {
797 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
798 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
799
800 // Lexicographically compare udiv expressions.
801 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
802 RC->getLHS(), DT, Depth + 1);
803 if (X != 0)
804 return X;
805 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
806 RC->getRHS(), DT, Depth + 1);
807 if (X == 0)
808 EqCacheSCEV.unionSets(LHS, RHS);
809 return X;
810 }
811
812 case scPtrToInt:
813 case scTruncate:
814 case scZeroExtend:
815 case scSignExtend: {
816 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
817 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
818
819 // Compare cast expressions by operand.
820 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
821 LC->getOperand(), RC->getOperand(), DT,
822 Depth + 1);
823 if (X == 0)
824 EqCacheSCEV.unionSets(LHS, RHS);
825 return X;
826 }
827
828 case scCouldNotCompute:
829 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 829)
;
830 }
831 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 831)
;
832}
833
834/// Given a list of SCEV objects, order them by their complexity, and group
835/// objects of the same complexity together by value. When this routine is
836/// finished, we know that any duplicates in the vector are consecutive and that
837/// complexity is monotonically increasing.
838///
839/// Note that we go take special precautions to ensure that we get deterministic
840/// results from this routine. In other words, we don't want the results of
841/// this to depend on where the addresses of various SCEV objects happened to
842/// land in memory.
843static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
844 LoopInfo *LI, DominatorTree &DT) {
845 if (Ops.size() < 2) return; // Noop
846
847 EquivalenceClasses<const SCEV *> EqCacheSCEV;
848 EquivalenceClasses<const Value *> EqCacheValue;
849 if (Ops.size() == 2) {
850 // This is the common case, which also happens to be trivially simple.
851 // Special case it.
852 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
853 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
854 std::swap(LHS, RHS);
855 return;
856 }
857
858 // Do the rough sort by complexity.
859 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
860 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) <
861 0;
862 });
863
864 // Now that we are sorted by complexity, group elements of the same
865 // complexity. Note that this is, at worst, N^2, but the vector is likely to
866 // be extremely short in practice. Note that we take this approach because we
867 // do not want to depend on the addresses of the objects we are grouping.
868 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
869 const SCEV *S = Ops[i];
870 unsigned Complexity = S->getSCEVType();
871
872 // If there are any objects of the same complexity and same value as this
873 // one, group them.
874 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
875 if (Ops[j] == S) { // Found a duplicate.
876 // Move it to immediately after i'th element.
877 std::swap(Ops[i+1], Ops[j]);
878 ++i; // no need to rescan it.
879 if (i == e-2) return; // Done!
880 }
881 }
882 }
883}
884
885/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
886/// least HugeExprThreshold nodes).
887static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
888 return any_of(Ops, [](const SCEV *S) {
889 return S->getExpressionSize() >= HugeExprThreshold;
890 });
891}
892
893//===----------------------------------------------------------------------===//
894// Simple SCEV method implementations
895//===----------------------------------------------------------------------===//
896
897/// Compute BC(It, K). The result has width W. Assume, K > 0.
898static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
899 ScalarEvolution &SE,
900 Type *ResultTy) {
901 // Handle the simplest case efficiently.
902 if (K == 1)
903 return SE.getTruncateOrZeroExtend(It, ResultTy);
904
905 // We are using the following formula for BC(It, K):
906 //
907 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
908 //
909 // Suppose, W is the bitwidth of the return value. We must be prepared for
910 // overflow. Hence, we must assure that the result of our computation is
911 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
912 // safe in modular arithmetic.
913 //
914 // However, this code doesn't use exactly that formula; the formula it uses
915 // is something like the following, where T is the number of factors of 2 in
916 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
917 // exponentiation:
918 //
919 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
920 //
921 // This formula is trivially equivalent to the previous formula. However,
922 // this formula can be implemented much more efficiently. The trick is that
923 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
924 // arithmetic. To do exact division in modular arithmetic, all we have
925 // to do is multiply by the inverse. Therefore, this step can be done at
926 // width W.
927 //
928 // The next issue is how to safely do the division by 2^T. The way this
929 // is done is by doing the multiplication step at a width of at least W + T
930 // bits. This way, the bottom W+T bits of the product are accurate. Then,
931 // when we perform the division by 2^T (which is equivalent to a right shift
932 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
933 // truncated out after the division by 2^T.
934 //
935 // In comparison to just directly using the first formula, this technique
936 // is much more efficient; using the first formula requires W * K bits,
937 // but this formula less than W + K bits. Also, the first formula requires
938 // a division step, whereas this formula only requires multiplies and shifts.
939 //
940 // It doesn't matter whether the subtraction step is done in the calculation
941 // width or the input iteration count's width; if the subtraction overflows,
942 // the result must be zero anyway. We prefer here to do it in the width of
943 // the induction variable because it helps a lot for certain cases; CodeGen
944 // isn't smart enough to ignore the overflow, which leads to much less
945 // efficient code if the width of the subtraction is wider than the native
946 // register width.
947 //
948 // (It's possible to not widen at all by pulling out factors of 2 before
949 // the multiplication; for example, K=2 can be calculated as
950 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
951 // extra arithmetic, so it's not an obvious win, and it gets
952 // much more complicated for K > 3.)
953
954 // Protection from insane SCEVs; this bound is conservative,
955 // but it probably doesn't matter.
956 if (K > 1000)
957 return SE.getCouldNotCompute();
958
959 unsigned W = SE.getTypeSizeInBits(ResultTy);
960
961 // Calculate K! / 2^T and T; we divide out the factors of two before
962 // multiplying for calculating K! / 2^T to avoid overflow.
963 // Other overflow doesn't matter because we only care about the bottom
964 // W bits of the result.
965 APInt OddFactorial(W, 1);
966 unsigned T = 1;
967 for (unsigned i = 3; i <= K; ++i) {
968 APInt Mult(W, i);
969 unsigned TwoFactors = Mult.countTrailingZeros();
970 T += TwoFactors;
971 Mult.lshrInPlace(TwoFactors);
972 OddFactorial *= Mult;
973 }
974
975 // We need at least W + T bits for the multiplication step
976 unsigned CalculationBits = W + T;
977
978 // Calculate 2^T, at width T+W.
979 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
980
981 // Calculate the multiplicative inverse of K! / 2^T;
982 // this multiplication factor will perform the exact division by
983 // K! / 2^T.
984 APInt Mod = APInt::getSignedMinValue(W+1);
985 APInt MultiplyFactor = OddFactorial.zext(W+1);
986 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
987 MultiplyFactor = MultiplyFactor.trunc(W);
988
989 // Calculate the product, at width T+W
990 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
991 CalculationBits);
992 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
993 for (unsigned i = 1; i != K; ++i) {
994 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
995 Dividend = SE.getMulExpr(Dividend,
996 SE.getTruncateOrZeroExtend(S, CalculationTy));
997 }
998
999 // Divide by 2^T
1000 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1001
1002 // Truncate the result, and divide by K! / 2^T.
1003
1004 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1005 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1006}
1007
1008/// Return the value of this chain of recurrences at the specified iteration
1009/// number. We can evaluate this recurrence by multiplying each element in the
1010/// chain by the binomial coefficient corresponding to it. In other words, we
1011/// can evaluate {A,+,B,+,C,+,D} as:
1012///
1013/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1014///
1015/// where BC(It, k) stands for binomial coefficient.
1016const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1017 ScalarEvolution &SE) const {
1018 const SCEV *Result = getStart();
1019 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1020 // The computation is correct in the face of overflow provided that the
1021 // multiplication is performed _after_ the evaluation of the binomial
1022 // coefficient.
1023 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1024 if (isa<SCEVCouldNotCompute>(Coeff))
1025 return Coeff;
1026
1027 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1028 }
1029 return Result;
1030}
1031
1032//===----------------------------------------------------------------------===//
1033// SCEV Expression folder implementations
1034//===----------------------------------------------------------------------===//
1035
1036const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty,
1037 unsigned Depth) {
1038 assert(Ty->isIntegerTy() && "Target type must be an integer type!")((Ty->isIntegerTy() && "Target type must be an integer type!"
) ? static_cast<void> (0) : __assert_fail ("Ty->isIntegerTy() && \"Target type must be an integer type!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1038, __PRETTY_FUNCTION__))
;
1039 assert(Depth <= 1 && "getPtrToIntExpr() should self-recurse at most once.")((Depth <= 1 && "getPtrToIntExpr() should self-recurse at most once."
) ? static_cast<void> (0) : __assert_fail ("Depth <= 1 && \"getPtrToIntExpr() should self-recurse at most once.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1039, __PRETTY_FUNCTION__))
;
1040
1041 // We could be called with an integer-typed operands during SCEV rewrites.
1042 // Since the operand is an integer already, just perform zext/trunc/self cast.
1043 if (!Op->getType()->isPointerTy())
1044 return getTruncateOrZeroExtend(Op, Ty);
1045
1046 // What would be an ID for such a SCEV cast expression?
1047 FoldingSetNodeID ID;
1048 ID.AddInteger(scPtrToInt);
1049 ID.AddPointer(Op);
1050
1051 void *IP = nullptr;
1052
1053 // Is there already an expression for such a cast?
1054 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1055 return getTruncateOrZeroExtend(S, Ty);
1056
1057 // If not, is this expression something we can't reduce any further?
1058 if (isa<SCEVUnknown>(Op)) {
1059 // Create an explicit cast node.
1060 // We can reuse the existing insert position since if we get here,
1061 // we won't have made any changes which would invalidate it.
1062 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
1063 assert(getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(((getDataLayout().getTypeSizeInBits(getEffectiveSCEVType( Op->
getType())) == getDataLayout().getTypeSizeInBits(IntPtrTy) &&
"We can only model ptrtoint if SCEV's effective (integer) type is "
"sufficiently wide to represent all possible pointer values."
) ? static_cast<void> (0) : __assert_fail ("getDataLayout().getTypeSizeInBits(getEffectiveSCEVType( Op->getType())) == getDataLayout().getTypeSizeInBits(IntPtrTy) && \"We can only model ptrtoint if SCEV's effective (integer) type is \" \"sufficiently wide to represent all possible pointer values.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1066, __PRETTY_FUNCTION__))
1064 Op->getType())) == getDataLayout().getTypeSizeInBits(IntPtrTy) &&((getDataLayout().getTypeSizeInBits(getEffectiveSCEVType( Op->
getType())) == getDataLayout().getTypeSizeInBits(IntPtrTy) &&
"We can only model ptrtoint if SCEV's effective (integer) type is "
"sufficiently wide to represent all possible pointer values."
) ? static_cast<void> (0) : __assert_fail ("getDataLayout().getTypeSizeInBits(getEffectiveSCEVType( Op->getType())) == getDataLayout().getTypeSizeInBits(IntPtrTy) && \"We can only model ptrtoint if SCEV's effective (integer) type is \" \"sufficiently wide to represent all possible pointer values.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1066, __PRETTY_FUNCTION__))
1065 "We can only model ptrtoint if SCEV's effective (integer) type is "((getDataLayout().getTypeSizeInBits(getEffectiveSCEVType( Op->
getType())) == getDataLayout().getTypeSizeInBits(IntPtrTy) &&
"We can only model ptrtoint if SCEV's effective (integer) type is "
"sufficiently wide to represent all possible pointer values."
) ? static_cast<void> (0) : __assert_fail ("getDataLayout().getTypeSizeInBits(getEffectiveSCEVType( Op->getType())) == getDataLayout().getTypeSizeInBits(IntPtrTy) && \"We can only model ptrtoint if SCEV's effective (integer) type is \" \"sufficiently wide to represent all possible pointer values.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1066, __PRETTY_FUNCTION__))
1066 "sufficiently wide to represent all possible pointer values.")((getDataLayout().getTypeSizeInBits(getEffectiveSCEVType( Op->
getType())) == getDataLayout().getTypeSizeInBits(IntPtrTy) &&
"We can only model ptrtoint if SCEV's effective (integer) type is "
"sufficiently wide to represent all possible pointer values."
) ? static_cast<void> (0) : __assert_fail ("getDataLayout().getTypeSizeInBits(getEffectiveSCEVType( Op->getType())) == getDataLayout().getTypeSizeInBits(IntPtrTy) && \"We can only model ptrtoint if SCEV's effective (integer) type is \" \"sufficiently wide to represent all possible pointer values.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1066, __PRETTY_FUNCTION__))
;
1067 SCEV *S = new (SCEVAllocator)
1068 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
1069 UniqueSCEVs.InsertNode(S, IP);
1070 addToLoopUseLists(S);
1071 return getTruncateOrZeroExtend(S, Ty);
1072 }
1073
1074 assert(Depth == 0 &&((Depth == 0 && "getPtrToIntExpr() should not self-recurse for non-SCEVUnknown's."
) ? static_cast<void> (0) : __assert_fail ("Depth == 0 && \"getPtrToIntExpr() should not self-recurse for non-SCEVUnknown's.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1075, __PRETTY_FUNCTION__))
1075 "getPtrToIntExpr() should not self-recurse for non-SCEVUnknown's.")((Depth == 0 && "getPtrToIntExpr() should not self-recurse for non-SCEVUnknown's."
) ? static_cast<void> (0) : __assert_fail ("Depth == 0 && \"getPtrToIntExpr() should not self-recurse for non-SCEVUnknown's.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1075, __PRETTY_FUNCTION__))
;
1076
1077 // Otherwise, we've got some expression that is more complex than just a
1078 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
1079 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
1080 // only, and the expressions must otherwise be integer-typed.
1081 // So sink the cast down to the SCEVUnknown's.
1082
1083 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
1084 /// which computes a pointer-typed value, and rewrites the whole expression
1085 /// tree so that *all* the computations are done on integers, and the only
1086 /// pointer-typed operands in the expression are SCEVUnknown.
1087 class SCEVPtrToIntSinkingRewriter
1088 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
1089 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
1090
1091 public:
1092 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
1093
1094 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
1095 SCEVPtrToIntSinkingRewriter Rewriter(SE);
1096 return Rewriter.visit(Scev);
1097 }
1098
1099 const SCEV *visit(const SCEV *S) {
1100 Type *STy = S->getType();
1101 // If the expression is not pointer-typed, just keep it as-is.
1102 if (!STy->isPointerTy())
1103 return S;
1104 // Else, recursively sink the cast down into it.
1105 return Base::visit(S);
1106 }
1107
1108 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1109 SmallVector<const SCEV *, 2> Operands;
1110 bool Changed = false;
1111 for (auto *Op : Expr->operands()) {
1112 Operands.push_back(visit(Op));
1113 Changed |= Op != Operands.back();
1114 }
1115 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1116 }
1117
1118 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1119 SmallVector<const SCEV *, 2> Operands;
1120 bool Changed = false;
1121 for (auto *Op : Expr->operands()) {
1122 Operands.push_back(visit(Op));
1123 Changed |= Op != Operands.back();
1124 }
1125 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1126 }
1127
1128 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1129 Type *ExprPtrTy = Expr->getType();
1130 assert(ExprPtrTy->isPointerTy() &&((ExprPtrTy->isPointerTy() && "Should only reach pointer-typed SCEVUnknown's."
) ? static_cast<void> (0) : __assert_fail ("ExprPtrTy->isPointerTy() && \"Should only reach pointer-typed SCEVUnknown's.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1131, __PRETTY_FUNCTION__))
1131 "Should only reach pointer-typed SCEVUnknown's.")((ExprPtrTy->isPointerTy() && "Should only reach pointer-typed SCEVUnknown's."
) ? static_cast<void> (0) : __assert_fail ("ExprPtrTy->isPointerTy() && \"Should only reach pointer-typed SCEVUnknown's.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1131, __PRETTY_FUNCTION__))
;
1132 Type *ExprIntPtrTy = SE.getDataLayout().getIntPtrType(ExprPtrTy);
1133 return SE.getPtrToIntExpr(Expr, ExprIntPtrTy, /*Depth=*/1);
1134 }
1135 };
1136
1137 // And actually perform the cast sinking.
1138 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
1139 assert(IntOp->getType()->isIntegerTy() &&((IntOp->getType()->isIntegerTy() && "We must have succeeded in sinking the cast, "
"and ending up with an integer-typed expression!") ? static_cast
<void> (0) : __assert_fail ("IntOp->getType()->isIntegerTy() && \"We must have succeeded in sinking the cast, \" \"and ending up with an integer-typed expression!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1141, __PRETTY_FUNCTION__))
1140 "We must have succeeded in sinking the cast, "((IntOp->getType()->isIntegerTy() && "We must have succeeded in sinking the cast, "
"and ending up with an integer-typed expression!") ? static_cast
<void> (0) : __assert_fail ("IntOp->getType()->isIntegerTy() && \"We must have succeeded in sinking the cast, \" \"and ending up with an integer-typed expression!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1141, __PRETTY_FUNCTION__))
1141 "and ending up with an integer-typed expression!")((IntOp->getType()->isIntegerTy() && "We must have succeeded in sinking the cast, "
"and ending up with an integer-typed expression!") ? static_cast
<void> (0) : __assert_fail ("IntOp->getType()->isIntegerTy() && \"We must have succeeded in sinking the cast, \" \"and ending up with an integer-typed expression!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1141, __PRETTY_FUNCTION__))
;
1142 return getTruncateOrZeroExtend(IntOp, Ty);
1143}
1144
1145const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1146 unsigned Depth) {
1147 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&((getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(
Ty) && "This is not a truncating conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && \"This is not a truncating conversion!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1148, __PRETTY_FUNCTION__))
1148 "This is not a truncating conversion!")((getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(
Ty) && "This is not a truncating conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && \"This is not a truncating conversion!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1148, __PRETTY_FUNCTION__))
;
1149 assert(isSCEVable(Ty) &&((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1150, __PRETTY_FUNCTION__))
1150 "This is not a conversion to a SCEVable type!")((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1150, __PRETTY_FUNCTION__))
;
1151 Ty = getEffectiveSCEVType(Ty);
1152
1153 FoldingSetNodeID ID;
1154 ID.AddInteger(scTruncate);
1155 ID.AddPointer(Op);
1156 ID.AddPointer(Ty);
1157 void *IP = nullptr;
1158 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1159
1160 // Fold if the operand is constant.
1161 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1162 return getConstant(
1163 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1164
1165 // trunc(trunc(x)) --> trunc(x)
1166 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1167 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1168
1169 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1170 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1171 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1172
1173 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1174 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1175 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1176
1177 if (Depth > MaxCastDepth) {
1178 SCEV *S =
1179 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1180 UniqueSCEVs.InsertNode(S, IP);
1181 addToLoopUseLists(S);
1182 return S;
1183 }
1184
1185 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1186 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1187 // if after transforming we have at most one truncate, not counting truncates
1188 // that replace other casts.
1189 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1190 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1191 SmallVector<const SCEV *, 4> Operands;
1192 unsigned numTruncs = 0;
1193 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1194 ++i) {
1195 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1196 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1197 isa<SCEVTruncateExpr>(S))
1198 numTruncs++;
1199 Operands.push_back(S);
1200 }
1201 if (numTruncs < 2) {
1202 if (isa<SCEVAddExpr>(Op))
1203 return getAddExpr(Operands);
1204 else if (isa<SCEVMulExpr>(Op))
1205 return getMulExpr(Operands);
1206 else
1207 llvm_unreachable("Unexpected SCEV type for Op.")::llvm::llvm_unreachable_internal("Unexpected SCEV type for Op."
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1207)
;
1208 }
1209 // Although we checked in the beginning that ID is not in the cache, it is
1210 // possible that during recursion and different modification ID was inserted
1211 // into the cache. So if we find it, just return it.
1212 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1213 return S;
1214 }
1215
1216 // If the input value is a chrec scev, truncate the chrec's operands.
1217 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1218 SmallVector<const SCEV *, 4> Operands;
1219 for (const SCEV *Op : AddRec->operands())
1220 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1221 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1222 }
1223
1224 // The cast wasn't folded; create an explicit cast node. We can reuse
1225 // the existing insert position since if we get here, we won't have
1226 // made any changes which would invalidate it.
1227 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1228 Op, Ty);
1229 UniqueSCEVs.InsertNode(S, IP);
1230 addToLoopUseLists(S);
1231 return S;
1232}
1233
1234// Get the limit of a recurrence such that incrementing by Step cannot cause
1235// signed overflow as long as the value of the recurrence within the
1236// loop does not exceed this limit before incrementing.
1237static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1238 ICmpInst::Predicate *Pred,
1239 ScalarEvolution *SE) {
1240 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1241 if (SE->isKnownPositive(Step)) {
1242 *Pred = ICmpInst::ICMP_SLT;
1243 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1244 SE->getSignedRangeMax(Step));
1245 }
1246 if (SE->isKnownNegative(Step)) {
1247 *Pred = ICmpInst::ICMP_SGT;
1248 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1249 SE->getSignedRangeMin(Step));
1250 }
1251 return nullptr;
1252}
1253
1254// Get the limit of a recurrence such that incrementing by Step cannot cause
1255// unsigned overflow as long as the value of the recurrence within the loop does
1256// not exceed this limit before incrementing.
1257static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1258 ICmpInst::Predicate *Pred,
1259 ScalarEvolution *SE) {
1260 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1261 *Pred = ICmpInst::ICMP_ULT;
1262
1263 return SE->getConstant(APInt::getMinValue(BitWidth) -
1264 SE->getUnsignedRangeMax(Step));
1265}
1266
1267namespace {
1268
1269struct ExtendOpTraitsBase {
1270 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1271 unsigned);
1272};
1273
1274// Used to make code generic over signed and unsigned overflow.
1275template <typename ExtendOp> struct ExtendOpTraits {
1276 // Members present:
1277 //
1278 // static const SCEV::NoWrapFlags WrapType;
1279 //
1280 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1281 //
1282 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1283 // ICmpInst::Predicate *Pred,
1284 // ScalarEvolution *SE);
1285};
1286
1287template <>
1288struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1289 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1290
1291 static const GetExtendExprTy GetExtendExpr;
1292
1293 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1294 ICmpInst::Predicate *Pred,
1295 ScalarEvolution *SE) {
1296 return getSignedOverflowLimitForStep(Step, Pred, SE);
1297 }
1298};
1299
1300const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1301 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1302
1303template <>
1304struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1305 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1306
1307 static const GetExtendExprTy GetExtendExpr;
1308
1309 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1310 ICmpInst::Predicate *Pred,
1311 ScalarEvolution *SE) {
1312 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1313 }
1314};
1315
1316const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1317 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1318
1319} // end anonymous namespace
1320
1321// The recurrence AR has been shown to have no signed/unsigned wrap or something
1322// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1323// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1324// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1325// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1326// expression "Step + sext/zext(PreIncAR)" is congruent with
1327// "sext/zext(PostIncAR)"
1328template <typename ExtendOpTy>
1329static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1330 ScalarEvolution *SE, unsigned Depth) {
1331 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1332 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1333
1334 const Loop *L = AR->getLoop();
1335 const SCEV *Start = AR->getStart();
1336 const SCEV *Step = AR->getStepRecurrence(*SE);
1337
1338 // Check for a simple looking step prior to loop entry.
1339 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1340 if (!SA)
1341 return nullptr;
1342
1343 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1344 // subtraction is expensive. For this purpose, perform a quick and dirty
1345 // difference, by checking for Step in the operand list.
1346 SmallVector<const SCEV *, 4> DiffOps;
1347 for (const SCEV *Op : SA->operands())
1348 if (Op != Step)
1349 DiffOps.push_back(Op);
1350
1351 if (DiffOps.size() == SA->getNumOperands())
1352 return nullptr;
1353
1354 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1355 // `Step`:
1356
1357 // 1. NSW/NUW flags on the step increment.
1358 auto PreStartFlags =
1359 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1360 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1361 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1362 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1363
1364 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1365 // "S+X does not sign/unsign-overflow".
1366 //
1367
1368 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1369 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1370 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1371 return PreStart;
1372
1373 // 2. Direct overflow check on the step operation's expression.
1374 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1375 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1376 const SCEV *OperandExtendedStart =
1377 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1378 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1379 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1380 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1381 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1382 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1383 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1384 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1385 }
1386 return PreStart;
1387 }
1388
1389 // 3. Loop precondition.
1390 ICmpInst::Predicate Pred;
1391 const SCEV *OverflowLimit =
1392 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1393
1394 if (OverflowLimit &&
1395 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1396 return PreStart;
1397
1398 return nullptr;
1399}
1400
1401// Get the normalized zero or sign extended expression for this AddRec's Start.
1402template <typename ExtendOpTy>
1403static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1404 ScalarEvolution *SE,
1405 unsigned Depth) {
1406 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1407
1408 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1409 if (!PreStart)
1410 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1411
1412 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1413 Depth),
1414 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1415}
1416
1417// Try to prove away overflow by looking at "nearby" add recurrences. A
1418// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1419// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1420//
1421// Formally:
1422//
1423// {S,+,X} == {S-T,+,X} + T
1424// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1425//
1426// If ({S-T,+,X} + T) does not overflow ... (1)
1427//
1428// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1429//
1430// If {S-T,+,X} does not overflow ... (2)
1431//
1432// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1433// == {Ext(S-T)+Ext(T),+,Ext(X)}
1434//
1435// If (S-T)+T does not overflow ... (3)
1436//
1437// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1438// == {Ext(S),+,Ext(X)} == LHS
1439//
1440// Thus, if (1), (2) and (3) are true for some T, then
1441// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1442//
1443// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1444// does not overflow" restricted to the 0th iteration. Therefore we only need
1445// to check for (1) and (2).
1446//
1447// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1448// is `Delta` (defined below).
1449template <typename ExtendOpTy>
1450bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1451 const SCEV *Step,
1452 const Loop *L) {
1453 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1454
1455 // We restrict `Start` to a constant to prevent SCEV from spending too much
1456 // time here. It is correct (but more expensive) to continue with a
1457 // non-constant `Start` and do a general SCEV subtraction to compute
1458 // `PreStart` below.
1459 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1460 if (!StartC)
1461 return false;
1462
1463 APInt StartAI = StartC->getAPInt();
1464
1465 for (unsigned Delta : {-2, -1, 1, 2}) {
1466 const SCEV *PreStart = getConstant(StartAI - Delta);
1467
1468 FoldingSetNodeID ID;
1469 ID.AddInteger(scAddRecExpr);
1470 ID.AddPointer(PreStart);
1471 ID.AddPointer(Step);
1472 ID.AddPointer(L);
1473 void *IP = nullptr;
1474 const auto *PreAR =
1475 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1476
1477 // Give up if we don't already have the add recurrence we need because
1478 // actually constructing an add recurrence is relatively expensive.
1479 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1480 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1481 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1482 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1483 DeltaS, &Pred, this);
1484 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1485 return true;
1486 }
1487 }
1488
1489 return false;
1490}
1491
1492// Finds an integer D for an expression (C + x + y + ...) such that the top
1493// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1494// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1495// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1496// the (C + x + y + ...) expression is \p WholeAddExpr.
1497static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1498 const SCEVConstant *ConstantTerm,
1499 const SCEVAddExpr *WholeAddExpr) {
1500 const APInt &C = ConstantTerm->getAPInt();
1501 const unsigned BitWidth = C.getBitWidth();
1502 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1503 uint32_t TZ = BitWidth;
1504 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1505 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1506 if (TZ) {
1507 // Set D to be as many least significant bits of C as possible while still
1508 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1509 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1510 }
1511 return APInt(BitWidth, 0);
1512}
1513
1514// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1515// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1516// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1517// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1518static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1519 const APInt &ConstantStart,
1520 const SCEV *Step) {
1521 const unsigned BitWidth = ConstantStart.getBitWidth();
1522 const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1523 if (TZ)
1524 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1525 : ConstantStart;
1526 return APInt(BitWidth, 0);
1527}
1528
1529const SCEV *
1530ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1531 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&((getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(
Ty) && "This is not an extending conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1532, __PRETTY_FUNCTION__))
1532 "This is not an extending conversion!")((getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(
Ty) && "This is not an extending conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1532, __PRETTY_FUNCTION__))
;
1533 assert(isSCEVable(Ty) &&((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1534, __PRETTY_FUNCTION__))
1534 "This is not a conversion to a SCEVable type!")((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1534, __PRETTY_FUNCTION__))
;
1535 Ty = getEffectiveSCEVType(Ty);
1536
1537 // Fold if the operand is constant.
1538 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1539 return getConstant(
1540 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1541
1542 // zext(zext(x)) --> zext(x)
1543 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1544 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1545
1546 // Before doing any expensive analysis, check to see if we've already
1547 // computed a SCEV for this Op and Ty.
1548 FoldingSetNodeID ID;
1549 ID.AddInteger(scZeroExtend);
1550 ID.AddPointer(Op);
1551 ID.AddPointer(Ty);
1552 void *IP = nullptr;
1553 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1554 if (Depth > MaxCastDepth) {
1555 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1556 Op, Ty);
1557 UniqueSCEVs.InsertNode(S, IP);
1558 addToLoopUseLists(S);
1559 return S;
1560 }
1561
1562 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1563 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1564 // It's possible the bits taken off by the truncate were all zero bits. If
1565 // so, we should be able to simplify this further.
1566 const SCEV *X = ST->getOperand();
1567 ConstantRange CR = getUnsignedRange(X);
1568 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1569 unsigned NewBits = getTypeSizeInBits(Ty);
1570 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1571 CR.zextOrTrunc(NewBits)))
1572 return getTruncateOrZeroExtend(X, Ty, Depth);
1573 }
1574
1575 // If the input value is a chrec scev, and we can prove that the value
1576 // did not overflow the old, smaller, value, we can zero extend all of the
1577 // operands (often constants). This allows analysis of something like
1578 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1579 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1580 if (AR->isAffine()) {
1581 const SCEV *Start = AR->getStart();
1582 const SCEV *Step = AR->getStepRecurrence(*this);
1583 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1584 const Loop *L = AR->getLoop();
1585
1586 if (!AR->hasNoUnsignedWrap()) {
1587 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1588 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1589 }
1590
1591 // If we have special knowledge that this addrec won't overflow,
1592 // we don't need to do any further analysis.
1593 if (AR->hasNoUnsignedWrap())
1594 return getAddRecExpr(
1595 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1596 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1597
1598 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1599 // Note that this serves two purposes: It filters out loops that are
1600 // simply not analyzable, and it covers the case where this code is
1601 // being called from within backedge-taken count analysis, such that
1602 // attempting to ask for the backedge-taken count would likely result
1603 // in infinite recursion. In the later case, the analysis code will
1604 // cope with a conservative value, and it will take care to purge
1605 // that value once it has finished.
1606 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1607 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1608 // Manually compute the final value for AR, checking for overflow.
1609
1610 // Check whether the backedge-taken count can be losslessly casted to
1611 // the addrec's type. The count is always unsigned.
1612 const SCEV *CastedMaxBECount =
1613 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1614 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1615 CastedMaxBECount, MaxBECount->getType(), Depth);
1616 if (MaxBECount == RecastedMaxBECount) {
1617 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1618 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1619 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1620 SCEV::FlagAnyWrap, Depth + 1);
1621 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1622 SCEV::FlagAnyWrap,
1623 Depth + 1),
1624 WideTy, Depth + 1);
1625 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1626 const SCEV *WideMaxBECount =
1627 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1628 const SCEV *OperandExtendedAdd =
1629 getAddExpr(WideStart,
1630 getMulExpr(WideMaxBECount,
1631 getZeroExtendExpr(Step, WideTy, Depth + 1),
1632 SCEV::FlagAnyWrap, Depth + 1),
1633 SCEV::FlagAnyWrap, Depth + 1);
1634 if (ZAdd == OperandExtendedAdd) {
1635 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1636 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1637 // Return the expression with the addrec on the outside.
1638 return getAddRecExpr(
1639 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1640 Depth + 1),
1641 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1642 AR->getNoWrapFlags());
1643 }
1644 // Similar to above, only this time treat the step value as signed.
1645 // This covers loops that count down.
1646 OperandExtendedAdd =
1647 getAddExpr(WideStart,
1648 getMulExpr(WideMaxBECount,
1649 getSignExtendExpr(Step, WideTy, Depth + 1),
1650 SCEV::FlagAnyWrap, Depth + 1),
1651 SCEV::FlagAnyWrap, Depth + 1);
1652 if (ZAdd == OperandExtendedAdd) {
1653 // Cache knowledge of AR NW, which is propagated to this AddRec.
1654 // Negative step causes unsigned wrap, but it still can't self-wrap.
1655 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1656 // Return the expression with the addrec on the outside.
1657 return getAddRecExpr(
1658 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1659 Depth + 1),
1660 getSignExtendExpr(Step, Ty, Depth + 1), L,
1661 AR->getNoWrapFlags());
1662 }
1663 }
1664 }
1665
1666 // Normally, in the cases we can prove no-overflow via a
1667 // backedge guarding condition, we can also compute a backedge
1668 // taken count for the loop. The exceptions are assumptions and
1669 // guards present in the loop -- SCEV is not great at exploiting
1670 // these to compute max backedge taken counts, but can still use
1671 // these to prove lack of overflow. Use this fact to avoid
1672 // doing extra work that may not pay off.
1673 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1674 !AC.assumptions().empty()) {
1675
1676 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1677 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1678 if (AR->hasNoUnsignedWrap()) {
1679 // Same as nuw case above - duplicated here to avoid a compile time
1680 // issue. It's not clear that the order of checks does matter, but
1681 // it's one of two issue possible causes for a change which was
1682 // reverted. Be conservative for the moment.
1683 return getAddRecExpr(
1684 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1685 Depth + 1),
1686 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1687 AR->getNoWrapFlags());
1688 }
1689
1690 // For a negative step, we can extend the operands iff doing so only
1691 // traverses values in the range zext([0,UINT_MAX]).
1692 if (isKnownNegative(Step)) {
1693 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1694 getSignedRangeMin(Step));
1695 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1696 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1697 // Cache knowledge of AR NW, which is propagated to this
1698 // AddRec. Negative step causes unsigned wrap, but it
1699 // still can't self-wrap.
1700 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1701 // Return the expression with the addrec on the outside.
1702 return getAddRecExpr(
1703 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1704 Depth + 1),
1705 getSignExtendExpr(Step, Ty, Depth + 1), L,
1706 AR->getNoWrapFlags());
1707 }
1708 }
1709 }
1710
1711 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1712 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1713 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1714 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1715 const APInt &C = SC->getAPInt();
1716 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1717 if (D != 0) {
1718 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1719 const SCEV *SResidual =
1720 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1721 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1722 return getAddExpr(SZExtD, SZExtR,
1723 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1724 Depth + 1);
1725 }
1726 }
1727
1728 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1729 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1730 return getAddRecExpr(
1731 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1732 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1733 }
1734 }
1735
1736 // zext(A % B) --> zext(A) % zext(B)
1737 {
1738 const SCEV *LHS;
1739 const SCEV *RHS;
1740 if (matchURem(Op, LHS, RHS))
1741 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1742 getZeroExtendExpr(RHS, Ty, Depth + 1));
1743 }
1744
1745 // zext(A / B) --> zext(A) / zext(B).
1746 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1747 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1748 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1749
1750 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1751 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1752 if (SA->hasNoUnsignedWrap()) {
1753 // If the addition does not unsign overflow then we can, by definition,
1754 // commute the zero extension with the addition operation.
1755 SmallVector<const SCEV *, 4> Ops;
1756 for (const auto *Op : SA->operands())
1757 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1758 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1759 }
1760
1761 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1762 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1763 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1764 //
1765 // Often address arithmetics contain expressions like
1766 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1767 // This transformation is useful while proving that such expressions are
1768 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1769 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1770 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1771 if (D != 0) {
1772 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1773 const SCEV *SResidual =
1774 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1775 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1776 return getAddExpr(SZExtD, SZExtR,
1777 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1778 Depth + 1);
1779 }
1780 }
1781 }
1782
1783 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1784 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1785 if (SM->hasNoUnsignedWrap()) {
1786 // If the multiply does not unsign overflow then we can, by definition,
1787 // commute the zero extension with the multiply operation.
1788 SmallVector<const SCEV *, 4> Ops;
1789 for (const auto *Op : SM->operands())
1790 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1791 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1792 }
1793
1794 // zext(2^K * (trunc X to iN)) to iM ->
1795 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1796 //
1797 // Proof:
1798 //
1799 // zext(2^K * (trunc X to iN)) to iM
1800 // = zext((trunc X to iN) << K) to iM
1801 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1802 // (because shl removes the top K bits)
1803 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1804 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1805 //
1806 if (SM->getNumOperands() == 2)
1807 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1808 if (MulLHS->getAPInt().isPowerOf2())
1809 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1810 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1811 MulLHS->getAPInt().logBase2();
1812 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1813 return getMulExpr(
1814 getZeroExtendExpr(MulLHS, Ty),
1815 getZeroExtendExpr(
1816 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1817 SCEV::FlagNUW, Depth + 1);
1818 }
1819 }
1820
1821 // The cast wasn't folded; create an explicit cast node.
1822 // Recompute the insert position, as it may have been invalidated.
1823 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1824 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1825 Op, Ty);
1826 UniqueSCEVs.InsertNode(S, IP);
1827 addToLoopUseLists(S);
1828 return S;
1829}
1830
1831const SCEV *
1832ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1833 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&((getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(
Ty) && "This is not an extending conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1834, __PRETTY_FUNCTION__))
1834 "This is not an extending conversion!")((getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(
Ty) && "This is not an extending conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1834, __PRETTY_FUNCTION__))
;
1835 assert(isSCEVable(Ty) &&((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1836, __PRETTY_FUNCTION__))
1836 "This is not a conversion to a SCEVable type!")((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 1836, __PRETTY_FUNCTION__))
;
1837 Ty = getEffectiveSCEVType(Ty);
1838
1839 // Fold if the operand is constant.
1840 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1841 return getConstant(
1842 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1843
1844 // sext(sext(x)) --> sext(x)
1845 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1846 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1847
1848 // sext(zext(x)) --> zext(x)
1849 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1850 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1851
1852 // Before doing any expensive analysis, check to see if we've already
1853 // computed a SCEV for this Op and Ty.
1854 FoldingSetNodeID ID;
1855 ID.AddInteger(scSignExtend);
1856 ID.AddPointer(Op);
1857 ID.AddPointer(Ty);
1858 void *IP = nullptr;
1859 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1860 // Limit recursion depth.
1861 if (Depth > MaxCastDepth) {
1862 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1863 Op, Ty);
1864 UniqueSCEVs.InsertNode(S, IP);
1865 addToLoopUseLists(S);
1866 return S;
1867 }
1868
1869 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1870 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1871 // It's possible the bits taken off by the truncate were all sign bits. If
1872 // so, we should be able to simplify this further.
1873 const SCEV *X = ST->getOperand();
1874 ConstantRange CR = getSignedRange(X);
1875 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1876 unsigned NewBits = getTypeSizeInBits(Ty);
1877 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1878 CR.sextOrTrunc(NewBits)))
1879 return getTruncateOrSignExtend(X, Ty, Depth);
1880 }
1881
1882 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1883 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1884 if (SA->hasNoSignedWrap()) {
1885 // If the addition does not sign overflow then we can, by definition,
1886 // commute the sign extension with the addition operation.
1887 SmallVector<const SCEV *, 4> Ops;
1888 for (const auto *Op : SA->operands())
1889 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1890 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1891 }
1892
1893 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1894 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1895 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1896 //
1897 // For instance, this will bring two seemingly different expressions:
1898 // 1 + sext(5 + 20 * %x + 24 * %y) and
1899 // sext(6 + 20 * %x + 24 * %y)
1900 // to the same form:
1901 // 2 + sext(4 + 20 * %x + 24 * %y)
1902 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1903 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1904 if (D != 0) {
1905 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1906 const SCEV *SResidual =
1907 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1908 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1909 return getAddExpr(SSExtD, SSExtR,
1910 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1911 Depth + 1);
1912 }
1913 }
1914 }
1915 // If the input value is a chrec scev, and we can prove that the value
1916 // did not overflow the old, smaller, value, we can sign extend all of the
1917 // operands (often constants). This allows analysis of something like
1918 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1919 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1920 if (AR->isAffine()) {
1921 const SCEV *Start = AR->getStart();
1922 const SCEV *Step = AR->getStepRecurrence(*this);
1923 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1924 const Loop *L = AR->getLoop();
1925
1926 if (!AR->hasNoSignedWrap()) {
1927 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1928 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1929 }
1930
1931 // If we have special knowledge that this addrec won't overflow,
1932 // we don't need to do any further analysis.
1933 if (AR->hasNoSignedWrap())
1934 return getAddRecExpr(
1935 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
1936 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
1937
1938 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1939 // Note that this serves two purposes: It filters out loops that are
1940 // simply not analyzable, and it covers the case where this code is
1941 // being called from within backedge-taken count analysis, such that
1942 // attempting to ask for the backedge-taken count would likely result
1943 // in infinite recursion. In the later case, the analysis code will
1944 // cope with a conservative value, and it will take care to purge
1945 // that value once it has finished.
1946 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1947 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1948 // Manually compute the final value for AR, checking for
1949 // overflow.
1950
1951 // Check whether the backedge-taken count can be losslessly casted to
1952 // the addrec's type. The count is always unsigned.
1953 const SCEV *CastedMaxBECount =
1954 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1955 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1956 CastedMaxBECount, MaxBECount->getType(), Depth);
1957 if (MaxBECount == RecastedMaxBECount) {
1958 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1959 // Check whether Start+Step*MaxBECount has no signed overflow.
1960 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
1961 SCEV::FlagAnyWrap, Depth + 1);
1962 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
1963 SCEV::FlagAnyWrap,
1964 Depth + 1),
1965 WideTy, Depth + 1);
1966 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
1967 const SCEV *WideMaxBECount =
1968 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1969 const SCEV *OperandExtendedAdd =
1970 getAddExpr(WideStart,
1971 getMulExpr(WideMaxBECount,
1972 getSignExtendExpr(Step, WideTy, Depth + 1),
1973 SCEV::FlagAnyWrap, Depth + 1),
1974 SCEV::FlagAnyWrap, Depth + 1);
1975 if (SAdd == OperandExtendedAdd) {
1976 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1977 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
1978 // Return the expression with the addrec on the outside.
1979 return getAddRecExpr(
1980 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
1981 Depth + 1),
1982 getSignExtendExpr(Step, Ty, Depth + 1), L,
1983 AR->getNoWrapFlags());
1984 }
1985 // Similar to above, only this time treat the step value as unsigned.
1986 // This covers loops that count up with an unsigned step.
1987 OperandExtendedAdd =
1988 getAddExpr(WideStart,
1989 getMulExpr(WideMaxBECount,
1990 getZeroExtendExpr(Step, WideTy, Depth + 1),
1991 SCEV::FlagAnyWrap, Depth + 1),
1992 SCEV::FlagAnyWrap, Depth + 1);
1993 if (SAdd == OperandExtendedAdd) {
1994 // If AR wraps around then
1995 //
1996 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1997 // => SAdd != OperandExtendedAdd
1998 //
1999 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2000 // (SAdd == OperandExtendedAdd => AR is NW)
2001
2002 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2003
2004 // Return the expression with the addrec on the outside.
2005 return getAddRecExpr(
2006 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2007 Depth + 1),
2008 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2009 AR->getNoWrapFlags());
2010 }
2011 }
2012 }
2013
2014 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2015 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2016 if (AR->hasNoSignedWrap()) {
2017 // Same as nsw case above - duplicated here to avoid a compile time
2018 // issue. It's not clear that the order of checks does matter, but
2019 // it's one of two issue possible causes for a change which was
2020 // reverted. Be conservative for the moment.
2021 return getAddRecExpr(
2022 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2023 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2024 }
2025
2026 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2027 // if D + (C - D + Step * n) could be proven to not signed wrap
2028 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2029 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2030 const APInt &C = SC->getAPInt();
2031 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2032 if (D != 0) {
2033 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2034 const SCEV *SResidual =
2035 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2036 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2037 return getAddExpr(SSExtD, SSExtR,
2038 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2039 Depth + 1);
2040 }
2041 }
2042
2043 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2044 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2045 return getAddRecExpr(
2046 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2047 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2048 }
2049 }
2050
2051 // If the input value is provably positive and we could not simplify
2052 // away the sext build a zext instead.
2053 if (isKnownNonNegative(Op))
2054 return getZeroExtendExpr(Op, Ty, Depth + 1);
2055
2056 // The cast wasn't folded; create an explicit cast node.
2057 // Recompute the insert position, as it may have been invalidated.
2058 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2059 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2060 Op, Ty);
2061 UniqueSCEVs.InsertNode(S, IP);
2062 addToLoopUseLists(S);
2063 return S;
2064}
2065
2066/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2067/// unspecified bits out to the given type.
2068const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2069 Type *Ty) {
2070 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&((getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(
Ty) && "This is not an extending conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2071, __PRETTY_FUNCTION__))
2071 "This is not an extending conversion!")((getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(
Ty) && "This is not an extending conversion!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && \"This is not an extending conversion!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2071, __PRETTY_FUNCTION__))
;
2072 assert(isSCEVable(Ty) &&((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2073, __PRETTY_FUNCTION__))
2073 "This is not a conversion to a SCEVable type!")((isSCEVable(Ty) && "This is not a conversion to a SCEVable type!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(Ty) && \"This is not a conversion to a SCEVable type!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2073, __PRETTY_FUNCTION__))
;
2074 Ty = getEffectiveSCEVType(Ty);
2075
2076 // Sign-extend negative constants.
2077 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2078 if (SC->getAPInt().isNegative())
2079 return getSignExtendExpr(Op, Ty);
2080
2081 // Peel off a truncate cast.
2082 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2083 const SCEV *NewOp = T->getOperand();
2084 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2085 return getAnyExtendExpr(NewOp, Ty);
2086 return getTruncateOrNoop(NewOp, Ty);
2087 }
2088
2089 // Next try a zext cast. If the cast is folded, use it.
2090 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2091 if (!isa<SCEVZeroExtendExpr>(ZExt))
2092 return ZExt;
2093
2094 // Next try a sext cast. If the cast is folded, use it.
2095 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2096 if (!isa<SCEVSignExtendExpr>(SExt))
2097 return SExt;
2098
2099 // Force the cast to be folded into the operands of an addrec.
2100 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2101 SmallVector<const SCEV *, 4> Ops;
2102 for (const SCEV *Op : AR->operands())
2103 Ops.push_back(getAnyExtendExpr(Op, Ty));
2104 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2105 }
2106
2107 // If the expression is obviously signed, use the sext cast value.
2108 if (isa<SCEVSMaxExpr>(Op))
2109 return SExt;
2110
2111 // Absent any other information, use the zext cast value.
2112 return ZExt;
2113}
2114
2115/// Process the given Ops list, which is a list of operands to be added under
2116/// the given scale, update the given map. This is a helper function for
2117/// getAddRecExpr. As an example of what it does, given a sequence of operands
2118/// that would form an add expression like this:
2119///
2120/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2121///
2122/// where A and B are constants, update the map with these values:
2123///
2124/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2125///
2126/// and add 13 + A*B*29 to AccumulatedConstant.
2127/// This will allow getAddRecExpr to produce this:
2128///
2129/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2130///
2131/// This form often exposes folding opportunities that are hidden in
2132/// the original operand list.
2133///
2134/// Return true iff it appears that any interesting folding opportunities
2135/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2136/// the common case where no interesting opportunities are present, and
2137/// is also used as a check to avoid infinite recursion.
2138static bool
2139CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2140 SmallVectorImpl<const SCEV *> &NewOps,
2141 APInt &AccumulatedConstant,
2142 const SCEV *const *Ops, size_t NumOperands,
2143 const APInt &Scale,
2144 ScalarEvolution &SE) {
2145 bool Interesting = false;
2146
2147 // Iterate over the add operands. They are sorted, with constants first.
2148 unsigned i = 0;
2149 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2150 ++i;
2151 // Pull a buried constant out to the outside.
2152 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2153 Interesting = true;
2154 AccumulatedConstant += Scale * C->getAPInt();
2155 }
2156
2157 // Next comes everything else. We're especially interested in multiplies
2158 // here, but they're in the middle, so just visit the rest with one loop.
2159 for (; i != NumOperands; ++i) {
2160 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2161 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2162 APInt NewScale =
2163 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2164 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2165 // A multiplication of a constant with another add; recurse.
2166 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2167 Interesting |=
2168 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2169 Add->op_begin(), Add->getNumOperands(),
2170 NewScale, SE);
2171 } else {
2172 // A multiplication of a constant with some other value. Update
2173 // the map.
2174 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2175 const SCEV *Key = SE.getMulExpr(MulOps);
2176 auto Pair = M.insert({Key, NewScale});
2177 if (Pair.second) {
2178 NewOps.push_back(Pair.first->first);
2179 } else {
2180 Pair.first->second += NewScale;
2181 // The map already had an entry for this value, which may indicate
2182 // a folding opportunity.
2183 Interesting = true;
2184 }
2185 }
2186 } else {
2187 // An ordinary operand. Update the map.
2188 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2189 M.insert({Ops[i], Scale});
2190 if (Pair.second) {
2191 NewOps.push_back(Pair.first->first);
2192 } else {
2193 Pair.first->second += Scale;
2194 // The map already had an entry for this value, which may indicate
2195 // a folding opportunity.
2196 Interesting = true;
2197 }
2198 }
2199 }
2200
2201 return Interesting;
2202}
2203
2204// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2205// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2206// can't-overflow flags for the operation if possible.
2207static SCEV::NoWrapFlags
2208StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2209 const ArrayRef<const SCEV *> Ops,
2210 SCEV::NoWrapFlags Flags) {
2211 using namespace std::placeholders;
2212
2213 using OBO = OverflowingBinaryOperator;
2214
2215 bool CanAnalyze =
2216 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2217 (void)CanAnalyze;
2218 assert(CanAnalyze && "don't call from other places!")((CanAnalyze && "don't call from other places!") ? static_cast
<void> (0) : __assert_fail ("CanAnalyze && \"don't call from other places!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2218, __PRETTY_FUNCTION__))
;
2219
2220 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2221 SCEV::NoWrapFlags SignOrUnsignWrap =
2222 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2223
2224 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2225 auto IsKnownNonNegative = [&](const SCEV *S) {
2226 return SE->isKnownNonNegative(S);
2227 };
2228
2229 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2230 Flags =
2231 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2232
2233 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2234
2235 if (SignOrUnsignWrap != SignOrUnsignMask &&
2236 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2237 isa<SCEVConstant>(Ops[0])) {
2238
2239 auto Opcode = [&] {
2240 switch (Type) {
2241 case scAddExpr:
2242 return Instruction::Add;
2243 case scMulExpr:
2244 return Instruction::Mul;
2245 default:
2246 llvm_unreachable("Unexpected SCEV op.")::llvm::llvm_unreachable_internal("Unexpected SCEV op.", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2246)
;
2247 }
2248 }();
2249
2250 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2251
2252 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2253 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2254 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2255 Opcode, C, OBO::NoSignedWrap);
2256 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2257 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2258 }
2259
2260 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2261 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2262 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2263 Opcode, C, OBO::NoUnsignedWrap);
2264 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2265 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2266 }
2267 }
2268
2269 return Flags;
2270}
2271
2272bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2273 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2274}
2275
2276/// Get a canonical add expression, or something simpler if possible.
2277const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2278 SCEV::NoWrapFlags OrigFlags,
2279 unsigned Depth) {
2280 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&((!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
"only nuw or nsw allowed") ? static_cast<void> (0) : __assert_fail
("!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && \"only nuw or nsw allowed\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2281, __PRETTY_FUNCTION__))
2281 "only nuw or nsw allowed")((!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
"only nuw or nsw allowed") ? static_cast<void> (0) : __assert_fail
("!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && \"only nuw or nsw allowed\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2281, __PRETTY_FUNCTION__))
;
2282 assert(!Ops.empty() && "Cannot get empty add!")((!Ops.empty() && "Cannot get empty add!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty add!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2282, __PRETTY_FUNCTION__))
;
2283 if (Ops.size() == 1) return Ops[0];
2284#ifndef NDEBUG
2285 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2286 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2287 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVAddExpr operand types don't match!") ? static_cast<void
> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVAddExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2288, __PRETTY_FUNCTION__))
2288 "SCEVAddExpr operand types don't match!")((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVAddExpr operand types don't match!") ? static_cast<void
> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVAddExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2288, __PRETTY_FUNCTION__))
;
2289#endif
2290
2291 // Sort by complexity, this groups all similar expression types together.
2292 GroupByComplexity(Ops, &LI, DT);
2293
2294 // If there are any constants, fold them together.
2295 unsigned Idx = 0;
2296 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2297 ++Idx;
2298 assert(Idx < Ops.size())((Idx < Ops.size()) ? static_cast<void> (0) : __assert_fail
("Idx < Ops.size()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2298, __PRETTY_FUNCTION__))
;
2299 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2300 // We found two constants, fold them together!
2301 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2302 if (Ops.size() == 2) return Ops[0];
2303 Ops.erase(Ops.begin()+1); // Erase the folded element
2304 LHSC = cast<SCEVConstant>(Ops[0]);
2305 }
2306
2307 // If we are left with a constant zero being added, strip it off.
2308 if (LHSC->getValue()->isZero()) {
2309 Ops.erase(Ops.begin());
2310 --Idx;
2311 }
2312
2313 if (Ops.size() == 1) return Ops[0];
2314 }
2315
2316 // Delay expensive flag strengthening until necessary.
2317 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2318 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2319 };
2320
2321 // Limit recursion calls depth.
2322 if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2323 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2324
2325 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) {
2326 // Don't strengthen flags if we have no new information.
2327 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2328 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2329 Add->setNoWrapFlags(ComputeFlags(Ops));
2330 return S;
2331 }
2332
2333 // Okay, check to see if the same value occurs in the operand list more than
2334 // once. If so, merge them together into an multiply expression. Since we
2335 // sorted the list, these values are required to be adjacent.
2336 Type *Ty = Ops[0]->getType();
2337 bool FoundMatch = false;
2338 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2339 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2340 // Scan ahead to count how many equal operands there are.
2341 unsigned Count = 2;
2342 while (i+Count != e && Ops[i+Count] == Ops[i])
2343 ++Count;
2344 // Merge the values into a multiply.
2345 const SCEV *Scale = getConstant(Ty, Count);
2346 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2347 if (Ops.size() == Count)
2348 return Mul;
2349 Ops[i] = Mul;
2350 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2351 --i; e -= Count - 1;
2352 FoundMatch = true;
2353 }
2354 if (FoundMatch)
2355 return getAddExpr(Ops, OrigFlags, Depth + 1);
2356
2357 // Check for truncates. If all the operands are truncated from the same
2358 // type, see if factoring out the truncate would permit the result to be
2359 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2360 // if the contents of the resulting outer trunc fold to something simple.
2361 auto FindTruncSrcType = [&]() -> Type * {
2362 // We're ultimately looking to fold an addrec of truncs and muls of only
2363 // constants and truncs, so if we find any other types of SCEV
2364 // as operands of the addrec then we bail and return nullptr here.
2365 // Otherwise, we return the type of the operand of a trunc that we find.
2366 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2367 return T->getOperand()->getType();
2368 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2369 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2370 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2371 return T->getOperand()->getType();
2372 }
2373 return nullptr;
2374 };
2375 if (auto *SrcType = FindTruncSrcType()) {
2376 SmallVector<const SCEV *, 8> LargeOps;
2377 bool Ok = true;
2378 // Check all the operands to see if they can be represented in the
2379 // source type of the truncate.
2380 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2381 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2382 if (T->getOperand()->getType() != SrcType) {
2383 Ok = false;
2384 break;
2385 }
2386 LargeOps.push_back(T->getOperand());
2387 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2388 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2389 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2390 SmallVector<const SCEV *, 8> LargeMulOps;
2391 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2392 if (const SCEVTruncateExpr *T =
2393 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2394 if (T->getOperand()->getType() != SrcType) {
2395 Ok = false;
2396 break;
2397 }
2398 LargeMulOps.push_back(T->getOperand());
2399 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2400 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2401 } else {
2402 Ok = false;
2403 break;
2404 }
2405 }
2406 if (Ok)
2407 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2408 } else {
2409 Ok = false;
2410 break;
2411 }
2412 }
2413 if (Ok) {
2414 // Evaluate the expression in the larger type.
2415 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2416 // If it folds to something simple, use it. Otherwise, don't.
2417 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2418 return getTruncateExpr(Fold, Ty);
2419 }
2420 }
2421
2422 // Skip past any other cast SCEVs.
2423 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2424 ++Idx;
2425
2426 // If there are add operands they would be next.
2427 if (Idx < Ops.size()) {
2428 bool DeletedAdd = false;
2429 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2430 if (Ops.size() > AddOpsInlineThreshold ||
2431 Add->getNumOperands() > AddOpsInlineThreshold)
2432 break;
2433 // If we have an add, expand the add operands onto the end of the operands
2434 // list.
2435 Ops.erase(Ops.begin()+Idx);
2436 Ops.append(Add->op_begin(), Add->op_end());
2437 DeletedAdd = true;
2438 }
2439
2440 // If we deleted at least one add, we added operands to the end of the list,
2441 // and they are not necessarily sorted. Recurse to resort and resimplify
2442 // any operands we just acquired.
2443 if (DeletedAdd)
2444 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2445 }
2446
2447 // Skip over the add expression until we get to a multiply.
2448 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2449 ++Idx;
2450
2451 // Check to see if there are any folding opportunities present with
2452 // operands multiplied by constant values.
2453 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2454 uint64_t BitWidth = getTypeSizeInBits(Ty);
2455 DenseMap<const SCEV *, APInt> M;
2456 SmallVector<const SCEV *, 8> NewOps;
2457 APInt AccumulatedConstant(BitWidth, 0);
2458 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2459 Ops.data(), Ops.size(),
2460 APInt(BitWidth, 1), *this)) {
2461 struct APIntCompare {
2462 bool operator()(const APInt &LHS, const APInt &RHS) const {
2463 return LHS.ult(RHS);
2464 }
2465 };
2466
2467 // Some interesting folding opportunity is present, so its worthwhile to
2468 // re-generate the operands list. Group the operands by constant scale,
2469 // to avoid multiplying by the same constant scale multiple times.
2470 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2471 for (const SCEV *NewOp : NewOps)
2472 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2473 // Re-generate the operands list.
2474 Ops.clear();
2475 if (AccumulatedConstant != 0)
2476 Ops.push_back(getConstant(AccumulatedConstant));
2477 for (auto &MulOp : MulOpLists)
2478 if (MulOp.first != 0)
2479 Ops.push_back(getMulExpr(
2480 getConstant(MulOp.first),
2481 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2482 SCEV::FlagAnyWrap, Depth + 1));
2483 if (Ops.empty())
2484 return getZero(Ty);
2485 if (Ops.size() == 1)
2486 return Ops[0];
2487 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2488 }
2489 }
2490
2491 // If we are adding something to a multiply expression, make sure the
2492 // something is not already an operand of the multiply. If so, merge it into
2493 // the multiply.
2494 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2495 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2496 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2497 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2498 if (isa<SCEVConstant>(MulOpSCEV))
2499 continue;
2500 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2501 if (MulOpSCEV == Ops[AddOp]) {
2502 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2503 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2504 if (Mul->getNumOperands() != 2) {
2505 // If the multiply has more than two operands, we must get the
2506 // Y*Z term.
2507 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2508 Mul->op_begin()+MulOp);
2509 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2510 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2511 }
2512 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2513 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2514 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2515 SCEV::FlagAnyWrap, Depth + 1);
2516 if (Ops.size() == 2) return OuterMul;
2517 if (AddOp < Idx) {
2518 Ops.erase(Ops.begin()+AddOp);
2519 Ops.erase(Ops.begin()+Idx-1);
2520 } else {
2521 Ops.erase(Ops.begin()+Idx);
2522 Ops.erase(Ops.begin()+AddOp-1);
2523 }
2524 Ops.push_back(OuterMul);
2525 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2526 }
2527
2528 // Check this multiply against other multiplies being added together.
2529 for (unsigned OtherMulIdx = Idx+1;
2530 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2531 ++OtherMulIdx) {
2532 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2533 // If MulOp occurs in OtherMul, we can fold the two multiplies
2534 // together.
2535 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2536 OMulOp != e; ++OMulOp)
2537 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2538 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2539 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2540 if (Mul->getNumOperands() != 2) {
2541 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2542 Mul->op_begin()+MulOp);
2543 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2544 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2545 }
2546 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2547 if (OtherMul->getNumOperands() != 2) {
2548 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2549 OtherMul->op_begin()+OMulOp);
2550 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2551 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2552 }
2553 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2554 const SCEV *InnerMulSum =
2555 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2556 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2557 SCEV::FlagAnyWrap, Depth + 1);
2558 if (Ops.size() == 2) return OuterMul;
2559 Ops.erase(Ops.begin()+Idx);
2560 Ops.erase(Ops.begin()+OtherMulIdx-1);
2561 Ops.push_back(OuterMul);
2562 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2563 }
2564 }
2565 }
2566 }
2567
2568 // If there are any add recurrences in the operands list, see if any other
2569 // added values are loop invariant. If so, we can fold them into the
2570 // recurrence.
2571 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2572 ++Idx;
2573
2574 // Scan over all recurrences, trying to fold loop invariants into them.
2575 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2576 // Scan all of the other operands to this add and add them to the vector if
2577 // they are loop invariant w.r.t. the recurrence.
2578 SmallVector<const SCEV *, 8> LIOps;
2579 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2580 const Loop *AddRecLoop = AddRec->getLoop();
2581 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2582 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2583 LIOps.push_back(Ops[i]);
2584 Ops.erase(Ops.begin()+i);
2585 --i; --e;
2586 }
2587
2588 // If we found some loop invariants, fold them into the recurrence.
2589 if (!LIOps.empty()) {
2590 // Compute nowrap flags for the addition of the loop-invariant ops and
2591 // the addrec. Temporarily push it as an operand for that purpose.
2592 LIOps.push_back(AddRec);
2593 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2594 LIOps.pop_back();
2595
2596 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2597 LIOps.push_back(AddRec->getStart());
2598
2599 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2600 AddRec->op_end());
2601 // This follows from the fact that the no-wrap flags on the outer add
2602 // expression are applicable on the 0th iteration, when the add recurrence
2603 // will be equal to its start value.
2604 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2605
2606 // Build the new addrec. Propagate the NUW and NSW flags if both the
2607 // outer add and the inner addrec are guaranteed to have no overflow.
2608 // Always propagate NW.
2609 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2610 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2611
2612 // If all of the other operands were loop invariant, we are done.
2613 if (Ops.size() == 1) return NewRec;
2614
2615 // Otherwise, add the folded AddRec by the non-invariant parts.
2616 for (unsigned i = 0;; ++i)
2617 if (Ops[i] == AddRec) {
2618 Ops[i] = NewRec;
2619 break;
2620 }
2621 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2622 }
2623
2624 // Okay, if there weren't any loop invariants to be folded, check to see if
2625 // there are multiple AddRec's with the same loop induction variable being
2626 // added together. If so, we can fold them.
2627 for (unsigned OtherIdx = Idx+1;
2628 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2629 ++OtherIdx) {
2630 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2631 // so that the 1st found AddRecExpr is dominated by all others.
2632 assert(DT.dominates(((DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->
getLoop()->getHeader(), AddRec->getLoop()->getHeader
()) && "AddRecExprs are not sorted in reverse dominance order?"
) ? static_cast<void> (0) : __assert_fail ("DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->getLoop()->getHeader()) && \"AddRecExprs are not sorted in reverse dominance order?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2635, __PRETTY_FUNCTION__))
2633 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),((DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->
getLoop()->getHeader(), AddRec->getLoop()->getHeader
()) && "AddRecExprs are not sorted in reverse dominance order?"
) ? static_cast<void> (0) : __assert_fail ("DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->getLoop()->getHeader()) && \"AddRecExprs are not sorted in reverse dominance order?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2635, __PRETTY_FUNCTION__))
2634 AddRec->getLoop()->getHeader()) &&((DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->
getLoop()->getHeader(), AddRec->getLoop()->getHeader
()) && "AddRecExprs are not sorted in reverse dominance order?"
) ? static_cast<void> (0) : __assert_fail ("DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->getLoop()->getHeader()) && \"AddRecExprs are not sorted in reverse dominance order?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2635, __PRETTY_FUNCTION__))
2635 "AddRecExprs are not sorted in reverse dominance order?")((DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->
getLoop()->getHeader(), AddRec->getLoop()->getHeader
()) && "AddRecExprs are not sorted in reverse dominance order?"
) ? static_cast<void> (0) : __assert_fail ("DT.dominates( cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), AddRec->getLoop()->getHeader()) && \"AddRecExprs are not sorted in reverse dominance order?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2635, __PRETTY_FUNCTION__))
;
2636 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2637 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2638 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2639 AddRec->op_end());
2640 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2641 ++OtherIdx) {
2642 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2643 if (OtherAddRec->getLoop() == AddRecLoop) {
2644 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2645 i != e; ++i) {
2646 if (i >= AddRecOps.size()) {
2647 AddRecOps.append(OtherAddRec->op_begin()+i,
2648 OtherAddRec->op_end());
2649 break;
2650 }
2651 SmallVector<const SCEV *, 2> TwoOps = {
2652 AddRecOps[i], OtherAddRec->getOperand(i)};
2653 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2654 }
2655 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2656 }
2657 }
2658 // Step size has changed, so we cannot guarantee no self-wraparound.
2659 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2660 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2661 }
2662 }
2663
2664 // Otherwise couldn't fold anything into this recurrence. Move onto the
2665 // next one.
2666 }
2667
2668 // Okay, it looks like we really DO need an add expr. Check to see if we
2669 // already have one, otherwise create a new one.
2670 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2671}
2672
2673const SCEV *
2674ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2675 SCEV::NoWrapFlags Flags) {
2676 FoldingSetNodeID ID;
2677 ID.AddInteger(scAddExpr);
2678 for (const SCEV *Op : Ops)
2679 ID.AddPointer(Op);
2680 void *IP = nullptr;
2681 SCEVAddExpr *S =
2682 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2683 if (!S) {
2684 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2685 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2686 S = new (SCEVAllocator)
2687 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2688 UniqueSCEVs.InsertNode(S, IP);
2689 addToLoopUseLists(S);
2690 }
2691 S->setNoWrapFlags(Flags);
2692 return S;
2693}
2694
2695const SCEV *
2696ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2697 const Loop *L, SCEV::NoWrapFlags Flags) {
2698 FoldingSetNodeID ID;
2699 ID.AddInteger(scAddRecExpr);
2700 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2701 ID.AddPointer(Ops[i]);
2702 ID.AddPointer(L);
2703 void *IP = nullptr;
2704 SCEVAddRecExpr *S =
2705 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2706 if (!S) {
2707 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2708 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2709 S = new (SCEVAllocator)
2710 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2711 UniqueSCEVs.InsertNode(S, IP);
2712 addToLoopUseLists(S);
2713 }
2714 setNoWrapFlags(S, Flags);
2715 return S;
2716}
2717
2718const SCEV *
2719ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2720 SCEV::NoWrapFlags Flags) {
2721 FoldingSetNodeID ID;
2722 ID.AddInteger(scMulExpr);
2723 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2724 ID.AddPointer(Ops[i]);
2725 void *IP = nullptr;
2726 SCEVMulExpr *S =
2727 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2728 if (!S) {
2729 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2730 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2731 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2732 O, Ops.size());
2733 UniqueSCEVs.InsertNode(S, IP);
2734 addToLoopUseLists(S);
2735 }
2736 S->setNoWrapFlags(Flags);
2737 return S;
2738}
2739
2740static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2741 uint64_t k = i*j;
2742 if (j > 1 && k / j != i) Overflow = true;
2743 return k;
2744}
2745
2746/// Compute the result of "n choose k", the binomial coefficient. If an
2747/// intermediate computation overflows, Overflow will be set and the return will
2748/// be garbage. Overflow is not cleared on absence of overflow.
2749static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2750 // We use the multiplicative formula:
2751 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2752 // At each iteration, we take the n-th term of the numeral and divide by the
2753 // (k-n)th term of the denominator. This division will always produce an
2754 // integral result, and helps reduce the chance of overflow in the
2755 // intermediate computations. However, we can still overflow even when the
2756 // final result would fit.
2757
2758 if (n == 0 || n == k) return 1;
2759 if (k > n) return 0;
2760
2761 if (k > n/2)
2762 k = n-k;
2763
2764 uint64_t r = 1;
2765 for (uint64_t i = 1; i <= k; ++i) {
2766 r = umul_ov(r, n-(i-1), Overflow);
2767 r /= i;
2768 }
2769 return r;
2770}
2771
2772/// Determine if any of the operands in this SCEV are a constant or if
2773/// any of the add or multiply expressions in this SCEV contain a constant.
2774static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2775 struct FindConstantInAddMulChain {
2776 bool FoundConstant = false;
2777
2778 bool follow(const SCEV *S) {
2779 FoundConstant |= isa<SCEVConstant>(S);
2780 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2781 }
2782
2783 bool isDone() const {
2784 return FoundConstant;
2785 }
2786 };
2787
2788 FindConstantInAddMulChain F;
2789 SCEVTraversal<FindConstantInAddMulChain> ST(F);
2790 ST.visitAll(StartExpr);
2791 return F.FoundConstant;
2792}
2793
2794/// Get a canonical multiply expression, or something simpler if possible.
2795const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2796 SCEV::NoWrapFlags OrigFlags,
2797 unsigned Depth) {
2798 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&((OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW
) && "only nuw or nsw allowed") ? static_cast<void
> (0) : __assert_fail ("OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && \"only nuw or nsw allowed\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2799, __PRETTY_FUNCTION__))
2799 "only nuw or nsw allowed")((OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW
) && "only nuw or nsw allowed") ? static_cast<void
> (0) : __assert_fail ("OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && \"only nuw or nsw allowed\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2799, __PRETTY_FUNCTION__))
;
2800 assert(!Ops.empty() && "Cannot get empty mul!")((!Ops.empty() && "Cannot get empty mul!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty mul!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2800, __PRETTY_FUNCTION__))
;
2801 if (Ops.size() == 1) return Ops[0];
2802#ifndef NDEBUG
2803 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2804 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2805 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVMulExpr operand types don't match!") ? static_cast<void
> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVMulExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2806, __PRETTY_FUNCTION__))
2806 "SCEVMulExpr operand types don't match!")((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"SCEVMulExpr operand types don't match!") ? static_cast<void
> (0) : __assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"SCEVMulExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2806, __PRETTY_FUNCTION__))
;
2807#endif
2808
2809 // Sort by complexity, this groups all similar expression types together.
2810 GroupByComplexity(Ops, &LI, DT);
2811
2812 // If there are any constants, fold them together.
2813 unsigned Idx = 0;
2814 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2815 ++Idx;
2816 assert(Idx < Ops.size())((Idx < Ops.size()) ? static_cast<void> (0) : __assert_fail
("Idx < Ops.size()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 2816, __PRETTY_FUNCTION__))
;
2817 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2818 // We found two constants, fold them together!
2819 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
2820 if (Ops.size() == 2) return Ops[0];
2821 Ops.erase(Ops.begin()+1); // Erase the folded element
2822 LHSC = cast<SCEVConstant>(Ops[0]);
2823 }
2824
2825 // If we have a multiply of zero, it will always be zero.
2826 if (LHSC->getValue()->isZero())
2827 return LHSC;
2828
2829 // If we are left with a constant one being multiplied, strip it off.
2830 if (LHSC->getValue()->isOne()) {
2831 Ops.erase(Ops.begin());
2832 --Idx;
2833 }
2834
2835 if (Ops.size() == 1)
2836 return Ops[0];
2837 }
2838
2839 // Delay expensive flag strengthening until necessary.
2840 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
2841 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
2842 };
2843
2844 // Limit recursion calls depth.
2845 if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2846 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
2847
2848 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) {
2849 // Don't strengthen flags if we have no new information.
2850 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
2851 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
2852 Mul->setNoWrapFlags(ComputeFlags(Ops));
2853 return S;
2854 }
2855
2856 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2857 if (Ops.size() == 2) {
2858 // C1*(C2+V) -> C1*C2 + C1*V
2859 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2860 // If any of Add's ops are Adds or Muls with a constant, apply this
2861 // transformation as well.
2862 //
2863 // TODO: There are some cases where this transformation is not
2864 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
2865 // this transformation should be narrowed down.
2866 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2867 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2868 SCEV::FlagAnyWrap, Depth + 1),
2869 getMulExpr(LHSC, Add->getOperand(1),
2870 SCEV::FlagAnyWrap, Depth + 1),
2871 SCEV::FlagAnyWrap, Depth + 1);
2872
2873 if (Ops[0]->isAllOnesValue()) {
2874 // If we have a mul by -1 of an add, try distributing the -1 among the
2875 // add operands.
2876 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2877 SmallVector<const SCEV *, 4> NewOps;
2878 bool AnyFolded = false;
2879 for (const SCEV *AddOp : Add->operands()) {
2880 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2881 Depth + 1);
2882 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2883 NewOps.push_back(Mul);
2884 }
2885 if (AnyFolded)
2886 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2887 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2888 // Negation preserves a recurrence's no self-wrap property.
2889 SmallVector<const SCEV *, 4> Operands;
2890 for (const SCEV *AddRecOp : AddRec->operands())
2891 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2892 Depth + 1));
2893
2894 return getAddRecExpr(Operands, AddRec->getLoop(),
2895 AddRec->getNoWrapFlags(SCEV::FlagNW));
2896 }
2897 }
2898 }
2899 }
2900
2901 // Skip over the add expression until we get to a multiply.
2902 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2903 ++Idx;
2904
2905 // If there are mul operands inline them all into this expression.
2906 if (Idx < Ops.size()) {
2907 bool DeletedMul = false;
2908 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2909 if (Ops.size() > MulOpsInlineThreshold)
2910 break;
2911 // If we have an mul, expand the mul operands onto the end of the
2912 // operands list.
2913 Ops.erase(Ops.begin()+Idx);
2914 Ops.append(Mul->op_begin(), Mul->op_end());
2915 DeletedMul = true;
2916 }
2917
2918 // If we deleted at least one mul, we added operands to the end of the
2919 // list, and they are not necessarily sorted. Recurse to resort and
2920 // resimplify any operands we just acquired.
2921 if (DeletedMul)
2922 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2923 }
2924
2925 // If there are any add recurrences in the operands list, see if any other
2926 // added values are loop invariant. If so, we can fold them into the
2927 // recurrence.
2928 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2929 ++Idx;
2930
2931 // Scan over all recurrences, trying to fold loop invariants into them.
2932 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2933 // Scan all of the other operands to this mul and add them to the vector
2934 // if they are loop invariant w.r.t. the recurrence.
2935 SmallVector<const SCEV *, 8> LIOps;
2936 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2937 const Loop *AddRecLoop = AddRec->getLoop();
2938 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2939 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2940 LIOps.push_back(Ops[i]);
2941 Ops.erase(Ops.begin()+i);
2942 --i; --e;
2943 }
2944
2945 // If we found some loop invariants, fold them into the recurrence.
2946 if (!LIOps.empty()) {
2947 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
2948 SmallVector<const SCEV *, 4> NewOps;
2949 NewOps.reserve(AddRec->getNumOperands());
2950 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
2951 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2952 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
2953 SCEV::FlagAnyWrap, Depth + 1));
2954
2955 // Build the new addrec. Propagate the NUW and NSW flags if both the
2956 // outer mul and the inner addrec are guaranteed to have no overflow.
2957 //
2958 // No self-wrap cannot be guaranteed after changing the step size, but
2959 // will be inferred if either NUW or NSW is true.
2960 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
2961 const SCEV *NewRec = getAddRecExpr(
2962 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
2963
2964 // If all of the other operands were loop invariant, we are done.
2965 if (Ops.size() == 1) return NewRec;
2966
2967 // Otherwise, multiply the folded AddRec by the non-invariant parts.
2968 for (unsigned i = 0;; ++i)
2969 if (Ops[i] == AddRec) {
2970 Ops[i] = NewRec;
2971 break;
2972 }
2973 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2974 }
2975
2976 // Okay, if there weren't any loop invariants to be folded, check to see
2977 // if there are multiple AddRec's with the same loop induction variable
2978 // being multiplied together. If so, we can fold them.
2979
2980 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2981 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2982 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2983 // ]]],+,...up to x=2n}.
2984 // Note that the arguments to choose() are always integers with values
2985 // known at compile time, never SCEV objects.
2986 //
2987 // The implementation avoids pointless extra computations when the two
2988 // addrec's are of different length (mathematically, it's equivalent to
2989 // an infinite stream of zeros on the right).
2990 bool OpsModified = false;
2991 for (unsigned OtherIdx = Idx+1;
2992 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2993 ++OtherIdx) {
2994 const SCEVAddRecExpr *OtherAddRec =
2995 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2996 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
2997 continue;
2998
2999 // Limit max number of arguments to avoid creation of unreasonably big
3000 // SCEVAddRecs with very complex operands.
3001 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3002 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3003 continue;
3004
3005 bool Overflow = false;
3006 Type *Ty = AddRec->getType();
3007 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3008 SmallVector<const SCEV*, 7> AddRecOps;
3009 for (int x = 0, xe = AddRec->getNumOperands() +
3010 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3011 SmallVector <const SCEV *, 7> SumOps;
3012 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3013 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3014 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3015 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3016 z < ze && !Overflow; ++z) {
3017 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3018 uint64_t Coeff;
3019 if (LargerThan64Bits)
3020 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3021 else
3022 Coeff = Coeff1*Coeff2;
3023 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3024 const SCEV *Term1 = AddRec->getOperand(y-z);
3025 const SCEV *Term2 = OtherAddRec->getOperand(z);
3026 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3027 SCEV::FlagAnyWrap, Depth + 1));
3028 }
3029 }
3030 if (SumOps.empty())
3031 SumOps.push_back(getZero(Ty));
3032 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3033 }
3034 if (!Overflow) {
3035 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3036 SCEV::FlagAnyWrap);
3037 if (Ops.size() == 2) return NewAddRec;
3038 Ops[Idx] = NewAddRec;
3039 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3040 OpsModified = true;
3041 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3042 if (!AddRec)
3043 break;
3044 }
3045 }
3046 if (OpsModified)
3047 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3048
3049 // Otherwise couldn't fold anything into this recurrence. Move onto the
3050 // next one.
3051 }
3052
3053 // Okay, it looks like we really DO need an mul expr. Check to see if we
3054 // already have one, otherwise create a new one.
3055 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3056}
3057
3058/// Represents an unsigned remainder expression based on unsigned division.
3059const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3060 const SCEV *RHS) {
3061 assert(getEffectiveSCEVType(LHS->getType()) ==((getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType
(RHS->getType()) && "SCEVURemExpr operand types don't match!"
) ? static_cast<void> (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVURemExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3063, __PRETTY_FUNCTION__))
3062 getEffectiveSCEVType(RHS->getType()) &&((getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType
(RHS->getType()) && "SCEVURemExpr operand types don't match!"
) ? static_cast<void> (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVURemExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3063, __PRETTY_FUNCTION__))
3063 "SCEVURemExpr operand types don't match!")((getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType
(RHS->getType()) && "SCEVURemExpr operand types don't match!"
) ? static_cast<void> (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVURemExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3063, __PRETTY_FUNCTION__))
;
3064
3065 // Short-circuit easy cases
3066 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3067 // If constant is one, the result is trivial
3068 if (RHSC->getValue()->isOne())
3069 return getZero(LHS->getType()); // X urem 1 --> 0
3070
3071 // If constant is a power of two, fold into a zext(trunc(LHS)).
3072 if (RHSC->getAPInt().isPowerOf2()) {
3073 Type *FullTy = LHS->getType();
3074 Type *TruncTy =
3075 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3076 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3077 }
3078 }
3079
3080 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3081 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3082 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3083 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3084}
3085
3086/// Get a canonical unsigned division expression, or something simpler if
3087/// possible.
3088const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3089 const SCEV *RHS) {
3090 assert(getEffectiveSCEVType(LHS->getType()) ==((getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType
(RHS->getType()) && "SCEVUDivExpr operand types don't match!"
) ? static_cast<void> (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVUDivExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3092, __PRETTY_FUNCTION__))
3091 getEffectiveSCEVType(RHS->getType()) &&((getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType
(RHS->getType()) && "SCEVUDivExpr operand types don't match!"
) ? static_cast<void> (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVUDivExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3092, __PRETTY_FUNCTION__))
3092 "SCEVUDivExpr operand types don't match!")((getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType
(RHS->getType()) && "SCEVUDivExpr operand types don't match!"
) ? static_cast<void> (0) : __assert_fail ("getEffectiveSCEVType(LHS->getType()) == getEffectiveSCEVType(RHS->getType()) && \"SCEVUDivExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3092, __PRETTY_FUNCTION__))
;
3093
3094 FoldingSetNodeID ID;
3095 ID.AddInteger(scUDivExpr);
3096 ID.AddPointer(LHS);
3097 ID.AddPointer(RHS);
3098 void *IP = nullptr;
3099 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3100 return S;
3101
3102 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3103 if (RHSC->getValue()->isOne())
3104 return LHS; // X udiv 1 --> x
3105 // If the denominator is zero, the result of the udiv is undefined. Don't
3106 // try to analyze it, because the resolution chosen here may differ from
3107 // the resolution chosen in other parts of the compiler.
3108 if (!RHSC->getValue()->isZero()) {
3109 // Determine if the division can be folded into the operands of
3110 // its operands.
3111 // TODO: Generalize this to non-constants by using known-bits information.
3112 Type *Ty = LHS->getType();
3113 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3114 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3115 // For non-power-of-two values, effectively round the value up to the
3116 // nearest power of two.
3117 if (!RHSC->getAPInt().isPowerOf2())
3118 ++MaxShiftAmt;
3119 IntegerType *ExtTy =
3120 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3121 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3122 if (const SCEVConstant *Step =
3123 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3124 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3125 const APInt &StepInt = Step->getAPInt();
3126 const APInt &DivInt = RHSC->getAPInt();
3127 if (!StepInt.urem(DivInt) &&
3128 getZeroExtendExpr(AR, ExtTy) ==
3129 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3130 getZeroExtendExpr(Step, ExtTy),
3131 AR->getLoop(), SCEV::FlagAnyWrap)) {
3132 SmallVector<const SCEV *, 4> Operands;
3133 for (const SCEV *Op : AR->operands())
3134 Operands.push_back(getUDivExpr(Op, RHS));
3135 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3136 }
3137 /// Get a canonical UDivExpr for a recurrence.
3138 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3139 // We can currently only fold X%N if X is constant.
3140 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3141 if (StartC && !DivInt.urem(StepInt) &&
3142 getZeroExtendExpr(AR, ExtTy) ==
3143 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3144 getZeroExtendExpr(Step, ExtTy),
3145 AR->getLoop(), SCEV::FlagAnyWrap)) {
3146 const APInt &StartInt = StartC->getAPInt();
3147 const APInt &StartRem = StartInt.urem(StepInt);
3148 if (StartRem != 0) {
3149 const SCEV *NewLHS =
3150 getAddRecExpr(getConstant(StartInt - StartRem), Step,
3151 AR->getLoop(), SCEV::FlagNW);
3152 if (LHS != NewLHS) {
3153 LHS = NewLHS;
3154
3155 // Reset the ID to include the new LHS, and check if it is
3156 // already cached.
3157 ID.clear();
3158 ID.AddInteger(scUDivExpr);
3159 ID.AddPointer(LHS);
3160 ID.AddPointer(RHS);
3161 IP = nullptr;
3162 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3163 return S;
3164 }
3165 }
3166 }
3167 }
3168 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3169 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3170 SmallVector<const SCEV *, 4> Operands;
3171 for (const SCEV *Op : M->operands())
3172 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3173 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3174 // Find an operand that's safely divisible.
3175 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3176 const SCEV *Op = M->getOperand(i);
3177 const SCEV *Div = getUDivExpr(Op, RHSC);
3178 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3179 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3180 M->op_end());
3181 Operands[i] = Div;
3182 return getMulExpr(Operands);
3183 }
3184 }
3185 }
3186
3187 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3188 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3189 if (auto *DivisorConstant =
3190 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3191 bool Overflow = false;
3192 APInt NewRHS =
3193 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3194 if (Overflow) {
3195 return getConstant(RHSC->getType(), 0, false);
3196 }
3197 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3198 }
3199 }
3200
3201 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3202 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3203 SmallVector<const SCEV *, 4> Operands;
3204 for (const SCEV *Op : A->operands())
3205 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3206 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3207 Operands.clear();
3208 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3209 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3210 if (isa<SCEVUDivExpr>(Op) ||
3211 getMulExpr(Op, RHS) != A->getOperand(i))
3212 break;
3213 Operands.push_back(Op);
3214 }
3215 if (Operands.size() == A->getNumOperands())
3216 return getAddExpr(Operands);
3217 }
3218 }
3219
3220 // Fold if both operands are constant.
3221 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3222 Constant *LHSCV = LHSC->getValue();
3223 Constant *RHSCV = RHSC->getValue();
3224 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3225 RHSCV)));
3226 }
3227 }
3228 }
3229
3230 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3231 // changes). Make sure we get a new one.
3232 IP = nullptr;
3233 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3234 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3235 LHS, RHS);
3236 UniqueSCEVs.InsertNode(S, IP);
3237 addToLoopUseLists(S);
3238 return S;
3239}
3240
3241static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3242 APInt A = C1->getAPInt().abs();
3243 APInt B = C2->getAPInt().abs();
3244 uint32_t ABW = A.getBitWidth();
3245 uint32_t BBW = B.getBitWidth();
3246
3247 if (ABW > BBW)
3248 B = B.zext(ABW);
3249 else if (ABW < BBW)
3250 A = A.zext(BBW);
3251
3252 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3253}
3254
3255/// Get a canonical unsigned division expression, or something simpler if
3256/// possible. There is no representation for an exact udiv in SCEV IR, but we
3257/// can attempt to remove factors from the LHS and RHS. We can't do this when
3258/// it's not exact because the udiv may be clearing bits.
3259const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3260 const SCEV *RHS) {
3261 // TODO: we could try to find factors in all sorts of things, but for now we
3262 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3263 // end of this file for inspiration.
3264
3265 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3266 if (!Mul || !Mul->hasNoUnsignedWrap())
3267 return getUDivExpr(LHS, RHS);
3268
3269 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3270 // If the mulexpr multiplies by a constant, then that constant must be the
3271 // first element of the mulexpr.
3272 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3273 if (LHSCst == RHSCst) {
3274 SmallVector<const SCEV *, 2> Operands;
3275 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3276 return getMulExpr(Operands);
3277 }
3278
3279 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3280 // that there's a factor provided by one of the other terms. We need to
3281 // check.
3282 APInt Factor = gcd(LHSCst, RHSCst);
3283 if (!Factor.isIntN(1)) {
3284 LHSCst =
3285 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3286 RHSCst =
3287 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3288 SmallVector<const SCEV *, 2> Operands;
3289 Operands.push_back(LHSCst);
3290 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3291 LHS = getMulExpr(Operands);
3292 RHS = RHSCst;
3293 Mul = dyn_cast<SCEVMulExpr>(LHS);
3294 if (!Mul)
3295 return getUDivExactExpr(LHS, RHS);
3296 }
3297 }
3298 }
3299
3300 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3301 if (Mul->getOperand(i) == RHS) {
3302 SmallVector<const SCEV *, 2> Operands;
3303 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3304 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3305 return getMulExpr(Operands);
3306 }
3307 }
3308
3309 return getUDivExpr(LHS, RHS);
3310}
3311
3312/// Get an add recurrence expression for the specified loop. Simplify the
3313/// expression as much as possible.
3314const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3315 const Loop *L,
3316 SCEV::NoWrapFlags Flags) {
3317 SmallVector<const SCEV *, 4> Operands;
3318 Operands.push_back(Start);
3319 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3320 if (StepChrec->getLoop() == L) {
3321 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3322 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3323 }
3324
3325 Operands.push_back(Step);
3326 return getAddRecExpr(Operands, L, Flags);
3327}
3328
3329/// Get an add recurrence expression for the specified loop. Simplify the
3330/// expression as much as possible.
3331const SCEV *
3332ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3333 const Loop *L, SCEV::NoWrapFlags Flags) {
3334 if (Operands.size() == 1) return Operands[0];
3335#ifndef NDEBUG
3336 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3337 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3338 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&((getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
"SCEVAddRecExpr operand types don't match!") ? static_cast<
void> (0) : __assert_fail ("getEffectiveSCEVType(Operands[i]->getType()) == ETy && \"SCEVAddRecExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3339, __PRETTY_FUNCTION__))
3339 "SCEVAddRecExpr operand types don't match!")((getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
"SCEVAddRecExpr operand types don't match!") ? static_cast<
void> (0) : __assert_fail ("getEffectiveSCEVType(Operands[i]->getType()) == ETy && \"SCEVAddRecExpr operand types don't match!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3339, __PRETTY_FUNCTION__))
;
3340 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3341 assert(isLoopInvariant(Operands[i], L) &&((isLoopInvariant(Operands[i], L) && "SCEVAddRecExpr operand is not loop-invariant!"
) ? static_cast<void> (0) : __assert_fail ("isLoopInvariant(Operands[i], L) && \"SCEVAddRecExpr operand is not loop-invariant!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3342, __PRETTY_FUNCTION__))
3342 "SCEVAddRecExpr operand is not loop-invariant!")((isLoopInvariant(Operands[i], L) && "SCEVAddRecExpr operand is not loop-invariant!"
) ? static_cast<void> (0) : __assert_fail ("isLoopInvariant(Operands[i], L) && \"SCEVAddRecExpr operand is not loop-invariant!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3342, __PRETTY_FUNCTION__))
;
3343#endif
3344
3345 if (Operands.back()->isZero()) {
3346 Operands.pop_back();
3347 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3348 }
3349
3350 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3351 // use that information to infer NUW and NSW flags. However, computing a
3352 // BE count requires calling getAddRecExpr, so we may not yet have a
3353 // meaningful BE count at this point (and if we don't, we'd be stuck
3354 // with a SCEVCouldNotCompute as the cached BE count).
3355
3356 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3357
3358 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3359 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3360 const Loop *NestedLoop = NestedAR->getLoop();
3361 if (L->contains(NestedLoop)
3362 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3363 : (!NestedLoop->contains(L) &&
3364 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3365 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3366 NestedAR->op_end());
3367 Operands[0] = NestedAR->getStart();
3368 // AddRecs require their operands be loop-invariant with respect to their
3369 // loops. Don't perform this transformation if it would break this
3370 // requirement.
3371 bool AllInvariant = all_of(
3372 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3373
3374 if (AllInvariant) {
3375 // Create a recurrence for the outer loop with the same step size.
3376 //
3377 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3378 // inner recurrence has the same property.
3379 SCEV::NoWrapFlags OuterFlags =
3380 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3381
3382 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3383 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3384 return isLoopInvariant(Op, NestedLoop);
3385 });
3386
3387 if (AllInvariant) {
3388 // Ok, both add recurrences are valid after the transformation.
3389 //
3390 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3391 // the outer recurrence has the same property.
3392 SCEV::NoWrapFlags InnerFlags =
3393 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3394 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3395 }
3396 }
3397 // Reset Operands to its original state.
3398 Operands[0] = NestedAR;
3399 }
3400 }
3401
3402 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3403 // already have one, otherwise create a new one.
3404 return getOrCreateAddRecExpr(Operands, L, Flags);
3405}
3406
3407const SCEV *
3408ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3409 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3410 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3411 // getSCEV(Base)->getType() has the same address space as Base->getType()
3412 // because SCEV::getType() preserves the address space.
3413 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3414 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3415 // instruction to its SCEV, because the Instruction may be guarded by control
3416 // flow and the no-overflow bits may not be valid for the expression in any
3417 // context. This can be fixed similarly to how these flags are handled for
3418 // adds.
3419 SCEV::NoWrapFlags OffsetWrap =
3420 GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3421
3422 Type *CurTy = GEP->getType();
3423 bool FirstIter = true;
3424 SmallVector<const SCEV *, 4> Offsets;
3425 for (const SCEV *IndexExpr : IndexExprs) {
3426 // Compute the (potentially symbolic) offset in bytes for this index.
3427 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3428 // For a struct, add the member offset.
3429 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3430 unsigned FieldNo = Index->getZExtValue();
3431 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3432 Offsets.push_back(FieldOffset);
3433
3434 // Update CurTy to the type of the field at Index.
3435 CurTy = STy->getTypeAtIndex(Index);
3436 } else {
3437 // Update CurTy to its element type.
3438 if (FirstIter) {
3439 assert(isa<PointerType>(CurTy) &&((isa<PointerType>(CurTy) && "The first index of a GEP indexes a pointer"
) ? static_cast<void> (0) : __assert_fail ("isa<PointerType>(CurTy) && \"The first index of a GEP indexes a pointer\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3440, __PRETTY_FUNCTION__))
3440 "The first index of a GEP indexes a pointer")((isa<PointerType>(CurTy) && "The first index of a GEP indexes a pointer"
) ? static_cast<void> (0) : __assert_fail ("isa<PointerType>(CurTy) && \"The first index of a GEP indexes a pointer\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3440, __PRETTY_FUNCTION__))
;
3441 CurTy = GEP->getSourceElementType();
3442 FirstIter = false;
3443 } else {
3444 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3445 }
3446 // For an array, add the element offset, explicitly scaled.
3447 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3448 // Getelementptr indices are signed.
3449 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3450
3451 // Multiply the index by the element size to compute the element offset.
3452 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3453 Offsets.push_back(LocalOffset);
3454 }
3455 }
3456
3457 // Handle degenerate case of GEP without offsets.
3458 if (Offsets.empty())
3459 return BaseExpr;
3460
3461 // Add the offsets together, assuming nsw if inbounds.
3462 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3463 // Add the base address and the offset. We cannot use the nsw flag, as the
3464 // base address is unsigned. However, if we know that the offset is
3465 // non-negative, we can use nuw.
3466 SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset)
3467 ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
3468 return getAddExpr(BaseExpr, Offset, BaseWrap);
3469}
3470
3471std::tuple<SCEV *, FoldingSetNodeID, void *>
3472ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3473 ArrayRef<const SCEV *> Ops) {
3474 FoldingSetNodeID ID;
3475 void *IP = nullptr;
3476 ID.AddInteger(SCEVType);
3477 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3478 ID.AddPointer(Ops[i]);
3479 return std::tuple<SCEV *, FoldingSetNodeID, void *>(
3480 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP);
3481}
3482
3483const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3484 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3485 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3486}
3487
3488const SCEV *ScalarEvolution::getSignumExpr(const SCEV *Op) {
3489 Type *Ty = Op->getType();
3490 return getSMinExpr(getSMaxExpr(Op, getMinusOne(Ty)), getOne(Ty));
3491}
3492
3493const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3494 SmallVectorImpl<const SCEV *> &Ops) {
3495 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!")((!Ops.empty() && "Cannot get empty (u|s)(min|max)!")
? static_cast<void> (0) : __assert_fail ("!Ops.empty() && \"Cannot get empty (u|s)(min|max)!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3495, __PRETTY_FUNCTION__))
;
3496 if (Ops.size() == 1) return Ops[0];
3497#ifndef NDEBUG
3498 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3499 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3500 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"Operand types don't match!") ? static_cast<void> (0) :
__assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"Operand types don't match!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3501, __PRETTY_FUNCTION__))
3501 "Operand types don't match!")((getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
"Operand types don't match!") ? static_cast<void> (0) :
__assert_fail ("getEffectiveSCEVType(Ops[i]->getType()) == ETy && \"Operand types don't match!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3501, __PRETTY_FUNCTION__))
;
3502#endif
3503
3504 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3505 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3506
3507 // Sort by complexity, this groups all similar expression types together.
3508 GroupByComplexity(Ops, &LI, DT);
3509
3510 // Check if we have created the same expression before.
3511 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) {
3512 return S;
3513 }
3514
3515 // If there are any constants, fold them together.
3516 unsigned Idx = 0;
3517 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3518 ++Idx;
3519 assert(Idx < Ops.size())((Idx < Ops.size()) ? static_cast<void> (0) : __assert_fail
("Idx < Ops.size()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3519, __PRETTY_FUNCTION__))
;
3520 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3521 if (Kind == scSMaxExpr)
3522 return APIntOps::smax(LHS, RHS);
3523 else if (Kind == scSMinExpr)
3524 return APIntOps::smin(LHS, RHS);
3525 else if (Kind == scUMaxExpr)
3526 return APIntOps::umax(LHS, RHS);
3527 else if (Kind == scUMinExpr)
3528 return APIntOps::umin(LHS, RHS);
3529 llvm_unreachable("Unknown SCEV min/max opcode")::llvm::llvm_unreachable_internal("Unknown SCEV min/max opcode"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3529)
;
3530 };
3531
3532 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3533 // We found two constants, fold them together!
3534 ConstantInt *Fold = ConstantInt::get(
3535 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3536 Ops[0] = getConstant(Fold);
3537 Ops.erase(Ops.begin()+1); // Erase the folded element
3538 if (Ops.size() == 1) return Ops[0];
3539 LHSC = cast<SCEVConstant>(Ops[0]);
3540 }
3541
3542 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3543 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3544
3545 if (IsMax ? IsMinV : IsMaxV) {
3546 // If we are left with a constant minimum(/maximum)-int, strip it off.
3547 Ops.erase(Ops.begin());
3548 --Idx;
3549 } else if (IsMax ? IsMaxV : IsMinV) {
3550 // If we have a max(/min) with a constant maximum(/minimum)-int,
3551 // it will always be the extremum.
3552 return LHSC;
3553 }
3554
3555 if (Ops.size() == 1) return Ops[0];
3556 }
3557
3558 // Find the first operation of the same kind
3559 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3560 ++Idx;
3561
3562 // Check to see if one of the operands is of the same kind. If so, expand its
3563 // operands onto our operand list, and recurse to simplify.
3564 if (Idx < Ops.size()) {
3565 bool DeletedAny = false;
3566 while (Ops[Idx]->getSCEVType() == Kind) {
3567 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3568 Ops.erase(Ops.begin()+Idx);
3569 Ops.append(SMME->op_begin(), SMME->op_end());
3570 DeletedAny = true;
3571 }
3572
3573 if (DeletedAny)
3574 return getMinMaxExpr(Kind, Ops);
3575 }
3576
3577 // Okay, check to see if the same value occurs in the operand list twice. If
3578 // so, delete one. Since we sorted the list, these values are required to
3579 // be adjacent.
3580 llvm::CmpInst::Predicate GEPred =
3581 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3582 llvm::CmpInst::Predicate LEPred =
3583 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3584 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3585 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3586 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3587 if (Ops[i] == Ops[i + 1] ||
3588 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3589 // X op Y op Y --> X op Y
3590 // X op Y --> X, if we know X, Y are ordered appropriately
3591 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3592 --i;
3593 --e;
3594 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3595 Ops[i + 1])) {
3596 // X op Y --> Y, if we know X, Y are ordered appropriately
3597 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3598 --i;
3599 --e;
3600 }
3601 }
3602
3603 if (Ops.size() == 1) return Ops[0];
3604
3605 assert(!Ops.empty() && "Reduced smax down to nothing!")((!Ops.empty() && "Reduced smax down to nothing!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"Reduced smax down to nothing!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3605, __PRETTY_FUNCTION__))
;
3606
3607 // Okay, it looks like we really DO need an expr. Check to see if we
3608 // already have one, otherwise create a new one.
3609 const SCEV *ExistingSCEV;
3610 FoldingSetNodeID ID;
3611 void *IP;
3612 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops);
3613 if (ExistingSCEV)
3614 return ExistingSCEV;
3615 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3616 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3617 SCEV *S = new (SCEVAllocator)
3618 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3619
3620 UniqueSCEVs.InsertNode(S, IP);
3621 addToLoopUseLists(S);
3622 return S;
3623}
3624
3625const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3626 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3627 return getSMaxExpr(Ops);
3628}
3629
3630const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3631 return getMinMaxExpr(scSMaxExpr, Ops);
3632}
3633
3634const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3635 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3636 return getUMaxExpr(Ops);
3637}
3638
3639const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3640 return getMinMaxExpr(scUMaxExpr, Ops);
3641}
3642
3643const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3644 const SCEV *RHS) {
3645 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3646 return getSMinExpr(Ops);
3647}
3648
3649const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3650 return getMinMaxExpr(scSMinExpr, Ops);
3651}
3652
3653const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3654 const SCEV *RHS) {
3655 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3656 return getUMinExpr(Ops);
3657}
3658
3659const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3660 return getMinMaxExpr(scUMinExpr, Ops);
3661}
3662
3663const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3664 if (isa<ScalableVectorType>(AllocTy)) {
3665 Constant *NullPtr = Constant::getNullValue(AllocTy->getPointerTo());
3666 Constant *One = ConstantInt::get(IntTy, 1);
3667 Constant *GEP = ConstantExpr::getGetElementPtr(AllocTy, NullPtr, One);
3668 // Note that the expression we created is the final expression, we don't
3669 // want to simplify it any further Also, if we call a normal getSCEV(),
3670 // we'll end up in an endless recursion. So just create an SCEVUnknown.
3671 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
3672 }
3673 // We can bypass creating a target-independent
3674 // constant expression and then folding it back into a ConstantInt.
3675 // This is just a compile-time optimization.
3676 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3677}
3678
3679const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3680 StructType *STy,
3681 unsigned FieldNo) {
3682 // We can bypass creating a target-independent
3683 // constant expression and then folding it back into a ConstantInt.
3684 // This is just a compile-time optimization.
3685 return getConstant(
3686 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3687}
3688
3689const SCEV *ScalarEvolution::getUnknown(Value *V) {
3690 // Don't attempt to do anything other than create a SCEVUnknown object
3691 // here. createSCEV only calls getUnknown after checking for all other
3692 // interesting possibilities, and any other code that calls getUnknown
3693 // is doing so in order to hide a value from SCEV canonicalization.
3694
3695 FoldingSetNodeID ID;
3696 ID.AddInteger(scUnknown);
3697 ID.AddPointer(V);
3698 void *IP = nullptr;
3699 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3700 assert(cast<SCEVUnknown>(S)->getValue() == V &&((cast<SCEVUnknown>(S)->getValue() == V && "Stale SCEVUnknown in uniquing map!"
) ? static_cast<void> (0) : __assert_fail ("cast<SCEVUnknown>(S)->getValue() == V && \"Stale SCEVUnknown in uniquing map!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3701, __PRETTY_FUNCTION__))
3701 "Stale SCEVUnknown in uniquing map!")((cast<SCEVUnknown>(S)->getValue() == V && "Stale SCEVUnknown in uniquing map!"
) ? static_cast<void> (0) : __assert_fail ("cast<SCEVUnknown>(S)->getValue() == V && \"Stale SCEVUnknown in uniquing map!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3701, __PRETTY_FUNCTION__))
;
3702 return S;
3703 }
3704 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3705 FirstUnknown);
3706 FirstUnknown = cast<SCEVUnknown>(S);
3707 UniqueSCEVs.InsertNode(S, IP);
3708 return S;
3709}
3710
3711//===----------------------------------------------------------------------===//
3712// Basic SCEV Analysis and PHI Idiom Recognition Code
3713//
3714
3715/// Test if values of the given type are analyzable within the SCEV
3716/// framework. This primarily includes integer types, and it can optionally
3717/// include pointer types if the ScalarEvolution class has access to
3718/// target-specific information.
3719bool ScalarEvolution::isSCEVable(Type *Ty) const {
3720 // Integers and pointers are always SCEVable.
3721 return Ty->isIntOrPtrTy();
3722}
3723
3724/// Return the size in bits of the specified type, for which isSCEVable must
3725/// return true.
3726uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3727 assert(isSCEVable(Ty) && "Type is not SCEVable!")((isSCEVable(Ty) && "Type is not SCEVable!") ? static_cast
<void> (0) : __assert_fail ("isSCEVable(Ty) && \"Type is not SCEVable!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3727, __PRETTY_FUNCTION__))
;
3728 if (Ty->isPointerTy())
3729 return getDataLayout().getIndexTypeSizeInBits(Ty);
3730 return getDataLayout().getTypeSizeInBits(Ty);
3731}
3732
3733/// Return a type with the same bitwidth as the given type and which represents
3734/// how SCEV will treat the given type, for which isSCEVable must return
3735/// true. For pointer types, this is the pointer index sized integer type.
3736Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3737 assert(isSCEVable(Ty) && "Type is not SCEVable!")((isSCEVable(Ty) && "Type is not SCEVable!") ? static_cast
<void> (0) : __assert_fail ("isSCEVable(Ty) && \"Type is not SCEVable!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3737, __PRETTY_FUNCTION__))
;
3738
3739 if (Ty->isIntegerTy())
3740 return Ty;
3741
3742 // The only other support type is pointer.
3743 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!")((Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"
) ? static_cast<void> (0) : __assert_fail ("Ty->isPointerTy() && \"Unexpected non-pointer non-integer type!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3743, __PRETTY_FUNCTION__))
;
3744 return getDataLayout().getIndexType(Ty);
3745}
3746
3747Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3748 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3749}
3750
3751const SCEV *ScalarEvolution::getCouldNotCompute() {
3752 return CouldNotCompute.get();
3753}
3754
3755bool ScalarEvolution::checkValidity(const SCEV *S) const {
3756 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3757 auto *SU = dyn_cast<SCEVUnknown>(S);
3758 return SU && SU->getValue() == nullptr;
3759 });
3760
3761 return !ContainsNulls;
3762}
3763
3764bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3765 HasRecMapType::iterator I = HasRecMap.find(S);
3766 if (I != HasRecMap.end())
3767 return I->second;
3768
3769 bool FoundAddRec =
3770 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
3771 HasRecMap.insert({S, FoundAddRec});
3772 return FoundAddRec;
3773}
3774
3775/// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3776/// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3777/// offset I, then return {S', I}, else return {\p S, nullptr}.
3778static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3779 const auto *Add = dyn_cast<SCEVAddExpr>(S);
3780 if (!Add)
3781 return {S, nullptr};
3782
3783 if (Add->getNumOperands() != 2)
3784 return {S, nullptr};
3785
3786 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3787 if (!ConstOp)
3788 return {S, nullptr};
3789
3790 return {Add->getOperand(1), ConstOp->getValue()};
3791}
3792
3793/// Return the ValueOffsetPair set for \p S. \p S can be represented
3794/// by the value and offset from any ValueOffsetPair in the set.
3795SetVector<ScalarEvolution::ValueOffsetPair> *
3796ScalarEvolution::getSCEVValues(const SCEV *S) {
3797 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3798 if (SI == ExprValueMap.end())
3799 return nullptr;
3800#ifndef NDEBUG
3801 if (VerifySCEVMap) {
3802 // Check there is no dangling Value in the set returned.
3803 for (const auto &VE : SI->second)
3804 assert(ValueExprMap.count(VE.first))((ValueExprMap.count(VE.first)) ? static_cast<void> (0)
: __assert_fail ("ValueExprMap.count(VE.first)", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3804, __PRETTY_FUNCTION__))
;
3805 }
3806#endif
3807 return &SI->second;
3808}
3809
3810/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3811/// cannot be used separately. eraseValueFromMap should be used to remove
3812/// V from ValueExprMap and ExprValueMap at the same time.
3813void ScalarEvolution::eraseValueFromMap(Value *V) {
3814 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3815 if (I != ValueExprMap.end()) {
3816 const SCEV *S = I->second;
3817 // Remove {V, 0} from the set of ExprValueMap[S]
3818 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3819 SV->remove({V, nullptr});
3820
3821 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3822 const SCEV *Stripped;
3823 ConstantInt *Offset;
3824 std::tie(Stripped, Offset) = splitAddExpr(S);
3825 if (Offset != nullptr) {
3826 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3827 SV->remove({V, Offset});
3828 }
3829 ValueExprMap.erase(V);
3830 }
3831}
3832
3833/// Check whether value has nuw/nsw/exact set but SCEV does not.
3834/// TODO: In reality it is better to check the poison recursively
3835/// but this is better than nothing.
3836static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3837 if (auto *I = dyn_cast<Instruction>(V)) {
3838 if (isa<OverflowingBinaryOperator>(I)) {
3839 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3840 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3841 return true;
3842 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3843 return true;
3844 }
3845 } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3846 return true;
3847 }
3848 return false;
3849}
3850
3851/// Return an existing SCEV if it exists, otherwise analyze the expression and
3852/// create a new one.
3853const SCEV *ScalarEvolution::getSCEV(Value *V) {
3854 assert(isSCEVable(V->getType()) && "Value is not SCEVable!")((isSCEVable(V->getType()) && "Value is not SCEVable!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(V->getType()) && \"Value is not SCEVable!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3854, __PRETTY_FUNCTION__))
;
3855
3856 const SCEV *S = getExistingSCEV(V);
3857 if (S == nullptr) {
3858 S = createSCEV(V);
3859 // During PHI resolution, it is possible to create two SCEVs for the same
3860 // V, so it is needed to double check whether V->S is inserted into
3861 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3862 std::pair<ValueExprMapType::iterator, bool> Pair =
3863 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3864 if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3865 ExprValueMap[S].insert({V, nullptr});
3866
3867 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3868 // ExprValueMap.
3869 const SCEV *Stripped = S;
3870 ConstantInt *Offset = nullptr;
3871 std::tie(Stripped, Offset) = splitAddExpr(S);
3872 // If stripped is SCEVUnknown, don't bother to save
3873 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3874 // increase the complexity of the expansion code.
3875 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3876 // because it may generate add/sub instead of GEP in SCEV expansion.
3877 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3878 !isa<GetElementPtrInst>(V))
3879 ExprValueMap[Stripped].insert({V, Offset});
3880 }
3881 }
3882 return S;
3883}
3884
3885const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3886 assert(isSCEVable(V->getType()) && "Value is not SCEVable!")((isSCEVable(V->getType()) && "Value is not SCEVable!"
) ? static_cast<void> (0) : __assert_fail ("isSCEVable(V->getType()) && \"Value is not SCEVable!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3886, __PRETTY_FUNCTION__))
;
3887
3888 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3889 if (I != ValueExprMap.end()) {
3890 const SCEV *S = I->second;
3891 if (checkValidity(S))
3892 return S;
3893 eraseValueFromMap(V);
3894 forgetMemoizedResults(S);
3895 }
3896 return nullptr;
3897}
3898
3899/// Return a SCEV corresponding to -V = -1*V
3900const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3901 SCEV::NoWrapFlags Flags) {
3902 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3903 return getConstant(
3904 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3905
3906 Type *Ty = V->getType();
3907 Ty = getEffectiveSCEVType(Ty);
3908 return getMulExpr(V, getMinusOne(Ty), Flags);
3909}
3910
3911/// If Expr computes ~A, return A else return nullptr
3912static const SCEV *MatchNotExpr(const SCEV *Expr) {
3913 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
3914 if (!Add || Add->getNumOperands() != 2 ||
3915 !Add->getOperand(0)->isAllOnesValue())
3916 return nullptr;
3917
3918 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
3919 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
3920 !AddRHS->getOperand(0)->isAllOnesValue())
3921 return nullptr;
3922
3923 return AddRHS->getOperand(1);
3924}
3925
3926/// Return a SCEV corresponding to ~V = -1-V
3927const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3928 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3929 return getConstant(
3930 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3931
3932 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
3933 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
3934 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
3935 SmallVector<const SCEV *, 2> MatchedOperands;
3936 for (const SCEV *Operand : MME->operands()) {
3937 const SCEV *Matched = MatchNotExpr(Operand);
3938 if (!Matched)
3939 return (const SCEV *)nullptr;
3940 MatchedOperands.push_back(Matched);
3941 }
3942 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
3943 MatchedOperands);
3944 };
3945 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
3946 return Replaced;
3947 }
3948
3949 Type *Ty = V->getType();
3950 Ty = getEffectiveSCEVType(Ty);
3951 return getMinusSCEV(getMinusOne(Ty), V);
3952}
3953
3954const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3955 SCEV::NoWrapFlags Flags,
3956 unsigned Depth) {
3957 // Fast path: X - X --> 0.
3958 if (LHS == RHS)
3959 return getZero(LHS->getType());
3960
3961 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3962 // makes it so that we cannot make much use of NUW.
3963 auto AddFlags = SCEV::FlagAnyWrap;
3964 const bool RHSIsNotMinSigned =
3965 !getSignedRangeMin(RHS).isMinSignedValue();
3966 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3967 // Let M be the minimum representable signed value. Then (-1)*RHS
3968 // signed-wraps if and only if RHS is M. That can happen even for
3969 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3970 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3971 // (-1)*RHS, we need to prove that RHS != M.
3972 //
3973 // If LHS is non-negative and we know that LHS - RHS does not
3974 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3975 // either by proving that RHS > M or that LHS >= 0.
3976 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3977 AddFlags = SCEV::FlagNSW;
3978 }
3979 }
3980
3981 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3982 // RHS is NSW and LHS >= 0.
3983 //
3984 // The difficulty here is that the NSW flag may have been proven
3985 // relative to a loop that is to be found in a recurrence in LHS and
3986 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3987 // larger scope than intended.
3988 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3989
3990 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
3991}
3992
3993const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
3994 unsigned Depth) {
3995 Type *SrcTy = V->getType();
3996 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot truncate or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3997, __PRETTY_FUNCTION__))
3997 "Cannot truncate or zero extend with non-integer arguments!")((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot truncate or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 3997, __PRETTY_FUNCTION__))
;
3998 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3999 return V; // No conversion
4000 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4001 return getTruncateExpr(V, Ty, Depth);
4002 return getZeroExtendExpr(V, Ty, Depth);
4003}
4004
4005const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4006 unsigned Depth) {
4007 Type *SrcTy = V->getType();
4008 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot truncate or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4009, __PRETTY_FUNCTION__))
4009 "Cannot truncate or zero extend with non-integer arguments!")((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot truncate or zero extend with non-integer arguments!"
) ? static_cast<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4009, __PRETTY_FUNCTION__))
;
4010 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4011 return V; // No conversion
4012 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4013 return getTruncateExpr(V, Ty, Depth);
4014 return getSignExtendExpr(V, Ty, Depth);
4015}
4016
4017const SCEV *
4018ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4019 Type *SrcTy = V->getType();
4020 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot noop or zero extend with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4021, __PRETTY_FUNCTION__))
4021 "Cannot noop or zero extend with non-integer arguments!")((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot noop or zero extend with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or zero extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4021, __PRETTY_FUNCTION__))
;
4022 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrZeroExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrZeroExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4023, __PRETTY_FUNCTION__))
4023 "getNoopOrZeroExtend cannot truncate!")((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrZeroExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrZeroExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4023, __PRETTY_FUNCTION__))
;
4024 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4025 return V; // No conversion
4026 return getZeroExtendExpr(V, Ty);
4027}
4028
4029const SCEV *
4030ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4031 Type *SrcTy = V->getType();
4032 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot noop or sign extend with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or sign extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4033, __PRETTY_FUNCTION__))
4033 "Cannot noop or sign extend with non-integer arguments!")((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot noop or sign extend with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or sign extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4033, __PRETTY_FUNCTION__))
;
4034 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrSignExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrSignExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4035, __PRETTY_FUNCTION__))
4035 "getNoopOrSignExtend cannot truncate!")((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrSignExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrSignExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4035, __PRETTY_FUNCTION__))
;
4036 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4037 return V; // No conversion
4038 return getSignExtendExpr(V, Ty);
4039}
4040
4041const SCEV *
4042ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4043 Type *SrcTy = V->getType();
4044 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot noop or any extend with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or any extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4045, __PRETTY_FUNCTION__))
4045 "Cannot noop or any extend with non-integer arguments!")((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot noop or any extend with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot noop or any extend with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4045, __PRETTY_FUNCTION__))
;
4046 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrAnyExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrAnyExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4047, __PRETTY_FUNCTION__))
4047 "getNoopOrAnyExtend cannot truncate!")((getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
"getNoopOrAnyExtend cannot truncate!") ? static_cast<void
> (0) : __assert_fail ("getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && \"getNoopOrAnyExtend cannot truncate!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4047, __PRETTY_FUNCTION__))
;
4048 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4049 return V; // No conversion
4050 return getAnyExtendExpr(V, Ty);
4051}
4052
4053const SCEV *
4054ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4055 Type *SrcTy = V->getType();
4056 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot truncate or noop with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or noop with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4057, __PRETTY_FUNCTION__))
4057 "Cannot truncate or noop with non-integer arguments!")((SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
"Cannot truncate or noop with non-integer arguments!") ? static_cast
<void> (0) : __assert_fail ("SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && \"Cannot truncate or noop with non-integer arguments!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4057, __PRETTY_FUNCTION__))
;
4058 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&((getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
"getTruncateOrNoop cannot extend!") ? static_cast<void>
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && \"getTruncateOrNoop cannot extend!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4059, __PRETTY_FUNCTION__))
4059 "getTruncateOrNoop cannot extend!")((getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
"getTruncateOrNoop cannot extend!") ? static_cast<void>
(0) : __assert_fail ("getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && \"getTruncateOrNoop cannot extend!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4059, __PRETTY_FUNCTION__))
;
4060 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4061 return V; // No conversion
4062 return getTruncateExpr(V, Ty);
4063}
4064
4065const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4066 const SCEV *RHS) {
4067 const SCEV *PromotedLHS = LHS;
4068 const SCEV *PromotedRHS = RHS;
4069
4070 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4071 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4072 else
4073 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4074
4075 return getUMaxExpr(PromotedLHS, PromotedRHS);
4076}
4077
4078const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4079 const SCEV *RHS) {
4080 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4081 return getUMinFromMismatchedTypes(Ops);
4082}
4083
4084const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4085 SmallVectorImpl<const SCEV *> &Ops) {
4086 assert(!Ops.empty() && "At least one operand must be!")((!Ops.empty() && "At least one operand must be!") ? static_cast
<void> (0) : __assert_fail ("!Ops.empty() && \"At least one operand must be!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4086, __PRETTY_FUNCTION__))
;
4087 // Trivial case.
4088 if (Ops.size() == 1)
4089 return Ops[0];
4090
4091 // Find the max type first.
4092 Type *MaxType = nullptr;
4093 for (auto *S : Ops)
4094 if (MaxType)
4095 MaxType = getWiderType(MaxType, S->getType());
4096 else
4097 MaxType = S->getType();
4098 assert(MaxType && "Failed to find maximum type!")((MaxType && "Failed to find maximum type!") ? static_cast
<void> (0) : __assert_fail ("MaxType && \"Failed to find maximum type!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4098, __PRETTY_FUNCTION__))
;
4099
4100 // Extend all ops to max type.
4101 SmallVector<const SCEV *, 2> PromotedOps;
4102 for (auto *S : Ops)
4103 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4104
4105 // Generate umin.
4106 return getUMinExpr(PromotedOps);
4107}
4108
4109const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4110 // A pointer operand may evaluate to a nonpointer expression, such as null.
4111 if (!V->getType()->isPointerTy())
4112 return V;
4113
4114 while (true) {
4115 if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) {
4116 V = Cast->getOperand();
4117 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4118 const SCEV *PtrOp = nullptr;
4119 for (const SCEV *NAryOp : NAry->operands()) {
4120 if (NAryOp->getType()->isPointerTy()) {
4121 // Cannot find the base of an expression with multiple pointer ops.
4122 if (PtrOp)
4123 return V;
4124 PtrOp = NAryOp;
4125 }
4126 }
4127 if (!PtrOp) // All operands were non-pointer.
4128 return V;
4129 V = PtrOp;
4130 } else // Not something we can look further into.
4131 return V;
4132 }
4133}
4134
4135/// Push users of the given Instruction onto the given Worklist.
4136static void
4137PushDefUseChildren(Instruction *I,
4138 SmallVectorImpl<Instruction *> &Worklist) {
4139 // Push the def-use children onto the Worklist stack.
4140 for (User *U : I->users())
4141 Worklist.push_back(cast<Instruction>(U));
4142}
4143
4144void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4145 SmallVector<Instruction *, 16> Worklist;
4146 PushDefUseChildren(PN, Worklist);
4147
4148 SmallPtrSet<Instruction *, 8> Visited;
4149 Visited.insert(PN);
4150 while (!Worklist.empty()) {
4151 Instruction *I = Worklist.pop_back_val();
4152 if (!Visited.insert(I).second)
4153 continue;
4154
4155 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4156 if (It != ValueExprMap.end()) {
4157 const SCEV *Old = It->second;
4158
4159 // Short-circuit the def-use traversal if the symbolic name
4160 // ceases to appear in expressions.
4161 if (Old != SymName && !hasOperand(Old, SymName))
4162 continue;
4163
4164 // SCEVUnknown for a PHI either means that it has an unrecognized
4165 // structure, it's a PHI that's in the progress of being computed
4166 // by createNodeForPHI, or it's a single-value PHI. In the first case,
4167 // additional loop trip count information isn't going to change anything.
4168 // In the second case, createNodeForPHI will perform the necessary
4169 // updates on its own when it gets to that point. In the third, we do
4170 // want to forget the SCEVUnknown.
4171 if (!isa<PHINode>(I) ||
4172 !isa<SCEVUnknown>(Old) ||
4173 (I != PN && Old == SymName)) {
4174 eraseValueFromMap(It->first);
4175 forgetMemoizedResults(Old);
4176 }
4177 }
4178
4179 PushDefUseChildren(I, Worklist);
4180 }
4181}
4182
4183namespace {
4184
4185/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4186/// expression in case its Loop is L. If it is not L then
4187/// if IgnoreOtherLoops is true then use AddRec itself
4188/// otherwise rewrite cannot be done.
4189/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4190class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4191public:
4192 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4193 bool IgnoreOtherLoops = true) {
4194 SCEVInitRewriter Rewriter(L, SE);
4195 const SCEV *Result = Rewriter.visit(S);
4196 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4197 return SE.getCouldNotCompute();
4198 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4199 ? SE.getCouldNotCompute()
4200 : Result;
4201 }
4202
4203 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4204 if (!SE.isLoopInvariant(Expr, L))
4205 SeenLoopVariantSCEVUnknown = true;
4206 return Expr;
4207 }
4208
4209 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4210 // Only re-write AddRecExprs for this loop.
4211 if (Expr->getLoop() == L)
4212 return Expr->getStart();
4213 SeenOtherLoops = true;
4214 return Expr;
4215 }
4216
4217 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4218
4219 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4220
4221private:
4222 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4223 : SCEVRewriteVisitor(SE), L(L) {}
4224
4225 const Loop *L;
4226 bool SeenLoopVariantSCEVUnknown = false;
4227 bool SeenOtherLoops = false;
4228};
4229
4230/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4231/// increment expression in case its Loop is L. If it is not L then
4232/// use AddRec itself.
4233/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4234class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4235public:
4236 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4237 SCEVPostIncRewriter Rewriter(L, SE);
4238 const SCEV *Result = Rewriter.visit(S);
4239 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4240 ? SE.getCouldNotCompute()
4241 : Result;
4242 }
4243
4244 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4245 if (!SE.isLoopInvariant(Expr, L))
4246 SeenLoopVariantSCEVUnknown = true;
4247 return Expr;
4248 }
4249
4250 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4251 // Only re-write AddRecExprs for this loop.
4252 if (Expr->getLoop() == L)
4253 return Expr->getPostIncExpr(SE);
4254 SeenOtherLoops = true;
4255 return Expr;
4256 }
4257
4258 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4259
4260 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4261
4262private:
4263 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4264 : SCEVRewriteVisitor(SE), L(L) {}
4265
4266 const Loop *L;
4267 bool SeenLoopVariantSCEVUnknown = false;
4268 bool SeenOtherLoops = false;
4269};
4270
4271/// This class evaluates the compare condition by matching it against the
4272/// condition of loop latch. If there is a match we assume a true value
4273/// for the condition while building SCEV nodes.
4274class SCEVBackedgeConditionFolder
4275 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4276public:
4277 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4278 ScalarEvolution &SE) {
4279 bool IsPosBECond = false;
4280 Value *BECond = nullptr;
4281 if (BasicBlock *Latch = L->getLoopLatch()) {
4282 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4283 if (BI && BI->isConditional()) {
4284 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&((BI->getSuccessor(0) != BI->getSuccessor(1) &&
"Both outgoing branches should not target same header!") ? static_cast
<void> (0) : __assert_fail ("BI->getSuccessor(0) != BI->getSuccessor(1) && \"Both outgoing branches should not target same header!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4285, __PRETTY_FUNCTION__))
4285 "Both outgoing branches should not target same header!")((BI->getSuccessor(0) != BI->getSuccessor(1) &&
"Both outgoing branches should not target same header!") ? static_cast
<void> (0) : __assert_fail ("BI->getSuccessor(0) != BI->getSuccessor(1) && \"Both outgoing branches should not target same header!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4285, __PRETTY_FUNCTION__))
;
4286 BECond = BI->getCondition();
4287 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4288 } else {
4289 return S;
4290 }
4291 }
4292 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4293 return Rewriter.visit(S);
4294 }
4295
4296 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4297 const SCEV *Result = Expr;
4298 bool InvariantF = SE.isLoopInvariant(Expr, L);
4299
4300 if (!InvariantF) {
4301 Instruction *I = cast<Instruction>(Expr->getValue());
4302 switch (I->getOpcode()) {
4303 case Instruction::Select: {
4304 SelectInst *SI = cast<SelectInst>(I);
4305 Optional<const SCEV *> Res =
4306 compareWithBackedgeCondition(SI->getCondition());
4307 if (Res.hasValue()) {
4308 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4309 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4310 }
4311 break;
4312 }
4313 default: {
4314 Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4315 if (Res.hasValue())
4316 Result = Res.getValue();
4317 break;
4318 }
4319 }
4320 }
4321 return Result;
4322 }
4323
4324private:
4325 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4326 bool IsPosBECond, ScalarEvolution &SE)
4327 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4328 IsPositiveBECond(IsPosBECond) {}
4329
4330 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4331
4332 const Loop *L;
4333 /// Loop back condition.
4334 Value *BackedgeCond = nullptr;
4335 /// Set to true if loop back is on positive branch condition.
4336 bool IsPositiveBECond;
4337};
4338
4339Optional<const SCEV *>
4340SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4341
4342 // If value matches the backedge condition for loop latch,
4343 // then return a constant evolution node based on loopback
4344 // branch taken.
4345 if (BackedgeCond == IC)
4346 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4347 : SE.getZero(Type::getInt1Ty(SE.getContext()));
4348 return None;
4349}
4350
4351class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4352public:
4353 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4354 ScalarEvolution &SE) {
4355 SCEVShiftRewriter Rewriter(L, SE);
4356 const SCEV *Result = Rewriter.visit(S);
4357 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4358 }
4359
4360 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4361 // Only allow AddRecExprs for this loop.
4362 if (!SE.isLoopInvariant(Expr, L))
4363 Valid = false;
4364 return Expr;
4365 }
4366
4367 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4368 if (Expr->getLoop() == L && Expr->isAffine())
4369 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4370 Valid = false;
4371 return Expr;
4372 }
4373
4374 bool isValid() { return Valid; }
4375
4376private:
4377 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4378 : SCEVRewriteVisitor(SE), L(L) {}
4379
4380 const Loop *L;
4381 bool Valid = true;
4382};
4383
4384} // end anonymous namespace
4385
4386SCEV::NoWrapFlags
4387ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4388 if (!AR->isAffine())
4389 return SCEV::FlagAnyWrap;
4390
4391 using OBO = OverflowingBinaryOperator;
4392
4393 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4394
4395 if (!AR->hasNoSignedWrap()) {
4396 ConstantRange AddRecRange = getSignedRange(AR);
4397 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4398
4399 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4400 Instruction::Add, IncRange, OBO::NoSignedWrap);
4401 if (NSWRegion.contains(AddRecRange))
4402 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4403 }
4404
4405 if (!AR->hasNoUnsignedWrap()) {
4406 ConstantRange AddRecRange = getUnsignedRange(AR);
4407 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4408
4409 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4410 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4411 if (NUWRegion.contains(AddRecRange))
4412 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4413 }
4414
4415 return Result;
4416}
4417
4418SCEV::NoWrapFlags
4419ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4420 SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4421
4422 if (AR->hasNoSignedWrap())
4423 return Result;
4424
4425 if (!AR->isAffine())
4426 return Result;
4427
4428 const SCEV *Step = AR->getStepRecurrence(*this);
4429 const Loop *L = AR->getLoop();
4430
4431 // Check whether the backedge-taken count is SCEVCouldNotCompute.
4432 // Note that this serves two purposes: It filters out loops that are
4433 // simply not analyzable, and it covers the case where this code is
4434 // being called from within backedge-taken count analysis, such that
4435 // attempting to ask for the backedge-taken count would likely result
4436 // in infinite recursion. In the later case, the analysis code will
4437 // cope with a conservative value, and it will take care to purge
4438 // that value once it has finished.
4439 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4440
4441 // Normally, in the cases we can prove no-overflow via a
4442 // backedge guarding condition, we can also compute a backedge
4443 // taken count for the loop. The exceptions are assumptions and
4444 // guards present in the loop -- SCEV is not great at exploiting
4445 // these to compute max backedge taken counts, but can still use
4446 // these to prove lack of overflow. Use this fact to avoid
4447 // doing extra work that may not pay off.
4448
4449 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4450 AC.assumptions().empty())
4451 return Result;
4452
4453 // If the backedge is guarded by a comparison with the pre-inc value the
4454 // addrec is safe. Also, if the entry is guarded by a comparison with the
4455 // start value and the backedge is guarded by a comparison with the post-inc
4456 // value, the addrec is safe.
4457 ICmpInst::Predicate Pred;
4458 const SCEV *OverflowLimit =
4459 getSignedOverflowLimitForStep(Step, &Pred, this);
4460 if (OverflowLimit &&
4461 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
4462 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
4463 Result = setFlags(Result, SCEV::FlagNSW);
4464 }
4465 return Result;
4466}
4467SCEV::NoWrapFlags
4468ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
4469 SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
4470
4471 if (AR->hasNoUnsignedWrap())
4472 return Result;
4473
4474 if (!AR->isAffine())
4475 return Result;
4476
4477 const SCEV *Step = AR->getStepRecurrence(*this);
4478 unsigned BitWidth = getTypeSizeInBits(AR->getType());
4479 const Loop *L = AR->getLoop();
4480
4481 // Check whether the backedge-taken count is SCEVCouldNotCompute.
4482 // Note that this serves two purposes: It filters out loops that are
4483 // simply not analyzable, and it covers the case where this code is
4484 // being called from within backedge-taken count analysis, such that
4485 // attempting to ask for the backedge-taken count would likely result
4486 // in infinite recursion. In the later case, the analysis code will
4487 // cope with a conservative value, and it will take care to purge
4488 // that value once it has finished.
4489 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
4490
4491 // Normally, in the cases we can prove no-overflow via a
4492 // backedge guarding condition, we can also compute a backedge
4493 // taken count for the loop. The exceptions are assumptions and
4494 // guards present in the loop -- SCEV is not great at exploiting
4495 // these to compute max backedge taken counts, but can still use
4496 // these to prove lack of overflow. Use this fact to avoid
4497 // doing extra work that may not pay off.
4498
4499 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
4500 AC.assumptions().empty())
4501 return Result;
4502
4503 // If the backedge is guarded by a comparison with the pre-inc value the
4504 // addrec is safe. Also, if the entry is guarded by a comparison with the
4505 // start value and the backedge is guarded by a comparison with the post-inc
4506 // value, the addrec is safe.
4507 if (isKnownPositive(Step)) {
4508 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
4509 getUnsignedRangeMax(Step));
4510 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
4511 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
4512 Result = setFlags(Result, SCEV::FlagNUW);
4513 }
4514 }
4515
4516 return Result;
4517}
4518
4519namespace {
4520
4521/// Represents an abstract binary operation. This may exist as a
4522/// normal instruction or constant expression, or may have been
4523/// derived from an expression tree.
4524struct BinaryOp {
4525 unsigned Opcode;
4526 Value *LHS;
4527 Value *RHS;
4528 bool IsNSW = false;
4529 bool IsNUW = false;
4530 bool IsExact = false;
4531
4532 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4533 /// constant expression.
4534 Operator *Op = nullptr;
4535
4536 explicit BinaryOp(Operator *Op)
4537 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4538 Op(Op) {
4539 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4540 IsNSW = OBO->hasNoSignedWrap();
4541 IsNUW = OBO->hasNoUnsignedWrap();
4542 }
4543 if (auto *PEO = dyn_cast<PossiblyExactOperator>(Op))
4544 IsExact = PEO->isExact();
4545 }
4546
4547 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4548 bool IsNUW = false, bool IsExact = false)
4549 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
4550 IsExact(IsExact) {}
4551};
4552
4553} // end anonymous namespace
4554
4555/// Try to map \p V into a BinaryOp, and return \c None on failure.
4556static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4557 auto *Op = dyn_cast<Operator>(V);
4558 if (!Op)
4559 return None;
4560
4561 // Implementation detail: all the cleverness here should happen without
4562 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4563 // SCEV expressions when possible, and we should not break that.
4564
4565 switch (Op->getOpcode()) {
4566 case Instruction::Add:
4567 case Instruction::Sub:
4568 case Instruction::Mul:
4569 case Instruction::UDiv:
4570 case Instruction::URem:
4571 case Instruction::And:
4572 case Instruction::Or:
4573 case Instruction::AShr:
4574 case Instruction::Shl:
4575 return BinaryOp(Op);
4576
4577 case Instruction::Xor:
4578 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4579 // If the RHS of the xor is a signmask, then this is just an add.
4580 // Instcombine turns add of signmask into xor as a strength reduction step.
4581 if (RHSC->getValue().isSignMask())
4582 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4583 return BinaryOp(Op);
4584
4585 case Instruction::LShr:
4586 // Turn logical shift right of a constant into a unsigned divide.
4587 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4588 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4589
4590 // If the shift count is not less than the bitwidth, the result of
4591 // the shift is undefined. Don't try to analyze it, because the
4592 // resolution chosen here may differ from the resolution chosen in
4593 // other parts of the compiler.
4594 if (SA->getValue().ult(BitWidth)) {
4595 Constant *X =
4596 ConstantInt::get(SA->getContext(),
4597 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4598 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4599 }
4600 }
4601 return BinaryOp(Op);
4602
4603 case Instruction::ExtractValue: {
4604 auto *EVI = cast<ExtractValueInst>(Op);
4605 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4606 break;
4607
4608 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4609 if (!WO)
4610 break;
4611
4612 Instruction::BinaryOps BinOp = WO->getBinaryOp();
4613 bool Signed = WO->isSigned();
4614 // TODO: Should add nuw/nsw flags for mul as well.
4615 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4616 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4617
4618 // Now that we know that all uses of the arithmetic-result component of
4619 // CI are guarded by the overflow check, we can go ahead and pretend
4620 // that the arithmetic is non-overflowing.
4621 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4622 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4623 }
4624
4625 default:
4626 break;
4627 }
4628
4629 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
4630 // semantics as a Sub, return a binary sub expression.
4631 if (auto *II = dyn_cast<IntrinsicInst>(V))
4632 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
4633 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
4634
4635 return None;
4636}
4637
4638/// Helper function to createAddRecFromPHIWithCasts. We have a phi
4639/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4640/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4641/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4642/// follows one of the following patterns:
4643/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4644/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4645/// If the SCEV expression of \p Op conforms with one of the expected patterns
4646/// we return the type of the truncation operation, and indicate whether the
4647/// truncated type should be treated as signed/unsigned by setting
4648/// \p Signed to true/false, respectively.
4649static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4650 bool &Signed, ScalarEvolution &SE) {
4651 // The case where Op == SymbolicPHI (that is, with no type conversions on
4652 // the way) is handled by the regular add recurrence creating logic and
4653 // would have already been triggered in createAddRecForPHI. Reaching it here
4654 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4655 // because one of the other operands of the SCEVAddExpr updating this PHI is
4656 // not invariant).
4657 //
4658 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4659 // this case predicates that allow us to prove that Op == SymbolicPHI will
4660 // be added.
4661 if (Op == SymbolicPHI)
4662 return nullptr;
4663
4664 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4665 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4666 if (SourceBits != NewBits)
4667 return nullptr;
4668
4669 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4670 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4671 if (!SExt && !ZExt)
4672 return nullptr;
4673 const SCEVTruncateExpr *Trunc =
4674 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4675 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4676 if (!Trunc)
4677 return nullptr;
4678 const SCEV *X = Trunc->getOperand();
4679 if (X != SymbolicPHI)
4680 return nullptr;
4681 Signed = SExt != nullptr;
4682 return Trunc->getType();
4683}
4684
4685static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4686 if (!PN->getType()->isIntegerTy())
4687 return nullptr;
4688 const Loop *L = LI.getLoopFor(PN->getParent());
4689 if (!L || L->getHeader() != PN->getParent())
4690 return nullptr;
4691 return L;
4692}
4693
4694// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4695// computation that updates the phi follows the following pattern:
4696// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4697// which correspond to a phi->trunc->sext/zext->add->phi update chain.
4698// If so, try to see if it can be rewritten as an AddRecExpr under some
4699// Predicates. If successful, return them as a pair. Also cache the results
4700// of the analysis.
4701//
4702// Example usage scenario:
4703// Say the Rewriter is called for the following SCEV:
4704// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4705// where:
4706// %X = phi i64 (%Start, %BEValue)
4707// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4708// and call this function with %SymbolicPHI = %X.
4709//
4710// The analysis will find that the value coming around the backedge has
4711// the following SCEV:
4712// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4713// Upon concluding that this matches the desired pattern, the function
4714// will return the pair {NewAddRec, SmallPredsVec} where:
4715// NewAddRec = {%Start,+,%Step}
4716// SmallPredsVec = {P1, P2, P3} as follows:
4717// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4718// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4719// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4720// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4721// under the predicates {P1,P2,P3}.
4722// This predicated rewrite will be cached in PredicatedSCEVRewrites:
4723// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4724//
4725// TODO's:
4726//
4727// 1) Extend the Induction descriptor to also support inductions that involve
4728// casts: When needed (namely, when we are called in the context of the
4729// vectorizer induction analysis), a Set of cast instructions will be
4730// populated by this method, and provided back to isInductionPHI. This is
4731// needed to allow the vectorizer to properly record them to be ignored by
4732// the cost model and to avoid vectorizing them (otherwise these casts,
4733// which are redundant under the runtime overflow checks, will be
4734// vectorized, which can be costly).
4735//
4736// 2) Support additional induction/PHISCEV patterns: We also want to support
4737// inductions where the sext-trunc / zext-trunc operations (partly) occur
4738// after the induction update operation (the induction increment):
4739//
4740// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4741// which correspond to a phi->add->trunc->sext/zext->phi update chain.
4742//
4743// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4744// which correspond to a phi->trunc->add->sext/zext->phi update chain.
4745//
4746// 3) Outline common code with createAddRecFromPHI to avoid duplication.
4747Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4748ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4749 SmallVector<const SCEVPredicate *, 3> Predicates;
4750
4751 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4752 // return an AddRec expression under some predicate.
4753
4754 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4755 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4756 assert(L && "Expecting an integer loop header phi")((L && "Expecting an integer loop header phi") ? static_cast
<void> (0) : __assert_fail ("L && \"Expecting an integer loop header phi\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4756, __PRETTY_FUNCTION__))
;
4757
4758 // The loop may have multiple entrances or multiple exits; we can analyze
4759 // this phi as an addrec if it has a unique entry value and a unique
4760 // backedge value.
4761 Value *BEValueV = nullptr, *StartValueV = nullptr;
4762 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4763 Value *V = PN->getIncomingValue(i);
4764 if (L->contains(PN->getIncomingBlock(i))) {
4765 if (!BEValueV) {
4766 BEValueV = V;
4767 } else if (BEValueV != V) {
4768 BEValueV = nullptr;
4769 break;
4770 }
4771 } else if (!StartValueV) {
4772 StartValueV = V;
4773 } else if (StartValueV != V) {
4774 StartValueV = nullptr;
4775 break;
4776 }
4777 }
4778 if (!BEValueV || !StartValueV)
4779 return None;
4780
4781 const SCEV *BEValue = getSCEV(BEValueV);
4782
4783 // If the value coming around the backedge is an add with the symbolic
4784 // value we just inserted, possibly with casts that we can ignore under
4785 // an appropriate runtime guard, then we found a simple induction variable!
4786 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4787 if (!Add)
4788 return None;
4789
4790 // If there is a single occurrence of the symbolic value, possibly
4791 // casted, replace it with a recurrence.
4792 unsigned FoundIndex = Add->getNumOperands();
4793 Type *TruncTy = nullptr;
4794 bool Signed;
4795 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4796 if ((TruncTy =
4797 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4798 if (FoundIndex == e) {
4799 FoundIndex = i;
4800 break;
4801 }
4802
4803 if (FoundIndex == Add->getNumOperands())
4804 return None;
4805
4806 // Create an add with everything but the specified operand.
4807 SmallVector<const SCEV *, 8> Ops;
4808 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4809 if (i != FoundIndex)
4810 Ops.push_back(Add->getOperand(i));
4811 const SCEV *Accum = getAddExpr(Ops);
4812
4813 // The runtime checks will not be valid if the step amount is
4814 // varying inside the loop.
4815 if (!isLoopInvariant(Accum, L))
4816 return None;
4817
4818 // *** Part2: Create the predicates
4819
4820 // Analysis was successful: we have a phi-with-cast pattern for which we
4821 // can return an AddRec expression under the following predicates:
4822 //
4823 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4824 // fits within the truncated type (does not overflow) for i = 0 to n-1.
4825 // P2: An Equal predicate that guarantees that
4826 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4827 // P3: An Equal predicate that guarantees that
4828 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4829 //
4830 // As we next prove, the above predicates guarantee that:
4831 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4832 //
4833 //
4834 // More formally, we want to prove that:
4835 // Expr(i+1) = Start + (i+1) * Accum
4836 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4837 //
4838 // Given that:
4839 // 1) Expr(0) = Start
4840 // 2) Expr(1) = Start + Accum
4841 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4842 // 3) Induction hypothesis (step i):
4843 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4844 //
4845 // Proof:
4846 // Expr(i+1) =
4847 // = Start + (i+1)*Accum
4848 // = (Start + i*Accum) + Accum
4849 // = Expr(i) + Accum
4850 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4851 // :: from step i
4852 //
4853 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4854 //
4855 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4856 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
4857 // + Accum :: from P3
4858 //
4859 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4860 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4861 //
4862 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4863 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4864 //
4865 // By induction, the same applies to all iterations 1<=i<n:
4866 //
4867
4868 // Create a truncated addrec for which we will add a no overflow check (P1).
4869 const SCEV *StartVal = getSCEV(StartValueV);
4870 const SCEV *PHISCEV =
4871 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4872 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4873
4874 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4875 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4876 // will be constant.
4877 //
4878 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4879 // add P1.
4880 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4881 SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4882 Signed ? SCEVWrapPredicate::IncrementNSSW
4883 : SCEVWrapPredicate::IncrementNUSW;
4884 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4885 Predicates.push_back(AddRecPred);
4886 }
4887
4888 // Create the Equal Predicates P2,P3:
4889
4890 // It is possible that the predicates P2 and/or P3 are computable at
4891 // compile time due to StartVal and/or Accum being constants.
4892 // If either one is, then we can check that now and escape if either P2
4893 // or P3 is false.
4894
4895 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4896 // for each of StartVal and Accum
4897 auto getExtendedExpr = [&](const SCEV *Expr,
4898 bool CreateSignExtend) -> const SCEV * {
4899 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant")((isLoopInvariant(Expr, L) && "Expr is expected to be invariant"
) ? static_cast<void> (0) : __assert_fail ("isLoopInvariant(Expr, L) && \"Expr is expected to be invariant\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4899, __PRETTY_FUNCTION__))
;
4900 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4901 const SCEV *ExtendedExpr =
4902 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4903 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4904 return ExtendedExpr;
4905 };
4906
4907 // Given:
4908 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4909 // = getExtendedExpr(Expr)
4910 // Determine whether the predicate P: Expr == ExtendedExpr
4911 // is known to be false at compile time
4912 auto PredIsKnownFalse = [&](const SCEV *Expr,
4913 const SCEV *ExtendedExpr) -> bool {
4914 return Expr != ExtendedExpr &&
4915 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4916 };
4917
4918 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4919 if (PredIsKnownFalse(StartVal, StartExtended)) {
4920 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)
;
4921 return None;
4922 }
4923
4924 // The Step is always Signed (because the overflow checks are either
4925 // NSSW or NUSW)
4926 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4927 if (PredIsKnownFalse(Accum, AccumExtended)) {
4928 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)
;
4929 return None;
4930 }
4931
4932 auto AppendPredicate = [&](const SCEV *Expr,
4933 const SCEV *ExtendedExpr) -> void {
4934 if (Expr != ExtendedExpr &&
4935 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4936 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4937 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "Added Predicate: " <<
*Pred; } } while (false)
;
4938 Predicates.push_back(Pred);
4939 }
4940 };
4941
4942 AppendPredicate(StartVal, StartExtended);
4943 AppendPredicate(Accum, AccumExtended);
4944
4945 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4946 // which the casts had been folded away. The caller can rewrite SymbolicPHI
4947 // into NewAR if it will also add the runtime overflow checks specified in
4948 // Predicates.
4949 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4950
4951 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4952 std::make_pair(NewAR, Predicates);
4953 // Remember the result of the analysis for this SCEV at this locayyytion.
4954 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4955 return PredRewrite;
4956}
4957
4958Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4959ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4960 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4961 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4962 if (!L)
4963 return None;
4964
4965 // Check to see if we already analyzed this PHI.
4966 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4967 if (I != PredicatedSCEVRewrites.end()) {
4968 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4969 I->second;
4970 // Analysis was done before and failed to create an AddRec:
4971 if (Rewrite.first == SymbolicPHI)
4972 return None;
4973 // Analysis was done before and succeeded to create an AddRec under
4974 // a predicate:
4975 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec")((isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"
) ? static_cast<void> (0) : __assert_fail ("isa<SCEVAddRecExpr>(Rewrite.first) && \"Expected an AddRec\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4975, __PRETTY_FUNCTION__))
;
4976 assert(!(Rewrite.second).empty() && "Expected to find Predicates")((!(Rewrite.second).empty() && "Expected to find Predicates"
) ? static_cast<void> (0) : __assert_fail ("!(Rewrite.second).empty() && \"Expected to find Predicates\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 4976, __PRETTY_FUNCTION__))
;
4977 return Rewrite;
4978 }
4979
4980 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4981 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4982
4983 // Record in the cache that the analysis failed
4984 if (!Rewrite) {
4985 SmallVector<const SCEVPredicate *, 3> Predicates;
4986 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4987 return None;
4988 }
4989
4990 return Rewrite;
4991}
4992
4993// FIXME: This utility is currently required because the Rewriter currently
4994// does not rewrite this expression:
4995// {0, +, (sext ix (trunc iy to ix) to iy)}
4996// into {0, +, %step},
4997// even when the following Equal predicate exists:
4998// "%step == (sext ix (trunc iy to ix) to iy)".
4999bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5000 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
5001 if (AR1 == AR2)
5002 return true;
5003
5004 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5005 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
5006 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
5007 return false;
5008 return true;
5009 };
5010
5011 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5012 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5013 return false;
5014 return true;
5015}
5016
5017/// A helper function for createAddRecFromPHI to handle simple cases.
5018///
5019/// This function tries to find an AddRec expression for the simplest (yet most
5020/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5021/// If it fails, createAddRecFromPHI will use a more general, but slow,
5022/// technique for finding the AddRec expression.
5023const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5024 Value *BEValueV,
5025 Value *StartValueV) {
5026 const Loop *L = LI.getLoopFor(PN->getParent());
5027 assert(L && L->getHeader() == PN->getParent())((L && L->getHeader() == PN->getParent()) ? static_cast
<void> (0) : __assert_fail ("L && L->getHeader() == PN->getParent()"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5027, __PRETTY_FUNCTION__))
;
5028 assert(BEValueV && StartValueV)((BEValueV && StartValueV) ? static_cast<void> (
0) : __assert_fail ("BEValueV && StartValueV", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5028, __PRETTY_FUNCTION__))
;
5029
5030 auto BO = MatchBinaryOp(BEValueV, DT);
5031 if (!BO)
5032 return nullptr;
5033
5034 if (BO->Opcode != Instruction::Add)
5035 return nullptr;
5036
5037 const SCEV *Accum = nullptr;
5038 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5039 Accum = getSCEV(BO->RHS);
5040 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5041 Accum = getSCEV(BO->LHS);
5042
5043 if (!Accum)
5044 return nullptr;
5045
5046 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5047 if (BO->IsNUW)
5048 Flags = setFlags(Flags, SCEV::FlagNUW);
5049 if (BO->IsNSW)
5050 Flags = setFlags(Flags, SCEV::FlagNSW);
5051
5052 const SCEV *StartVal = getSCEV(StartValueV);
5053 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5054
5055 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5056
5057 // We can add Flags to the post-inc expression only if we
5058 // know that it is *undefined behavior* for BEValueV to
5059 // overflow.
5060 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5061 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5062 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5063
5064 return PHISCEV;
5065}
5066
5067const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5068 const Loop *L = LI.getLoopFor(PN->getParent());
5069 if (!L || L->getHeader() != PN->getParent())
5070 return nullptr;
5071
5072 // The loop may have multiple entrances or multiple exits; we can analyze
5073 // this phi as an addrec if it has a unique entry value and a unique
5074 // backedge value.
5075 Value *BEValueV = nullptr, *StartValueV = nullptr;
5076 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5077 Value *V = PN->getIncomingValue(i);
5078 if (L->contains(PN->getIncomingBlock(i))) {
5079 if (!BEValueV) {
5080 BEValueV = V;
5081 } else if (BEValueV != V) {
5082 BEValueV = nullptr;
5083 break;
5084 }
5085 } else if (!StartValueV) {
5086 StartValueV = V;
5087 } else if (StartValueV != V) {
5088 StartValueV = nullptr;
5089 break;
5090 }
5091 }
5092 if (!BEValueV || !StartValueV)
5093 return nullptr;
5094
5095 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&((ValueExprMap.find_as(PN) == ValueExprMap.end() && "PHI node already processed?"
) ? static_cast<void> (0) : __assert_fail ("ValueExprMap.find_as(PN) == ValueExprMap.end() && \"PHI node already processed?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5096, __PRETTY_FUNCTION__))
5096 "PHI node already processed?")((ValueExprMap.find_as(PN) == ValueExprMap.end() && "PHI node already processed?"
) ? static_cast<void> (0) : __assert_fail ("ValueExprMap.find_as(PN) == ValueExprMap.end() && \"PHI node already processed?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5096, __PRETTY_FUNCTION__))
;
5097
5098 // First, try to find AddRec expression without creating a fictituos symbolic
5099 // value for PN.
5100 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5101 return S;
5102
5103 // Handle PHI node value symbolically.
5104 const SCEV *SymbolicName = getUnknown(PN);
5105 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5106
5107 // Using this symbolic name for the PHI, analyze the value coming around
5108 // the back-edge.
5109 const SCEV *BEValue = getSCEV(BEValueV);
5110
5111 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5112 // has a special value for the first iteration of the loop.
5113
5114 // If the value coming around the backedge is an add with the symbolic
5115 // value we just inserted, then we found a simple induction variable!
5116 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5117 // If there is a single occurrence of the symbolic value, replace it
5118 // with a recurrence.
5119 unsigned FoundIndex = Add->getNumOperands();
5120 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5121 if (Add->getOperand(i) == SymbolicName)
5122 if (FoundIndex == e) {
5123 FoundIndex = i;
5124 break;
5125 }
5126
5127 if (FoundIndex != Add->getNumOperands()) {
5128 // Create an add with everything but the specified operand.
5129 SmallVector<const SCEV *, 8> Ops;
5130 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5131 if (i != FoundIndex)
5132 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5133 L, *this));
5134 const SCEV *Accum = getAddExpr(Ops);
5135
5136 // This is not a valid addrec if the step amount is varying each
5137 // loop iteration, but is not itself an addrec in this loop.
5138 if (isLoopInvariant(Accum, L) ||
5139 (isa<SCEVAddRecExpr>(Accum) &&
5140 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5141 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5142
5143 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5144 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5145 if (BO->IsNUW)
5146 Flags = setFlags(Flags, SCEV::FlagNUW);
5147 if (BO->IsNSW)
5148 Flags = setFlags(Flags, SCEV::FlagNSW);
5149 }
5150 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5151 // If the increment is an inbounds GEP, then we know the address
5152 // space cannot be wrapped around. We cannot make any guarantee
5153 // about signed or unsigned overflow because pointers are
5154 // unsigned but we may have a negative index from the base
5155 // pointer. We can guarantee that no unsigned wrap occurs if the
5156 // indices form a positive value.
5157 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5158 Flags = setFlags(Flags, SCEV::FlagNW);
5159
5160 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5161 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5162 Flags = setFlags(Flags, SCEV::FlagNUW);
5163 }
5164
5165 // We cannot transfer nuw and nsw flags from subtraction
5166 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5167 // for instance.
5168 }
5169
5170 const SCEV *StartVal = getSCEV(StartValueV);
5171 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5172
5173 // Okay, for the entire analysis of this edge we assumed the PHI
5174 // to be symbolic. We now need to go back and purge all of the
5175 // entries for the scalars that use the symbolic expression.
5176 forgetSymbolicName(PN, SymbolicName);
5177 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5178
5179 // We can add Flags to the post-inc expression only if we
5180 // know that it is *undefined behavior* for BEValueV to
5181 // overflow.
5182 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5183 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5184 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5185
5186 return PHISCEV;
5187 }
5188 }
5189 } else {
5190 // Otherwise, this could be a loop like this:
5191 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5192 // In this case, j = {1,+,1} and BEValue is j.
5193 // Because the other in-value of i (0) fits the evolution of BEValue
5194 // i really is an addrec evolution.
5195 //
5196 // We can generalize this saying that i is the shifted value of BEValue
5197 // by one iteration:
5198 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5199 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5200 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5201 if (Shifted != getCouldNotCompute() &&
5202 Start != getCouldNotCompute()) {
5203 const SCEV *StartVal = getSCEV(StartValueV);
5204 if (Start == StartVal) {
5205 // Okay, for the entire analysis of this edge we assumed the PHI
5206 // to be symbolic. We now need to go back and purge all of the
5207 // entries for the scalars that use the symbolic expression.
5208 forgetSymbolicName(PN, SymbolicName);
5209 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5210 return Shifted;
5211 }
5212 }
5213 }
5214
5215 // Remove the temporary PHI node SCEV that has been inserted while intending
5216 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5217 // as it will prevent later (possibly simpler) SCEV expressions to be added
5218 // to the ValueExprMap.
5219 eraseValueFromMap(PN);
5220
5221 return nullptr;
5222}
5223
5224// Checks if the SCEV S is available at BB. S is considered available at BB
5225// if S can be materialized at BB without introducing a fault.
5226static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5227 BasicBlock *BB) {
5228 struct CheckAvailable {
5229 bool TraversalDone = false;
5230 bool Available = true;
5231
5232 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
5233 BasicBlock *BB = nullptr;
5234 DominatorTree &DT;
5235
5236 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5237 : L(L), BB(BB), DT(DT) {}
5238
5239 bool setUnavailable() {
5240 TraversalDone = true;
5241 Available = false;
5242 return false;
5243 }
5244
5245 bool follow(const SCEV *S) {
5246 switch (S->getSCEVType()) {
5247 case scConstant:
5248 case scPtrToInt:
5249 case scTruncate:
5250 case scZeroExtend:
5251 case scSignExtend:
5252 case scAddExpr:
5253 case scMulExpr:
5254 case scUMaxExpr:
5255 case scSMaxExpr:
5256 case scUMinExpr:
5257 case scSMinExpr:
5258 // These expressions are available if their operand(s) is/are.
5259 return true;
5260
5261 case scAddRecExpr: {
5262 // We allow add recurrences that are on the loop BB is in, or some
5263 // outer loop. This guarantees availability because the value of the
5264 // add recurrence at BB is simply the "current" value of the induction
5265 // variable. We can relax this in the future; for instance an add
5266 // recurrence on a sibling dominating loop is also available at BB.
5267 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5268 if (L && (ARLoop == L || ARLoop->contains(L)))
5269 return true;
5270
5271 return setUnavailable();
5272 }
5273
5274 case scUnknown: {
5275 // For SCEVUnknown, we check for simple dominance.
5276 const auto *SU = cast<SCEVUnknown>(S);
5277 Value *V = SU->getValue();
5278
5279 if (isa<Argument>(V))
5280 return false;
5281
5282 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5283 return false;
5284
5285 return setUnavailable();
5286 }
5287
5288 case scUDivExpr:
5289 case scCouldNotCompute:
5290 // We do not try to smart about these at all.
5291 return setUnavailable();
5292 }
5293 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5293)
;
5294 }
5295
5296 bool isDone() { return TraversalDone; }
5297 };
5298
5299 CheckAvailable CA(L, BB, DT);
5300 SCEVTraversal<CheckAvailable> ST(CA);
5301
5302 ST.visitAll(S);
5303 return CA.Available;
5304}
5305
5306// Try to match a control flow sequence that branches out at BI and merges back
5307// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5308// match.
5309static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5310 Value *&C, Value *&LHS, Value *&RHS) {
5311 C = BI->getCondition();
5312
5313 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5314 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5315
5316 if (!LeftEdge.isSingleEdge())
5317 return false;
5318
5319 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()")((RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"
) ? static_cast<void> (0) : __assert_fail ("RightEdge.isSingleEdge() && \"Follows from LeftEdge.isSingleEdge()\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5319, __PRETTY_FUNCTION__))
;
5320
5321 Use &LeftUse = Merge->getOperandUse(0);
5322 Use &RightUse = Merge->getOperandUse(1);
5323
5324 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5325 LHS = LeftUse;
5326 RHS = RightUse;
5327 return true;
5328 }
5329
5330 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5331 LHS = RightUse;
5332 RHS = LeftUse;
5333 return true;
5334 }
5335
5336 return false;
5337}
5338
5339const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5340 auto IsReachable =
5341 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5342 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5343 const Loop *L = LI.getLoopFor(PN->getParent());
5344
5345 // We don't want to break LCSSA, even in a SCEV expression tree.
5346 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5347 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5348 return nullptr;
5349
5350 // Try to match
5351 //
5352 // br %cond, label %left, label %right
5353 // left:
5354 // br label %merge
5355 // right:
5356 // br label %merge
5357 // merge:
5358 // V = phi [ %x, %left ], [ %y, %right ]
5359 //
5360 // as "select %cond, %x, %y"
5361
5362 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5363 assert(IDom && "At least the entry block should dominate PN")((IDom && "At least the entry block should dominate PN"
) ? static_cast<void> (0) : __assert_fail ("IDom && \"At least the entry block should dominate PN\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5363, __PRETTY_FUNCTION__))
;
5364
5365 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5366 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5367
5368 if (BI && BI->isConditional() &&
5369 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5370 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5371 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5372 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5373 }
5374
5375 return nullptr;
5376}
5377
5378const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5379 if (const SCEV *S = createAddRecFromPHI(PN))
5380 return S;
5381
5382 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5383 return S;
5384
5385 // If the PHI has a single incoming value, follow that value, unless the
5386 // PHI's incoming blocks are in a different loop, in which case doing so
5387 // risks breaking LCSSA form. Instcombine would normally zap these, but
5388 // it doesn't have DominatorTree information, so it may miss cases.
5389 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5390 if (LI.replacementPreservesLCSSAForm(PN, V))
5391 return getSCEV(V);
5392
5393 // If it's not a loop phi, we can't handle it yet.
5394 return getUnknown(PN);
5395}
5396
5397const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5398 Value *Cond,
5399 Value *TrueVal,
5400 Value *FalseVal) {
5401 // Handle "constant" branch or select. This can occur for instance when a
5402 // loop pass transforms an inner loop and moves on to process the outer loop.
5403 if (auto *CI = dyn_cast<ConstantInt>(Cond))
5404 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5405
5406 // Try to match some simple smax or umax patterns.
5407 auto *ICI = dyn_cast<ICmpInst>(Cond);
5408 if (!ICI)
5409 return getUnknown(I);
5410
5411 Value *LHS = ICI->getOperand(0);
5412 Value *RHS = ICI->getOperand(1);
5413
5414 switch (ICI->getPredicate()) {
5415 case ICmpInst::ICMP_SLT:
5416 case ICmpInst::ICMP_SLE:
5417 std::swap(LHS, RHS);
5418 LLVM_FALLTHROUGH[[gnu::fallthrough]];
5419 case ICmpInst::ICMP_SGT:
5420 case ICmpInst::ICMP_SGE:
5421 // a >s b ? a+x : b+x -> smax(a, b)+x
5422 // a >s b ? b+x : a+x -> smin(a, b)+x
5423 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5424 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5425 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5426 const SCEV *LA = getSCEV(TrueVal);
5427 const SCEV *RA = getSCEV(FalseVal);
5428 const SCEV *LDiff = getMinusSCEV(LA, LS);
5429 const SCEV *RDiff = getMinusSCEV(RA, RS);
5430 if (LDiff == RDiff)
5431 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5432 LDiff = getMinusSCEV(LA, RS);
5433 RDiff = getMinusSCEV(RA, LS);
5434 if (LDiff == RDiff)
5435 return getAddExpr(getSMinExpr(LS, RS), LDiff);
5436 }
5437 break;
5438 case ICmpInst::ICMP_ULT:
5439 case ICmpInst::ICMP_ULE:
5440 std::swap(LHS, RHS);
5441 LLVM_FALLTHROUGH[[gnu::fallthrough]];
5442 case ICmpInst::ICMP_UGT:
5443 case ICmpInst::ICMP_UGE:
5444 // a >u b ? a+x : b+x -> umax(a, b)+x
5445 // a >u b ? b+x : a+x -> umin(a, b)+x
5446 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5447 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5448 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5449 const SCEV *LA = getSCEV(TrueVal);
5450 const SCEV *RA = getSCEV(FalseVal);
5451 const SCEV *LDiff = getMinusSCEV(LA, LS);
5452 const SCEV *RDiff = getMinusSCEV(RA, RS);
5453 if (LDiff == RDiff)
5454 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5455 LDiff = getMinusSCEV(LA, RS);
5456 RDiff = getMinusSCEV(RA, LS);
5457 if (LDiff == RDiff)
5458 return getAddExpr(getUMinExpr(LS, RS), LDiff);
5459 }
5460 break;
5461 case ICmpInst::ICMP_NE:
5462 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
5463 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5464 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5465 const SCEV *One = getOne(I->getType());
5466 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5467 const SCEV *LA = getSCEV(TrueVal);
5468 const SCEV *RA = getSCEV(FalseVal);
5469 const SCEV *LDiff = getMinusSCEV(LA, LS);
5470 const SCEV *RDiff = getMinusSCEV(RA, One);
5471 if (LDiff == RDiff)
5472 return getAddExpr(getUMaxExpr(One, LS), LDiff);
5473 }
5474 break;
5475 case ICmpInst::ICMP_EQ:
5476 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
5477 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5478 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5479 const SCEV *One = getOne(I->getType());
5480 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5481 const SCEV *LA = getSCEV(TrueVal);
5482 const SCEV *RA = getSCEV(FalseVal);
5483 const SCEV *LDiff = getMinusSCEV(LA, One);
5484 const SCEV *RDiff = getMinusSCEV(RA, LS);
5485 if (LDiff == RDiff)
5486 return getAddExpr(getUMaxExpr(One, LS), LDiff);
5487 }
5488 break;
5489 default:
5490 break;
5491 }
5492
5493 return getUnknown(I);
5494}
5495
5496/// Expand GEP instructions into add and multiply operations. This allows them
5497/// to be analyzed by regular SCEV code.
5498const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5499 // Don't attempt to analyze GEPs over unsized objects.
5500 if (!GEP->getSourceElementType()->isSized())
5501 return getUnknown(GEP);
5502
5503 SmallVector<const SCEV *, 4> IndexExprs;
5504 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5505 IndexExprs.push_back(getSCEV(*Index));
5506 return getGEPExpr(GEP, IndexExprs);
5507}
5508
5509uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5510 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5511 return C->getAPInt().countTrailingZeros();
5512
5513 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S))
5514 return GetMinTrailingZeros(I->getOperand());
5515
5516 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5517 return std::min(GetMinTrailingZeros(T->getOperand()),
5518 (uint32_t)getTypeSizeInBits(T->getType()));
5519
5520 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5521 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5522 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5523 ? getTypeSizeInBits(E->getType())
5524 : OpRes;
5525 }
5526
5527 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5528 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5529 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5530 ? getTypeSizeInBits(E->getType())
5531 : OpRes;
5532 }
5533
5534 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5535 // The result is the min of all operands results.
5536 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5537 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5538 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5539 return MinOpRes;
5540 }
5541
5542 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5543 // The result is the sum of all operands results.
5544 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5545 uint32_t BitWidth = getTypeSizeInBits(M->getType());
5546 for (unsigned i = 1, e = M->getNumOperands();
5547 SumOpRes != BitWidth && i != e; ++i)
5548 SumOpRes =
5549 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5550 return SumOpRes;
5551 }
5552
5553 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5554 // The result is the min of all operands results.
5555 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5556 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5557 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5558 return MinOpRes;
5559 }
5560
5561 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5562 // The result is the min of all operands results.
5563 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5564 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5565 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5566 return MinOpRes;
5567 }
5568
5569 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5570 // The result is the min of all operands results.
5571 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5572 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5573 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5574 return MinOpRes;
5575 }
5576
5577 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5578 // For a SCEVUnknown, ask ValueTracking.
5579 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5580 return Known.countMinTrailingZeros();
5581 }
5582
5583 // SCEVUDivExpr
5584 return 0;
5585}
5586
5587uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5588 auto I = MinTrailingZerosCache.find(S);
5589 if (I != MinTrailingZerosCache.end())
5590 return I->second;
5591
5592 uint32_t Result = GetMinTrailingZerosImpl(S);
5593 auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5594 assert(InsertPair.second && "Should insert a new key")((InsertPair.second && "Should insert a new key") ? static_cast
<void> (0) : __assert_fail ("InsertPair.second && \"Should insert a new key\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5594, __PRETTY_FUNCTION__))
;
5595 return InsertPair.first->second;
5596}
5597
5598/// Helper method to assign a range to V from metadata present in the IR.
5599static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5600 if (Instruction *I = dyn_cast<Instruction>(V))
5601 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5602 return getConstantRangeFromMetadata(*MD);
5603
5604 return None;
5605}
5606
5607void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
5608 SCEV::NoWrapFlags Flags) {
5609 if (AddRec->getNoWrapFlags(Flags) != Flags) {
5610 AddRec->setNoWrapFlags(Flags);
5611 UnsignedRanges.erase(AddRec);
5612 SignedRanges.erase(AddRec);
5613 }
5614}
5615
5616/// Determine the range for a particular SCEV. If SignHint is
5617/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5618/// with a "cleaner" unsigned (resp. signed) representation.
5619const ConstantRange &
5620ScalarEvolution::getRangeRef(const SCEV *S,
5621 ScalarEvolution::RangeSignHint SignHint) {
5622 DenseMap<const SCEV *, ConstantRange> &Cache =
5623 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5624 : SignedRanges;
5625 ConstantRange::PreferredRangeType RangeType =
5626 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
5627 ? ConstantRange::Unsigned : ConstantRange::Signed;
5628
5629 // See if we've computed this range already.
5630 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5631 if (I != Cache.end())
5632 return I->second;
5633
5634 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5635 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5636
5637 unsigned BitWidth = getTypeSizeInBits(S->getType());
5638 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5639 using OBO = OverflowingBinaryOperator;
5640
5641 // If the value has known zeros, the maximum value will have those known zeros
5642 // as well.
5643 uint32_t TZ = GetMinTrailingZeros(S);
5644 if (TZ != 0) {
5645 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5646 ConservativeResult =
5647 ConstantRange(APInt::getMinValue(BitWidth),
5648 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5649 else
5650 ConservativeResult = ConstantRange(
5651 APInt::getSignedMinValue(BitWidth),
5652 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5653 }
5654
5655 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5656 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5657 unsigned WrapType = OBO::AnyWrap;
5658 if (Add->hasNoSignedWrap())
5659 WrapType |= OBO::NoSignedWrap;
5660 if (Add->hasNoUnsignedWrap())
5661 WrapType |= OBO::NoUnsignedWrap;
5662 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5663 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
5664 WrapType, RangeType);
5665 return setRange(Add, SignHint,
5666 ConservativeResult.intersectWith(X, RangeType));
5667 }
5668
5669 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5670 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5671 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5672 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5673 return setRange(Mul, SignHint,
5674 ConservativeResult.intersectWith(X, RangeType));
5675 }
5676
5677 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5678 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5679 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5680 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5681 return setRange(SMax, SignHint,
5682 ConservativeResult.intersectWith(X, RangeType));
5683 }
5684
5685 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5686 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5687 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5688 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5689 return setRange(UMax, SignHint,
5690 ConservativeResult.intersectWith(X, RangeType));
5691 }
5692
5693 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
5694 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
5695 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
5696 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
5697 return setRange(SMin, SignHint,
5698 ConservativeResult.intersectWith(X, RangeType));
5699 }
5700
5701 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
5702 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
5703 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
5704 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
5705 return setRange(UMin, SignHint,
5706 ConservativeResult.intersectWith(X, RangeType));
5707 }
5708
5709 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5710 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5711 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5712 return setRange(UDiv, SignHint,
5713 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
5714 }
5715
5716 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5717 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5718 return setRange(ZExt, SignHint,
5719 ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
5720 RangeType));
5721 }
5722
5723 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5724 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5725 return setRange(SExt, SignHint,
5726 ConservativeResult.intersectWith(X.signExtend(BitWidth),
5727 RangeType));
5728 }
5729
5730 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
5731 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
5732 return setRange(PtrToInt, SignHint, X);
5733 }
5734
5735 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5736 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5737 return setRange(Trunc, SignHint,
5738 ConservativeResult.intersectWith(X.truncate(BitWidth),
5739 RangeType));
5740 }
5741
5742 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5743 // If there's no unsigned wrap, the value will never be less than its
5744 // initial value.
5745 if (AddRec->hasNoUnsignedWrap()) {
5746 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
5747 if (!UnsignedMinValue.isNullValue())
5748 ConservativeResult = ConservativeResult.intersectWith(
5749 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
5750 }
5751
5752 // If there's no signed wrap, and all the operands except initial value have
5753 // the same sign or zero, the value won't ever be:
5754 // 1: smaller than initial value if operands are non negative,
5755 // 2: bigger than initial value if operands are non positive.
5756 // For both cases, value can not cross signed min/max boundary.
5757 if (AddRec->hasNoSignedWrap()) {
5758 bool AllNonNeg = true;
5759 bool AllNonPos = true;
5760 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
5761 if (!isKnownNonNegative(AddRec->getOperand(i)))
5762 AllNonNeg = false;
5763 if (!isKnownNonPositive(AddRec->getOperand(i)))
5764 AllNonPos = false;
5765 }
5766 if (AllNonNeg)
5767 ConservativeResult = ConservativeResult.intersectWith(
5768 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
5769 APInt::getSignedMinValue(BitWidth)),
5770 RangeType);
5771 else if (AllNonPos)
5772 ConservativeResult = ConservativeResult.intersectWith(
5773 ConstantRange::getNonEmpty(
5774 APInt::getSignedMinValue(BitWidth),
5775 getSignedRangeMax(AddRec->getStart()) + 1),
5776 RangeType);
5777 }
5778
5779 // TODO: non-affine addrec
5780 if (AddRec->isAffine()) {
5781 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
5782 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5783 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5784 auto RangeFromAffine = getRangeForAffineAR(
5785 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5786 BitWidth);
5787 ConservativeResult =
5788 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
5789
5790 auto RangeFromFactoring = getRangeViaFactoring(
5791 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5792 BitWidth);
5793 ConservativeResult =
5794 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
5795 }
5796
5797 // Now try symbolic BE count and more powerful methods.
5798 if (UseExpensiveRangeSharpening) {
5799 const SCEV *SymbolicMaxBECount =
5800 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
5801 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
5802 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5803 AddRec->hasNoSelfWrap()) {
5804 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
5805 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
5806 ConservativeResult =
5807 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
5808 }
5809 }
5810 }
5811
5812 return setRange(AddRec, SignHint, std::move(ConservativeResult));
5813 }
5814
5815 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5816 // Check if the IR explicitly contains !range metadata.
5817 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5818 if (MDRange.hasValue())
5819 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
5820 RangeType);
5821
5822 // Split here to avoid paying the compile-time cost of calling both
5823 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
5824 // if needed.
5825 const DataLayout &DL = getDataLayout();
5826 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5827 // For a SCEVUnknown, ask ValueTracking.
5828 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5829 if (Known.getBitWidth() != BitWidth)
5830 Known = Known.zextOrTrunc(BitWidth);
5831 // If Known does not result in full-set, intersect with it.
5832 if (Known.getMinValue() != Known.getMaxValue() + 1)
5833 ConservativeResult = ConservativeResult.intersectWith(
5834 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
5835 RangeType);
5836 } else {
5837 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&((SignHint == ScalarEvolution::HINT_RANGE_SIGNED && "generalize as needed!"
) ? static_cast<void> (0) : __assert_fail ("SignHint == ScalarEvolution::HINT_RANGE_SIGNED && \"generalize as needed!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5838, __PRETTY_FUNCTION__))
5838 "generalize as needed!")((SignHint == ScalarEvolution::HINT_RANGE_SIGNED && "generalize as needed!"
) ? static_cast<void> (0) : __assert_fail ("SignHint == ScalarEvolution::HINT_RANGE_SIGNED && \"generalize as needed!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5838, __PRETTY_FUNCTION__))
;
5839 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5840 // If the pointer size is larger than the index size type, this can cause
5841 // NS to be larger than BitWidth. So compensate for this.
5842 if (U->getType()->isPointerTy()) {
5843 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
5844 int ptrIdxDiff = ptrSize - BitWidth;
5845 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
5846 NS -= ptrIdxDiff;
5847 }
5848
5849 if (NS > 1)
5850 ConservativeResult = ConservativeResult.intersectWith(
5851 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5852 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
5853 RangeType);
5854 }
5855
5856 // A range of Phi is a subset of union of all ranges of its input.
5857 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5858 // Make sure that we do not run over cycled Phis.
5859 if (PendingPhiRanges.insert(Phi).second) {
5860 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5861 for (auto &Op : Phi->operands()) {
5862 auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5863 RangeFromOps = RangeFromOps.unionWith(OpRange);
5864 // No point to continue if we already have a full set.
5865 if (RangeFromOps.isFullSet())
5866 break;
5867 }
5868 ConservativeResult =
5869 ConservativeResult.intersectWith(RangeFromOps, RangeType);
5870 bool Erased = PendingPhiRanges.erase(Phi);
5871 assert(Erased && "Failed to erase Phi properly?")((Erased && "Failed to erase Phi properly?") ? static_cast
<void> (0) : __assert_fail ("Erased && \"Failed to erase Phi properly?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5871, __PRETTY_FUNCTION__))
;
5872 (void) Erased;
5873 }
5874 }
5875
5876 return setRange(U, SignHint, std::move(ConservativeResult));
5877 }
5878
5879 return setRange(S, SignHint, std::move(ConservativeResult));
5880}
5881
5882// Given a StartRange, Step and MaxBECount for an expression compute a range of
5883// values that the expression can take. Initially, the expression has a value
5884// from StartRange and then is changed by Step up to MaxBECount times. Signed
5885// argument defines if we treat Step as signed or unsigned.
5886static ConstantRange getRangeForAffineARHelper(APInt Step,
5887 const ConstantRange &StartRange,
5888 const APInt &MaxBECount,
5889 unsigned BitWidth, bool Signed) {
5890 // If either Step or MaxBECount is 0, then the expression won't change, and we
5891 // just need to return the initial range.
5892 if (Step == 0 || MaxBECount == 0)
5893 return StartRange;
5894
5895 // If we don't know anything about the initial value (i.e. StartRange is
5896 // FullRange), then we don't know anything about the final range either.
5897 // Return FullRange.
5898 if (StartRange.isFullSet())
5899 return ConstantRange::getFull(BitWidth);
5900
5901 // If Step is signed and negative, then we use its absolute value, but we also
5902 // note that we're moving in the opposite direction.
5903 bool Descending = Signed && Step.isNegative();
5904
5905 if (Signed)
5906 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5907 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5908 // This equations hold true due to the well-defined wrap-around behavior of
5909 // APInt.
5910 Step = Step.abs();
5911
5912 // Check if Offset is more than full span of BitWidth. If it is, the
5913 // expression is guaranteed to overflow.
5914 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5915 return ConstantRange::getFull(BitWidth);
5916
5917 // Offset is by how much the expression can change. Checks above guarantee no
5918 // overflow here.
5919 APInt Offset = Step * MaxBECount;
5920
5921 // Minimum value of the final range will match the minimal value of StartRange
5922 // if the expression is increasing and will be decreased by Offset otherwise.
5923 // Maximum value of the final range will match the maximal value of StartRange
5924 // if the expression is decreasing and will be increased by Offset otherwise.
5925 APInt StartLower = StartRange.getLower();
5926 APInt StartUpper = StartRange.getUpper() - 1;
5927 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5928 : (StartUpper + std::move(Offset));
5929
5930 // It's possible that the new minimum/maximum value will fall into the initial
5931 // range (due to wrap around). This means that the expression can take any
5932 // value in this bitwidth, and we have to return full range.
5933 if (StartRange.contains(MovedBoundary))
5934 return ConstantRange::getFull(BitWidth);
5935
5936 APInt NewLower =
5937 Descending ? std::move(MovedBoundary) : std::move(StartLower);
5938 APInt NewUpper =
5939 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5940 NewUpper += 1;
5941
5942 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5943 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
5944}
5945
5946ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5947 const SCEV *Step,
5948 const SCEV *MaxBECount,
5949 unsigned BitWidth) {
5950 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&((!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits
(MaxBECount->getType()) <= BitWidth && "Precondition!"
) ? static_cast<void> (0) : __assert_fail ("!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && \"Precondition!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5952, __PRETTY_FUNCTION__))
5951 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&((!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits
(MaxBECount->getType()) <= BitWidth && "Precondition!"
) ? static_cast<void> (0) : __assert_fail ("!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && \"Precondition!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5952, __PRETTY_FUNCTION__))
5952 "Precondition!")((!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits
(MaxBECount->getType()) <= BitWidth && "Precondition!"
) ? static_cast<void> (0) : __assert_fail ("!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && \"Precondition!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5952, __PRETTY_FUNCTION__))
;
5953
5954 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5955 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5956
5957 // First, consider step signed.
5958 ConstantRange StartSRange = getSignedRange(Start);
5959 ConstantRange StepSRange = getSignedRange(Step);
5960
5961 // If Step can be both positive and negative, we need to find ranges for the
5962 // maximum absolute step values in both directions and union them.
5963 ConstantRange SR =
5964 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5965 MaxBECountValue, BitWidth, /* Signed = */ true);
5966 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5967 StartSRange, MaxBECountValue,
5968 BitWidth, /* Signed = */ true));
5969
5970 // Next, consider step unsigned.
5971 ConstantRange UR = getRangeForAffineARHelper(
5972 getUnsignedRangeMax(Step), getUnsignedRange(Start),
5973 MaxBECountValue, BitWidth, /* Signed = */ false);
5974
5975 // Finally, intersect signed and unsigned ranges.
5976 return SR.intersectWith(UR, ConstantRange::Smallest);
5977}
5978
5979ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
5980 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
5981 ScalarEvolution::RangeSignHint SignHint) {
5982 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n")((AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"
) ? static_cast<void> (0) : __assert_fail ("AddRec->isAffine() && \"Non-affine AddRecs are not suppored!\\n\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5982, __PRETTY_FUNCTION__))
;
5983 assert(AddRec->hasNoSelfWrap() &&((AddRec->hasNoSelfWrap() && "This only works for non-self-wrapping AddRecs!"
) ? static_cast<void> (0) : __assert_fail ("AddRec->hasNoSelfWrap() && \"This only works for non-self-wrapping AddRecs!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5984, __PRETTY_FUNCTION__))
5984 "This only works for non-self-wrapping AddRecs!")((AddRec->hasNoSelfWrap() && "This only works for non-self-wrapping AddRecs!"
) ? static_cast<void> (0) : __assert_fail ("AddRec->hasNoSelfWrap() && \"This only works for non-self-wrapping AddRecs!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 5984, __PRETTY_FUNCTION__))
;
5985 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
5986 const SCEV *Step = AddRec->getStepRecurrence(*this);
5987 // Only deal with constant step to save compile time.
5988 if (!isa<SCEVConstant>(Step))
5989 return ConstantRange::getFull(BitWidth);
5990 // Let's make sure that we can prove that we do not self-wrap during
5991 // MaxBECount iterations. We need this because MaxBECount is a maximum
5992 // iteration count estimate, and we might infer nw from some exit for which we
5993 // do not know max exit count (or any other side reasoning).
5994 // TODO: Turn into assert at some point.
5995 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
5996 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
5997 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
5998 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
5999 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
6000 MaxItersWithoutWrap))
6001 return ConstantRange::getFull(BitWidth);
6002
6003 ICmpInst::Predicate LEPred =
6004 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
6005 ICmpInst::Predicate GEPred =
6006 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
6007 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
6008
6009 // We know that there is no self-wrap. Let's take Start and End values and
6010 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
6011 // the iteration. They either lie inside the range [Min(Start, End),
6012 // Max(Start, End)] or outside it:
6013 //
6014 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
6015 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
6016 //
6017 // No self wrap flag guarantees that the intermediate values cannot be BOTH
6018 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
6019 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
6020 // Start <= End and step is positive, or Start >= End and step is negative.
6021 const SCEV *Start = AddRec->getStart();
6022 ConstantRange StartRange = getRangeRef(Start, SignHint);
6023 ConstantRange EndRange = getRangeRef(End, SignHint);
6024 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
6025 // If they already cover full iteration space, we will know nothing useful
6026 // even if we prove what we want to prove.
6027 if (RangeBetween.isFullSet())
6028 return RangeBetween;
6029 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
6030 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
6031 : RangeBetween.isWrappedSet();
6032 if (IsWrappedSet)
6033 return ConstantRange::getFull(BitWidth);
6034
6035 if (isKnownPositive(Step) &&
6036 isKnownPredicateViaConstantRanges(LEPred, Start, End))
6037 return RangeBetween;
6038 else if (isKnownNegative(Step) &&
6039 isKnownPredicateViaConstantRanges(GEPred, Start, End))
6040 return RangeBetween;
6041 return ConstantRange::getFull(BitWidth);
6042}
6043
6044ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
6045 const SCEV *Step,
6046 const SCEV *MaxBECount,
6047 unsigned BitWidth) {
6048 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
6049 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
6050
6051 struct SelectPattern {
6052 Value *Condition = nullptr;
6053 APInt TrueValue;
6054 APInt FalseValue;
6055
6056 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
6057 const SCEV *S) {
6058 Optional<unsigned> CastOp;
6059 APInt Offset(BitWidth, 0);
6060
6061 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&((SE.getTypeSizeInBits(S->getType()) == BitWidth &&
"Should be!") ? static_cast<void> (0) : __assert_fail (
"SE.getTypeSizeInBits(S->getType()) == BitWidth && \"Should be!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 6062, __PRETTY_FUNCTION__))
6062 "Should be!")((SE.getTypeSizeInBits(S->getType()) == BitWidth &&
"Should be!") ? static_cast<void> (0) : __assert_fail (
"SE.getTypeSizeInBits(S->getType()) == BitWidth && \"Should be!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 6062, __PRETTY_FUNCTION__))
;
6063
6064 // Peel off a constant offset:
6065 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
6066 // In the future we could consider being smarter here and handle
6067 // {Start+Step,+,Step} too.
6068 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
6069 return;
6070
6071 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
6072 S = SA->getOperand(1);
6073 }
6074
6075 // Peel off a cast operation
6076 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
6077 CastOp = SCast->getSCEVType();
6078 S = SCast->getOperand();
6079 }
6080
6081 using namespace llvm::PatternMatch;
6082
6083 auto *SU = dyn_cast<SCEVUnknown>(S);
6084 const APInt *TrueVal, *FalseVal;
6085 if (!SU ||
6086 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
6087 m_APInt(FalseVal)))) {
6088 Condition = nullptr;
6089 return;
6090 }
6091
6092 TrueValue = *TrueVal;
6093 FalseValue = *FalseVal;
6094
6095 // Re-apply the cast we peeled off earlier
6096 if (CastOp.hasValue())
6097 switch (*CastOp) {
6098 default:
6099 llvm_unreachable("Unknown SCEV cast type!")::llvm::llvm_unreachable_internal("Unknown SCEV cast type!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 6099)
;
6100
6101 case scTruncate:
6102 TrueValue = TrueValue.trunc(BitWidth);
6103 FalseValue = FalseValue.trunc(BitWidth);
6104 break;
6105 case scZeroExtend:
6106 TrueValue = TrueValue.zext(BitWidth);
6107 FalseValue = FalseValue.zext(BitWidth);
6108 break;
6109 case scSignExtend:
6110 TrueValue = TrueValue.sext(BitWidth);
6111 FalseValue = FalseValue.sext(BitWidth);
6112 break;
6113 }
6114
6115 // Re-apply the constant offset we peeled off earlier
6116 TrueValue += Offset;
6117 FalseValue += Offset;
6118 }
6119
6120 bool isRecognized() { return Condition != nullptr; }
6121 };
6122
6123 SelectPattern StartPattern(*this, BitWidth, Start);
6124 if (!StartPattern.isRecognized())
6125 return ConstantRange::getFull(BitWidth);
6126
6127 SelectPattern StepPattern(*this, BitWidth, Step);
6128 if (!StepPattern.isRecognized())
6129 return ConstantRange::getFull(BitWidth);
6130
6131 if (StartPattern.Condition != StepPattern.Condition) {
6132 // We don't handle this case today; but we could, by considering four
6133 // possibilities below instead of two. I'm not sure if there are cases where
6134 // that will help over what getRange already does, though.
6135 return ConstantRange::getFull(BitWidth);
6136 }
6137
6138 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
6139 // construct arbitrary general SCEV expressions here. This function is called
6140 // from deep in the call stack, and calling getSCEV (on a sext instruction,
6141 // say) can end up caching a suboptimal value.
6142
6143 // FIXME: without the explicit `this` receiver below, MSVC errors out with
6144 // C2352 and C2512 (otherwise it isn't needed).
6145
6146 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
6147 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
6148 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
6149 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
6150
6151 ConstantRange TrueRange =
6152 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
6153 ConstantRange FalseRange =
6154 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
6155
6156 return TrueRange.unionWith(FalseRange);
6157}
6158
6159SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
6160 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
6161 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
6162
6163 // Return early if there are no flags to propagate to the SCEV.
6164 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6165 if (BinOp->hasNoUnsignedWrap())
6166 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
6167 if (BinOp->hasNoSignedWrap())
6168 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
6169 if (Flags == SCEV::FlagAnyWrap)
6170 return SCEV::FlagAnyWrap;
6171
6172 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
6173}
6174
6175bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
6176 // Here we check that I is in the header of the innermost loop containing I,
6177 // since we only deal with instructions in the loop header. The actual loop we
6178 // need to check later will come from an add recurrence, but getting that
6179 // requires computing the SCEV of the operands, which can be expensive. This
6180 // check we can do cheaply to rule out some cases early.
6181 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
6182 if (InnermostContainingLoop == nullptr ||
6183 InnermostContainingLoop->getHeader() != I->getParent())
6184 return false;
6185
6186 // Only proceed if we can prove that I does not yield poison.
6187 if (!programUndefinedIfPoison(I))
6188 return false;
6189
6190 // At this point we know that if I is executed, then it does not wrap
6191 // according to at least one of NSW or NUW. If I is not executed, then we do
6192 // not know if the calculation that I represents would wrap. Multiple
6193 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6194 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6195 // derived from other instructions that map to the same SCEV. We cannot make
6196 // that guarantee for cases where I is not executed. So we need to find the
6197 // loop that I is considered in relation to and prove that I is executed for
6198 // every iteration of that loop. That implies that the value that I
6199 // calculates does not wrap anywhere in the loop, so then we can apply the
6200 // flags to the SCEV.
6201 //
6202 // We check isLoopInvariant to disambiguate in case we are adding recurrences
6203 // from different loops, so that we know which loop to prove that I is
6204 // executed in.
6205 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
6206 // I could be an extractvalue from a call to an overflow intrinsic.
6207 // TODO: We can do better here in some cases.
6208 if (!isSCEVable(I->getOperand(OpIndex)->getType()))
6209 return false;
6210 const SCEV *Op = getSCEV(I->getOperand(OpIndex));
6211 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6212 bool AllOtherOpsLoopInvariant = true;
6213 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
6214 ++OtherOpIndex) {
6215 if (OtherOpIndex != OpIndex) {
6216 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
6217 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6218 AllOtherOpsLoopInvariant = false;
6219 break;
6220 }
6221 }
6222 }
6223 if (AllOtherOpsLoopInvariant &&
6224 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6225 return true;
6226 }
6227 }
6228 return false;
6229}
6230
6231bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6232 // If we know that \c I can never be poison period, then that's enough.
6233 if (isSCEVExprNeverPoison(I))
6234 return true;
6235
6236 // For an add recurrence specifically, we assume that infinite loops without
6237 // side effects are undefined behavior, and then reason as follows:
6238 //
6239 // If the add recurrence is poison in any iteration, it is poison on all
6240 // future iterations (since incrementing poison yields poison). If the result
6241 // of the add recurrence is fed into the loop latch condition and the loop
6242 // does not contain any throws or exiting blocks other than the latch, we now
6243 // have the ability to "choose" whether the backedge is taken or not (by
6244 // choosing a sufficiently evil value for the poison feeding into the branch)
6245 // for every iteration including and after the one in which \p I first became
6246 // poison. There are two possibilities (let's call the iteration in which \p
6247 // I first became poison as K):
6248 //
6249 // 1. In the set of iterations including and after K, the loop body executes
6250 // no side effects. In this case executing the backege an infinte number
6251 // of times will yield undefined behavior.
6252 //
6253 // 2. In the set of iterations including and after K, the loop body executes
6254 // at least one side effect. In this case, that specific instance of side
6255 // effect is control dependent on poison, which also yields undefined
6256 // behavior.
6257
6258 auto *ExitingBB = L->getExitingBlock();
6259 auto *LatchBB = L->getLoopLatch();
6260 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6261 return false;
6262
6263 SmallPtrSet<const Instruction *, 16> Pushed;
6264 SmallVector<const Instruction *, 8> PoisonStack;
6265
6266 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
6267 // things that are known to be poison under that assumption go on the
6268 // PoisonStack.
6269 Pushed.insert(I);
6270 PoisonStack.push_back(I);
6271
6272 bool LatchControlDependentOnPoison = false;
6273 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6274 const Instruction *Poison = PoisonStack.pop_back_val();
6275
6276 for (auto *PoisonUser : Poison->users()) {
6277 if (propagatesPoison(cast<Operator>(PoisonUser))) {
6278 if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6279 PoisonStack.push_back(cast<Instruction>(PoisonUser));
6280 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6281 assert(BI->isConditional() && "Only possibility!")((BI->isConditional() && "Only possibility!") ? static_cast
<void> (0) : __assert_fail ("BI->isConditional() && \"Only possibility!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 6281, __PRETTY_FUNCTION__))
;
6282 if (BI->getParent() == LatchBB) {
6283 LatchControlDependentOnPoison = true;
6284 break;
6285 }
6286 }
6287 }
6288 }
6289
6290 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6291}
6292
6293ScalarEvolution::LoopProperties
6294ScalarEvolution::getLoopProperties(const Loop *L) {
6295 using LoopProperties = ScalarEvolution::LoopProperties;
6296
6297 auto Itr = LoopPropertiesCache.find(L);
6298 if (Itr == LoopPropertiesCache.end()) {
6299 auto HasSideEffects = [](Instruction *I) {
6300 if (auto *SI = dyn_cast<StoreInst>(I))
6301 return !SI->isSimple();
6302
6303 return I->mayHaveSideEffects();
6304 };
6305
6306 LoopProperties LP = {/* HasNoAbnormalExits */ true,
6307 /*HasNoSideEffects*/ true};
6308
6309 for (auto *BB : L->getBlocks())
6310 for (auto &I : *BB) {
6311 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6312 LP.HasNoAbnormalExits = false;
6313 if (HasSideEffects(&I))
6314 LP.HasNoSideEffects = false;
6315 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6316 break; // We're already as pessimistic as we can get.
6317 }
6318
6319 auto InsertPair = LoopPropertiesCache.insert({L, LP});
6320 assert(InsertPair.second && "We just checked!")((InsertPair.second && "We just checked!") ? static_cast
<void> (0) : __assert_fail ("InsertPair.second && \"We just checked!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 6320, __PRETTY_FUNCTION__))
;
6321 Itr = InsertPair.first;
6322 }
6323
6324 return Itr->second;
6325}
6326
6327const SCEV *ScalarEvolution::createSCEV(Value *V) {
6328 if (!isSCEVable(V->getType()))
6329 return getUnknown(V);
6330
6331 if (Instruction *I = dyn_cast<Instruction>(V)) {
6332 // Don't attempt to analyze instructions in blocks that aren't
6333 // reachable. Such instructions don't matter, and they aren't required
6334 // to obey basic rules for definitions dominating uses which this
6335 // analysis depends on.
6336 if (!DT.isReachableFromEntry(I->getParent()))
6337 return getUnknown(UndefValue::get(V->getType()));
6338 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6339 return getConstant(CI);
6340 else if (isa<ConstantPointerNull>(V))
6341 // FIXME: we shouldn't special-case null pointer constant.
6342 return getZero(V->getType());
6343 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6344 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6345 else if (!isa<ConstantExpr>(V))
6346 return getUnknown(V);
6347
6348 Operator *U = cast<Operator>(V);
6349 if (auto BO = MatchBinaryOp(U, DT)) {
6350 switch (BO->Opcode) {
6351 case Instruction::Add: {
6352 // The simple thing to do would be to just call getSCEV on both operands
6353 // and call getAddExpr with the result. However if we're looking at a
6354 // bunch of things all added together, this can be quite inefficient,
6355 // because it leads to N-1 getAddExpr calls for N ultimate operands.
6356 // Instead, gather up all the operands and make a single getAddExpr call.
6357 // LLVM IR canonical form means we need only traverse the left operands.
6358 SmallVector<const SCEV *, 4> AddOps;
6359 do {
6360 if (BO->Op) {
6361 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6362 AddOps.push_back(OpSCEV);
6363 break;
6364 }
6365
6366 // If a NUW or NSW flag can be applied to the SCEV for this
6367 // addition, then compute the SCEV for this addition by itself
6368 // with a separate call to getAddExpr. We need to do that
6369 // instead of pushing the operands of the addition onto AddOps,
6370 // since the flags are only known to apply to this particular
6371 // addition - they may not apply to other additions that can be
6372 // formed with operands from AddOps.
6373 const SCEV *RHS = getSCEV(BO->RHS);
6374 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6375 if (Flags != SCEV::FlagAnyWrap) {
6376 const SCEV *LHS = getSCEV(BO->LHS);
6377 if (BO->Opcode == Instruction::Sub)
6378 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6379 else
6380 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6381 break;
6382 }
6383 }
6384
6385 if (BO->Opcode == Instruction::Sub)
6386 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6387 else
6388 AddOps.push_back(getSCEV(BO->RHS));
6389
6390 auto NewBO = MatchBinaryOp(BO->LHS, DT);
6391 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6392 NewBO->Opcode != Instruction::Sub)) {
6393 AddOps.push_back(getSCEV(BO->LHS));
6394 break;
6395 }
6396 BO = NewBO;
6397 } while (true);
6398
6399 return getAddExpr(AddOps);
6400 }
6401
6402 case Instruction::Mul: {
6403 SmallVector<const SCEV *, 4> MulOps;
6404 do {
6405 if (BO->Op) {
6406 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6407 MulOps.push_back(OpSCEV);
6408 break;
6409 }
6410
6411 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6412 if (Flags != SCEV::FlagAnyWrap) {
6413 MulOps.push_back(
6414 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6415 break;
6416 }
6417 }
6418
6419 MulOps.push_back(getSCEV(BO->RHS));
6420 auto NewBO = MatchBinaryOp(BO->LHS, DT);
6421 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6422 MulOps.push_back(getSCEV(BO->LHS));
6423 break;
6424 }
6425 BO = NewBO;
6426 } while (true);
6427
6428 return getMulExpr(MulOps);
6429 }
6430 case Instruction::UDiv:
6431 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6432 case Instruction::URem:
6433 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6434 case Instruction::Sub: {
6435 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6436 if (BO->Op)
6437 Flags = getNoWrapFlagsFromUB(BO->Op);
6438 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6439 }
6440 case Instruction::And:
6441 // For an expression like x&255 that merely masks off the high bits,
6442 // use zext(trunc(x)) as the SCEV expression.
6443 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6444 if (CI->isZero())
6445 return getSCEV(BO->RHS);
6446 if (CI->isMinusOne())
6447 return getSCEV(BO->LHS);
6448 const APInt &A = CI->getValue();
6449
6450 // Instcombine's ShrinkDemandedConstant may strip bits out of
6451 // constants, obscuring what would otherwise be a low-bits mask.
6452 // Use computeKnownBits to compute what ShrinkDemandedConstant
6453 // knew about to reconstruct a low-bits mask value.
6454 unsigned LZ = A.countLeadingZeros();
6455 unsigned TZ = A.countTrailingZeros();
6456 unsigned BitWidth = A.getBitWidth();
6457 KnownBits Known(BitWidth);
6458 computeKnownBits(BO->LHS, Known, getDataLayout(),
6459 0, &AC, nullptr, &DT);
6460
6461 APInt EffectiveMask =
6462 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6463 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6464 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6465 const SCEV *LHS = getSCEV(BO->LHS);
6466 const SCEV *ShiftedLHS = nullptr;
6467 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6468 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6469 // For an expression like (x * 8) & 8, simplify the multiply.
6470 unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6471 unsigned GCD = std::min(MulZeros, TZ);
6472 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6473 SmallVector<const SCEV*, 4> MulOps;
6474 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6475 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6476 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6477 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6478 }
6479 }
6480 if (!ShiftedLHS)
6481 ShiftedLHS = getUDivExpr(LHS, MulCount);
6482 return getMulExpr(
6483 getZeroExtendExpr(
6484 getTruncateExpr(ShiftedLHS,
6485 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6486 BO->LHS->getType()),
6487 MulCount);
6488 }
6489 }
6490 break;
6491
6492 case Instruction::Or:
6493 // If the RHS of the Or is a constant, we may have something like:
6494 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
6495 // optimizations will transparently handle this case.
6496 //
6497 // In order for this transformation to be safe, the LHS must be of the
6498 // form X*(2^n) and the Or constant must be less than 2^n.
6499 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6500 const SCEV *LHS = getSCEV(BO->LHS);
6501 const APInt &CIVal = CI->getValue();
6502 if (GetMinTrailingZeros(LHS) >=
6503 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6504 // Build a plain add SCEV.
6505 return getAddExpr(LHS, getSCEV(CI),
6506 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW));
6507 }
6508 }
6509 break;
6510
6511 case Instruction::Xor:
6512 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6513 // If the RHS of xor is -1, then this is a not operation.
6514 if (CI->isMinusOne())
6515 return getNotSCEV(getSCEV(BO->LHS));
6516
6517 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6518 // This is a variant of the check for xor with -1, and it handles
6519 // the case where instcombine has trimmed non-demanded bits out
6520 // of an xor with -1.
6521 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6522 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6523 if (LBO->getOpcode() == Instruction::And &&
6524 LCI->getValue() == CI->getValue())
6525 if (const SCEVZeroExtendExpr *Z =
6526 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6527 Type *UTy = BO->LHS->getType();
6528 const SCEV *Z0 = Z->getOperand();
6529 Type *Z0Ty = Z0->getType();
6530 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6531
6532 // If C is a low-bits mask, the zero extend is serving to
6533 // mask off the high bits. Complement the operand and
6534 // re-apply the zext.
6535 if (CI->getValue().isMask(Z0TySize))
6536 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6537
6538 // If C is a single bit, it may be in the sign-bit position
6539 // before the zero-extend. In this case, represent the xor
6540 // using an add, which is equivalent, and re-apply the zext.
6541 APInt Trunc = CI->getValue().trunc(Z0TySize);
6542 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6543 Trunc.isSignMask())
6544 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6545 UTy);
6546 }
6547 }
6548 break;
6549
6550 case Instruction::Shl:
6551 // Turn shift left of a constant amount into a multiply.
6552 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6553 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6554
6555 // If the shift count is not less than the bitwidth, the result of
6556 // the shift is undefined. Don't try to analyze it, because the
6557 // resolution chosen here may differ from the resolution chosen in
6558 // other parts of the compiler.
6559 if (SA->getValue().uge(BitWidth))
6560 break;
6561
6562 // We can safely preserve the nuw flag in all cases. It's also safe to
6563 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
6564 // requires special handling. It can be preserved as long as we're not
6565 // left shifting by bitwidth - 1.
6566 auto Flags = SCEV::FlagAnyWrap;
6567 if (BO->Op) {
6568 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
6569 if ((MulFlags & SCEV::FlagNSW) &&
6570 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
6571 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
6572 if (MulFlags & SCEV::FlagNUW)
6573 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
6574 }
6575
6576 Constant *X = ConstantInt::get(
6577 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6578 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6579 }
6580 break;
6581
6582 case Instruction::AShr: {
6583 // AShr X, C, where C is a constant.
6584 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6585 if (!CI)
6586 break;
6587
6588 Type *OuterTy = BO->LHS->getType();
6589 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6590 // If the shift count is not less than the bitwidth, the result of
6591 // the shift is undefined. Don't try to analyze it, because the
6592 // resolution chosen here may differ from the resolution chosen in
6593 // other parts of the compiler.
6594 if (CI->getValue().uge(BitWidth))
6595 break;
6596
6597 if (CI->isZero())
6598 return getSCEV(BO->LHS); // shift by zero --> noop
6599
6600 uint64_t AShrAmt = CI->getZExtValue();
6601 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6602
6603 Operator *L = dyn_cast<Operator>(BO->LHS);
6604 if (L && L->getOpcode() == Instruction::Shl) {
6605 // X = Shl A, n
6606 // Y = AShr X, m
6607 // Both n and m are constant.
6608
6609 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6610 if (L->getOperand(1) == BO->RHS)
6611 // For a two-shift sext-inreg, i.e. n = m,
6612 // use sext(trunc(x)) as the SCEV expression.
6613 return getSignExtendExpr(
6614 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6615
6616 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6617 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6618 uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6619 if (ShlAmt > AShrAmt) {
6620 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6621 // expression. We already checked that ShlAmt < BitWidth, so
6622 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6623 // ShlAmt - AShrAmt < Amt.
6624 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6625 ShlAmt - AShrAmt);
6626 return getSignExtendExpr(
6627 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6628 getConstant(Mul)), OuterTy);
6629 }
6630 }
6631 }
6632 if (BO->IsExact) {
6633 // Given exact arithmetic in-bounds right-shift by a constant,
6634 // we can lower it into: (abs(x) EXACT/u (1<<C)) * signum(x)
6635 const SCEV *X = getSCEV(BO->LHS);
6636 const SCEV *AbsX = getAbsExpr(X, /*IsNSW=*/false);
6637 APInt Mult = APInt::getOneBitSet(BitWidth, AShrAmt);
6638 const SCEV *Div = getUDivExactExpr(AbsX, getConstant(Mult));
6639 return getMulExpr(Div, getSignumExpr(X), SCEV::FlagNSW);
6640 }
6641 break;
6642 }
6643 }
6644 }
6645
6646 switch (U->getOpcode()) {
6647 case Instruction::Trunc:
6648 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6649
6650 case Instruction::ZExt:
6651 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6652
6653 case Instruction::SExt:
6654 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6655 // The NSW flag of a subtract does not always survive the conversion to
6656 // A + (-1)*B. By pushing sign extension onto its operands we are much
6657 // more likely to preserve NSW and allow later AddRec optimisations.
6658 //
6659 // NOTE: This is effectively duplicating this logic from getSignExtend:
6660 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6661 // but by that point the NSW information has potentially been lost.
6662 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6663 Type *Ty = U->getType();
6664 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6665 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6666 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6667 }
6668 }
6669 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6670
6671 case Instruction::BitCast:
6672 // BitCasts are no-op casts so we just eliminate the cast.
6673 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6674 return getSCEV(U->getOperand(0));
6675 break;
6676
6677 case Instruction::PtrToInt: {
6678 // Pointer to integer cast is straight-forward, so do model it.
6679 Value *Ptr = U->getOperand(0);
6680 const SCEV *Op = getSCEV(Ptr);
6681 Type *DstIntTy = U->getType();
6682 // SCEV doesn't have constant pointer expression type, but it supports
6683 // nullptr constant (and only that one), which is modelled in SCEV as a
6684 // zero integer constant. So just skip the ptrtoint cast for constants.
6685 if (isa<SCEVConstant>(Op))
6686 return getTruncateOrZeroExtend(Op, DstIntTy);
6687 Type *PtrTy = Ptr->getType();
6688 Type *IntPtrTy = getDataLayout().getIntPtrType(PtrTy);
6689 // But only if effective SCEV (integer) type is wide enough to represent
6690 // all possible pointer values.
6691 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(PtrTy)) !=
6692 getDataLayout().getTypeSizeInBits(IntPtrTy))
6693 return getUnknown(V);
6694 return getPtrToIntExpr(Op, DstIntTy);
6695 }
6696 case Instruction::IntToPtr:
6697 // Just don't deal with inttoptr casts.
6698 return getUnknown(V);
6699
6700 case Instruction::SDiv:
6701 // If both operands are non-negative, this is just an udiv.
6702 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
6703 isKnownNonNegative(getSCEV(U->getOperand(1))))
6704 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
6705 break;
6706
6707 case Instruction::SRem:
6708 // If both operands are non-negative, this is just an urem.
6709 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
6710 isKnownNonNegative(getSCEV(U->getOperand(1))))
6711 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
6712 break;
6713
6714 case Instruction::GetElementPtr:
6715 return createNodeForGEP(cast<GEPOperator>(U));
6716
6717 case Instruction::PHI:
6718 return createNodeForPHI(cast<PHINode>(U));
6719
6720 case Instruction::Select:
6721 // U can also be a select constant expr, which let fall through. Since
6722 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6723 // constant expressions cannot have instructions as operands, we'd have
6724 // returned getUnknown for a select constant expressions anyway.
6725 if (isa<Instruction>(U))
6726 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6727 U->getOperand(1), U->getOperand(2));
6728 break;
6729
6730 case Instruction::Call:
6731 case Instruction::Invoke:
6732 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
6733 return getSCEV(RV);
6734
6735 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
6736 switch (II->getIntrinsicID()) {
6737 case Intrinsic::abs:
6738 return getAbsExpr(
6739 getSCEV(II->getArgOperand(0)),
6740 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
6741 case Intrinsic::umax:
6742 return getUMaxExpr(getSCEV(II->getArgOperand(0)),
6743 getSCEV(II->getArgOperand(1)));
6744 case Intrinsic::umin:
6745 return getUMinExpr(getSCEV(II->getArgOperand(0)),
6746 getSCEV(II->getArgOperand(1)));
6747 case Intrinsic::smax:
6748 return getSMaxExpr(getSCEV(II->getArgOperand(0)),
6749 getSCEV(II->getArgOperand(1)));
6750 case Intrinsic::smin:
6751 return getSMinExpr(getSCEV(II->getArgOperand(0)),
6752 getSCEV(II->getArgOperand(1)));
6753 case Intrinsic::usub_sat: {
6754 const SCEV *X = getSCEV(II->getArgOperand(0));
6755 const SCEV *Y = getSCEV(II->getArgOperand(1));
6756 const SCEV *ClampedY = getUMinExpr(X, Y);
6757 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
6758 }
6759 case Intrinsic::uadd_sat: {
6760 const SCEV *X = getSCEV(II->getArgOperand(0));
6761 const SCEV *Y = getSCEV(II->getArgOperand(1));
6762 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
6763 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
6764 }
6765 case Intrinsic::start_loop_iterations:
6766 // A start_loop_iterations is just equivalent to the first operand for
6767 // SCEV purposes.
6768 return getSCEV(II->getArgOperand(0));
6769 default:
6770 break;
6771 }
6772 }
6773 break;
6774 }
6775
6776 return getUnknown(V);
6777}
6778
6779//===----------------------------------------------------------------------===//
6780// Iteration Count Computation Code
6781//
6782
6783static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6784 if (!ExitCount)
6785 return 0;
6786
6787 ConstantInt *ExitConst = ExitCount->getValue();
6788
6789 // Guard against huge trip counts.
6790 if (ExitConst->getValue().getActiveBits() > 32)
6791 return 0;
6792
6793 // In case of integer overflow, this returns 0, which is correct.
6794 return ((unsigned)ExitConst->getZExtValue()) + 1;
6795}
6796
6797unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6798 if (BasicBlock *ExitingBB = L->getExitingBlock())
6799 return getSmallConstantTripCount(L, ExitingBB);
6800
6801 // No trip count information for multiple exits.
6802 return 0;
6803}
6804
6805unsigned
6806ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6807 const BasicBlock *ExitingBlock) {
6808 assert(ExitingBlock && "Must pass a non-null exiting block!")((ExitingBlock && "Must pass a non-null exiting block!"
) ? static_cast<void> (0) : __assert_fail ("ExitingBlock && \"Must pass a non-null exiting block!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 6808, __PRETTY_FUNCTION__))
;
6809 assert(L->isLoopExiting(ExitingBlock) &&((L->isLoopExiting(ExitingBlock) && "Exiting block must actually branch out of the loop!"
) ? static_cast<void> (0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 6810, __PRETTY_FUNCTION__))
6810 "Exiting block must actually branch out of the loop!")((L->isLoopExiting(ExitingBlock) && "Exiting block must actually branch out of the loop!"
) ? static_cast<void> (0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 6810, __PRETTY_FUNCTION__))
;
6811 const SCEVConstant *ExitCount =
6812 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6813 return getConstantTripCount(ExitCount);
6814}
6815
6816unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6817 const auto *MaxExitCount =
6818 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
6819 return getConstantTripCount(MaxExitCount);
6820}
6821
6822unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6823 if (BasicBlock *ExitingBB = L->getExitingBlock())
6824 return getSmallConstantTripMultiple(L, ExitingBB);
6825
6826 // No trip multiple information for multiple exits.
6827 return 0;
6828}
6829
6830/// Returns the largest constant divisor of the trip count of this loop as a
6831/// normal unsigned value, if possible. This means that the actual trip count is
6832/// always a multiple of the returned value (don't forget the trip count could
6833/// very well be zero as well!).
6834///
6835/// Returns 1 if the trip count is unknown or not guaranteed to be the
6836/// multiple of a constant (which is also the case if the trip count is simply
6837/// constant, use getSmallConstantTripCount for that case), Will also return 1
6838/// if the trip count is very large (>= 2^32).
6839///
6840/// As explained in the comments for getSmallConstantTripCount, this assumes
6841/// that control exits the loop via ExitingBlock.
6842unsigned
6843ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6844 const BasicBlock *ExitingBlock) {
6845 assert(ExitingBlock && "Must pass a non-null exiting block!")((ExitingBlock && "Must pass a non-null exiting block!"
) ? static_cast<void> (0) : __assert_fail ("ExitingBlock && \"Must pass a non-null exiting block!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 6845, __PRETTY_FUNCTION__))
;
6846 assert(L->isLoopExiting(ExitingBlock) &&((L->isLoopExiting(ExitingBlock) && "Exiting block must actually branch out of the loop!"
) ? static_cast<void> (0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 6847, __PRETTY_FUNCTION__))
6847 "Exiting block must actually branch out of the loop!")((L->isLoopExiting(ExitingBlock) && "Exiting block must actually branch out of the loop!"
) ? static_cast<void> (0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 6847, __PRETTY_FUNCTION__))
;
6848 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6849 if (ExitCount == getCouldNotCompute())
6850 return 1;
6851
6852 // Get the trip count from the BE count by adding 1.
6853 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6854
6855 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6856 if (!TC)
6857 // Attempt to factor more general cases. Returns the greatest power of
6858 // two divisor. If overflow happens, the trip count expression is still
6859 // divisible by the greatest power of 2 divisor returned.
6860 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6861
6862 ConstantInt *Result = TC->getValue();
6863
6864 // Guard against huge trip counts (this requires checking
6865 // for zero to handle the case where the trip count == -1 and the
6866 // addition wraps).
6867 if (!Result || Result->getValue().getActiveBits() > 32 ||
6868 Result->getValue().getActiveBits() == 0)
6869 return 1;
6870
6871 return (unsigned)Result->getZExtValue();
6872}
6873
6874const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6875 const BasicBlock *ExitingBlock,
6876 ExitCountKind Kind) {
6877 switch (Kind) {
6878 case Exact:
6879 case SymbolicMaximum:
6880 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6881 case ConstantMaximum:
6882 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
6883 };
6884 llvm_unreachable("Invalid ExitCountKind!")::llvm::llvm_unreachable_internal("Invalid ExitCountKind!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 6884)
;
6885}
6886
6887const SCEV *
6888ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6889 SCEVUnionPredicate &Preds) {
6890 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
6891}
6892
6893const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
6894 ExitCountKind Kind) {
6895 switch (Kind) {
6896 case Exact:
6897 return getBackedgeTakenInfo(L).getExact(L, this);
6898 case ConstantMaximum:
6899 return getBackedgeTakenInfo(L).getConstantMax(this);
6900 case SymbolicMaximum:
6901 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
6902 };
6903 llvm_unreachable("Invalid ExitCountKind!")::llvm::llvm_unreachable_internal("Invalid ExitCountKind!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 6903)
;
6904}
6905
6906bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6907 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
6908}
6909
6910/// Push PHI nodes in the header of the given loop onto the given Worklist.
6911static void
6912PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6913 BasicBlock *Header = L->getHeader();
6914
6915 // Push all Loop-header PHIs onto the Worklist stack.
6916 for (PHINode &PN : Header->phis())
6917 Worklist.push_back(&PN);
6918}
6919
6920const ScalarEvolution::BackedgeTakenInfo &
6921ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6922 auto &BTI = getBackedgeTakenInfo(L);
6923 if (BTI.hasFullInfo())
6924 return BTI;
6925
6926 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6927
6928 if (!Pair.second)
6929 return Pair.first->second;
6930
6931 BackedgeTakenInfo Result =
6932 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6933
6934 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6935}
6936
6937ScalarEvolution::BackedgeTakenInfo &
6938ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6939 // Initially insert an invalid entry for this loop. If the insertion
6940 // succeeds, proceed to actually compute a backedge-taken count and
6941 // update the value. The temporary CouldNotCompute value tells SCEV
6942 // code elsewhere that it shouldn't attempt to request a new
6943 // backedge-taken count, which could result in infinite recursion.
6944 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6945 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6946 if (!Pair.second)
6947 return Pair.first->second;
6948
6949 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6950 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6951 // must be cleared in this scope.
6952 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6953
6954 // In product build, there are no usage of statistic.
6955 (void)NumTripCountsComputed;
6956 (void)NumTripCountsNotComputed;
6957#if LLVM_ENABLE_STATS1 || !defined(NDEBUG)
6958 const SCEV *BEExact = Result.getExact(L, this);
6959 if (BEExact != getCouldNotCompute()) {
6960 assert(isLoopInvariant(BEExact, L) &&((isLoopInvariant(BEExact, L) && isLoopInvariant(Result
.getConstantMax(this), L) && "Computed backedge-taken count isn't loop invariant for loop!"
) ? static_cast<void> (0) : __assert_fail ("isLoopInvariant(BEExact, L) && isLoopInvariant(Result.getConstantMax(this), L) && \"Computed backedge-taken count isn't loop invariant for loop!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 6962, __PRETTY_FUNCTION__))
6961 isLoopInvariant(Result.getConstantMax(this), L) &&((isLoopInvariant(BEExact, L) && isLoopInvariant(Result
.getConstantMax(this), L) && "Computed backedge-taken count isn't loop invariant for loop!"
) ? static_cast<void> (0) : __assert_fail ("isLoopInvariant(BEExact, L) && isLoopInvariant(Result.getConstantMax(this), L) && \"Computed backedge-taken count isn't loop invariant for loop!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 6962, __PRETTY_FUNCTION__))
6962 "Computed backedge-taken count isn't loop invariant for loop!")((isLoopInvariant(BEExact, L) && isLoopInvariant(Result
.getConstantMax(this), L) && "Computed backedge-taken count isn't loop invariant for loop!"
) ? static_cast<void> (0) : __assert_fail ("isLoopInvariant(BEExact, L) && isLoopInvariant(Result.getConstantMax(this), L) && \"Computed backedge-taken count isn't loop invariant for loop!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 6962, __PRETTY_FUNCTION__))
;
6963 ++NumTripCountsComputed;
6964 } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
6965 isa<PHINode>(L->getHeader()->begin())) {
6966 // Only count loops that have phi nodes as not being computable.
6967 ++NumTripCountsNotComputed;
6968 }
6969#endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
6970
6971 // Now that we know more about the trip count for this loop, forget any
6972 // existing SCEV values for PHI nodes in this loop since they are only
6973 // conservative estimates made without the benefit of trip count
6974 // information. This is similar to the code in forgetLoop, except that
6975 // it handles SCEVUnknown PHI nodes specially.
6976 if (Result.hasAnyInfo()) {
6977 SmallVector<Instruction *, 16> Worklist;
6978 PushLoopPHIs(L, Worklist);
6979
6980 SmallPtrSet<Instruction *, 8> Discovered;
6981 while (!Worklist.empty()) {
6982 Instruction *I = Worklist.pop_back_val();
6983
6984 ValueExprMapType::iterator It =
6985 ValueExprMap.find_as(static_cast<Value *>(I));
6986 if (It != ValueExprMap.end()) {
6987 const SCEV *Old = It->second;
6988
6989 // SCEVUnknown for a PHI either means that it has an unrecognized
6990 // structure, or it's a PHI that's in the progress of being computed
6991 // by createNodeForPHI. In the former case, additional loop trip
6992 // count information isn't going to change anything. In the later
6993 // case, createNodeForPHI will perform the necessary updates on its
6994 // own when it gets to that point.
6995 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6996 eraseValueFromMap(It->first);
6997 forgetMemoizedResults(Old);
6998 }
6999 if (PHINode *PN = dyn_cast<PHINode>(I))
7000 ConstantEvolutionLoopExitValue.erase(PN);
7001 }
7002
7003 // Since we don't need to invalidate anything for correctness and we're
7004 // only invalidating to make SCEV's results more precise, we get to stop
7005 // early to avoid invalidating too much. This is especially important in
7006 // cases like:
7007 //
7008 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
7009 // loop0:
7010 // %pn0 = phi
7011 // ...
7012 // loop1:
7013 // %pn1 = phi
7014 // ...
7015 //
7016 // where both loop0 and loop1's backedge taken count uses the SCEV
7017 // expression for %v. If we don't have the early stop below then in cases
7018 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
7019 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
7020 // count for loop1, effectively nullifying SCEV's trip count cache.
7021 for (auto *U : I->users())
7022 if (auto *I = dyn_cast<Instruction>(U)) {
7023 auto *LoopForUser = LI.getLoopFor(I->getParent());
7024 if (LoopForUser && L->contains(LoopForUser) &&
7025 Discovered.insert(I).second)
7026 Worklist.push_back(I);
7027 }
7028 }
7029 }
7030
7031 // Re-lookup the insert position, since the call to
7032 // computeBackedgeTakenCount above could result in a
7033 // recusive call to getBackedgeTakenInfo (on a different
7034 // loop), which would invalidate the iterator computed
7035 // earlier.
7036 return BackedgeTakenCounts.find(L)->second = std::move(Result);
7037}
7038
7039void ScalarEvolution::forgetAllLoops() {
7040 // This method is intended to forget all info about loops. It should
7041 // invalidate caches as if the following happened:
7042 // - The trip counts of all loops have changed arbitrarily
7043 // - Every llvm::Value has been updated in place to produce a different
7044 // result.
7045 BackedgeTakenCounts.clear();
7046 PredicatedBackedgeTakenCounts.clear();
7047 LoopPropertiesCache.clear();
7048 ConstantEvolutionLoopExitValue.clear();
7049 ValueExprMap.clear();
7050 ValuesAtScopes.clear();
7051 LoopDispositions.clear();
7052 BlockDispositions.clear();
7053 UnsignedRanges.clear();
7054 SignedRanges.clear();
7055 ExprValueMap.clear();
7056 HasRecMap.clear();
7057 MinTrailingZerosCache.clear();
7058 PredicatedSCEVRewrites.clear();
7059}
7060
7061void ScalarEvolution::forgetLoop(const Loop *L) {
7062 // Drop any stored trip count value.
7063 auto RemoveLoopFromBackedgeMap =
7064 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
7065 auto BTCPos = Map.find(L);
7066 if (BTCPos != Map.end()) {
7067 BTCPos->second.clear();
7068 Map.erase(BTCPos);
7069 }
7070 };
7071
7072 SmallVector<const Loop *, 16> LoopWorklist(1, L);
7073 SmallVector<Instruction *, 32> Worklist;
7074 SmallPtrSet<Instruction *, 16> Visited;
7075
7076 // Iterate over all the loops and sub-loops to drop SCEV information.
7077 while (!LoopWorklist.empty()) {
7078 auto *CurrL = LoopWorklist.pop_back_val();
7079
7080 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
7081 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
7082
7083 // Drop information about predicated SCEV rewrites for this loop.
7084 for (auto I = PredicatedSCEVRewrites.begin();
7085 I != PredicatedSCEVRewrites.end();) {
7086 std::pair<const SCEV *, const Loop *> Entry = I->first;
7087 if (Entry.second == CurrL)
7088 PredicatedSCEVRewrites.erase(I++);
7089 else
7090 ++I;
7091 }
7092
7093 auto LoopUsersItr = LoopUsers.find(CurrL);
7094 if (LoopUsersItr != LoopUsers.end()) {
7095 for (auto *S : LoopUsersItr->second)
7096 forgetMemoizedResults(S);
7097 LoopUsers.erase(LoopUsersItr);
7098 }
7099
7100 // Drop information about expressions based on loop-header PHIs.
7101 PushLoopPHIs(CurrL, Worklist);
7102
7103 while (!Worklist.empty()) {
7104 Instruction *I = Worklist.pop_back_val();
7105 if (!Visited.insert(I).second)
7106 continue;
7107
7108 ValueExprMapType::iterator It =
7109 ValueExprMap.find_as(static_cast<Value *>(I));
7110 if (It != ValueExprMap.end()) {
7111 eraseValueFromMap(It->first);
7112 forgetMemoizedResults(It->second);
7113 if (PHINode *PN = dyn_cast<PHINode>(I))
7114 ConstantEvolutionLoopExitValue.erase(PN);
7115 }
7116
7117 PushDefUseChildren(I, Worklist);
7118 }
7119
7120 LoopPropertiesCache.erase(CurrL);
7121 // Forget all contained loops too, to avoid dangling entries in the
7122 // ValuesAtScopes map.
7123 LoopWorklist.append(CurrL->begin(), CurrL->end());
7124 }
7125}
7126
7127void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
7128 while (Loop *Parent = L->getParentLoop())
7129 L = Parent;
7130 forgetLoop(L);
7131}
7132
7133void ScalarEvolution::forgetValue(Value *V) {
7134 Instruction *I = dyn_cast<Instruction>(V);
7135 if (!I) return;
7136
7137 // Drop information about expressions based on loop-header PHIs.
7138 SmallVector<Instruction *, 16> Worklist;
7139 Worklist.push_back(I);
7140
7141 SmallPtrSet<Instruction *, 8> Visited;
7142 while (!Worklist.empty()) {
7143 I = Worklist.pop_back_val();
7144 if (!Visited.insert(I).second)
7145 continue;
7146
7147 ValueExprMapType::iterator It =
7148 ValueExprMap.find_as(static_cast<Value *>(I));
7149 if (It != ValueExprMap.end()) {
7150 eraseValueFromMap(It->first);
7151 forgetMemoizedResults(It->second);
7152 if (PHINode *PN = dyn_cast<PHINode>(I))
7153 ConstantEvolutionLoopExitValue.erase(PN);
7154 }
7155
7156 PushDefUseChildren(I, Worklist);
7157 }
7158}
7159
7160void ScalarEvolution::forgetLoopDispositions(const Loop *L) {
7161 LoopDispositions.clear();
7162}
7163
7164/// Get the exact loop backedge taken count considering all loop exits. A
7165/// computable result can only be returned for loops with all exiting blocks
7166/// dominating the latch. howFarToZero assumes that the limit of each loop test
7167/// is never skipped. This is a valid assumption as long as the loop exits via
7168/// that test. For precise results, it is the caller's responsibility to specify
7169/// the relevant loop exiting block using getExact(ExitingBlock, SE).
7170const SCEV *
7171ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
7172 SCEVUnionPredicate *Preds) const {
7173 // If any exits were not computable, the loop is not computable.
7174 if (!isComplete() || ExitNotTaken.empty())
7175 return SE->getCouldNotCompute();
7176
7177 const BasicBlock *Latch = L->getLoopLatch();
7178 // All exiting blocks we have collected must dominate the only backedge.
7179 if (!Latch)
7180 return SE->getCouldNotCompute();
7181
7182 // All exiting blocks we have gathered dominate loop's latch, so exact trip
7183 // count is simply a minimum out of all these calculated exit counts.
7184 SmallVector<const SCEV *, 2> Ops;
7185 for (auto &ENT : ExitNotTaken) {
7186 const SCEV *BECount = ENT.ExactNotTaken;
7187 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!")((BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"
) ? static_cast<void> (0) : __assert_fail ("BECount != SE->getCouldNotCompute() && \"Bad exit SCEV!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7187, __PRETTY_FUNCTION__))
;
7188 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&((SE->DT.dominates(ENT.ExitingBlock, Latch) && "We should only have known counts for exiting blocks that dominate "
"latch!") ? static_cast<void> (0) : __assert_fail ("SE->DT.dominates(ENT.ExitingBlock, Latch) && \"We should only have known counts for exiting blocks that dominate \" \"latch!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7190, __PRETTY_FUNCTION__))
7189 "We should only have known counts for exiting blocks that dominate "((SE->DT.dominates(ENT.ExitingBlock, Latch) && "We should only have known counts for exiting blocks that dominate "
"latch!") ? static_cast<void> (0) : __assert_fail ("SE->DT.dominates(ENT.ExitingBlock, Latch) && \"We should only have known counts for exiting blocks that dominate \" \"latch!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7190, __PRETTY_FUNCTION__))
7190 "latch!")((SE->DT.dominates(ENT.ExitingBlock, Latch) && "We should only have known counts for exiting blocks that dominate "
"latch!") ? static_cast<void> (0) : __assert_fail ("SE->DT.dominates(ENT.ExitingBlock, Latch) && \"We should only have known counts for exiting blocks that dominate \" \"latch!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7190, __PRETTY_FUNCTION__))
;
7191
7192 Ops.push_back(BECount);
7193
7194 if (Preds && !ENT.hasAlwaysTruePredicate())
7195 Preds->add(ENT.Predicate.get());
7196
7197 assert((Preds || ENT.hasAlwaysTruePredicate()) &&(((Preds || ENT.hasAlwaysTruePredicate()) && "Predicate should be always true!"
) ? static_cast<void> (0) : __assert_fail ("(Preds || ENT.hasAlwaysTruePredicate()) && \"Predicate should be always true!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7198, __PRETTY_FUNCTION__))
7198 "Predicate should be always true!")(((Preds || ENT.hasAlwaysTruePredicate()) && "Predicate should be always true!"
) ? static_cast<void> (0) : __assert_fail ("(Preds || ENT.hasAlwaysTruePredicate()) && \"Predicate should be always true!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7198, __PRETTY_FUNCTION__))
;
7199 }
7200
7201 return SE->getUMinFromMismatchedTypes(Ops);
7202}
7203
7204/// Get the exact not taken count for this loop exit.
7205const SCEV *
7206ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
7207 ScalarEvolution *SE) const {
7208 for (auto &ENT : ExitNotTaken)
7209 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7210 return ENT.ExactNotTaken;
7211
7212 return SE->getCouldNotCompute();
7213}
7214
7215const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
7216 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
7217 for (auto &ENT : ExitNotTaken)
7218 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
7219 return ENT.MaxNotTaken;
7220
7221 return SE->getCouldNotCompute();
7222}
7223
7224/// getConstantMax - Get the constant max backedge taken count for the loop.
7225const SCEV *
7226ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
7227 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7228 return !ENT.hasAlwaysTruePredicate();
7229 };
7230
7231 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax())
7232 return SE->getCouldNotCompute();
7233
7234 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||(((isa<SCEVCouldNotCompute>(getConstantMax()) || isa<
SCEVConstant>(getConstantMax())) && "No point in having a non-constant max backedge taken count!"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(getConstantMax()) || isa<SCEVConstant>(getConstantMax())) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7236, __PRETTY_FUNCTION__))
7235 isa<SCEVConstant>(getConstantMax())) &&(((isa<SCEVCouldNotCompute>(getConstantMax()) || isa<
SCEVConstant>(getConstantMax())) && "No point in having a non-constant max backedge taken count!"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(getConstantMax()) || isa<SCEVConstant>(getConstantMax())) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7236, __PRETTY_FUNCTION__))
7236 "No point in having a non-constant max backedge taken count!")(((isa<SCEVCouldNotCompute>(getConstantMax()) || isa<
SCEVConstant>(getConstantMax())) && "No point in having a non-constant max backedge taken count!"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(getConstantMax()) || isa<SCEVConstant>(getConstantMax())) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7236, __PRETTY_FUNCTION__))
;
7237 return getConstantMax();
7238}
7239
7240const SCEV *
7241ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
7242 ScalarEvolution *SE) {
7243 if (!SymbolicMax)
7244 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
7245 return SymbolicMax;
7246}
7247
7248bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
7249 ScalarEvolution *SE) const {
7250 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
7251 return !ENT.hasAlwaysTruePredicate();
7252 };
7253 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
7254}
7255
7256bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
7257 ScalarEvolution *SE) const {
7258 if (getConstantMax() && getConstantMax() != SE->getCouldNotCompute() &&
7259 SE->hasOperand(getConstantMax(), S))
7260 return true;
7261
7262 for (auto &ENT : ExitNotTaken)
7263 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
7264 SE->hasOperand(ENT.ExactNotTaken, S))
7265 return true;
7266
7267 return false;
7268}
7269
7270ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
7271 : ExactNotTaken(E), MaxNotTaken(E) {
7272 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant
>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7274, __PRETTY_FUNCTION__))
7273 isa<SCEVConstant>(MaxNotTaken)) &&(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant
>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7274, __PRETTY_FUNCTION__))
7274 "No point in having a non-constant max backedge taken count!")(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant
>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7274, __PRETTY_FUNCTION__))
;
7275}
7276
7277ScalarEvolution::ExitLimit::ExitLimit(
7278 const SCEV *E, const SCEV *M, bool MaxOrZero,
7279 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
7280 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
7281 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||(((isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute
>(MaxNotTaken)) && "Exact is not allowed to be less precise than Max"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute>(MaxNotTaken)) && \"Exact is not allowed to be less precise than Max\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7283, __PRETTY_FUNCTION__))
7282 !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&(((isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute
>(MaxNotTaken)) && "Exact is not allowed to be less precise than Max"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute>(MaxNotTaken)) && \"Exact is not allowed to be less precise than Max\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7283, __PRETTY_FUNCTION__))
7283 "Exact is not allowed to be less precise than Max")(((isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute
>(MaxNotTaken)) && "Exact is not allowed to be less precise than Max"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute>(MaxNotTaken)) && \"Exact is not allowed to be less precise than Max\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7283, __PRETTY_FUNCTION__))
;
7284 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant
>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7286, __PRETTY_FUNCTION__))
7285 isa<SCEVConstant>(MaxNotTaken)) &&(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant
>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7286, __PRETTY_FUNCTION__))
7286 "No point in having a non-constant max backedge taken count!")(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant
>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7286, __PRETTY_FUNCTION__))
;
7287 for (auto *PredSet : PredSetList)
7288 for (auto *P : *PredSet)
7289 addPredicate(P);
7290}
7291
7292ScalarEvolution::ExitLimit::ExitLimit(
7293 const SCEV *E, const SCEV *M, bool MaxOrZero,
7294 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
7295 : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
7296 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant
>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7298, __PRETTY_FUNCTION__))
7297 isa<SCEVConstant>(MaxNotTaken)) &&(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant
>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7298, __PRETTY_FUNCTION__))
7298 "No point in having a non-constant max backedge taken count!")(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant
>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7298, __PRETTY_FUNCTION__))
;
7299}
7300
7301ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
7302 bool MaxOrZero)
7303 : ExitLimit(E, M, MaxOrZero, None) {
7304 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant
>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7306, __PRETTY_FUNCTION__))
7305 isa<SCEVConstant>(MaxNotTaken)) &&(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant
>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7306, __PRETTY_FUNCTION__))
7306 "No point in having a non-constant max backedge taken count!")(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant
>(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7306, __PRETTY_FUNCTION__))
;
7307}
7308
7309/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7310/// computable exit into a persistent ExitNotTakenInfo array.
7311ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7312 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
7313 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
7314 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
7315 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7316
7317 ExitNotTaken.reserve(ExitCounts.size());
7318 std::transform(
7319 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7320 [&](const EdgeExitInfo &EEI) {
7321 BasicBlock *ExitBB = EEI.first;
7322 const ExitLimit &EL = EEI.second;
7323 if (EL.Predicates.empty())
7324 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7325 nullptr);
7326
7327 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7328 for (auto *Pred : EL.Predicates)
7329 Predicate->add(Pred);
7330
7331 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken,
7332 std::move(Predicate));
7333 });
7334 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||(((isa<SCEVCouldNotCompute>(ConstantMax) || isa<SCEVConstant
>(ConstantMax)) && "No point in having a non-constant max backedge taken count!"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ConstantMax) || isa<SCEVConstant>(ConstantMax)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7336, __PRETTY_FUNCTION__))
7335 isa<SCEVConstant>(ConstantMax)) &&(((isa<SCEVCouldNotCompute>(ConstantMax) || isa<SCEVConstant
>(ConstantMax)) && "No point in having a non-constant max backedge taken count!"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ConstantMax) || isa<SCEVConstant>(ConstantMax)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7336, __PRETTY_FUNCTION__))
7336 "No point in having a non-constant max backedge taken count!")(((isa<SCEVCouldNotCompute>(ConstantMax) || isa<SCEVConstant
>(ConstantMax)) && "No point in having a non-constant max backedge taken count!"
) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ConstantMax) || isa<SCEVConstant>(ConstantMax)) && \"No point in having a non-constant max backedge taken count!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7336, __PRETTY_FUNCTION__))
;
7337}
7338
7339/// Invalidate this result and free the ExitNotTakenInfo array.
7340void ScalarEvolution::BackedgeTakenInfo::clear() {
7341 ExitNotTaken.clear();
7342}
7343
7344/// Compute the number of times the backedge of the specified loop will execute.
7345ScalarEvolution::BackedgeTakenInfo
7346ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7347 bool AllowPredicates) {
7348 SmallVector<BasicBlock *, 8> ExitingBlocks;
7349 L->getExitingBlocks(ExitingBlocks);
7350
7351 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7352
7353 SmallVector<EdgeExitInfo, 4> ExitCounts;
7354 bool CouldComputeBECount = true;
7355 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7356 const SCEV *MustExitMaxBECount = nullptr;
7357 const SCEV *MayExitMaxBECount = nullptr;
7358 bool MustExitMaxOrZero = false;
7359
7360 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7361 // and compute maxBECount.
7362 // Do a union of all the predicates here.
7363 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7364 BasicBlock *ExitBB = ExitingBlocks[i];
7365
7366 // We canonicalize untaken exits to br (constant), ignore them so that
7367 // proving an exit untaken doesn't negatively impact our ability to reason
7368 // about the loop as whole.
7369 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
7370 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
7371 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7372 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne()))
7373 continue;
7374 }
7375
7376 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7377
7378 assert((AllowPredicates || EL.Predicates.empty()) &&(((AllowPredicates || EL.Predicates.empty()) && "Predicated exit limit when predicates are not allowed!"
) ? static_cast<void> (0) : __assert_fail ("(AllowPredicates || EL.Predicates.empty()) && \"Predicated exit limit when predicates are not allowed!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7379, __PRETTY_FUNCTION__))
7379 "Predicated exit limit when predicates are not allowed!")(((AllowPredicates || EL.Predicates.empty()) && "Predicated exit limit when predicates are not allowed!"
) ? static_cast<void> (0) : __assert_fail ("(AllowPredicates || EL.Predicates.empty()) && \"Predicated exit limit when predicates are not allowed!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7379, __PRETTY_FUNCTION__))
;
7380
7381 // 1. For each exit that can be computed, add an entry to ExitCounts.
7382 // CouldComputeBECount is true only if all exits can be computed.
7383 if (EL.ExactNotTaken == getCouldNotCompute())
7384 // We couldn't compute an exact value for this exit, so
7385 // we won't be able to compute an exact value for the loop.
7386 CouldComputeBECount = false;
7387 else
7388 ExitCounts.emplace_back(ExitBB, EL);
7389
7390 // 2. Derive the loop's MaxBECount from each exit's max number of
7391 // non-exiting iterations. Partition the loop exits into two kinds:
7392 // LoopMustExits and LoopMayExits.
7393 //
7394 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7395 // is a LoopMayExit. If any computable LoopMustExit is found, then
7396 // MaxBECount is the minimum EL.MaxNotTaken of computable
7397 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7398 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7399 // computable EL.MaxNotTaken.
7400 if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7401 DT.dominates(ExitBB, Latch)) {
7402 if (!MustExitMaxBECount) {
7403 MustExitMaxBECount = EL.MaxNotTaken;
7404 MustExitMaxOrZero = EL.MaxOrZero;
7405 } else {
7406 MustExitMaxBECount =
7407 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7408 }
7409 } else if (MayExitMaxBECount != getCouldNotCompute()) {
7410 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7411 MayExitMaxBECount = EL.MaxNotTaken;
7412 else {
7413 MayExitMaxBECount =
7414 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7415 }
7416 }
7417 }
7418 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7419 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7420 // The loop backedge will be taken the maximum or zero times if there's
7421 // a single exit that must be taken the maximum or zero times.
7422 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7423 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7424 MaxBECount, MaxOrZero);
7425}
7426
7427ScalarEvolution::ExitLimit
7428ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7429 bool AllowPredicates) {
7430 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?")((L->contains(ExitingBlock) && "Exit count for non-loop block?"
) ? static_cast<void> (0) : __assert_fail ("L->contains(ExitingBlock) && \"Exit count for non-loop block?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7430, __PRETTY_FUNCTION__))
;
7431 // If our exiting block does not dominate the latch, then its connection with
7432 // loop's exit limit may be far from trivial.
7433 const BasicBlock *Latch = L->getLoopLatch();
7434 if (!Latch || !DT.dominates(ExitingBlock, Latch))
7435 return getCouldNotCompute();
7436
7437 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7438 Instruction *Term = ExitingBlock->getTerminator();
7439 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7440 assert(BI->isConditional() && "If unconditional, it can't be in loop!")((BI->isConditional() && "If unconditional, it can't be in loop!"
) ? static_cast<void> (0) : __assert_fail ("BI->isConditional() && \"If unconditional, it can't be in loop!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7440, __PRETTY_FUNCTION__))
;
7441 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7442 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&((ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
"It should have one successor in loop and one exit block!") ?
static_cast<void> (0) : __assert_fail ("ExitIfTrue == L->contains(BI->getSuccessor(1)) && \"It should have one successor in loop and one exit block!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7443, __PRETTY_FUNCTION__))
7443 "It should have one successor in loop and one exit block!")((ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
"It should have one successor in loop and one exit block!") ?
static_cast<void> (0) : __assert_fail ("ExitIfTrue == L->contains(BI->getSuccessor(1)) && \"It should have one successor in loop and one exit block!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7443, __PRETTY_FUNCTION__))
;
7444 // Proceed to the next level to examine the exit condition expression.
7445 return computeExitLimitFromCond(
7446 L, BI->getCondition(), ExitIfTrue,
7447 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7448 }
7449
7450 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7451 // For switch, make sure that there is a single exit from the loop.
7452 BasicBlock *Exit = nullptr;
7453 for (auto *SBB : successors(ExitingBlock))
7454 if (!L->contains(SBB)) {
7455 if (Exit) // Multiple exit successors.
7456 return getCouldNotCompute();
7457 Exit = SBB;
7458 }
7459 assert(Exit && "Exiting block must have at least one exit")((Exit && "Exiting block must have at least one exit"
) ? static_cast<void> (0) : __assert_fail ("Exit && \"Exiting block must have at least one exit\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7459, __PRETTY_FUNCTION__))
;
7460 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7461 /*ControlsExit=*/IsOnlyExit);
7462 }
7463
7464 return getCouldNotCompute();
7465}
7466
7467ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7468 const Loop *L, Value *ExitCond, bool ExitIfTrue,
7469 bool ControlsExit, bool AllowPredicates) {
7470 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7471 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7472 ControlsExit, AllowPredicates);
7473}
7474
7475Optional<ScalarEvolution::ExitLimit>
7476ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7477 bool ExitIfTrue, bool ControlsExit,
7478 bool AllowPredicates) {
7479 (void)this->L;
7480 (void)this->ExitIfTrue;
7481 (void)this->AllowPredicates;
7482
7483 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&((this->L == L && this->ExitIfTrue == ExitIfTrue
&& this->AllowPredicates == AllowPredicates &&
"Variance in assumed invariant key components!") ? static_cast
<void> (0) : __assert_fail ("this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7485, __PRETTY_FUNCTION__))
7484 this->AllowPredicates == AllowPredicates &&((this->L == L && this->ExitIfTrue == ExitIfTrue
&& this->AllowPredicates == AllowPredicates &&
"Variance in assumed invariant key components!") ? static_cast
<void> (0) : __assert_fail ("this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7485, __PRETTY_FUNCTION__))
7485 "Variance in assumed invariant key components!")((this->L == L && this->ExitIfTrue == ExitIfTrue
&& this->AllowPredicates == AllowPredicates &&
"Variance in assumed invariant key components!") ? static_cast
<void> (0) : __assert_fail ("this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7485, __PRETTY_FUNCTION__))
;
7486 auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7487 if (Itr == TripCountMap.end())
7488 return None;
7489 return Itr->second;
7490}
7491
7492void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7493 bool ExitIfTrue,
7494 bool ControlsExit,
7495 bool AllowPredicates,
7496 const ExitLimit &EL) {
7497 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&((this->L == L && this->ExitIfTrue == ExitIfTrue
&& this->AllowPredicates == AllowPredicates &&
"Variance in assumed invariant key components!") ? static_cast
<void> (0) : __assert_fail ("this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7499, __PRETTY_FUNCTION__))
7498 this->AllowPredicates == AllowPredicates &&((this->L == L && this->ExitIfTrue == ExitIfTrue
&& this->AllowPredicates == AllowPredicates &&
"Variance in assumed invariant key components!") ? static_cast
<void> (0) : __assert_fail ("this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7499, __PRETTY_FUNCTION__))
7499 "Variance in assumed invariant key components!")((this->L == L && this->ExitIfTrue == ExitIfTrue
&& this->AllowPredicates == AllowPredicates &&
"Variance in assumed invariant key components!") ? static_cast
<void> (0) : __assert_fail ("this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7499, __PRETTY_FUNCTION__))
;
7500
7501 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7502 assert(InsertResult.second && "Expected successful insertion!")((InsertResult.second && "Expected successful insertion!"
) ? static_cast<void> (0) : __assert_fail ("InsertResult.second && \"Expected successful insertion!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7502, __PRETTY_FUNCTION__))
;
7503 (void)InsertResult;
7504 (void)ExitIfTrue;
7505}
7506
7507ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7508 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7509 bool ControlsExit, bool AllowPredicates) {
7510
7511 if (auto MaybeEL =
7512 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7513 return *MaybeEL;
7514
7515 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7516 ControlsExit, AllowPredicates);
7517 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7518 return EL;
7519}
7520
7521ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7522 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7523 bool ControlsExit, bool AllowPredicates) {
7524 // Handle BinOp conditions (And, Or).
7525 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
7526 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7527 return *LimitFromBinOp;
7528
7529 // With an icmp, it may be feasible to compute an exact backedge-taken count.
7530 // Proceed to the next level to examine the icmp.
7531 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7532 ExitLimit EL =
7533 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7534 if (EL.hasFullInfo() || !AllowPredicates)
7535 return EL;
7536
7537 // Try again, but use SCEV predicates this time.
7538 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7539 /*AllowPredicates=*/true);
7540 }
7541
7542 // Check for a constant condition. These are normally stripped out by
7543 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7544 // preserve the CFG and is temporarily leaving constant conditions
7545 // in place.
7546 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7547 if (ExitIfTrue == !CI->getZExtValue())
7548 // The backedge is always taken.
7549 return getCouldNotCompute();
7550 else
7551 // The backedge is never taken.
7552 return getZero(CI->getType());
7553 }
7554
7555 // If it's not an integer or pointer comparison then compute it the hard way.
7556 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7557}
7558
7559Optional<ScalarEvolution::ExitLimit>
7560ScalarEvolution::computeExitLimitFromCondFromBinOp(
7561 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7562 bool ControlsExit, bool AllowPredicates) {
7563 // Check if the controlling expression for this loop is an And or Or.
7564 if (auto *BO = dyn_cast<BinaryOperator>(ExitCond)) {
7565 if (BO->getOpcode() == Instruction::And)
7566 return computeExitLimitFromCondFromBinOpHelper(
7567 Cache, L, BO, !ExitIfTrue, ExitIfTrue, ControlsExit, AllowPredicates,
7568 ConstantInt::get(BO->getType(), 1));
7569 if (BO->getOpcode() == Instruction::Or)
7570 return computeExitLimitFromCondFromBinOpHelper(
7571 Cache, L, BO, ExitIfTrue, ExitIfTrue, ControlsExit, AllowPredicates,
7572 ConstantInt::get(BO->getType(), 0));
7573 }
7574 return None;
7575}
7576
7577ScalarEvolution::ExitLimit
7578ScalarEvolution::computeExitLimitFromCondFromBinOpHelper(
7579 ExitLimitCacheTy &Cache, const Loop *L, BinaryOperator *BO,
7580 bool EitherMayExit, bool ExitIfTrue, bool ControlsExit,
7581 bool AllowPredicates, const Constant *NeutralElement) {
7582 ExitLimit EL0 = computeExitLimitFromCondCached(
7583 Cache, L, BO->getOperand(0), ExitIfTrue, ControlsExit && !EitherMayExit,
7584 AllowPredicates);
7585 ExitLimit EL1 = computeExitLimitFromCondCached(
7586 Cache, L, BO->getOperand(1), ExitIfTrue, ControlsExit && !EitherMayExit,
7587 AllowPredicates);
7588 // Be robust against unsimplified IR for the form "op i1 X,
7589 // NeutralElement"
7590 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
7591 return CI == NeutralElement ? EL0 : EL1;
7592 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0)))
7593 return CI == NeutralElement ? EL1 : EL0;
7594 const SCEV *BECount = getCouldNotCompute();
7595 const SCEV *MaxBECount = getCouldNotCompute();
7596 if (EitherMayExit) {
7597 // Both conditions must be same for the loop to continue executing.
7598 // Choose the less conservative count.
7599 if (EL0.ExactNotTaken == getCouldNotCompute() ||
7600 EL1.ExactNotTaken == getCouldNotCompute())
7601 BECount = getCouldNotCompute();
7602 else
7603 BECount =
7604 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7605 if (EL0.MaxNotTaken == getCouldNotCompute())
7606 MaxBECount = EL1.MaxNotTaken;
7607 else if (EL1.MaxNotTaken == getCouldNotCompute())
7608 MaxBECount = EL0.MaxNotTaken;
7609 else
7610 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7611 } else {
7612 // Both conditions must be same at the same time for the loop to exit.
7613 // For now, be conservative.
7614 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7615 BECount = EL0.ExactNotTaken;
7616 }
7617
7618 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7619 // to be more aggressive when computing BECount than when computing
7620 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
7621 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7622 // to not.
7623 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7624 !isa<SCEVCouldNotCompute>(BECount))
7625 MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7626
7627 return ExitLimit(BECount, MaxBECount, false,
7628 { &EL0.Predicates, &EL1.Predicates });
7629}
7630
7631ScalarEvolution::ExitLimit
7632ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7633 ICmpInst *ExitCond,
7634 bool ExitIfTrue,
7635 bool ControlsExit,
7636 bool AllowPredicates) {
7637 // If the condition was exit on true, convert the condition to exit on false
7638 ICmpInst::Predicate Pred;
7639 if (!ExitIfTrue)
7640 Pred = ExitCond->getPredicate();
7641 else
7642 Pred = ExitCond->getInversePredicate();
7643 const ICmpInst::Predicate OriginalPred = Pred;
7644
7645 // Handle common loops like: for (X = "string"; *X; ++X)
7646 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7647 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7648 ExitLimit ItCnt =
7649 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7650 if (ItCnt.hasAnyInfo())
7651 return ItCnt;
7652 }
7653
7654 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7655 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7656
7657 // Try to evaluate any dependencies out of the loop.
7658 LHS = getSCEVAtScope(LHS, L);
7659 RHS = getSCEVAtScope(RHS, L);
7660
7661 // At this point, we would like to compute how many iterations of the
7662 // loop the predicate will return true for these inputs.
7663 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7664 // If there is a loop-invariant, force it into the RHS.
7665 std::swap(LHS, RHS);
7666 Pred = ICmpInst::getSwappedPredicate(Pred);
7667 }
7668
7669 // Simplify the operands before analyzing them.
7670 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7671
7672 // If we have a comparison of a chrec against a constant, try to use value
7673 // ranges to answer this query.
7674 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7675 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7676 if (AddRec->getLoop() == L) {
7677 // Form the constant range.
7678 ConstantRange CompRange =
7679 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7680
7681 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7682 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7683 }
7684
7685 switch (Pred) {
7686 case ICmpInst::ICMP_NE: { // while (X != Y)
7687 // Convert to: while (X-Y != 0)
7688 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7689 AllowPredicates);
7690 if (EL.hasAnyInfo()) return EL;
7691 break;
7692 }
7693 case ICmpInst::ICMP_EQ: { // while (X == Y)
7694 // Convert to: while (X-Y == 0)
7695 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7696 if (EL.hasAnyInfo()) return EL;
7697 break;
7698 }
7699 case ICmpInst::ICMP_SLT:
7700 case ICmpInst::ICMP_ULT: { // while (X < Y)
7701 bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7702 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7703 AllowPredicates);
7704 if (EL.hasAnyInfo()) return EL;
7705 break;
7706 }
7707 case ICmpInst::ICMP_SGT:
7708 case ICmpInst::ICMP_UGT: { // while (X > Y)
7709 bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7710 ExitLimit EL =
7711 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7712 AllowPredicates);
7713 if (EL.hasAnyInfo()) return EL;
7714 break;
7715 }
7716 default:
7717 break;
7718 }
7719
7720 auto *ExhaustiveCount =
7721 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7722
7723 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7724 return ExhaustiveCount;
7725
7726 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7727 ExitCond->getOperand(1), L, OriginalPred);
7728}
7729
7730ScalarEvolution::ExitLimit
7731ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7732 SwitchInst *Switch,
7733 BasicBlock *ExitingBlock,
7734 bool ControlsExit) {
7735 assert(!L->contains(ExitingBlock) && "Not an exiting block!")((!L->contains(ExitingBlock) && "Not an exiting block!"
) ? static_cast<void> (0) : __assert_fail ("!L->contains(ExitingBlock) && \"Not an exiting block!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7735, __PRETTY_FUNCTION__))
;
7736
7737 // Give up if the exit is the default dest of a switch.
7738 if (Switch->getDefaultDest() == ExitingBlock)
7739 return getCouldNotCompute();
7740
7741 assert(L->contains(Switch->getDefaultDest()) &&((L->contains(Switch->getDefaultDest()) && "Default case must not exit the loop!"
) ? static_cast<void> (0) : __assert_fail ("L->contains(Switch->getDefaultDest()) && \"Default case must not exit the loop!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7742, __PRETTY_FUNCTION__))
7742 "Default case must not exit the loop!")((L->contains(Switch->getDefaultDest()) && "Default case must not exit the loop!"
) ? static_cast<void> (0) : __assert_fail ("L->contains(Switch->getDefaultDest()) && \"Default case must not exit the loop!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7742, __PRETTY_FUNCTION__))
;
7743 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7744 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7745
7746 // while (X != Y) --> while (X-Y != 0)
7747 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7748 if (EL.hasAnyInfo())
7749 return EL;
7750
7751 return getCouldNotCompute();
7752}
7753
7754static ConstantInt *
7755EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7756 ScalarEvolution &SE) {
7757 const SCEV *InVal = SE.getConstant(C);
7758 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7759 assert(isa<SCEVConstant>(Val) &&((isa<SCEVConstant>(Val) && "Evaluation of SCEV at constant didn't fold correctly?"
) ? static_cast<void> (0) : __assert_fail ("isa<SCEVConstant>(Val) && \"Evaluation of SCEV at constant didn't fold correctly?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7760, __PRETTY_FUNCTION__))
7760 "Evaluation of SCEV at constant didn't fold correctly?")((isa<SCEVConstant>(Val) && "Evaluation of SCEV at constant didn't fold correctly?"
) ? static_cast<void> (0) : __assert_fail ("isa<SCEVConstant>(Val) && \"Evaluation of SCEV at constant didn't fold correctly?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7760, __PRETTY_FUNCTION__))
;
7761 return cast<SCEVConstant>(Val)->getValue();
7762}
7763
7764/// Given an exit condition of 'icmp op load X, cst', try to see if we can
7765/// compute the backedge execution count.
7766ScalarEvolution::ExitLimit
7767ScalarEvolution::computeLoadConstantCompareExitLimit(
7768 LoadInst *LI,
7769 Constant *RHS,
7770 const Loop *L,
7771 ICmpInst::Predicate predicate) {
7772 if (LI->isVolatile()) return getCouldNotCompute();
7773
7774 // Check to see if the loaded pointer is a getelementptr of a global.
7775 // TODO: Use SCEV instead of manually grubbing with GEPs.
7776 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7777 if (!GEP) return getCouldNotCompute();
7778
7779 // Make sure that it is really a constant global we are gepping, with an
7780 // initializer, and make sure the first IDX is really 0.
7781 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7782 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7783 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7784 !cast<Constant>(GEP->getOperand(1))->isNullValue())
7785 return getCouldNotCompute();
7786
7787 // Okay, we allow one non-constant index into the GEP instruction.
7788 Value *VarIdx = nullptr;
7789 std::vector<Constant*> Indexes;
7790 unsigned VarIdxNum = 0;
7791 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7792 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7793 Indexes.push_back(CI);
7794 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7795 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
7796 VarIdx = GEP->getOperand(i);
7797 VarIdxNum = i-2;
7798 Indexes.push_back(nullptr);
7799 }
7800
7801 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7802 if (!VarIdx)
7803 return getCouldNotCompute();
7804
7805 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7806 // Check to see if X is a loop variant variable value now.
7807 const SCEV *Idx = getSCEV(VarIdx);
7808 Idx = getSCEVAtScope(Idx, L);
7809
7810 // We can only recognize very limited forms of loop index expressions, in
7811 // particular, only affine AddRec's like {C1,+,C2}.
7812 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7813 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7814 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7815 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7816 return getCouldNotCompute();
7817
7818 unsigned MaxSteps = MaxBruteForceIterations;
7819 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7820 ConstantInt *ItCst = ConstantInt::get(
7821 cast<IntegerType>(IdxExpr->getType()), IterationNum);
7822 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7823
7824 // Form the GEP offset.
7825 Indexes[VarIdxNum] = Val;
7826
7827 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7828 Indexes);
7829 if (!Result) break; // Cannot compute!
7830
7831 // Evaluate the condition for this iteration.
7832 Result = ConstantExpr::getICmp(predicate, Result, RHS);
7833 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
7834 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7835 ++NumArrayLenItCounts;
7836 return getConstant(ItCst); // Found terminating iteration!
7837 }
7838 }
7839 return getCouldNotCompute();
7840}
7841
7842ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7843 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7844 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7845 if (!RHS)
7846 return getCouldNotCompute();
7847
7848 const BasicBlock *Latch = L->getLoopLatch();
7849 if (!Latch)
7850 return getCouldNotCompute();
7851
7852 const BasicBlock *Predecessor = L->getLoopPredecessor();
7853 if (!Predecessor)
7854 return getCouldNotCompute();
7855
7856 // Return true if V is of the form "LHS `shift_op` <positive constant>".
7857 // Return LHS in OutLHS and shift_opt in OutOpCode.
7858 auto MatchPositiveShift =
7859 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7860
7861 using namespace PatternMatch;
7862
7863 ConstantInt *ShiftAmt;
7864 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7865 OutOpCode = Instruction::LShr;
7866 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7867 OutOpCode = Instruction::AShr;
7868 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7869 OutOpCode = Instruction::Shl;
7870 else
7871 return false;
7872
7873 return ShiftAmt->getValue().isStrictlyPositive();
7874 };
7875
7876 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7877 //
7878 // loop:
7879 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7880 // %iv.shifted = lshr i32 %iv, <positive constant>
7881 //
7882 // Return true on a successful match. Return the corresponding PHI node (%iv
7883 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7884 auto MatchShiftRecurrence =
7885 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7886 Optional<Instruction::BinaryOps> PostShiftOpCode;
7887
7888 {
7889 Instruction::BinaryOps OpC;
7890 Value *V;
7891
7892 // If we encounter a shift instruction, "peel off" the shift operation,
7893 // and remember that we did so. Later when we inspect %iv's backedge
7894 // value, we will make sure that the backedge value uses the same
7895 // operation.
7896 //
7897 // Note: the peeled shift operation does not have to be the same
7898 // instruction as the one feeding into the PHI's backedge value. We only
7899 // really care about it being the same *kind* of shift instruction --
7900 // that's all that is required for our later inferences to hold.
7901 if (MatchPositiveShift(LHS, V, OpC)) {
7902 PostShiftOpCode = OpC;
7903 LHS = V;
7904 }
7905 }
7906
7907 PNOut = dyn_cast<PHINode>(LHS);
7908 if (!PNOut || PNOut->getParent() != L->getHeader())
7909 return false;
7910
7911 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7912 Value *OpLHS;
7913
7914 return
7915 // The backedge value for the PHI node must be a shift by a positive
7916 // amount
7917 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7918
7919 // of the PHI node itself
7920 OpLHS == PNOut &&
7921
7922 // and the kind of shift should be match the kind of shift we peeled
7923 // off, if any.
7924 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7925 };
7926
7927 PHINode *PN;
7928 Instruction::BinaryOps OpCode;
7929 if (!MatchShiftRecurrence(LHS, PN, OpCode))
7930 return getCouldNotCompute();
7931
7932 const DataLayout &DL = getDataLayout();
7933
7934 // The key rationale for this optimization is that for some kinds of shift
7935 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7936 // within a finite number of iterations. If the condition guarding the
7937 // backedge (in the sense that the backedge is taken if the condition is true)
7938 // is false for the value the shift recurrence stabilizes to, then we know
7939 // that the backedge is taken only a finite number of times.
7940
7941 ConstantInt *StableValue = nullptr;
7942 switch (OpCode) {
7943 default:
7944 llvm_unreachable("Impossible case!")::llvm::llvm_unreachable_internal("Impossible case!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7944)
;
7945
7946 case Instruction::AShr: {
7947 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7948 // bitwidth(K) iterations.
7949 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7950 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7951 Predecessor->getTerminator(), &DT);
7952 auto *Ty = cast<IntegerType>(RHS->getType());
7953 if (Known.isNonNegative())
7954 StableValue = ConstantInt::get(Ty, 0);
7955 else if (Known.isNegative())
7956 StableValue = ConstantInt::get(Ty, -1, true);
7957 else
7958 return getCouldNotCompute();
7959
7960 break;
7961 }
7962 case Instruction::LShr:
7963 case Instruction::Shl:
7964 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7965 // stabilize to 0 in at most bitwidth(K) iterations.
7966 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7967 break;
7968 }
7969
7970 auto *Result =
7971 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7972 assert(Result->getType()->isIntegerTy(1) &&((Result->getType()->isIntegerTy(1) && "Otherwise cannot be an operand to a branch instruction"
) ? static_cast<void> (0) : __assert_fail ("Result->getType()->isIntegerTy(1) && \"Otherwise cannot be an operand to a branch instruction\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7973, __PRETTY_FUNCTION__))
7973 "Otherwise cannot be an operand to a branch instruction")((Result->getType()->isIntegerTy(1) && "Otherwise cannot be an operand to a branch instruction"
) ? static_cast<void> (0) : __assert_fail ("Result->getType()->isIntegerTy(1) && \"Otherwise cannot be an operand to a branch instruction\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 7973, __PRETTY_FUNCTION__))
;
7974
7975 if (Result->isZeroValue()) {
7976 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7977 const SCEV *UpperBound =
7978 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7979 return ExitLimit(getCouldNotCompute(), UpperBound, false);
7980 }
7981
7982 return getCouldNotCompute();
7983}
7984
7985/// Return true if we can constant fold an instruction of the specified type,
7986/// assuming that all operands were constants.
7987static bool CanConstantFold(const Instruction *I) {
7988 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7989 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7990 isa<LoadInst>(I) || isa<ExtractValueInst>(I))
7991 return true;
7992
7993 if (const CallInst *CI = dyn_cast<CallInst>(I))
7994 if (const Function *F = CI->getCalledFunction())
7995 return canConstantFoldCallTo(CI, F);
7996 return false;
7997}
7998
7999/// Determine whether this instruction can constant evolve within this loop
8000/// assuming its operands can all constant evolve.
8001static bool canConstantEvolve(Instruction *I, const Loop *L) {
8002 // An instruction outside of the loop can't be derived from a loop PHI.
8003 if (!L->contains(I)) return false;
8004
8005 if (isa<PHINode>(I)) {
8006 // We don't currently keep track of the control flow needed to evaluate
8007 // PHIs, so we cannot handle PHIs inside of loops.
8008 return L->getHeader() == I->getParent();
8009 }
8010
8011 // If we won't be able to constant fold this expression even if the operands
8012 // are constants, bail early.
8013 return CanConstantFold(I);
8014}
8015
8016/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
8017/// recursing through each instruction operand until reaching a loop header phi.
8018static PHINode *
8019getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
8020 DenseMap<Instruction *, PHINode *> &PHIMap,
8021 unsigned Depth) {
8022 if (Depth > MaxConstantEvolvingDepth)
8023 return nullptr;
8024
8025 // Otherwise, we can evaluate this instruction if all of its operands are
8026 // constant or derived from a PHI node themselves.
8027 PHINode *PHI = nullptr;
8028 for (Value *Op : UseInst->operands()) {
8029 if (isa<Constant>(Op)) continue;
8030
8031 Instruction *OpInst = dyn_cast<Instruction>(Op);
8032 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
8033
8034 PHINode *P = dyn_cast<PHINode>(OpInst);
8035 if (!P)
8036 // If this operand is already visited, reuse the prior result.
8037 // We may have P != PHI if this is the deepest point at which the
8038 // inconsistent paths meet.
8039 P = PHIMap.lookup(OpInst);
8040 if (!P) {
8041 // Recurse and memoize the results, whether a phi is found or not.
8042 // This recursive call invalidates pointers into PHIMap.
8043 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
8044 PHIMap[OpInst] = P;
8045 }
8046 if (!P)
8047 return nullptr; // Not evolving from PHI
8048 if (PHI && PHI != P)
8049 return nullptr; // Evolving from multiple different PHIs.
8050 PHI = P;
8051 }
8052 // This is a expression evolving from a constant PHI!
8053 return PHI;
8054}
8055
8056/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
8057/// in the loop that V is derived from. We allow arbitrary operations along the
8058/// way, but the operands of an operation must either be constants or a value
8059/// derived from a constant PHI. If this expression does not fit with these
8060/// constraints, return null.
8061static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
8062 Instruction *I = dyn_cast<Instruction>(V);
8063 if (!I || !canConstantEvolve(I, L)) return nullptr;
8064
8065 if (PHINode *PN = dyn_cast<PHINode>(I))
8066 return PN;
8067
8068 // Record non-constant instructions contained by the loop.
8069 DenseMap<Instruction *, PHINode *> PHIMap;
8070 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
8071}
8072
8073/// EvaluateExpression - Given an expression that passes the
8074/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
8075/// in the loop has the value PHIVal. If we can't fold this expression for some
8076/// reason, return null.
8077static Constant *EvaluateExpression(Value *V, const Loop *L,
8078 DenseMap<Instruction *, Constant *> &Vals,
8079 const DataLayout &DL,
8080 const TargetLibraryInfo *TLI) {
8081 // Convenient constant check, but redundant for recursive calls.
8082 if (Constant *C = dyn_cast<Constant>(V)) return C;
8083 Instruction *I = dyn_cast<Instruction>(V);
8084 if (!I) return nullptr;
8085
8086 if (Constant *C = Vals.lookup(I)) return C;
8087
8088 // An instruction inside the loop depends on a value outside the loop that we
8089 // weren't given a mapping for, or a value such as a call inside the loop.
8090 if (!canConstantEvolve(I, L)) return nullptr;
8091
8092 // An unmapped PHI can be due to a branch or another loop inside this loop,
8093 // or due to this not being the initial iteration through a loop where we
8094 // couldn't compute the evolution of this particular PHI last time.
8095 if (isa<PHINode>(I)) return nullptr;
8096
8097 std::vector<Constant*> Operands(I->getNumOperands());
8098
8099 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
8100 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
8101 if (!Operand) {
8102 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
8103 if (!Operands[i]) return nullptr;
8104 continue;
8105 }
8106 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
8107 Vals[Operand] = C;
8108 if (!C) return nullptr;
8109 Operands[i] = C;
8110 }
8111
8112 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8113 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8114 Operands[1], DL, TLI);
8115 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8116 if (!LI->isVolatile())
8117 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8118 }
8119 return ConstantFoldInstOperands(I, Operands, DL, TLI);
8120}
8121
8122
8123// If every incoming value to PN except the one for BB is a specific Constant,
8124// return that, else return nullptr.
8125static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
8126 Constant *IncomingVal = nullptr;
8127
8128 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8129 if (PN->getIncomingBlock(i) == BB)
8130 continue;
8131
8132 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
8133 if (!CurrentVal)
8134 return nullptr;
8135
8136 if (IncomingVal != CurrentVal) {
8137 if (IncomingVal)
8138 return nullptr;
8139 IncomingVal = CurrentVal;
8140 }
8141 }
8142
8143 return IncomingVal;
8144}
8145
8146/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
8147/// in the header of its containing loop, we know the loop executes a
8148/// constant number of times, and the PHI node is just a recurrence
8149/// involving constants, fold it.
8150Constant *
8151ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
8152 const APInt &BEs,
8153 const Loop *L) {
8154 auto I = ConstantEvolutionLoopExitValue.find(PN);
8155 if (I != ConstantEvolutionLoopExitValue.end())
8156 return I->second;
8157
8158 if (BEs.ugt(MaxBruteForceIterations))
8159 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
8160
8161 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
8162
8163 DenseMap<Instruction *, Constant *> CurrentIterVals;
8164 BasicBlock *Header = L->getHeader();
8165 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!")((PN->getParent() == Header && "Can't evaluate PHI not in loop header!"
) ? static_cast<void> (0) : __assert_fail ("PN->getParent() == Header && \"Can't evaluate PHI not in loop header!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 8165, __PRETTY_FUNCTION__))
;
8166
8167 BasicBlock *Latch = L->getLoopLatch();
8168 if (!Latch)
8169 return nullptr;
8170
8171 for (PHINode &PHI : Header->phis()) {
8172 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8173 CurrentIterVals[&PHI] = StartCST;
8174 }
8175 if (!CurrentIterVals.count(PN))
8176 return RetVal = nullptr;
8177
8178 Value *BEValue = PN->getIncomingValueForBlock(Latch);
8179
8180 // Execute the loop symbolically to determine the exit value.
8181 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&((BEs.getActiveBits() < 8 * sizeof(unsigned) && "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"
) ? static_cast<void> (0) : __assert_fail ("BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && \"BEs is <= MaxBruteForceIterations which is an 'unsigned'!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 8182, __PRETTY_FUNCTION__))
8182 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!")((BEs.getActiveBits() < 8 * sizeof(unsigned) && "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"
) ? static_cast<void> (0) : __assert_fail ("BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && \"BEs is <= MaxBruteForceIterations which is an 'unsigned'!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 8182, __PRETTY_FUNCTION__))
;
8183
8184 unsigned NumIterations = BEs.getZExtValue(); // must be in range
8185 unsigned IterationNum = 0;
8186 const DataLayout &DL = getDataLayout();
8187 for (; ; ++IterationNum) {
8188 if (IterationNum == NumIterations)
8189 return RetVal = CurrentIterVals[PN]; // Got exit value!
8190
8191 // Compute the value of the PHIs for the next iteration.
8192 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
8193 DenseMap<Instruction *, Constant *> NextIterVals;
8194 Constant *NextPHI =
8195 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8196 if (!NextPHI)
8197 return nullptr; // Couldn't evaluate!
8198 NextIterVals[PN] = NextPHI;
8199
8200 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
8201
8202 // Also evaluate the other PHI nodes. However, we don't get to stop if we
8203 // cease to be able to evaluate one of them or if they stop evolving,
8204 // because that doesn't necessarily prevent us from computing PN.
8205 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
8206 for (const auto &I : CurrentIterVals) {
8207 PHINode *PHI = dyn_cast<PHINode>(I.first);
8208 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
8209 PHIsToCompute.emplace_back(PHI, I.second);
8210 }
8211 // We use two distinct loops because EvaluateExpression may invalidate any
8212 // iterators into CurrentIterVals.
8213 for (const auto &I : PHIsToCompute) {
8214 PHINode *PHI = I.first;
8215 Constant *&NextPHI = NextIterVals[PHI];
8216 if (!NextPHI) { // Not already computed.
8217 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8218 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8219 }
8220 if (NextPHI != I.second)
8221 StoppedEvolving = false;
8222 }
8223
8224 // If all entries in CurrentIterVals == NextIterVals then we can stop
8225 // iterating, the loop can't continue to change.
8226 if (StoppedEvolving)
8227 return RetVal = CurrentIterVals[PN];
8228
8229 CurrentIterVals.swap(NextIterVals);
8230 }
8231}
8232
8233const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
8234 Value *Cond,
8235 bool ExitWhen) {
8236 PHINode *PN = getConstantEvolvingPHI(Cond, L);
8237 if (!PN) return getCouldNotCompute();
8238
8239 // If the loop is canonicalized, the PHI will have exactly two entries.
8240 // That's the only form we support here.
8241 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
8242
8243 DenseMap<Instruction *, Constant *> CurrentIterVals;
8244 BasicBlock *Header = L->getHeader();
8245 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!")((PN->getParent() == Header && "Can't evaluate PHI not in loop header!"
) ? static_cast<void> (0) : __assert_fail ("PN->getParent() == Header && \"Can't evaluate PHI not in loop header!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 8245, __PRETTY_FUNCTION__))
;
8246
8247 BasicBlock *Latch = L->getLoopLatch();
8248 assert(Latch && "Should follow from NumIncomingValues == 2!")((Latch && "Should follow from NumIncomingValues == 2!"
) ? static_cast<void> (0) : __assert_fail ("Latch && \"Should follow from NumIncomingValues == 2!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 8248, __PRETTY_FUNCTION__))
;
8249
8250 for (PHINode &PHI : Header->phis()) {
8251 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
8252 CurrentIterVals[&PHI] = StartCST;
8253 }
8254 if (!CurrentIterVals.count(PN))
8255 return getCouldNotCompute();
8256
8257 // Okay, we find a PHI node that defines the trip count of this loop. Execute
8258 // the loop symbolically to determine when the condition gets a value of
8259 // "ExitWhen".
8260 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
8261 const DataLayout &DL = getDataLayout();
8262 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
8263 auto *CondVal = dyn_cast_or_null<ConstantInt>(
8264 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
8265
8266 // Couldn't symbolically evaluate.
8267 if (!CondVal) return getCouldNotCompute();
8268
8269 if (CondVal->getValue() == uint64_t(ExitWhen)) {
8270 ++NumBruteForceTripCountsComputed;
8271 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
8272 }
8273
8274 // Update all the PHI nodes for the next iteration.
8275 DenseMap<Instruction *, Constant *> NextIterVals;
8276
8277 // Create a list of which PHIs we need to compute. We want to do this before
8278 // calling EvaluateExpression on them because that may invalidate iterators
8279 // into CurrentIterVals.
8280 SmallVector<PHINode *, 8> PHIsToCompute;
8281 for (const auto &I : CurrentIterVals) {
8282 PHINode *PHI = dyn_cast<PHINode>(I.first);
8283 if (!PHI || PHI->getParent() != Header) continue;
8284 PHIsToCompute.push_back(PHI);
8285 }
8286 for (PHINode *PHI : PHIsToCompute) {
8287 Constant *&NextPHI = NextIterVals[PHI];
8288 if (NextPHI) continue; // Already computed!
8289
8290 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
8291 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8292 }
8293 CurrentIterVals.swap(NextIterVals);
8294 }
8295
8296 // Too many iterations were needed to evaluate.
8297 return getCouldNotCompute();
8298}
8299
8300const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
8301 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
8302 ValuesAtScopes[V];
8303 // Check to see if we've folded this expression at this loop before.
8304 for (auto &LS : Values)
8305 if (LS.first == L)
8306 return LS.second ? LS.second : V;
8307
8308 Values.emplace_back(L, nullptr);
8309
8310 // Otherwise compute it.
8311 const SCEV *C = computeSCEVAtScope(V, L);
8312 for (auto &LS : reverse(ValuesAtScopes[V]))
8313 if (LS.first == L) {
8314 LS.second = C;
8315 break;
8316 }
8317 return C;
8318}
8319
8320/// This builds up a Constant using the ConstantExpr interface. That way, we
8321/// will return Constants for objects which aren't represented by a
8322/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8323/// Returns NULL if the SCEV isn't representable as a Constant.
8324static Constant *BuildConstantFromSCEV(const SCEV *V) {
8325 switch (V->getSCEVType()) {
8326 case scCouldNotCompute:
8327 case scAddRecExpr:
8328 return nullptr;
8329 case scConstant:
8330 return cast<SCEVConstant>(V)->getValue();
8331 case scUnknown:
8332 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8333 case scSignExtend: {
8334 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8335 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8336 return ConstantExpr::getSExt(CastOp, SS->getType());
8337 return nullptr;
8338 }
8339 case scZeroExtend: {
8340 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8341 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8342 return ConstantExpr::getZExt(CastOp, SZ->getType());
8343 return nullptr;
8344 }
8345 case scPtrToInt: {
8346 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
8347 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
8348 return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
8349
8350 return nullptr;
8351 }
8352 case scTruncate: {
8353 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8354 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8355 return ConstantExpr::getTrunc(CastOp, ST->getType());
8356 return nullptr;
8357 }
8358 case scAddExpr: {
8359 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8360 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8361 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8362 unsigned AS = PTy->getAddressSpace();
8363 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8364 C = ConstantExpr::getBitCast(C, DestPtrTy);
8365 }
8366 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8367 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8368 if (!C2)
8369 return nullptr;
8370
8371 // First pointer!
8372 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8373 unsigned AS = C2->getType()->getPointerAddressSpace();
8374 std::swap(C, C2);
8375 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8376 // The offsets have been converted to bytes. We can add bytes to an
8377 // i8* by GEP with the byte count in the first index.
8378 C = ConstantExpr::getBitCast(C, DestPtrTy);
8379 }
8380
8381 // Don't bother trying to sum two pointers. We probably can't
8382 // statically compute a load that results from it anyway.
8383 if (C2->getType()->isPointerTy())
8384 return nullptr;
8385
8386 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8387 if (PTy->getElementType()->isStructTy())
8388 C2 = ConstantExpr::getIntegerCast(
8389 C2, Type::getInt32Ty(C->getContext()), true);
8390 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8391 } else
8392 C = ConstantExpr::getAdd(C, C2);
8393 }
8394 return C;
8395 }
8396 return nullptr;
8397 }
8398 case scMulExpr: {
8399 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8400 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8401 // Don't bother with pointers at all.
8402 if (C->getType()->isPointerTy())
8403 return nullptr;
8404 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8405 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8406 if (!C2 || C2->getType()->isPointerTy())
8407 return nullptr;
8408 C = ConstantExpr::getMul(C, C2);
8409 }
8410 return C;
8411 }
8412 return nullptr;
8413 }
8414 case scUDivExpr: {
8415 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8416 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8417 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8418 if (LHS->getType() == RHS->getType())
8419 return ConstantExpr::getUDiv(LHS, RHS);
8420 return nullptr;
8421 }
8422 case scSMaxExpr:
8423 case scUMaxExpr:
8424 case scSMinExpr:
8425 case scUMinExpr:
8426 return nullptr; // TODO: smax, umax, smin, umax.
8427 }
8428 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 8428)
;
8429}
8430
8431const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8432 if (isa<SCEVConstant>(V)) return V;
8433
8434 // If this instruction is evolved from a constant-evolving PHI, compute the
8435 // exit value from the loop without using SCEVs.
8436 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8437 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8438 if (PHINode *PN = dyn_cast<PHINode>(I)) {
8439 const Loop *CurrLoop = this->LI[I->getParent()];
8440 // Looking for loop exit value.
8441 if (CurrLoop && CurrLoop->getParentLoop() == L &&
8442 PN->getParent() == CurrLoop->getHeader()) {
8443 // Okay, there is no closed form solution for the PHI node. Check
8444 // to see if the loop that contains it has a known backedge-taken
8445 // count. If so, we may be able to force computation of the exit
8446 // value.
8447 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
8448 // This trivial case can show up in some degenerate cases where
8449 // the incoming IR has not yet been fully simplified.
8450 if (BackedgeTakenCount->isZero()) {
8451 Value *InitValue = nullptr;
8452 bool MultipleInitValues = false;
8453 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8454 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
8455 if (!InitValue)
8456 InitValue = PN->getIncomingValue(i);
8457 else if (InitValue != PN->getIncomingValue(i)) {
8458 MultipleInitValues = true;
8459 break;
8460 }
8461 }
8462 }
8463 if (!MultipleInitValues && InitValue)
8464 return getSCEV(InitValue);
8465 }
8466 // Do we have a loop invariant value flowing around the backedge
8467 // for a loop which must execute the backedge?
8468 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
8469 isKnownPositive(BackedgeTakenCount) &&
8470 PN->getNumIncomingValues() == 2) {
8471
8472 unsigned InLoopPred =
8473 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
8474 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
8475 if (CurrLoop->isLoopInvariant(BackedgeVal))
8476 return getSCEV(BackedgeVal);
8477 }
8478 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8479 // Okay, we know how many times the containing loop executes. If
8480 // this is a constant evolving PHI node, get the final value at
8481 // the specified iteration number.
8482 Constant *RV = getConstantEvolutionLoopExitValue(
8483 PN, BTCC->getAPInt(), CurrLoop);
8484 if (RV) return getSCEV(RV);
8485 }
8486 }
8487
8488 // If there is a single-input Phi, evaluate it at our scope. If we can
8489 // prove that this replacement does not break LCSSA form, use new value.
8490 if (PN->getNumOperands() == 1) {
8491 const SCEV *Input = getSCEV(PN->getOperand(0));
8492 const SCEV *InputAtScope = getSCEVAtScope(Input, L);
8493 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
8494 // for the simplest case just support constants.
8495 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
8496 }
8497 }
8498
8499 // Okay, this is an expression that we cannot symbolically evaluate
8500 // into a SCEV. Check to see if it's possible to symbolically evaluate
8501 // the arguments into constants, and if so, try to constant propagate the
8502 // result. This is particularly useful for computing loop exit values.
8503 if (CanConstantFold(I)) {
8504 SmallVector<Constant *, 4> Operands;
8505 bool MadeImprovement = false;
8506 for (Value *Op : I->operands()) {
8507 if (Constant *C = dyn_cast<Constant>(Op)) {
8508 Operands.push_back(C);
8509 continue;
8510 }
8511
8512 // If any of the operands is non-constant and if they are
8513 // non-integer and non-pointer, don't even try to analyze them
8514 // with scev techniques.
8515 if (!isSCEVable(Op->getType()))
8516 return V;
8517
8518 const SCEV *OrigV = getSCEV(Op);
8519 const SCEV *OpV = getSCEVAtScope(OrigV, L);
8520 MadeImprovement |= OrigV != OpV;
8521
8522 Constant *C = BuildConstantFromSCEV(OpV);
8523 if (!C) return V;
8524 if (C->getType() != Op->getType())
8525 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8526 Op->getType(),
8527 false),
8528 C, Op->getType());
8529 Operands.push_back(C);
8530 }
8531
8532 // Check to see if getSCEVAtScope actually made an improvement.
8533 if (MadeImprovement) {
8534 Constant *C = nullptr;
8535 const DataLayout &DL = getDataLayout();
8536 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8537 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8538 Operands[1], DL, &TLI);
8539 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) {
8540 if (!Load->isVolatile())
8541 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(),
8542 DL);
8543 } else
8544 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8545 if (!C) return V;
8546 return getSCEV(C);
8547 }
8548 }
8549 }
8550
8551 // This is some other type of SCEVUnknown, just return it.
8552 return V;
8553 }
8554
8555 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8556 // Avoid performing the look-up in the common case where the specified
8557 // expression has no loop-variant portions.
8558 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8559 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8560 if (OpAtScope != Comm->getOperand(i)) {
8561 // Okay, at least one of these operands is loop variant but might be
8562 // foldable. Build a new instance of the folded commutative expression.
8563 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8564 Comm->op_begin()+i);
8565 NewOps.push_back(OpAtScope);
8566
8567 for (++i; i != e; ++i) {
8568 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8569 NewOps.push_back(OpAtScope);
8570 }
8571 if (isa<SCEVAddExpr>(Comm))
8572 return getAddExpr(NewOps, Comm->getNoWrapFlags());
8573 if (isa<SCEVMulExpr>(Comm))
8574 return getMulExpr(NewOps, Comm->getNoWrapFlags());
8575 if (isa<SCEVMinMaxExpr>(Comm))
8576 return getMinMaxExpr(Comm->getSCEVType(), NewOps);
8577 llvm_unreachable("Unknown commutative SCEV type!")::llvm::llvm_unreachable_internal("Unknown commutative SCEV type!"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 8577)
;
8578 }
8579 }
8580 // If we got here, all operands are loop invariant.
8581 return Comm;
8582 }
8583
8584 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8585 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8586 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8587 if (LHS == Div->getLHS() && RHS == Div->getRHS())
8588 return Div; // must be loop invariant
8589 return getUDivExpr(LHS, RHS);
8590 }
8591
8592 // If this is a loop recurrence for a loop that does not contain L, then we
8593 // are dealing with the final value computed by the loop.
8594 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8595 // First, attempt to evaluate each operand.
8596 // Avoid performing the look-up in the common case where the specified
8597 // expression has no loop-variant portions.
8598 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8599 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8600 if (OpAtScope == AddRec->getOperand(i))
8601 continue;
8602
8603 // Okay, at least one of these operands is loop variant but might be
8604 // foldable. Build a new instance of the folded commutative expression.
8605 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8606 AddRec->op_begin()+i);
8607 NewOps.push_back(OpAtScope);
8608 for (++i; i != e; ++i)
8609 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8610
8611 const SCEV *FoldedRec =
8612 getAddRecExpr(NewOps, AddRec->getLoop(),
8613 AddRec->getNoWrapFlags(SCEV::FlagNW));
8614 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8615 // The addrec may be folded to a nonrecurrence, for example, if the
8616 // induction variable is multiplied by zero after constant folding. Go
8617 // ahead and return the folded value.
8618 if (!AddRec)
8619 return FoldedRec;
8620 break;
8621 }
8622
8623 // If the scope is outside the addrec's loop, evaluate it by using the
8624 // loop exit value of the addrec.
8625 if (!AddRec->getLoop()->contains(L)) {
8626 // To evaluate this recurrence, we need to know how many times the AddRec
8627 // loop iterates. Compute this now.
8628 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8629 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8630
8631 // Then, evaluate the AddRec.
8632 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8633 }
8634
8635 return AddRec;
8636 }
8637
8638 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8639 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8640 if (Op == Cast->getOperand())
8641 return Cast; // must be loop invariant
8642 return getZeroExtendExpr(Op, Cast->getType());
8643 }
8644
8645 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8646 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8647 if (Op == Cast->getOperand())
8648 return Cast; // must be loop invariant
8649 return getSignExtendExpr(Op, Cast->getType());
8650 }
8651
8652 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8653 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8654 if (Op == Cast->getOperand())
8655 return Cast; // must be loop invariant
8656 return getTruncateExpr(Op, Cast->getType());
8657 }
8658
8659 if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) {
8660 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8661 if (Op == Cast->getOperand())
8662 return Cast; // must be loop invariant
8663 return getPtrToIntExpr(Op, Cast->getType());
8664 }
8665
8666 llvm_unreachable("Unknown SCEV type!")::llvm::llvm_unreachable_internal("Unknown SCEV type!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 8666)
;
8667}
8668
8669const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8670 return getSCEVAtScope(getSCEV(V), L);
8671}
8672
8673const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
8674 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
8675 return stripInjectiveFunctions(ZExt->getOperand());
8676 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
8677 return stripInjectiveFunctions(SExt->getOperand());
8678 return S;
8679}
8680
8681/// Finds the minimum unsigned root of the following equation:
8682///
8683/// A * X = B (mod N)
8684///
8685/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8686/// A and B isn't important.
8687///
8688/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8689static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8690 ScalarEvolution &SE) {
8691 uint32_t BW = A.getBitWidth();
8692 assert(BW == SE.getTypeSizeInBits(B->getType()))((BW == SE.getTypeSizeInBits(B->getType())) ? static_cast<
void> (0) : __assert_fail ("BW == SE.getTypeSizeInBits(B->getType())"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 8692, __PRETTY_FUNCTION__))
;
8693 assert(A != 0 && "A must be non-zero.")((A != 0 && "A must be non-zero.") ? static_cast<void
> (0) : __assert_fail ("A != 0 && \"A must be non-zero.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 8693, __PRETTY_FUNCTION__))
;
8694
8695 // 1. D = gcd(A, N)
8696 //
8697 // The gcd of A and N may have only one prime factor: 2. The number of
8698 // trailing zeros in A is its multiplicity
8699 uint32_t Mult2 = A.countTrailingZeros();
8700 // D = 2^Mult2
8701
8702 // 2. Check if B is divisible by D.
8703 //
8704 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8705 // is not less than multiplicity of this prime factor for D.
8706 if (SE.GetMinTrailingZeros(B) < Mult2)
8707 return SE.getCouldNotCompute();
8708
8709 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8710 // modulo (N / D).
8711 //
8712 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8713 // (N / D) in general. The inverse itself always fits into BW bits, though,
8714 // so we immediately truncate it.
8715 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
8716 APInt Mod(BW + 1, 0);
8717 Mod.setBit(BW - Mult2); // Mod = N / D
8718 APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8719
8720 // 4. Compute the minimum unsigned root of the equation:
8721 // I * (B / D) mod (N / D)
8722 // To simplify the computation, we factor out the divide by D:
8723 // (I * B mod N) / D
8724 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8725 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8726}
8727
8728/// For a given quadratic addrec, generate coefficients of the corresponding
8729/// quadratic equation, multiplied by a common value to ensure that they are
8730/// integers.
8731/// The returned value is a tuple { A, B, C, M, BitWidth }, where
8732/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
8733/// were multiplied by, and BitWidth is the bit width of the original addrec
8734/// coefficients.
8735/// This function returns None if the addrec coefficients are not compile-
8736/// time constants.
8737static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
8738GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
8739 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!")((AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"
) ? static_cast<void> (0) : __assert_fail ("AddRec->getNumOperands() == 3 && \"This is not a quadratic chrec!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 8739, __PRETTY_FUNCTION__))
;
8740 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8741 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8742 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8743 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << __func__ << ": analyzing quadratic addrec: "
<< *AddRec << '\n'; } } while (false)
8744 << *AddRec << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << __func__ << ": analyzing quadratic addrec: "
<< *AddRec << '\n'; } } while (false)
;
8745
8746 // We currently can only solve this if the coefficients are constants.
8747 if (!LC || !MC || !NC) {
8748 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)
;
8749 return None;
8750 }
8751
8752 APInt L = LC->getAPInt();
8753 APInt M = MC->getAPInt();
8754 APInt N = NC->getAPInt();
8755 assert(!N.isNullValue() && "This is not a quadratic addrec")((!N.isNullValue() && "This is not a quadratic addrec"
) ? static_cast<void> (0) : __assert_fail ("!N.isNullValue() && \"This is not a quadratic addrec\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 8755, __PRETTY_FUNCTION__))
;
8756
8757 unsigned BitWidth = LC->getAPInt().getBitWidth();
8758 unsigned NewWidth = BitWidth + 1;
8759 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << __func__ << ": addrec coeff bw: "
<< BitWidth << '\n'; } } while (false)
8760 << BitWidth << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << __func__ << ": addrec coeff bw: "
<< BitWidth << '\n'; } } while (false)
;
8761 // The sign-extension (as opposed to a zero-extension) here matches the
8762 // extension used in SolveQuadraticEquationWrap (with the same motivation).
8763 N = N.sext(NewWidth);
8764 M = M.sext(NewWidth);
8765 L = L.sext(NewWidth);
8766
8767 // The increments are M, M+N, M+2N, ..., so the accumulated values are
8768 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
8769 // L+M, L+2M+N, L+3M+3N, ...
8770 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
8771 //
8772 // The equation Acc = 0 is then
8773 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
8774 // In a quadratic form it becomes:
8775 // N n^2 + (2M-N) n + 2L = 0.
8776
8777 APInt A = N;
8778 APInt B = 2 * M - A;
8779 APInt C = 2 * L;
8780 APInt T = APInt(NewWidth, 2);
8781 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)
8782 << "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)
8783 << ", 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)
;
8784 return std::make_tuple(A, B, C, T, BitWidth);
8785}
8786
8787/// Helper function to compare optional APInts:
8788/// (a) if X and Y both exist, return min(X, Y),
8789/// (b) if neither X nor Y exist, return None,
8790/// (c) if exactly one of X and Y exists, return that value.
8791static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
8792 if (X.hasValue() && Y.hasValue()) {
8793 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
8794 APInt XW = X->sextOrSelf(W);
8795 APInt YW = Y->sextOrSelf(W);
8796 return XW.slt(YW) ? *X : *Y;
8797 }
8798 if (!X.hasValue() && !Y.hasValue())
8799 return None;
8800 return X.hasValue() ? *X : *Y;
8801}
8802
8803/// Helper function to truncate an optional APInt to a given BitWidth.
8804/// When solving addrec-related equations, it is preferable to return a value
8805/// that has the same bit width as the original addrec's coefficients. If the
8806/// solution fits in the original bit width, truncate it (except for i1).
8807/// Returning a value of a different bit width may inhibit some optimizations.
8808///
8809/// In general, a solution to a quadratic equation generated from an addrec
8810/// may require BW+1 bits, where BW is the bit width of the addrec's
8811/// coefficients. The reason is that the coefficients of the quadratic
8812/// equation are BW+1 bits wide (to avoid truncation when converting from
8813/// the addrec to the equation).
8814static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
8815 if (!X.hasValue())
8816 return None;
8817 unsigned W = X->getBitWidth();
8818 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
8819 return X->trunc(BitWidth);
8820 return X;
8821}
8822
8823/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
8824/// iterations. The values L, M, N are assumed to be signed, and they
8825/// should all have the same bit widths.
8826/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
8827/// where BW is the bit width of the addrec's coefficients.
8828/// If the calculated value is a BW-bit integer (for BW > 1), it will be
8829/// returned as such, otherwise the bit width of the returned value may
8830/// be greater than BW.
8831///
8832/// This function returns None if
8833/// (a) the addrec coefficients are not constant, or
8834/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
8835/// like x^2 = 5, no integer solutions exist, in other cases an integer
8836/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
8837static Optional<APInt>
8838SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8839 APInt A, B, C, M;
8840 unsigned BitWidth;
8841 auto T = GetQuadraticEquation(AddRec);
8842 if (!T.hasValue())
8843 return None;
8844
8845 std::tie(A, B, C, M, BitWidth) = *T;
8846 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)
;
8847 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
8848 if (!X.hasValue())
8849 return None;
8850
8851 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
8852 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
8853 if (!V->isZero())
8854 return None;
8855
8856 return TruncIfPossible(X, BitWidth);
8857}
8858
8859/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
8860/// iterations. The values M, N are assumed to be signed, and they
8861/// should all have the same bit widths.
8862/// Find the least n such that c(n) does not belong to the given range,
8863/// while c(n-1) does.
8864///
8865/// This function returns None if
8866/// (a) the addrec coefficients are not constant, or
8867/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
8868/// bounds of the range.
8869static Optional<APInt>
8870SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
8871 const ConstantRange &Range, ScalarEvolution &SE) {
8872 assert(AddRec->getOperand(0)->isZero() &&((AddRec->getOperand(0)->isZero() && "Starting value of addrec should be 0"
) ? static_cast<void> (0) : __assert_fail ("AddRec->getOperand(0)->isZero() && \"Starting value of addrec should be 0\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 8873, __PRETTY_FUNCTION__))
8873 "Starting value of addrec should be 0")((AddRec->getOperand(0)->isZero() && "Starting value of addrec should be 0"
) ? static_cast<void> (0) : __assert_fail ("AddRec->getOperand(0)->isZero() && \"Starting value of addrec should be 0\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 8873, __PRETTY_FUNCTION__))
;
8874 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)
8875 << 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)
;
8876 // This case is handled in getNumIterationsInRange. Here we can assume that
8877 // we start in the range.
8878 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&((Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType
()), 0)) && "Addrec's initial value should be in range"
) ? static_cast<void> (0) : __assert_fail ("Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && \"Addrec's initial value should be in range\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 8879, __PRETTY_FUNCTION__))
8879 "Addrec's initial value should be in range")((Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType
()), 0)) && "Addrec's initial value should be in range"
) ? static_cast<void> (0) : __assert_fail ("Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && \"Addrec's initial value should be in range\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 8879, __PRETTY_FUNCTION__))
;
8880
8881 APInt A, B, C, M;
8882 unsigned BitWidth;
8883 auto T = GetQuadraticEquation(AddRec);
8884 if (!T.hasValue())
8885 return None;
8886
8887 // Be careful about the return value: there can be two reasons for not
8888 // returning an actual number. First, if no solutions to the equations
8889 // were found, and second, if the solutions don't leave the given range.
8890 // The first case means that the actual solution is "unknown", the second
8891 // means that it's known, but not valid. If the solution is unknown, we
8892 // cannot make any conclusions.
8893 // Return a pair: the optional solution and a flag indicating if the
8894 // solution was found.
8895 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
8896 // Solve for signed overflow and unsigned overflow, pick the lower
8897 // solution.
8898 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)
8899 << 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)
;
8900 Bound *= M; // The quadratic equation multiplier.
8901
8902 Optional<APInt> SO = None;
8903 if (BitWidth > 1) {
8904 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "SolveQuadraticAddRecRange: solving for "
"signed overflow\n"; } } while (false)
8905 "signed overflow\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "SolveQuadraticAddRecRange: solving for "
"signed overflow\n"; } } while (false)
;
8906 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
8907 }
8908 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "SolveQuadraticAddRecRange: solving for "
"unsigned overflow\n"; } } while (false)
8909 "unsigned overflow\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { dbgs() << "SolveQuadraticAddRecRange: solving for "
"unsigned overflow\n"; } } while (false)
;
8910 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
8911 BitWidth+1);
8912
8913 auto LeavesRange = [&] (const APInt &X) {
8914 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
8915 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
8916 if (Range.contains(V0->getValue()))
8917 return false;
8918 // X should be at least 1, so X-1 is non-negative.
8919 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
8920 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
8921 if (Range.contains(V1->getValue()))
8922 return true;
8923 return false;
8924 };
8925
8926 // If SolveQuadraticEquationWrap returns None, it means that there can
8927 // be a solution, but the function failed to find it. We cannot treat it
8928 // as "no solution".
8929 if (!SO.hasValue() || !UO.hasValue())
8930 return { None, false };
8931
8932 // Check the smaller value first to see if it leaves the range.
8933 // At this point, both SO and UO must have values.
8934 Optional<APInt> Min = MinOptional(SO, UO);
8935 if (LeavesRange(*Min))
8936 return { Min, true };
8937 Optional<APInt> Max = Min == SO ? UO : SO;
8938 if (LeavesRange(*Max))
8939 return { Max, true };
8940
8941 // Solutions were found, but were eliminated, hence the "true".
8942 return { None, true };
8943 };
8944
8945 std::tie(A, B, C, M, BitWidth) = *T;
8946 // Lower bound is inclusive, subtract 1 to represent the exiting value.
8947 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
8948 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
8949 auto SL = SolveForBoundary(Lower);
8950 auto SU = SolveForBoundary(Upper);
8951 // If any of the solutions was unknown, no meaninigful conclusions can
8952 // be made.
8953 if (!SL.second || !SU.second)
8954 return None;
8955
8956 // Claim: The correct solution is not some value between Min and Max.
8957 //
8958 // Justification: Assuming that Min and Max are different values, one of
8959 // them is when the first signed overflow happens, the other is when the
8960 // first unsigned overflow happens. Crossing the range boundary is only
8961 // possible via an overflow (treating 0 as a special case of it, modeling
8962 // an overflow as crossing k*2^W for some k).
8963 //
8964 // The interesting case here is when Min was eliminated as an invalid
8965 // solution, but Max was not. The argument is that if there was another
8966 // overflow between Min and Max, it would also have been eliminated if
8967 // it was considered.
8968 //
8969 // For a given boundary, it is possible to have two overflows of the same
8970 // type (signed/unsigned) without having the other type in between: this
8971 // can happen when the vertex of the parabola is between the iterations
8972 // corresponding to the overflows. This is only possible when the two
8973 // overflows cross k*2^W for the same k. In such case, if the second one
8974 // left the range (and was the first one to do so), the first overflow
8975 // would have to enter the range, which would mean that either we had left
8976 // the range before or that we started outside of it. Both of these cases
8977 // are contradictions.
8978 //
8979 // Claim: In the case where SolveForBoundary returns None, the correct
8980 // solution is not some value between the Max for this boundary and the
8981 // Min of the other boundary.
8982 //
8983 // Justification: Assume that we had such Max_A and Min_B corresponding
8984 // to range boundaries A and B and such that Max_A < Min_B. If there was
8985 // a solution between Max_A and Min_B, it would have to be caused by an
8986 // overflow corresponding to either A or B. It cannot correspond to B,
8987 // since Min_B is the first occurrence of such an overflow. If it
8988 // corresponded to A, it would have to be either a signed or an unsigned
8989 // overflow that is larger than both eliminated overflows for A. But
8990 // between the eliminated overflows and this overflow, the values would
8991 // cover the entire value space, thus crossing the other boundary, which
8992 // is a contradiction.
8993
8994 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
8995}
8996
8997ScalarEvolution::ExitLimit
8998ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
8999 bool AllowPredicates) {
9000
9001 // This is only used for loops with a "x != y" exit test. The exit condition
9002 // is now expressed as a single expression, V = x-y. So the exit test is
9003 // effectively V != 0. We know and take advantage of the fact that this
9004 // expression only being used in a comparison by zero context.
9005
9006 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
9007 // If the value is a constant
9008 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9009 // If the value is already zero, the branch will execute zero times.
9010 if (C->getValue()->isZero()) return C;
9011 return getCouldNotCompute(); // Otherwise it will loop infinitely.
9012 }
9013
9014 const SCEVAddRecExpr *AddRec =
9015 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
9016
9017 if (!AddRec && AllowPredicates)
9018 // Try to make this an AddRec using runtime tests, in the first X
9019 // iterations of this loop, where X is the SCEV expression found by the
9020 // algorithm below.
9021 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
9022
9023 if (!AddRec || AddRec->getLoop() != L)
9024 return getCouldNotCompute();
9025
9026 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
9027 // the quadratic equation to solve it.
9028 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
9029 // We can only use this value if the chrec ends up with an exact zero
9030 // value at this index. When solving for "X*X != 5", for example, we
9031 // should not accept a root of 2.
9032 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
9033 const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
9034 return ExitLimit(R, R, false, Predicates);
9035 }
9036 return getCouldNotCompute();
9037 }
9038
9039 // Otherwise we can only handle this if it is affine.
9040 if (!AddRec->isAffine())
9041 return getCouldNotCompute();
9042
9043 // If this is an affine expression, the execution count of this branch is
9044 // the minimum unsigned root of the following equation:
9045 //
9046 // Start + Step*N = 0 (mod 2^BW)
9047 //
9048 // equivalent to:
9049 //
9050 // Step*N = -Start (mod 2^BW)
9051 //
9052 // where BW is the common bit width of Start and Step.
9053
9054 // Get the initial value for the loop.
9055 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
9056 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
9057
9058 // For now we handle only constant steps.
9059 //
9060 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
9061 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
9062 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
9063 // We have not yet seen any such cases.
9064 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
9065 if (!StepC || StepC->getValue()->isZero())
9066 return getCouldNotCompute();
9067
9068 // For positive steps (counting up until unsigned overflow):
9069 // N = -Start/Step (as unsigned)
9070 // For negative steps (counting down to zero):
9071 // N = Start/-Step
9072 // First compute the unsigned distance from zero in the direction of Step.
9073 bool CountDown = StepC->getAPInt().isNegative();
9074 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
9075
9076 // Handle unitary steps, which cannot wraparound.
9077 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
9078 // N = Distance (as unsigned)
9079 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
9080 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
9081 APInt MaxBECountBase = getUnsignedRangeMax(Distance);
9082 if (MaxBECountBase.ult(MaxBECount))
9083 MaxBECount = MaxBECountBase;
9084
9085 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
9086 // we end up with a loop whose backedge-taken count is n - 1. Detect this
9087 // case, and see if we can improve the bound.
9088 //
9089 // Explicitly handling this here is necessary because getUnsignedRange
9090 // isn't context-sensitive; it doesn't know that we only care about the
9091 // range inside the loop.
9092 const SCEV *Zero = getZero(Distance->getType());
9093 const SCEV *One = getOne(Distance->getType());
9094 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
9095 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
9096 // If Distance + 1 doesn't overflow, we can compute the maximum distance
9097 // as "unsigned_max(Distance + 1) - 1".
9098 ConstantRange CR = getUnsignedRange(DistancePlusOne);
9099 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
9100 }
9101 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
9102 }
9103
9104 // If the condition controls loop exit (the loop exits only if the expression
9105 // is true) and the addition is no-wrap we can use unsigned divide to
9106 // compute the backedge count. In this case, the step may not divide the
9107 // distance, but we don't care because if the condition is "missed" the loop
9108 // will have undefined behavior due to wrapping.
9109 if (ControlsExit && AddRec->hasNoSelfWrap() &&
9110 loopHasNoAbnormalExits(AddRec->getLoop())) {
9111 const SCEV *Exact =
9112 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
9113 const SCEV *Max =
9114 Exact == getCouldNotCompute()
9115 ? Exact
9116 : getConstant(getUnsignedRangeMax(Exact));
9117 return ExitLimit(Exact, Max, false, Predicates);
9118 }
9119
9120 // Solve the general equation.
9121 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
9122 getNegativeSCEV(Start), *this);
9123 const SCEV *M = E == getCouldNotCompute()
9124 ? E
9125 : getConstant(getUnsignedRangeMax(E));
9126 return ExitLimit(E, M, false, Predicates);
9127}
9128
9129ScalarEvolution::ExitLimit
9130ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
9131 // Loops that look like: while (X == 0) are very strange indeed. We don't
9132 // handle them yet except for the trivial case. This could be expanded in the
9133 // future as needed.
9134
9135 // If the value is a constant, check to see if it is known to be non-zero
9136 // already. If so, the backedge will execute zero times.
9137 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
9138 if (!C->getValue()->isZero())
9139 return getZero(C->getType());
9140 return getCouldNotCompute(); // Otherwise it will loop infinitely.
9141 }
9142
9143 // We could implement others, but I really doubt anyone writes loops like
9144 // this, and if they did, they would already be constant folded.
9145 return getCouldNotCompute();
9146}
9147
9148std::pair<const BasicBlock *, const BasicBlock *>
9149ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
9150 const {
9151 // If the block has a unique predecessor, then there is no path from the
9152 // predecessor to the block that does not go through the direct edge
9153 // from the predecessor to the block.
9154 if (const BasicBlock *Pred = BB->getSinglePredecessor())
9155 return {Pred, BB};
9156
9157 // A loop's header is defined to be a block that dominates the loop.
9158 // If the header has a unique predecessor outside the loop, it must be
9159 // a block that has exactly one successor that can reach the loop.
9160 if (const Loop *L = LI.getLoopFor(BB))
9161 return {L->getLoopPredecessor(), L->getHeader()};
9162
9163 return {nullptr, nullptr};
9164}
9165
9166/// SCEV structural equivalence is usually sufficient for testing whether two
9167/// expressions are equal, however for the purposes of looking for a condition
9168/// guarding a loop, it can be useful to be a little more general, since a
9169/// front-end may have replicated the controlling expression.
9170static bool HasSameValue(const SCEV *A, const SCEV *B) {
9171 // Quick check to see if they are the same SCEV.
9172 if (A == B) return true;
9173
9174 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
9175 // Not all instructions that are "identical" compute the same value. For
9176 // instance, two distinct alloca instructions allocating the same type are
9177 // identical and do not read memory; but compute distinct values.
9178 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
9179 };
9180
9181 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
9182 // two different instructions with the same value. Check for this case.
9183 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
9184 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
9185 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
9186 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
9187 if (ComputesEqualValues(AI, BI))
9188 return true;
9189
9190 // Otherwise assume they may have a different value.
9191 return false;
9192}
9193
9194bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
9195 const SCEV *&LHS, const SCEV *&RHS,
9196 unsigned Depth) {
9197 bool Changed = false;
9198 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
9199 // '0 != 0'.
9200 auto TrivialCase = [&](bool TriviallyTrue) {
9201 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
9202 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9203 return true;
9204 };
9205 // If we hit the max recursion limit bail out.
9206 if (Depth >= 3)
9207 return false;
9208
9209 // Canonicalize a constant to the right side.
9210 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
9211 // Check for both operands constant.
9212 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
9213 if (ConstantExpr::getICmp(Pred,
9214 LHSC->getValue(),
9215 RHSC->getValue())->isNullValue())
9216 return TrivialCase(false);
9217 else
9218 return TrivialCase(true);
9219 }
9220 // Otherwise swap the operands to put the constant on the right.
9221 std::swap(LHS, RHS);
9222 Pred = ICmpInst::getSwappedPredicate(Pred);
9223 Changed = true;
9224 }
9225
9226 // If we're comparing an addrec with a value which is loop-invariant in the
9227 // addrec's loop, put the addrec on the left. Also make a dominance check,
9228 // as both operands could be addrecs loop-invariant in each other's loop.
9229 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
9230 const Loop *L = AR->getLoop();
9231 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
9232 std::swap(LHS, RHS);
9233 Pred = ICmpInst::getSwappedPredicate(Pred);
9234 Changed = true;
9235 }
9236 }
9237
9238 // If there's a constant operand, canonicalize comparisons with boundary
9239 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
9240 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
9241 const APInt &RA = RC->getAPInt();
9242
9243 bool SimplifiedByConstantRange = false;
9244
9245 if (!ICmpInst::isEquality(Pred)) {
9246 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
9247 if (ExactCR.isFullSet())
9248 return TrivialCase(true);
9249 else if (ExactCR.isEmptySet())
9250 return TrivialCase(false);
9251
9252 APInt NewRHS;
9253 CmpInst::Predicate NewPred;
9254 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
9255 ICmpInst::isEquality(NewPred)) {
9256 // We were able to convert an inequality to an equality.
9257 Pred = NewPred;
9258 RHS = getConstant(NewRHS);
9259 Changed = SimplifiedByConstantRange = true;
9260 }
9261 }
9262
9263 if (!SimplifiedByConstantRange) {
9264 switch (Pred) {
9265 default:
9266 break;
9267 case ICmpInst::ICMP_EQ:
9268 case ICmpInst::ICMP_NE:
9269 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
9270 if (!RA)
9271 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
9272 if (const SCEVMulExpr *ME =
9273 dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
9274 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
9275 ME->getOperand(0)->isAllOnesValue()) {
9276 RHS = AE->getOperand(1);
9277 LHS = ME->getOperand(1);
9278 Changed = true;
9279 }
9280 break;
9281
9282
9283 // The "Should have been caught earlier!" messages refer to the fact
9284 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
9285 // should have fired on the corresponding cases, and canonicalized the
9286 // check to trivial case.
9287
9288 case ICmpInst::ICMP_UGE:
9289 assert(!RA.isMinValue() && "Should have been caught earlier!")((!RA.isMinValue() && "Should have been caught earlier!"
) ? static_cast<void> (0) : __assert_fail ("!RA.isMinValue() && \"Should have been caught earlier!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9289, __PRETTY_FUNCTION__))
;
9290 Pred = ICmpInst::ICMP_UGT;
9291 RHS = getConstant(RA - 1);
9292 Changed = true;
9293 break;
9294 case ICmpInst::ICMP_ULE:
9295 assert(!RA.isMaxValue() && "Should have been caught earlier!")((!RA.isMaxValue() && "Should have been caught earlier!"
) ? static_cast<void> (0) : __assert_fail ("!RA.isMaxValue() && \"Should have been caught earlier!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9295, __PRETTY_FUNCTION__))
;
9296 Pred = ICmpInst::ICMP_ULT;
9297 RHS = getConstant(RA + 1);
9298 Changed = true;
9299 break;
9300 case ICmpInst::ICMP_SGE:
9301 assert(!RA.isMinSignedValue() && "Should have been caught earlier!")((!RA.isMinSignedValue() && "Should have been caught earlier!"
) ? static_cast<void> (0) : __assert_fail ("!RA.isMinSignedValue() && \"Should have been caught earlier!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9301, __PRETTY_FUNCTION__))
;
9302 Pred = ICmpInst::ICMP_SGT;
9303 RHS = getConstant(RA - 1);
9304 Changed = true;
9305 break;
9306 case ICmpInst::ICMP_SLE:
9307 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!")((!RA.isMaxSignedValue() && "Should have been caught earlier!"
) ? static_cast<void> (0) : __assert_fail ("!RA.isMaxSignedValue() && \"Should have been caught earlier!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9307, __PRETTY_FUNCTION__))
;
9308 Pred = ICmpInst::ICMP_SLT;
9309 RHS = getConstant(RA + 1);
9310 Changed = true;
9311 break;
9312 }
9313 }
9314 }
9315
9316 // Check for obvious equality.
9317 if (HasSameValue(LHS, RHS)) {
9318 if (ICmpInst::isTrueWhenEqual(Pred))
9319 return TrivialCase(true);
9320 if (ICmpInst::isFalseWhenEqual(Pred))
9321 return TrivialCase(false);
9322 }
9323
9324 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9325 // adding or subtracting 1 from one of the operands.
9326 switch (Pred) {
9327 case ICmpInst::ICMP_SLE:
9328 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9329 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9330 SCEV::FlagNSW);
9331 Pred = ICmpInst::ICMP_SLT;
9332 Changed = true;
9333 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9334 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
9335 SCEV::FlagNSW);
9336 Pred = ICmpInst::ICMP_SLT;
9337 Changed = true;
9338 }
9339 break;
9340 case ICmpInst::ICMP_SGE:
9341 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9342 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
9343 SCEV::FlagNSW);
9344 Pred = ICmpInst::ICMP_SGT;
9345 Changed = true;
9346 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9347 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9348 SCEV::FlagNSW);
9349 Pred = ICmpInst::ICMP_SGT;
9350 Changed = true;
9351 }
9352 break;
9353 case ICmpInst::ICMP_ULE:
9354 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9355 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9356 SCEV::FlagNUW);
9357 Pred = ICmpInst::ICMP_ULT;
9358 Changed = true;
9359 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9360 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9361 Pred = ICmpInst::ICMP_ULT;
9362 Changed = true;
9363 }
9364 break;
9365 case ICmpInst::ICMP_UGE:
9366 if (!getUnsignedRangeMin(RHS).isMinValue()) {
9367 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9368 Pred = ICmpInst::ICMP_UGT;
9369 Changed = true;
9370 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9371 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9372 SCEV::FlagNUW);
9373 Pred = ICmpInst::ICMP_UGT;
9374 Changed = true;
9375 }
9376 break;
9377 default:
9378 break;
9379 }
9380
9381 // TODO: More simplifications are possible here.
9382
9383 // Recursively simplify until we either hit a recursion limit or nothing
9384 // changes.
9385 if (Changed)
9386 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9387
9388 return Changed;
9389}
9390
9391bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9392 return getSignedRangeMax(S).isNegative();
9393}
9394
9395bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9396 return getSignedRangeMin(S).isStrictlyPositive();
9397}
9398
9399bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9400 return !getSignedRangeMin(S).isNegative();
9401}
9402
9403bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9404 return !getSignedRangeMax(S).isStrictlyPositive();
9405}
9406
9407bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9408 return isKnownNegative(S) || isKnownPositive(S);
9409}
9410
9411std::pair<const SCEV *, const SCEV *>
9412ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9413 // Compute SCEV on entry of loop L.
9414 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9415 if (Start == getCouldNotCompute())
9416 return { Start, Start };
9417 // Compute post increment SCEV for loop L.
9418 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9419 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute")((PostInc != getCouldNotCompute() && "Unexpected could not compute"
) ? static_cast<void> (0) : __assert_fail ("PostInc != getCouldNotCompute() && \"Unexpected could not compute\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9419, __PRETTY_FUNCTION__))
;
9420 return { Start, PostInc };
9421}
9422
9423bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9424 const SCEV *LHS, const SCEV *RHS) {
9425 // First collect all loops.
9426 SmallPtrSet<const Loop *, 8> LoopsUsed;
9427 getUsedLoops(LHS, LoopsUsed);
9428 getUsedLoops(RHS, LoopsUsed);
9429
9430 if (LoopsUsed.empty())
9431 return false;
9432
9433 // Domination relationship must be a linear order on collected loops.
9434#ifndef NDEBUG
9435 for (auto *L1 : LoopsUsed)
9436 for (auto *L2 : LoopsUsed)
9437 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||(((DT.dominates(L1->getHeader(), L2->getHeader()) || DT
.dominates(L2->getHeader(), L1->getHeader())) &&
"Domination relationship is not a linear order") ? static_cast
<void> (0) : __assert_fail ("(DT.dominates(L1->getHeader(), L2->getHeader()) || DT.dominates(L2->getHeader(), L1->getHeader())) && \"Domination relationship is not a linear order\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9439, __PRETTY_FUNCTION__))
9438 DT.dominates(L2->getHeader(), L1->getHeader())) &&(((DT.dominates(L1->getHeader(), L2->getHeader()) || DT
.dominates(L2->getHeader(), L1->getHeader())) &&
"Domination relationship is not a linear order") ? static_cast
<void> (0) : __assert_fail ("(DT.dominates(L1->getHeader(), L2->getHeader()) || DT.dominates(L2->getHeader(), L1->getHeader())) && \"Domination relationship is not a linear order\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9439, __PRETTY_FUNCTION__))
9439 "Domination relationship is not a linear order")(((DT.dominates(L1->getHeader(), L2->getHeader()) || DT
.dominates(L2->getHeader(), L1->getHeader())) &&
"Domination relationship is not a linear order") ? static_cast
<void> (0) : __assert_fail ("(DT.dominates(L1->getHeader(), L2->getHeader()) || DT.dominates(L2->getHeader(), L1->getHeader())) && \"Domination relationship is not a linear order\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9439, __PRETTY_FUNCTION__))
;
9440#endif
9441
9442 const Loop *MDL =
9443 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9444 [&](const Loop *L1, const Loop *L2) {
9445 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9446 });
9447
9448 // Get init and post increment value for LHS.
9449 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9450 // if LHS contains unknown non-invariant SCEV then bail out.
9451 if (SplitLHS.first == getCouldNotCompute())
9452 return false;
9453 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC")((SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"
) ? static_cast<void> (0) : __assert_fail ("SplitLHS.second != getCouldNotCompute() && \"Unexpected CNC\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9453, __PRETTY_FUNCTION__))
;
9454 // Get init and post increment value for RHS.
9455 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9456 // if RHS contains unknown non-invariant SCEV then bail out.
9457 if (SplitRHS.first == getCouldNotCompute())
9458 return false;
9459 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC")((SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"
) ? static_cast<void> (0) : __assert_fail ("SplitRHS.second != getCouldNotCompute() && \"Unexpected CNC\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9459, __PRETTY_FUNCTION__))
;
9460 // It is possible that init SCEV contains an invariant load but it does
9461 // not dominate MDL and is not available at MDL loop entry, so we should
9462 // check it here.
9463 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9464 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9465 return false;
9466
9467 // It seems backedge guard check is faster than entry one so in some cases
9468 // it can speed up whole estimation by short circuit
9469 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9470 SplitRHS.second) &&
9471 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
9472}
9473
9474bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9475 const SCEV *LHS, const SCEV *RHS) {
9476 // Canonicalize the inputs first.
9477 (void)SimplifyICmpOperands(Pred, LHS, RHS);
9478
9479 if (isKnownViaInduction(Pred, LHS, RHS))
9480 return true;
9481
9482 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9483 return true;
9484
9485 // Otherwise see what can be done with some simple reasoning.
9486 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9487}
9488
9489bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
9490 const SCEV *LHS, const SCEV *RHS,
9491 const Instruction *Context) {
9492 // TODO: Analyze guards and assumes from Context's block.
9493 return isKnownPredicate(Pred, LHS, RHS) ||
54
Assuming the condition is false
9494 isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS);
55
Called C++ object pointer is null
9495}
9496
9497bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9498 const SCEVAddRecExpr *LHS,
9499 const SCEV *RHS) {
9500 const Loop *L = LHS->getLoop();
9501 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9502 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9503}
9504
9505Optional<ScalarEvolution::MonotonicPredicateType>
9506ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
9507 ICmpInst::Predicate Pred,
9508 Optional<const SCEV *> NumIter,
9509 const Instruction *Context) {
9510 assert((!NumIter || !isa<SCEVCouldNotCompute>(*NumIter)) &&(((!NumIter || !isa<SCEVCouldNotCompute>(*NumIter)) &&
"provided number of iterations must be computable!") ? static_cast
<void> (0) : __assert_fail ("(!NumIter || !isa<SCEVCouldNotCompute>(*NumIter)) && \"provided number of iterations must be computable!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9511, __PRETTY_FUNCTION__))
16
Assuming the condition is false
17
Assuming the object is not a 'SCEVCouldNotCompute'
18
'?' condition is true
9511 "provided number of iterations must be computable!")(((!NumIter || !isa<SCEVCouldNotCompute>(*NumIter)) &&
"provided number of iterations must be computable!") ? static_cast
<void> (0) : __assert_fail ("(!NumIter || !isa<SCEVCouldNotCompute>(*NumIter)) && \"provided number of iterations must be computable!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9511, __PRETTY_FUNCTION__))
;
9512 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred, NumIter, Context);
19
Passing null pointer value via 4th parameter 'Context'
20
Calling 'ScalarEvolution::getMonotonicPredicateTypeImpl'
9513
9514#ifndef NDEBUG
9515 // Verify an invariant: inverting the predicate should turn a monotonically
9516 // increasing change to a monotonically decreasing one, and vice versa.
9517 if (Result) {
9518 auto ResultSwapped = getMonotonicPredicateTypeImpl(
9519 LHS, ICmpInst::getSwappedPredicate(Pred), NumIter, Context);
9520
9521 assert(ResultSwapped.hasValue() && "should be able to analyze both!")((ResultSwapped.hasValue() && "should be able to analyze both!"
) ? static_cast<void> (0) : __assert_fail ("ResultSwapped.hasValue() && \"should be able to analyze both!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9521, __PRETTY_FUNCTION__))
;
9522 assert(ResultSwapped.getValue() != Result.getValue() &&((ResultSwapped.getValue() != Result.getValue() && "monotonicity should flip as we flip the predicate"
) ? static_cast<void> (0) : __assert_fail ("ResultSwapped.getValue() != Result.getValue() && \"monotonicity should flip as we flip the predicate\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9523, __PRETTY_FUNCTION__))
9523 "monotonicity should flip as we flip the predicate")((ResultSwapped.getValue() != Result.getValue() && "monotonicity should flip as we flip the predicate"
) ? static_cast<void> (0) : __assert_fail ("ResultSwapped.getValue() != Result.getValue() && \"monotonicity should flip as we flip the predicate\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9523, __PRETTY_FUNCTION__))
;
9524 }
9525#endif
9526
9527 return Result;
9528}
9529
9530Optional<ScalarEvolution::MonotonicPredicateType>
9531ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
9532 ICmpInst::Predicate Pred,
9533 Optional<const SCEV *> NumIter,
9534 const Instruction *Context) {
9535 // A zero step value for LHS means the induction variable is essentially a
9536 // loop invariant value. We don't really depend on the predicate actually
9537 // flipping from false to true (for increasing predicates, and the other way
9538 // around for decreasing predicates), all we care about is that *if* the
9539 // predicate changes then it only changes from false to true.
9540 //
9541 // A zero step value in itself is not very useful, but there may be places
9542 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9543 // as general as possible.
9544
9545 // Only handle LE/LT/GE/GT predicates.
9546 if (!ICmpInst::isRelational(Pred))
21
Taking false branch
9547 return None;
9548
9549 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
9550 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&(((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred))
&& "Should be greater or less!") ? static_cast<void
> (0) : __assert_fail ("(IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && \"Should be greater or less!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9551, __PRETTY_FUNCTION__))
22
'?' condition is true
9551 "Should be greater or less!")(((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred))
&& "Should be greater or less!") ? static_cast<void
> (0) : __assert_fail ("(IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && \"Should be greater or less!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9551, __PRETTY_FUNCTION__))
;
9552
9553 bool IsUnsigned = ICmpInst::isUnsigned(Pred);
9554 assert((IsUnsigned || ICmpInst::isSigned(Pred)) &&(((IsUnsigned || ICmpInst::isSigned(Pred)) && "Should be either signed or unsigned!"
) ? static_cast<void> (0) : __assert_fail ("(IsUnsigned || ICmpInst::isSigned(Pred)) && \"Should be either signed or unsigned!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9555, __PRETTY_FUNCTION__))
23
Assuming 'IsUnsigned' is false
24
Assuming the condition is true
25
'?' condition is true
9555 "Should be either signed or unsigned!")(((IsUnsigned || ICmpInst::isSigned(Pred)) && "Should be either signed or unsigned!"
) ? static_cast<void> (0) : __assert_fail ("(IsUnsigned || ICmpInst::isSigned(Pred)) && \"Should be either signed or unsigned!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9555, __PRETTY_FUNCTION__))
;
9556 // Check if we can prove no-wrap in the relevant range.
9557
9558 const SCEV *Step = LHS->getStepRecurrence(*this);
9559 bool IsStepNonNegative = isKnownNonNegative(Step);
9560 bool IsStepNonPositive = isKnownNonPositive(Step);
9561 // We need to know which direction the iteration is going.
9562 if (!IsStepNonNegative && !IsStepNonPositive)
26
Assuming 'IsStepNonNegative' is true
9563 return None;
9564
9565 auto ProvedNoWrap = [&]() {
9566 // If the AddRec already has the flag, we are done.
9567 if (IsUnsigned
27.1
'IsUnsigned' is false
27.1
'IsUnsigned' is false
27.1
'IsUnsigned' is false
? LHS->hasNoUnsignedWrap() : LHS->hasNoSignedWrap())
28
'?' condition is false
29
Calling 'SCEVNAryExpr::hasNoSignedWrap'
32
Returning from 'SCEVNAryExpr::hasNoSignedWrap'
33
Taking false branch
9568 return true;
9569
9570 if (!NumIter)
34
Calling 'Optional::operator bool'
42
Returning from 'Optional::operator bool'
43
Taking false branch
9571 return false;
9572 // We could not prove no-wrap on all iteration space. Can we prove it for
9573 // first iterations? In order to achieve it, check that:
9574 // 1. The addrec does not self-wrap;
9575 // 2. start <= end for non-negative step and start >= end for non-positive
9576 // step.
9577 bool HasNoSelfWrap = LHS->hasNoSelfWrap();
44
Calling 'SCEVNAryExpr::hasNoSelfWrap'
47
Returning from 'SCEVNAryExpr::hasNoSelfWrap'
9578 if (!HasNoSelfWrap
47.1
'HasNoSelfWrap' is true
47.1
'HasNoSelfWrap' is true
47.1
'HasNoSelfWrap' is true
)
48
Taking false branch
9579 // If num iter has same type as the AddRec, and step is +/- 1, even max
9580 // possible number of iterations is not enough to self-wrap.
9581 if (NumIter.getValue()->getType() == LHS->getType())
9582 if (Step == getOne(LHS->getType()) ||
9583 Step == getMinusOne(LHS->getType()))
9584 HasNoSelfWrap = true;
9585 if (!HasNoSelfWrap
48.1
'HasNoSelfWrap' is true
48.1
'HasNoSelfWrap' is true
48.1
'HasNoSelfWrap' is true
)
49
Taking false branch
9586 return false;
9587 const SCEV *Start = LHS->getStart();
9588 const SCEV *End = LHS->evaluateAtIteration(*NumIter, *this);
9589 ICmpInst::Predicate NoOverflowPred =
9590 IsStepNonNegative
49.1
'IsStepNonNegative' is true
49.1
'IsStepNonNegative' is true
49.1
'IsStepNonNegative' is true
? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SGE;
50
'?' condition is true
9591 if (IsUnsigned
50.1
'IsUnsigned' is false
50.1
'IsUnsigned' is false
50.1
'IsUnsigned' is false
)
51
Taking false branch
9592 NoOverflowPred = ICmpInst::getUnsignedPredicate(NoOverflowPred);
9593 return isKnownPredicateAt(NoOverflowPred, Start, End, Context);
52
Passing null pointer value via 4th parameter 'Context'
53
Calling 'ScalarEvolution::isKnownPredicateAt'
9594 };
9595
9596 // If nothing worked, bail.
9597 if (!ProvedNoWrap())
27
Calling 'operator()'
9598 return None;
9599
9600 if (IsUnsigned)
9601 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9602 else {
9603 if (IsStepNonNegative)
9604 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9605
9606 if (IsStepNonPositive)
9607 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
9608
9609 return None;
9610 }
9611}
9612
9613Optional<ScalarEvolution::LoopInvariantPredicate>
9614ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
9615 const SCEV *LHS, const SCEV *RHS,
9616 const Loop *L) {
9617
9618 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9619 if (!isLoopInvariant(RHS, L)) {
1
Calling 'ScalarEvolution::isLoopInvariant'
4
Returning from 'ScalarEvolution::isLoopInvariant'
5
Taking true branch
9620 if (!isLoopInvariant(LHS, L))
6
Calling 'ScalarEvolution::isLoopInvariant'
9
Returning from 'ScalarEvolution::isLoopInvariant'
10
Taking false branch
9621 return None;
9622
9623 std::swap(LHS, RHS);
9624 Pred = ICmpInst::getSwappedPredicate(Pred);
9625 }
9626
9627 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11
Assuming 'LHS' is a 'SCEVAddRecExpr'
9628 if (!ArLHS
11.1
'ArLHS' is non-null
11.1
'ArLHS' is non-null
11.1
'ArLHS' is non-null
|| ArLHS->getLoop() != L)
12
Assuming the condition is false
13
Taking false branch
9629 return None;
9630
9631 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
14
Passing null pointer value via 4th parameter 'Context'
15
Calling 'ScalarEvolution::getMonotonicPredicateType'
9632 if (!MonotonicType)
9633 return None;
9634 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9635 // true as the loop iterates, and the backedge is control dependent on
9636 // "ArLHS `Pred` RHS" == true then we can reason as follows:
9637 //
9638 // * if the predicate was false in the first iteration then the predicate
9639 // is never evaluated again, since the loop exits without taking the
9640 // backedge.
9641 // * if the predicate was true in the first iteration then it will
9642 // continue to be true for all future iterations since it is
9643 // monotonically increasing.
9644 //
9645 // For both the above possibilities, we can replace the loop varying
9646 // predicate with its value on the first iteration of the loop (which is
9647 // loop invariant).
9648 //
9649 // A similar reasoning applies for a monotonically decreasing predicate, by
9650 // replacing true with false and false with true in the above two bullets.
9651 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
9652 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
9653
9654 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
9655 return None;
9656
9657 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS);
9658}
9659
9660Optional<ScalarEvolution::LoopInvariantPredicate>
9661ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
9662 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9663 const Instruction *Context, const SCEV *MaxIter) {
9664 // Try to prove the following set of facts:
9665 // - The predicate is monotonic in the iteration space.
9666 // - If the check does not fail on the 1st iteration:
9667 // - It will not fail on the MaxIter'th iteration.
9668 // If the check does fail on the 1st iteration, we leave the loop and no
9669 // other checks matter.
9670
9671 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9672 if (!isLoopInvariant(RHS, L)) {
9673 if (!isLoopInvariant(LHS, L))
9674 return None;
9675
9676 std::swap(LHS, RHS);
9677 Pred = ICmpInst::getSwappedPredicate(Pred);
9678 }
9679
9680 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9681 if (!AR || AR->getLoop() != L)
9682 return None;
9683
9684 if (!getMonotonicPredicateType(AR, Pred, MaxIter, Context))
9685 return None;
9686
9687 // Value of IV on suggested last iteration.
9688 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
9689 // Does it still meet the requirement?
9690 if (!isKnownPredicateAt(Pred, Last, RHS, Context))
9691 return None;
9692
9693 // Everything is fine.
9694 return ScalarEvolution::LoopInvariantPredicate(Pred, AR->getStart(), RHS);
9695}
9696
9697bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9698 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
9699 if (HasSameValue(LHS, RHS))
9700 return ICmpInst::isTrueWhenEqual(Pred);
9701
9702 // This code is split out from isKnownPredicate because it is called from
9703 // within isLoopEntryGuardedByCond.
9704
9705 auto CheckRanges =
9706 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
9707 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
9708 .contains(RangeLHS);
9709 };
9710
9711 // The check at the top of the function catches the case where the values are
9712 // known to be equal.
9713 if (Pred == CmpInst::ICMP_EQ)
9714 return false;
9715
9716 if (Pred == CmpInst::ICMP_NE)
9717 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
9718 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
9719 isKnownNonZero(getMinusSCEV(LHS, RHS));
9720
9721 if (CmpInst::isSigned(Pred))
9722 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
9723
9724 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
9725}
9726
9727bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
9728 const SCEV *LHS,
9729 const SCEV *RHS) {
9730 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
9731 // Return Y via OutY.
9732 auto MatchBinaryAddToConst =
9733 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
9734 SCEV::NoWrapFlags ExpectedFlags) {
9735 const SCEV *NonConstOp, *ConstOp;
9736 SCEV::NoWrapFlags FlagsPresent;
9737
9738 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
9739 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
9740 return false;
9741
9742 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
9743 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
9744 };
9745
9746 APInt C;
9747
9748 switch (Pred) {
9749 default:
9750 break;
9751
9752 case ICmpInst::ICMP_SGE:
9753 std::swap(LHS, RHS);
9754 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9755 case ICmpInst::ICMP_SLE:
9756 // X s<= (X + C)<nsw> if C >= 0
9757 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
9758 return true;
9759
9760 // (X + C)<nsw> s<= X if C <= 0
9761 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
9762 !C.isStrictlyPositive())
9763 return true;
9764 break;
9765
9766 case ICmpInst::ICMP_SGT:
9767 std::swap(LHS, RHS);
9768 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9769 case ICmpInst::ICMP_SLT:
9770 // X s< (X + C)<nsw> if C > 0
9771 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
9772 C.isStrictlyPositive())
9773 return true;
9774
9775 // (X + C)<nsw> s< X if C < 0
9776 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
9777 return true;
9778 break;
9779
9780 case ICmpInst::ICMP_UGE:
9781 std::swap(LHS, RHS);
9782 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9783 case ICmpInst::ICMP_ULE:
9784 // X u<= (X + C)<nuw> for any C
9785 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW))
9786 return true;
9787 break;
9788
9789 case ICmpInst::ICMP_UGT:
9790 std::swap(LHS, RHS);
9791 LLVM_FALLTHROUGH[[gnu::fallthrough]];
9792 case ICmpInst::ICMP_ULT:
9793 // X u< (X + C)<nuw> if C != 0
9794 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue())
9795 return true;
9796 break;
9797 }
9798
9799 return false;
9800}
9801
9802bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
9803 const SCEV *LHS,
9804 const SCEV *RHS) {
9805 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
9806 return false;
9807
9808 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9809 // the stack can result in exponential time complexity.
9810 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
9811
9812 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9813 //
9814 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9815 // isKnownPredicate. isKnownPredicate is more powerful, but also more
9816 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9817 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
9818 // use isKnownPredicate later if needed.
9819 return isKnownNonNegative(RHS) &&
9820 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9821 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9822}
9823
9824bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
9825 ICmpInst::Predicate Pred,
9826 const SCEV *LHS, const SCEV *RHS) {
9827 // No need to even try if we know the module has no guards.
9828 if (!HasGuards)
9829 return false;
9830
9831 return any_of(*BB, [&](const Instruction &I) {
9832 using namespace llvm::PatternMatch;
9833
9834 Value *Condition;
9835 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9836 m_Value(Condition))) &&
9837 isImpliedCond(Pred, LHS, RHS, Condition, false);
9838 });
9839}
9840
9841/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9842/// protected by a conditional between LHS and RHS. This is used to
9843/// to eliminate casts.
9844bool
9845ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9846 ICmpInst::Predicate Pred,
9847 const SCEV *LHS, const SCEV *RHS) {
9848 // Interpret a null as meaning no loop, where there is obviously no guard
9849 // (interprocedural conditions notwithstanding).
9850 if (!L) return true;
9851
9852 if (VerifyIR)
9853 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&((!verifyFunction(*L->getHeader()->getParent(), &dbgs
()) && "This cannot be done on broken IR!") ? static_cast
<void> (0) : __assert_fail ("!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && \"This cannot be done on broken IR!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9854, __PRETTY_FUNCTION__))
9854 "This cannot be done on broken IR!")((!verifyFunction(*L->getHeader()->getParent(), &dbgs
()) && "This cannot be done on broken IR!") ? static_cast
<void> (0) : __assert_fail ("!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && \"This cannot be done on broken IR!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9854, __PRETTY_FUNCTION__))
;
9855
9856
9857 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9858 return true;
9859
9860 BasicBlock *Latch = L->getLoopLatch();
9861 if (!Latch)
9862 return false;
9863
9864 BranchInst *LoopContinuePredicate =
9865 dyn_cast<BranchInst>(Latch->getTerminator());
9866 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
9867 isImpliedCond(Pred, LHS, RHS,
9868 LoopContinuePredicate->getCondition(),
9869 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
9870 return true;
9871
9872 // We don't want more than one activation of the following loops on the stack
9873 // -- that can lead to O(n!) time complexity.
9874 if (WalkingBEDominatingConds)
9875 return false;
9876
9877 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
9878
9879 // See if we can exploit a trip count to prove the predicate.
9880 const auto &BETakenInfo = getBackedgeTakenInfo(L);
9881 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
9882 if (LatchBECount != getCouldNotCompute()) {
9883 // We know that Latch branches back to the loop header exactly
9884 // LatchBECount times. This means the backdege condition at Latch is
9885 // equivalent to "{0,+,1} u< LatchBECount".
9886 Type *Ty = LatchBECount->getType();
9887 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
9888 const SCEV *LoopCounter =
9889 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
9890 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
9891 LatchBECount))
9892 return true;
9893 }
9894
9895 // Check conditions due to any @llvm.assume intrinsics.
9896 for (auto &AssumeVH : AC.assumptions()) {
9897 if (!AssumeVH)
9898 continue;
9899 auto *CI = cast<CallInst>(AssumeVH);
9900 if (!DT.dominates(CI, Latch->getTerminator()))
9901 continue;
9902
9903 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9904 return true;
9905 }
9906
9907 // If the loop is not reachable from the entry block, we risk running into an
9908 // infinite loop as we walk up into the dom tree. These loops do not matter
9909 // anyway, so we just return a conservative answer when we see them.
9910 if (!DT.isReachableFromEntry(L->getHeader()))
9911 return false;
9912
9913 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9914 return true;
9915
9916 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9917 DTN != HeaderDTN; DTN = DTN->getIDom()) {
9918 assert(DTN && "should reach the loop header before reaching the root!")((DTN && "should reach the loop header before reaching the root!"
) ? static_cast<void> (0) : __assert_fail ("DTN && \"should reach the loop header before reaching the root!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9918, __PRETTY_FUNCTION__))
;
9919
9920 BasicBlock *BB = DTN->getBlock();
9921 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9922 return true;
9923
9924 BasicBlock *PBB = BB->getSinglePredecessor();
9925 if (!PBB)
9926 continue;
9927
9928 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9929 if (!ContinuePredicate || !ContinuePredicate->isConditional())
9930 continue;
9931
9932 Value *Condition = ContinuePredicate->getCondition();
9933
9934 // If we have an edge `E` within the loop body that dominates the only
9935 // latch, the condition guarding `E` also guards the backedge. This
9936 // reasoning works only for loops with a single latch.
9937
9938 BasicBlockEdge DominatingEdge(PBB, BB);
9939 if (DominatingEdge.isSingleEdge()) {
9940 // We're constructively (and conservatively) enumerating edges within the
9941 // loop body that dominate the latch. The dominator tree better agree
9942 // with us on this:
9943 assert(DT.dominates(DominatingEdge, Latch) && "should be!")((DT.dominates(DominatingEdge, Latch) && "should be!"
) ? static_cast<void> (0) : __assert_fail ("DT.dominates(DominatingEdge, Latch) && \"should be!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9943, __PRETTY_FUNCTION__))
;
9944
9945 if (isImpliedCond(Pred, LHS, RHS, Condition,
9946 BB != ContinuePredicate->getSuccessor(0)))
9947 return true;
9948 }
9949 }
9950
9951 return false;
9952}
9953
9954bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
9955 ICmpInst::Predicate Pred,
9956 const SCEV *LHS,
9957 const SCEV *RHS) {
9958 if (VerifyIR)
9959 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&((!verifyFunction(*BB->getParent(), &dbgs()) &&
"This cannot be done on broken IR!") ? static_cast<void>
(0) : __assert_fail ("!verifyFunction(*BB->getParent(), &dbgs()) && \"This cannot be done on broken IR!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9960, __PRETTY_FUNCTION__))
9960 "This cannot be done on broken IR!")((!verifyFunction(*BB->getParent(), &dbgs()) &&
"This cannot be done on broken IR!") ? static_cast<void>
(0) : __assert_fail ("!verifyFunction(*BB->getParent(), &dbgs()) && \"This cannot be done on broken IR!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 9960, __PRETTY_FUNCTION__))
;
9961
9962 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9963 return true;
9964
9965 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9966 // the facts (a >= b && a != b) separately. A typical situation is when the
9967 // non-strict comparison is known from ranges and non-equality is known from
9968 // dominating predicates. If we are proving strict comparison, we always try
9969 // to prove non-equality and non-strict comparison separately.
9970 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
9971 const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9972 bool ProvedNonStrictComparison = false;
9973 bool ProvedNonEquality = false;
9974
9975 if (ProvingStrictComparison) {
9976 ProvedNonStrictComparison =
9977 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
9978 ProvedNonEquality =
9979 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
9980 if (ProvedNonStrictComparison && ProvedNonEquality)
9981 return true;
9982 }
9983
9984 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
9985 auto ProveViaGuard = [&](const BasicBlock *Block) {
9986 if (isImpliedViaGuard(Block, Pred, LHS, RHS))
9987 return true;
9988 if (ProvingStrictComparison) {
9989 if (!ProvedNonStrictComparison)
9990 ProvedNonStrictComparison =
9991 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
9992 if (!ProvedNonEquality)
9993 ProvedNonEquality =
9994 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
9995 if (ProvedNonStrictComparison && ProvedNonEquality)
9996 return true;
9997 }
9998 return false;
9999 };
10000
10001 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
10002 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
10003 const Instruction *Context = &BB->front();
10004 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context))
10005 return true;
10006 if (ProvingStrictComparison) {
10007 if (!ProvedNonStrictComparison)
10008 ProvedNonStrictComparison = isImpliedCond(NonStrictPredicate, LHS, RHS,
10009 Condition, Inverse, Context);
10010 if (!ProvedNonEquality)
10011 ProvedNonEquality = isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS,
10012 Condition, Inverse, Context);
10013 if (ProvedNonStrictComparison && ProvedNonEquality)
10014 return true;
10015 }
10016 return false;
10017 };
10018
10019 // Starting at the block's predecessor, climb up the predecessor chain, as long
10020 // as there are predecessors that can be found that have unique successors
10021 // leading to the original block.
10022 const Loop *ContainingLoop = LI.getLoopFor(BB);
10023 const BasicBlock *PredBB;
10024 if (ContainingLoop && ContainingLoop->getHeader() == BB)
10025 PredBB = ContainingLoop->getLoopPredecessor();
10026 else
10027 PredBB = BB->getSinglePredecessor();
10028 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
10029 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
10030 if (ProveViaGuard(Pair.first))
10031 return true;
10032
10033 const BranchInst *LoopEntryPredicate =
10034 dyn_cast<BranchInst>(Pair.first->getTerminator());
10035 if (!LoopEntryPredicate ||
10036 LoopEntryPredicate->isUnconditional())
10037 continue;
10038
10039 if (ProveViaCond(LoopEntryPredicate->getCondition(),
10040 LoopEntryPredicate->getSuccessor(0) != Pair.second))
10041 return true;
10042 }
10043
10044 // Check conditions due to any @llvm.assume intrinsics.
10045 for (auto &AssumeVH : AC.assumptions()) {
10046 if (!AssumeVH)
10047 continue;
10048 auto *CI = cast<CallInst>(AssumeVH);
10049 if (!DT.dominates(CI, BB))
10050 continue;
10051
10052 if (ProveViaCond(CI->getArgOperand(0), false))
10053 return true;
10054 }
10055
10056 return false;
10057}
10058
10059bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
10060 ICmpInst::Predicate Pred,
10061 const SCEV *LHS,
10062 const SCEV *RHS) {
10063 // Interpret a null as meaning no loop, where there is obviously no guard
10064 // (interprocedural conditions notwithstanding).
10065 if (!L)
10066 return false;
10067
10068 // Both LHS and RHS must be available at loop entry.
10069 assert(isAvailableAtLoopEntry(LHS, L) &&((isAvailableAtLoopEntry(LHS, L) && "LHS is not available at Loop Entry"
) ? static_cast<void> (0) : __assert_fail ("isAvailableAtLoopEntry(LHS, L) && \"LHS is not available at Loop Entry\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10070, __PRETTY_FUNCTION__))
10070 "LHS is not available at Loop Entry")((isAvailableAtLoopEntry(LHS, L) && "LHS is not available at Loop Entry"
) ? static_cast<void> (0) : __assert_fail ("isAvailableAtLoopEntry(LHS, L) && \"LHS is not available at Loop Entry\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10070, __PRETTY_FUNCTION__))
;
10071 assert(isAvailableAtLoopEntry(RHS, L) &&((isAvailableAtLoopEntry(RHS, L) && "RHS is not available at Loop Entry"
) ? static_cast<void> (0) : __assert_fail ("isAvailableAtLoopEntry(RHS, L) && \"RHS is not available at Loop Entry\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10072, __PRETTY_FUNCTION__))
10072 "RHS is not available at Loop Entry")((isAvailableAtLoopEntry(RHS, L) && "RHS is not available at Loop Entry"
) ? static_cast<void> (0) : __assert_fail ("isAvailableAtLoopEntry(RHS, L) && \"RHS is not available at Loop Entry\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10072, __PRETTY_FUNCTION__))
;
10073 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
10074}
10075
10076bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10077 const SCEV *RHS,
10078 const Value *FoundCondValue, bool Inverse,
10079 const Instruction *Context) {
10080 if (!PendingLoopPredicates.insert(FoundCondValue).second)
10081 return false;
10082
10083 auto ClearOnExit =
10084 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
10085
10086 // Recursively handle And and Or conditions.
10087 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
10088 if (BO->getOpcode() == Instruction::And) {
10089 if (!Inverse)
10090 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse,
10091 Context) ||
10092 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse,
10093 Context);
10094 } else if (BO->getOpcode() == Instruction::Or) {
10095 if (Inverse)
10096 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse,
10097 Context) ||
10098 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse,
10099 Context);
10100 }
10101 }
10102
10103 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
10104 if (!ICI) return false;
10105
10106 // Now that we found a conditional branch that dominates the loop or controls
10107 // the loop latch. Check to see if it is the comparison we are looking for.
10108 ICmpInst::Predicate FoundPred;
10109 if (Inverse)
10110 FoundPred = ICI->getInversePredicate();
10111 else
10112 FoundPred = ICI->getPredicate();
10113
10114 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
10115 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
10116
10117 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context);
10118}
10119
10120bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
10121 const SCEV *RHS,
10122 ICmpInst::Predicate FoundPred,
10123 const SCEV *FoundLHS, const SCEV *FoundRHS,
10124 const Instruction *Context) {
10125 // Balance the types.
10126 if (getTypeSizeInBits(LHS->getType()) <
10127 getTypeSizeInBits(FoundLHS->getType())) {
10128 // For unsigned and equality predicates, try to prove that both found
10129 // operands fit into narrow unsigned range. If so, try to prove facts in
10130 // narrow types.
10131 if (!CmpInst::isSigned(FoundPred)) {
10132 auto *NarrowType = LHS->getType();
10133 auto *WideType = FoundLHS->getType();
10134 auto BitWidth = getTypeSizeInBits(NarrowType);
10135 const SCEV *MaxValue = getZeroExtendExpr(
10136 getConstant(APInt::getMaxValue(BitWidth)), WideType);
10137 if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) &&
10138 isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) {
10139 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
10140 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
10141 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
10142 TruncFoundRHS, Context))
10143 return true;
10144 }
10145 }
10146
10147 if (CmpInst::isSigned(Pred)) {
10148 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
10149 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
10150 } else {
10151 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
10152 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
10153 }
10154 } else if (getTypeSizeInBits(LHS->getType()) >
10155 getTypeSizeInBits(FoundLHS->getType())) {
10156 if (CmpInst::isSigned(FoundPred)) {
10157 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
10158 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
10159 } else {
10160 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
10161 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
10162 }
10163 }
10164 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
10165 FoundRHS, Context);
10166}
10167
10168bool ScalarEvolution::isImpliedCondBalancedTypes(
10169 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10170 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
10171 const Instruction *Context) {
10172 assert(getTypeSizeInBits(LHS->getType()) ==((getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(FoundLHS
->getType()) && "Types should be balanced!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(FoundLHS->getType()) && \"Types should be balanced!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10174, __PRETTY_FUNCTION__))
10173 getTypeSizeInBits(FoundLHS->getType()) &&((getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(FoundLHS
->getType()) && "Types should be balanced!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(FoundLHS->getType()) && \"Types should be balanced!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10174, __PRETTY_FUNCTION__))
10174 "Types should be balanced!")((getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(FoundLHS
->getType()) && "Types should be balanced!") ? static_cast
<void> (0) : __assert_fail ("getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(FoundLHS->getType()) && \"Types should be balanced!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10174, __PRETTY_FUNCTION__))
;
10175 // Canonicalize the query to match the way instcombine will have
10176 // canonicalized the comparison.
10177 if (SimplifyICmpOperands(Pred, LHS, RHS))
10178 if (LHS == RHS)
10179 return CmpInst::isTrueWhenEqual(Pred);
10180 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
10181 if (FoundLHS == FoundRHS)
10182 return CmpInst::isFalseWhenEqual(FoundPred);
10183
10184 // Check to see if we can make the LHS or RHS match.
10185 if (LHS == FoundRHS || RHS == FoundLHS) {
10186 if (isa<SCEVConstant>(RHS)) {
10187 std::swap(FoundLHS, FoundRHS);
10188 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
10189 } else {
10190 std::swap(LHS, RHS);
10191 Pred = ICmpInst::getSwappedPredicate(Pred);
10192 }
10193 }
10194
10195 // Check whether the found predicate is the same as the desired predicate.
10196 if (FoundPred == Pred)
10197 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10198
10199 // Check whether swapping the found predicate makes it the same as the
10200 // desired predicate.
10201 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
10202 if (isa<SCEVConstant>(RHS))
10203 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context);
10204 else
10205 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), RHS,
10206 LHS, FoundLHS, FoundRHS, Context);
10207 }
10208
10209 // Unsigned comparison is the same as signed comparison when both the operands
10210 // are non-negative.
10211 if (CmpInst::isUnsigned(FoundPred) &&
10212 CmpInst::getSignedPredicate(FoundPred) == Pred &&
10213 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
10214 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context);
10215
10216 // Check if we can make progress by sharpening ranges.
10217 if (FoundPred == ICmpInst::ICMP_NE &&
10218 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
10219
10220 const SCEVConstant *C = nullptr;
10221 const SCEV *V = nullptr;
10222
10223 if (isa<SCEVConstant>(FoundLHS)) {
10224 C = cast<SCEVConstant>(FoundLHS);
10225 V = FoundRHS;
10226 } else {
10227 C = cast<SCEVConstant>(FoundRHS);
10228 V = FoundLHS;
10229 }
10230
10231 // The guarding predicate tells us that C != V. If the known range
10232 // of V is [C, t), we can sharpen the range to [C + 1, t). The
10233 // range we consider has to correspond to same signedness as the
10234 // predicate we're interested in folding.
10235
10236 APInt Min = ICmpInst::isSigned(Pred) ?
10237 getSignedRangeMin(V) : getUnsignedRangeMin(V);
10238
10239 if (Min == C->getAPInt()) {
10240 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
10241 // This is true even if (Min + 1) wraps around -- in case of
10242 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
10243
10244 APInt SharperMin = Min + 1;
10245
10246 switch (Pred) {
10247 case ICmpInst::ICMP_SGE:
10248 case ICmpInst::ICMP_UGE:
10249 // We know V `Pred` SharperMin. If this implies LHS `Pred`
10250 // RHS, we're done.
10251 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
10252 Context))
10253 return true;
10254 LLVM_FALLTHROUGH[[gnu::fallthrough]];
10255
10256 case ICmpInst::ICMP_SGT:
10257 case ICmpInst::ICMP_UGT:
10258 // We know from the range information that (V `Pred` Min ||
10259 // V == Min). We know from the guarding condition that !(V
10260 // == Min). This gives us
10261 //
10262 // V `Pred` Min || V == Min && !(V == Min)
10263 // => V `Pred` Min
10264 //
10265 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
10266
10267 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min),
10268 Context))
10269 return true;
10270 break;
10271
10272 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
10273 case ICmpInst::ICMP_SLE:
10274 case ICmpInst::ICMP_ULE:
10275 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10276 LHS, V, getConstant(SharperMin), Context))
10277 return true;
10278 LLVM_FALLTHROUGH[[gnu::fallthrough]];
10279
10280 case ICmpInst::ICMP_SLT:
10281 case ICmpInst::ICMP_ULT:
10282 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
10283 LHS, V, getConstant(Min), Context))
10284 return true;
10285 break;
10286
10287 default:
10288 // No change
10289 break;
10290 }
10291 }
10292 }
10293
10294 // Check whether the actual condition is beyond sufficient.
10295 if (FoundPred == ICmpInst::ICMP_EQ)
10296 if (ICmpInst::isTrueWhenEqual(Pred))
10297 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context))
10298 return true;
10299 if (Pred == ICmpInst::ICMP_NE)
10300 if (!ICmpInst::isTrueWhenEqual(FoundPred))
10301 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS,
10302 Context))
10303 return true;
10304
10305 // Otherwise assume the worst.
10306 return false;
10307}
10308
10309bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
10310 const SCEV *&L, const SCEV *&R,
10311 SCEV::NoWrapFlags &Flags) {
10312 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
10313 if (!AE || AE->getNumOperands() != 2)
10314 return false;
10315
10316 L = AE->getOperand(0);
10317 R = AE->getOperand(1);
10318 Flags = AE->getNoWrapFlags();
10319 return true;
10320}
10321
10322Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
10323 const SCEV *Less) {
10324 // We avoid subtracting expressions here because this function is usually
10325 // fairly deep in the call stack (i.e. is called many times).
10326
10327 // X - X = 0.
10328 if (More == Less)
10329 return APInt(getTypeSizeInBits(More->getType()), 0);
10330
10331 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
10332 const auto *LAR = cast<SCEVAddRecExpr>(Less);
10333 const auto *MAR = cast<SCEVAddRecExpr>(More);
10334
10335 if (LAR->getLoop() != MAR->getLoop())
10336 return None;
10337
10338 // We look at affine expressions only; not for correctness but to keep
10339 // getStepRecurrence cheap.
10340 if (!LAR->isAffine() || !MAR->isAffine())
10341 return None;
10342
10343 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
10344 return None;
10345
10346 Less = LAR->getStart();
10347 More = MAR->getStart();
10348
10349 // fall through
10350 }
10351
10352 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
10353 const auto &M = cast<SCEVConstant>(More)->getAPInt();
10354 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
10355 return M - L;
10356 }
10357
10358 SCEV::NoWrapFlags Flags;
10359 const SCEV *LLess = nullptr, *RLess = nullptr;
10360 const SCEV *LMore = nullptr, *RMore = nullptr;
10361 const SCEVConstant *C1 = nullptr, *C2 = nullptr;
10362 // Compare (X + C1) vs X.
10363 if (splitBinaryAdd(Less, LLess, RLess, Flags))
10364 if ((C1 = dyn_cast<SCEVConstant>(LLess)))
10365 if (RLess == More)
10366 return -(C1->getAPInt());
10367
10368 // Compare X vs (X + C2).
10369 if (splitBinaryAdd(More, LMore, RMore, Flags))
10370 if ((C2 = dyn_cast<SCEVConstant>(LMore)))
10371 if (RMore == Less)
10372 return C2->getAPInt();
10373
10374 // Compare (X + C1) vs (X + C2).
10375 if (C1 && C2 && RLess == RMore)
10376 return C2->getAPInt() - C1->getAPInt();
10377
10378 return None;
10379}
10380
10381bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
10382 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10383 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) {
10384 // Try to recognize the following pattern:
10385 //
10386 // FoundRHS = ...
10387 // ...
10388 // loop:
10389 // FoundLHS = {Start,+,W}
10390 // context_bb: // Basic block from the same loop
10391 // known(Pred, FoundLHS, FoundRHS)
10392 //
10393 // If some predicate is known in the context of a loop, it is also known on
10394 // each iteration of this loop, including the first iteration. Therefore, in
10395 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
10396 // prove the original pred using this fact.
10397 if (!Context)
10398 return false;
10399 const BasicBlock *ContextBB = Context->getParent();
10400 // Make sure AR varies in the context block.
10401 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
10402 const Loop *L = AR->getLoop();
10403 // Make sure that context belongs to the loop and executes on 1st iteration
10404 // (if it ever executes at all).
10405 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10406 return false;
10407 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
10408 return false;
10409 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
10410 }
10411
10412 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
10413 const Loop *L = AR->getLoop();
10414 // Make sure that context belongs to the loop and executes on 1st iteration
10415 // (if it ever executes at all).
10416 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
10417 return false;
10418 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
10419 return false;
10420 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
10421 }
10422
10423 return false;
10424}
10425
10426bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
10427 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
10428 const SCEV *FoundLHS, const SCEV *FoundRHS) {
10429 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
10430 return false;
10431
10432 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
10433 if (!AddRecLHS)
10434 return false;
10435
10436 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
10437 if (!AddRecFoundLHS)
10438 return false;
10439
10440 // We'd like to let SCEV reason about control dependencies, so we constrain
10441 // both the inequalities to be about add recurrences on the same loop. This
10442 // way we can use isLoopEntryGuardedByCond later.
10443
10444 const Loop *L = AddRecFoundLHS->getLoop();
10445 if (L != AddRecLHS->getLoop())
10446 return false;
10447
10448 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
10449 //
10450 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
10451 // ... (2)
10452 //
10453 // Informal proof for (2), assuming (1) [*]:
10454 //
10455 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
10456 //
10457 // Then
10458 //
10459 // FoundLHS s< FoundRHS s< INT_MIN - C
10460 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
10461 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
10462 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
10463 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
10464 // <=> FoundLHS + C s< FoundRHS + C
10465 //
10466 // [*]: (1) can be proved by ruling out overflow.
10467 //
10468 // [**]: This can be proved by analyzing all the four possibilities:
10469 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
10470 // (A s>= 0, B s>= 0).
10471 //
10472 // Note:
10473 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
10474 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
10475 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
10476 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
10477 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
10478 // C)".
10479
10480 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
10481 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
10482 if (!LDiff || !RDiff || *LDiff != *RDiff)
10483 return false;
10484
10485 if (LDiff->isMinValue())
10486 return true;
10487
10488 APInt FoundRHSLimit;
10489
10490 if (Pred == CmpInst::ICMP_ULT) {
10491 FoundRHSLimit = -(*RDiff);
10492 } else {
10493 assert(Pred == CmpInst::ICMP_SLT && "Checked above!")((Pred == CmpInst::ICMP_SLT && "Checked above!") ? static_cast
<void> (0) : __assert_fail ("Pred == CmpInst::ICMP_SLT && \"Checked above!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10493, __PRETTY_FUNCTION__))
;
10494 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
10495 }
10496
10497 // Try to prove (1) or (2), as needed.
10498 return isAvailableAtLoopEntry(FoundRHS, L) &&
10499 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
10500 getConstant(FoundRHSLimit));
10501}
10502
10503bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
10504 const SCEV *LHS, const SCEV *RHS,
10505 const SCEV *FoundLHS,
10506 const SCEV *FoundRHS, unsigned Depth) {
10507 const PHINode *LPhi = nullptr, *RPhi = nullptr;
10508
10509 auto ClearOnExit = make_scope_exit([&]() {
10510 if (LPhi) {
10511 bool Erased = PendingMerges.erase(LPhi);
10512 assert(Erased && "Failed to erase LPhi!")((Erased && "Failed to erase LPhi!") ? static_cast<
void> (0) : __assert_fail ("Erased && \"Failed to erase LPhi!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10512, __PRETTY_FUNCTION__))
;
10513 (void)Erased;
10514 }
10515 if (RPhi) {
10516 bool Erased = PendingMerges.erase(RPhi);
10517 assert(Erased && "Failed to erase RPhi!")((Erased && "Failed to erase RPhi!") ? static_cast<
void> (0) : __assert_fail ("Erased && \"Failed to erase RPhi!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10517, __PRETTY_FUNCTION__))
;
10518 (void)Erased;
10519 }
10520 });
10521
10522 // Find respective Phis and check that they are not being pending.
10523 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
10524 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
10525 if (!PendingMerges.insert(Phi).second)
10526 return false;
10527 LPhi = Phi;
10528 }
10529 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
10530 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
10531 // If we detect a loop of Phi nodes being processed by this method, for
10532 // example:
10533 //
10534 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
10535 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
10536 //
10537 // we don't want to deal with a case that complex, so return conservative
10538 // answer false.
10539 if (!PendingMerges.insert(Phi).second)
10540 return false;
10541 RPhi = Phi;
10542 }
10543
10544 // If none of LHS, RHS is a Phi, nothing to do here.
10545 if (!LPhi && !RPhi)
10546 return false;
10547
10548 // If there is a SCEVUnknown Phi we are interested in, make it left.
10549 if (!LPhi) {
10550 std::swap(LHS, RHS);
10551 std::swap(FoundLHS, FoundRHS);
10552 std::swap(LPhi, RPhi);
10553 Pred = ICmpInst::getSwappedPredicate(Pred);
10554 }
10555
10556 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!")((LPhi && "LPhi should definitely be a SCEVUnknown Phi!"
) ? static_cast<void> (0) : __assert_fail ("LPhi && \"LPhi should definitely be a SCEVUnknown Phi!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10556, __PRETTY_FUNCTION__))
;
10557 const BasicBlock *LBB = LPhi->getParent();
10558 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10559
10560 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
10561 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
10562 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
10563 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
10564 };
10565
10566 if (RPhi && RPhi->getParent() == LBB) {
10567 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10568 // If we compare two Phis from the same block, and for each entry block
10569 // the predicate is true for incoming values from this block, then the
10570 // predicate is also true for the Phis.
10571 for (const BasicBlock *IncBB : predecessors(LBB)) {
10572 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10573 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
10574 if (!ProvedEasily(L, R))
10575 return false;
10576 }
10577 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
10578 // Case two: RHS is also a Phi from the same basic block, and it is an
10579 // AddRec. It means that there is a loop which has both AddRec and Unknown
10580 // PHIs, for it we can compare incoming values of AddRec from above the loop
10581 // and latch with their respective incoming values of LPhi.
10582 // TODO: Generalize to handle loops with many inputs in a header.
10583 if (LPhi->getNumIncomingValues() != 2) return false;
10584
10585 auto *RLoop = RAR->getLoop();
10586 auto *Predecessor = RLoop->getLoopPredecessor();
10587 assert(Predecessor && "Loop with AddRec with no predecessor?")((Predecessor && "Loop with AddRec with no predecessor?"
) ? static_cast<void> (0) : __assert_fail ("Predecessor && \"Loop with AddRec with no predecessor?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10587, __PRETTY_FUNCTION__))
;
10588 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
10589 if (!ProvedEasily(L1, RAR->getStart()))
10590 return false;
10591 auto *Latch = RLoop->getLoopLatch();
10592 assert(Latch && "Loop with AddRec with no latch?")((Latch && "Loop with AddRec with no latch?") ? static_cast
<void> (0) : __assert_fail ("Latch && \"Loop with AddRec with no latch?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10592, __PRETTY_FUNCTION__))
;
10593 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
10594 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
10595 return false;
10596 } else {
10597 // In all other cases go over inputs of LHS and compare each of them to RHS,
10598 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10599 // At this point RHS is either a non-Phi, or it is a Phi from some block
10600 // different from LBB.
10601 for (const BasicBlock *IncBB : predecessors(LBB)) {
10602 // Check that RHS is available in this block.
10603 if (!dominates(RHS, IncBB))
10604 return false;
10605 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10606 if (!ProvedEasily(L, RHS))
10607 return false;
10608 }
10609 }
10610 return true;
10611}
10612
10613bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
10614 const SCEV *LHS, const SCEV *RHS,
10615 const SCEV *FoundLHS,
10616 const SCEV *FoundRHS,
10617 const Instruction *Context) {
10618 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
10619 return true;
10620
10621 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
10622 return true;
10623
10624 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
10625 Context))
10626 return true;
10627
10628 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
10629 FoundLHS, FoundRHS) ||
10630 // ~x < ~y --> x > y
10631 isImpliedCondOperandsHelper(Pred, LHS, RHS,
10632 getNotSCEV(FoundRHS),
10633 getNotSCEV(FoundLHS));
10634}
10635
10636/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
10637template <typename MinMaxExprType>
10638static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
10639 const SCEV *Candidate) {
10640 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
10641 if (!MinMaxExpr)
10642 return false;
10643
10644 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end();
10645}
10646
10647static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
10648 ICmpInst::Predicate Pred,
10649 const SCEV *LHS, const SCEV *RHS) {
10650 // If both sides are affine addrecs for the same loop, with equal
10651 // steps, and we know the recurrences don't wrap, then we only
10652 // need to check the predicate on the starting values.
10653
10654 if (!ICmpInst::isRelational(Pred))
10655 return false;
10656
10657 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
10658 if (!LAR)
10659 return false;
10660 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10661 if (!RAR)
10662 return false;
10663 if (LAR->getLoop() != RAR->getLoop())
10664 return false;
10665 if (!LAR->isAffine() || !RAR->isAffine())
10666 return false;
10667
10668 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
10669 return false;
10670
10671 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
10672 SCEV::FlagNSW : SCEV::FlagNUW;
10673 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
10674 return false;
10675
10676 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
10677}
10678
10679/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
10680/// expression?
10681static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
10682 ICmpInst::Predicate Pred,
10683 const SCEV *LHS, const SCEV *RHS) {
10684 switch (Pred) {
10685 default:
10686 return false;
10687
10688 case ICmpInst::ICMP_SGE:
10689 std::swap(LHS, RHS);
10690 LLVM_FALLTHROUGH[[gnu::fallthrough]];
10691 case ICmpInst::ICMP_SLE:
10692 return
10693 // min(A, ...) <= A
10694 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
10695 // A <= max(A, ...)
10696 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
10697
10698 case ICmpInst::ICMP_UGE:
10699 std::swap(LHS, RHS);
10700 LLVM_FALLTHROUGH[[gnu::fallthrough]];
10701 case ICmpInst::ICMP_ULE:
10702 return
10703 // min(A, ...) <= A
10704 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
10705 // A <= max(A, ...)
10706 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
10707 }
10708
10709 llvm_unreachable("covered switch fell through?!")::llvm::llvm_unreachable_internal("covered switch fell through?!"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10709)
;
10710}
10711
10712bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
10713 const SCEV *LHS, const SCEV *RHS,
10714 const SCEV *FoundLHS,
10715 const SCEV *FoundRHS,
10716 unsigned Depth) {
10717 assert(getTypeSizeInBits(LHS->getType()) ==((getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(RHS
->getType()) && "LHS and RHS have different sizes?"
) ? static_cast<void> (0) : __assert_fail ("getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(RHS->getType()) && \"LHS and RHS have different sizes?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10719, __PRETTY_FUNCTION__))
10718 getTypeSizeInBits(RHS->getType()) &&((getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(RHS
->getType()) && "LHS and RHS have different sizes?"
) ? static_cast<void> (0) : __assert_fail ("getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(RHS->getType()) && \"LHS and RHS have different sizes?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10719, __PRETTY_FUNCTION__))
10719 "LHS and RHS have different sizes?")((getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(RHS
->getType()) && "LHS and RHS have different sizes?"
) ? static_cast<void> (0) : __assert_fail ("getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(RHS->getType()) && \"LHS and RHS have different sizes?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10719, __PRETTY_FUNCTION__))
;
10720 assert(getTypeSizeInBits(FoundLHS->getType()) ==((getTypeSizeInBits(FoundLHS->getType()) == getTypeSizeInBits
(FoundRHS->getType()) && "FoundLHS and FoundRHS have different sizes?"
) ? static_cast<void> (0) : __assert_fail ("getTypeSizeInBits(FoundLHS->getType()) == getTypeSizeInBits(FoundRHS->getType()) && \"FoundLHS and FoundRHS have different sizes?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10722, __PRETTY_FUNCTION__))
10721 getTypeSizeInBits(FoundRHS->getType()) &&((getTypeSizeInBits(FoundLHS->getType()) == getTypeSizeInBits
(FoundRHS->getType()) && "FoundLHS and FoundRHS have different sizes?"
) ? static_cast<void> (0) : __assert_fail ("getTypeSizeInBits(FoundLHS->getType()) == getTypeSizeInBits(FoundRHS->getType()) && \"FoundLHS and FoundRHS have different sizes?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10722, __PRETTY_FUNCTION__))
10722 "FoundLHS and FoundRHS have different sizes?")((getTypeSizeInBits(FoundLHS->getType()) == getTypeSizeInBits
(FoundRHS->getType()) && "FoundLHS and FoundRHS have different sizes?"
) ? static_cast<void> (0) : __assert_fail ("getTypeSizeInBits(FoundLHS->getType()) == getTypeSizeInBits(FoundRHS->getType()) && \"FoundLHS and FoundRHS have different sizes?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10722, __PRETTY_FUNCTION__))
;
10723 // We want to avoid hurting the compile time with analysis of too big trees.
10724 if (Depth > MaxSCEVOperationsImplicationDepth)
10725 return false;
10726
10727 // We only want to work with GT comparison so far.
10728 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
10729 Pred = CmpInst::getSwappedPredicate(Pred);
10730 std::swap(LHS, RHS);
10731 std::swap(FoundLHS, FoundRHS);
10732 }
10733
10734 // For unsigned, try to reduce it to corresponding signed comparison.
10735 if (Pred == ICmpInst::ICMP_UGT)
10736 // We can replace unsigned predicate with its signed counterpart if all
10737 // involved values are non-negative.
10738 // TODO: We could have better support for unsigned.
10739 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
10740 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
10741 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
10742 // use this fact to prove that LHS and RHS are non-negative.
10743 const SCEV *MinusOne = getMinusOne(LHS->getType());
10744 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
10745 FoundRHS) &&
10746 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
10747 FoundRHS))
10748 Pred = ICmpInst::ICMP_SGT;
10749 }
10750
10751 if (Pred != ICmpInst::ICMP_SGT)
10752 return false;
10753
10754 auto GetOpFromSExt = [&](const SCEV *S) {
10755 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
10756 return Ext->getOperand();
10757 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
10758 // the constant in some cases.
10759 return S;
10760 };
10761
10762 // Acquire values from extensions.
10763 auto *OrigLHS = LHS;
10764 auto *OrigFoundLHS = FoundLHS;
10765 LHS = GetOpFromSExt(LHS);
10766 FoundLHS = GetOpFromSExt(FoundLHS);
10767
10768 // Is the SGT predicate can be proved trivially or using the found context.
10769 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
10770 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
10771 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
10772 FoundRHS, Depth + 1);
10773 };
10774
10775 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
10776 // We want to avoid creation of any new non-constant SCEV. Since we are
10777 // going to compare the operands to RHS, we should be certain that we don't
10778 // need any size extensions for this. So let's decline all cases when the
10779 // sizes of types of LHS and RHS do not match.
10780 // TODO: Maybe try to get RHS from sext to catch more cases?
10781 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
10782 return false;
10783
10784 // Should not overflow.
10785 if (!LHSAddExpr->hasNoSignedWrap())
10786 return false;
10787
10788 auto *LL = LHSAddExpr->getOperand(0);
10789 auto *LR = LHSAddExpr->getOperand(1);
10790 auto *MinusOne = getMinusOne(RHS->getType());
10791
10792 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
10793 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
10794 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
10795 };
10796 // Try to prove the following rule:
10797 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
10798 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
10799 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
10800 return true;
10801 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
10802 Value *LL, *LR;
10803 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
10804
10805 using namespace llvm::PatternMatch;
10806
10807 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
10808 // Rules for division.
10809 // We are going to perform some comparisons with Denominator and its
10810 // derivative expressions. In general case, creating a SCEV for it may
10811 // lead to a complex analysis of the entire graph, and in particular it
10812 // can request trip count recalculation for the same loop. This would
10813 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
10814 // this, we only want to create SCEVs that are constants in this section.
10815 // So we bail if Denominator is not a constant.
10816 if (!isa<ConstantInt>(LR))
10817 return false;
10818
10819 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
10820
10821 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
10822 // then a SCEV for the numerator already exists and matches with FoundLHS.
10823 auto *Numerator = getExistingSCEV(LL);
10824 if (!Numerator || Numerator->getType() != FoundLHS->getType())
10825 return false;
10826
10827 // Make sure that the numerator matches with FoundLHS and the denominator
10828 // is positive.
10829 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
10830 return false;
10831
10832 auto *DTy = Denominator->getType();
10833 auto *FRHSTy = FoundRHS->getType();
10834 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
10835 // One of types is a pointer and another one is not. We cannot extend
10836 // them properly to a wider type, so let us just reject this case.
10837 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
10838 // to avoid this check.
10839 return false;
10840
10841 // Given that:
10842 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
10843 auto *WTy = getWiderType(DTy, FRHSTy);
10844 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
10845 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
10846
10847 // Try to prove the following rule:
10848 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
10849 // For example, given that FoundLHS > 2. It means that FoundLHS is at
10850 // least 3. If we divide it by Denominator < 4, we will have at least 1.
10851 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
10852 if (isKnownNonPositive(RHS) &&
10853 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
10854 return true;
10855
10856 // Try to prove the following rule:
10857 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
10858 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
10859 // If we divide it by Denominator > 2, then:
10860 // 1. If FoundLHS is negative, then the result is 0.
10861 // 2. If FoundLHS is non-negative, then the result is non-negative.
10862 // Anyways, the result is non-negative.
10863 auto *MinusOne = getMinusOne(WTy);
10864 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
10865 if (isKnownNegative(RHS) &&
10866 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
10867 return true;
10868 }
10869 }
10870
10871 // If our expression contained SCEVUnknown Phis, and we split it down and now
10872 // need to prove something for them, try to prove the predicate for every
10873 // possible incoming values of those Phis.
10874 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
10875 return true;
10876
10877 return false;
10878}
10879
10880static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
10881 const SCEV *LHS, const SCEV *RHS) {
10882 // zext x u<= sext x, sext x s<= zext x
10883 switch (Pred) {
10884 case ICmpInst::ICMP_SGE:
10885 std::swap(LHS, RHS);
10886 LLVM_FALLTHROUGH[[gnu::fallthrough]];
10887 case ICmpInst::ICMP_SLE: {
10888 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
10889 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
10890 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
10891 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
10892 return true;
10893 break;
10894 }
10895 case ICmpInst::ICMP_UGE:
10896 std::swap(LHS, RHS);
10897 LLVM_FALLTHROUGH[[gnu::fallthrough]];
10898 case ICmpInst::ICMP_ULE: {
10899 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt.
10900 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
10901 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
10902 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
10903 return true;
10904 break;
10905 }
10906 default:
10907 break;
10908 };
10909 return false;
10910}
10911
10912bool
10913ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
10914 const SCEV *LHS, const SCEV *RHS) {
10915 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
10916 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
10917 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
10918 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
10919 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
10920}
10921
10922bool
10923ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
10924 const SCEV *LHS, const SCEV *RHS,
10925 const SCEV *FoundLHS,
10926 const SCEV *FoundRHS) {
10927 switch (Pred) {
10928 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!")::llvm::llvm_unreachable_internal("Unexpected ICmpInst::Predicate value!"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 10928)
;
10929 case ICmpInst::ICMP_EQ:
10930 case ICmpInst::ICMP_NE:
10931 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
10932 return true;
10933 break;
10934 case ICmpInst::ICMP_SLT:
10935 case ICmpInst::ICMP_SLE:
10936 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
10937 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
10938 return true;
10939 break;
10940 case ICmpInst::ICMP_SGT:
10941 case ICmpInst::ICMP_SGE:
10942 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
10943 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
10944 return true;
10945 break;
10946 case ICmpInst::ICMP_ULT:
10947 case ICmpInst::ICMP_ULE:
10948 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
10949 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
10950 return true;
10951 break;
10952 case ICmpInst::ICMP_UGT:
10953 case ICmpInst::ICMP_UGE:
10954 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
10955 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
10956 return true;
10957 break;
10958 }
10959
10960 // Maybe it can be proved via operations?
10961 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
10962 return true;
10963
10964 return false;
10965}
10966
10967bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
10968 const SCEV *LHS,
10969 const SCEV *RHS,
10970 const SCEV *FoundLHS,
10971 const SCEV *FoundRHS) {
10972 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
10973 // The restriction on `FoundRHS` be lifted easily -- it exists only to
10974 // reduce the compile time impact of this optimization.
10975 return false;
10976
10977 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
10978 if (!Addend)
10979 return false;
10980
10981 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
10982
10983 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
10984 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
10985 ConstantRange FoundLHSRange =
10986 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
10987
10988 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
10989 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
10990
10991 // We can also compute the range of values for `LHS` that satisfy the
10992 // consequent, "`LHS` `Pred` `RHS`":
10993 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
10994 ConstantRange SatisfyingLHSRange =
10995 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
10996
10997 // The antecedent implies the consequent if every value of `LHS` that
10998 // satisfies the antecedent also satisfies the consequent.
10999 return SatisfyingLHSRange.contains(LHSRange);
11000}
11001
11002bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
11003 bool IsSigned, bool NoWrap) {
11004 assert(isKnownPositive(Stride) && "Positive stride expected!")((isKnownPositive(Stride) && "Positive stride expected!"
) ? static_cast<void> (0) : __assert_fail ("isKnownPositive(Stride) && \"Positive stride expected!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 11004, __PRETTY_FUNCTION__))
;
11005
11006 if (NoWrap) return false;
11007
11008 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11009 const SCEV *One = getOne(Stride->getType());
11010
11011 if (IsSigned) {
11012 APInt MaxRHS = getSignedRangeMax(RHS);
11013 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
11014 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11015
11016 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
11017 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
11018 }
11019
11020 APInt MaxRHS = getUnsignedRangeMax(RHS);
11021 APInt MaxValue = APInt::getMaxValue(BitWidth);
11022 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11023
11024 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
11025 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
11026}
11027
11028bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
11029 bool IsSigned, bool NoWrap) {
11030 if (NoWrap) return false;
11031
11032 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
11033 const SCEV *One = getOne(Stride->getType());
11034
11035 if (IsSigned) {
11036 APInt MinRHS = getSignedRangeMin(RHS);
11037 APInt MinValue = APInt::getSignedMinValue(BitWidth);
11038 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
11039
11040 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
11041 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
11042 }
11043
11044 APInt MinRHS = getUnsignedRangeMin(RHS);
11045 APInt MinValue = APInt::getMinValue(BitWidth);
11046 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
11047
11048 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
11049 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
11050}
11051
11052const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
11053 bool Equality) {
11054 const SCEV *One = getOne(Step->getType());
11055 Delta = Equality ? getAddExpr(Delta, Step)
11056 : getAddExpr(Delta, getMinusSCEV(Step, One));
11057 return getUDivExpr(Delta, Step);
11058}
11059
11060const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
11061 const SCEV *Stride,
11062 const SCEV *End,
11063 unsigned BitWidth,
11064 bool IsSigned) {
11065
11066 assert(!isKnownNonPositive(Stride) &&((!isKnownNonPositive(Stride) && "Stride is expected strictly positive!"
) ? static_cast<void> (0) : __assert_fail ("!isKnownNonPositive(Stride) && \"Stride is expected strictly positive!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 11067, __PRETTY_FUNCTION__))
11067 "Stride is expected strictly positive!")((!isKnownNonPositive(Stride) && "Stride is expected strictly positive!"
) ? static_cast<void> (0) : __assert_fail ("!isKnownNonPositive(Stride) && \"Stride is expected strictly positive!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 11067, __PRETTY_FUNCTION__))
;
11068 // Calculate the maximum backedge count based on the range of values
11069 // permitted by Start, End, and Stride.
11070 const SCEV *MaxBECount;
11071 APInt MinStart =
11072 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
11073
11074 APInt StrideForMaxBECount =
11075 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
11076
11077 // We already know that the stride is positive, so we paper over conservatism
11078 // in our range computation by forcing StrideForMaxBECount to be at least one.
11079 // In theory this is unnecessary, but we expect MaxBECount to be a
11080 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
11081 // is nothing to constant fold it to).
11082 APInt One(BitWidth, 1, IsSigned);
11083 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
11084
11085 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
11086 : APInt::getMaxValue(BitWidth);
11087 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
11088
11089 // Although End can be a MAX expression we estimate MaxEnd considering only
11090 // the case End = RHS of the loop termination condition. This is safe because
11091 // in the other case (End - Start) is zero, leading to a zero maximum backedge
11092 // taken count.
11093 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
11094 : APIntOps::umin(getUnsignedRangeMax(End), Limit);
11095
11096 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
11097 getConstant(StrideForMaxBECount) /* Step */,
11098 false /* Equality */);
11099
11100 return MaxBECount;
11101}
11102
11103ScalarEvolution::ExitLimit
11104ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
11105 const Loop *L, bool IsSigned,
11106 bool ControlsExit, bool AllowPredicates) {
11107 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11108
11109 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11110 bool PredicatedIV = false;
11111
11112 if (!IV && AllowPredicates) {
11113 // Try to make this an AddRec using runtime tests, in the first X
11114 // iterations of this loop, where X is the SCEV expression found by the
11115 // algorithm below.
11116 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11117 PredicatedIV = true;
11118 }
11119
11120 // Avoid weird loops
11121 if (!IV || IV->getLoop() != L || !IV->isAffine())
11122 return getCouldNotCompute();
11123
11124 bool NoWrap = ControlsExit &&
11125 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
11126
11127 const SCEV *Stride = IV->getStepRecurrence(*this);
11128
11129 bool PositiveStride = isKnownPositive(Stride);
11130
11131 // Avoid negative or zero stride values.
11132 if (!PositiveStride) {
11133 // We can compute the correct backedge taken count for loops with unknown
11134 // strides if we can prove that the loop is not an infinite loop with side
11135 // effects. Here's the loop structure we are trying to handle -
11136 //
11137 // i = start
11138 // do {
11139 // A[i] = i;
11140 // i += s;
11141 // } while (i < end);
11142 //
11143 // The backedge taken count for such loops is evaluated as -
11144 // (max(end, start + stride) - start - 1) /u stride
11145 //
11146 // The additional preconditions that we need to check to prove correctness
11147 // of the above formula is as follows -
11148 //
11149 // a) IV is either nuw or nsw depending upon signedness (indicated by the
11150 // NoWrap flag).
11151 // b) loop is single exit with no side effects.
11152 //
11153 //
11154 // Precondition a) implies that if the stride is negative, this is a single
11155 // trip loop. The backedge taken count formula reduces to zero in this case.
11156 //
11157 // Precondition b) implies that the unknown stride cannot be zero otherwise
11158 // we have UB.
11159 //
11160 // The positive stride case is the same as isKnownPositive(Stride) returning
11161 // true (original behavior of the function).
11162 //
11163 // We want to make sure that the stride is truly unknown as there are edge
11164 // cases where ScalarEvolution propagates no wrap flags to the
11165 // post-increment/decrement IV even though the increment/decrement operation
11166 // itself is wrapping. The computed backedge taken count may be wrong in
11167 // such cases. This is prevented by checking that the stride is not known to
11168 // be either positive or non-positive. For example, no wrap flags are
11169 // propagated to the post-increment IV of this loop with a trip count of 2 -
11170 //
11171 // unsigned char i;
11172 // for(i=127; i<128; i+=129)
11173 // A[i] = i;
11174 //
11175 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
11176 !loopHasNoSideEffects(L))
11177 return getCouldNotCompute();
11178 } else if (!Stride->isOne() &&
11179 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
11180 // Avoid proven overflow cases: this will ensure that the backedge taken
11181 // count will not generate any unsigned overflow. Relaxed no-overflow
11182 // conditions exploit NoWrapFlags, allowing to optimize in presence of
11183 // undefined behaviors like the case of C language.
11184 return getCouldNotCompute();
11185
11186 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
11187 : ICmpInst::ICMP_ULT;
11188 const SCEV *Start = IV->getStart();
11189 const SCEV *End = RHS;
11190 // When the RHS is not invariant, we do not know the end bound of the loop and
11191 // cannot calculate the ExactBECount needed by ExitLimit. However, we can
11192 // calculate the MaxBECount, given the start, stride and max value for the end
11193 // bound of the loop (RHS), and the fact that IV does not overflow (which is
11194 // checked above).
11195 if (!isLoopInvariant(RHS, L)) {
11196 const SCEV *MaxBECount = computeMaxBECountForLT(
11197 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11198 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
11199 false /*MaxOrZero*/, Predicates);
11200 }
11201 // If the backedge is taken at least once, then it will be taken
11202 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
11203 // is the LHS value of the less-than comparison the first time it is evaluated
11204 // and End is the RHS.
11205 const SCEV *BECountIfBackedgeTaken =
11206 computeBECount(getMinusSCEV(End, Start), Stride, false);
11207 // If the loop entry is guarded by the result of the backedge test of the
11208 // first loop iteration, then we know the backedge will be taken at least
11209 // once and so the backedge taken count is as above. If not then we use the
11210 // expression (max(End,Start)-Start)/Stride to describe the backedge count,
11211 // as if the backedge is taken at least once max(End,Start) is End and so the
11212 // result is as above, and if not max(End,Start) is Start so we get a backedge
11213 // count of zero.
11214 const SCEV *BECount;
11215 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
11216 BECount = BECountIfBackedgeTaken;
11217 else {
11218 // If we know that RHS >= Start in the context of loop, then we know that
11219 // max(RHS, Start) = RHS at this point.
11220 if (isLoopEntryGuardedByCond(
11221 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start))
11222 End = RHS;
11223 else
11224 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
11225 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
11226 }
11227
11228 const SCEV *MaxBECount;
11229 bool MaxOrZero = false;
11230 if (isa<SCEVConstant>(BECount))
11231 MaxBECount = BECount;
11232 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
11233 // If we know exactly how many times the backedge will be taken if it's
11234 // taken at least once, then the backedge count will either be that or
11235 // zero.
11236 MaxBECount = BECountIfBackedgeTaken;
11237 MaxOrZero = true;
11238 } else {
11239 MaxBECount = computeMaxBECountForLT(
11240 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
11241 }
11242
11243 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
11244 !isa<SCEVCouldNotCompute>(BECount))
11245 MaxBECount = getConstant(getUnsignedRangeMax(BECount));
11246
11247 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
11248}
11249
11250ScalarEvolution::ExitLimit
11251ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
11252 const Loop *L, bool IsSigned,
11253 bool ControlsExit, bool AllowPredicates) {
11254 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
11255 // We handle only IV > Invariant
11256 if (!isLoopInvariant(RHS, L))
11257 return getCouldNotCompute();
11258
11259 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
11260 if (!IV && AllowPredicates)
11261 // Try to make this an AddRec using runtime tests, in the first X
11262 // iterations of this loop, where X is the SCEV expression found by the
11263 // algorithm below.
11264 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
11265
11266 // Avoid weird loops
11267 if (!IV || IV->getLoop() != L || !IV->isAffine())
11268 return getCouldNotCompute();
11269
11270 bool NoWrap = ControlsExit &&
11271 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
11272
11273 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
11274
11275 // Avoid negative or zero stride values
11276 if (!isKnownPositive(Stride))
11277 return getCouldNotCompute();
11278
11279 // Avoid proven overflow cases: this will ensure that the backedge taken count
11280 // will not generate any unsigned overflow. Relaxed no-overflow conditions
11281 // exploit NoWrapFlags, allowing to optimize in presence of undefined
11282 // behaviors like the case of C language.
11283 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
11284 return getCouldNotCompute();
11285
11286 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
11287 : ICmpInst::ICMP_UGT;
11288
11289 const SCEV *Start = IV->getStart();
11290 const SCEV *End = RHS;
11291 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
11292 // If we know that Start >= RHS in the context of loop, then we know that
11293 // min(RHS, Start) = RHS at this point.
11294 if (isLoopEntryGuardedByCond(
11295 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
11296 End = RHS;
11297 else
11298 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
11299 }
11300
11301 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
11302
11303 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
11304 : getUnsignedRangeMax(Start);
11305
11306 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
11307 : getUnsignedRangeMin(Stride);
11308
11309 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
11310 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
11311 : APInt::getMinValue(BitWidth) + (MinStride - 1);
11312
11313 // Although End can be a MIN expression we estimate MinEnd considering only
11314 // the case End = RHS. This is safe because in the other case (Start - End)
11315 // is zero, leading to a zero maximum backedge taken count.
11316 APInt MinEnd =
11317 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
11318 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
11319
11320 const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
11321 ? BECount
11322 : computeBECount(getConstant(MaxStart - MinEnd),
11323 getConstant(MinStride), false);
11324
11325 if (isa<SCEVCouldNotCompute>(MaxBECount))
11326 MaxBECount = BECount;
11327
11328 return ExitLimit(BECount, MaxBECount, false, Predicates);
11329}
11330
11331const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
11332 ScalarEvolution &SE) const {
11333 if (Range.isFullSet()) // Infinite loop.
11334 return SE.getCouldNotCompute();
11335
11336 // If the start is a non-zero constant, shift the range to simplify things.
11337 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
11338 if (!SC->getValue()->isZero()) {
11339 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
11340 Operands[0] = SE.getZero(SC->getType());
11341 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
11342 getNoWrapFlags(FlagNW));
11343 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
11344 return ShiftedAddRec->getNumIterationsInRange(
11345 Range.subtract(SC->getAPInt()), SE);
11346 // This is strange and shouldn't happen.
11347 return SE.getCouldNotCompute();
11348 }
11349
11350 // The only time we can solve this is when we have all constant indices.
11351 // Otherwise, we cannot determine the overflow conditions.
11352 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
11353 return SE.getCouldNotCompute();
11354
11355 // Okay at this point we know that all elements of the chrec are constants and
11356 // that the start element is zero.
11357
11358 // First check to see if the range contains zero. If not, the first
11359 // iteration exits.
11360 unsigned BitWidth = SE.getTypeSizeInBits(getType());
11361 if (!Range.contains(APInt(BitWidth, 0)))
11362 return SE.getZero(getType());
11363
11364 if (isAffine()) {
11365 // If this is an affine expression then we have this situation:
11366 // Solve {0,+,A} in Range === Ax in Range
11367
11368 // We know that zero is in the range. If A is positive then we know that
11369 // the upper value of the range must be the first possible exit value.
11370 // If A is negative then the lower of the range is the last possible loop
11371 // value. Also note that we already checked for a full range.
11372 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
11373 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
11374
11375 // The exit value should be (End+A)/A.
11376 APInt ExitVal = (End + A).udiv(A);
11377 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
11378
11379 // Evaluate at the exit value. If we really did fall out of the valid
11380 // range, then we computed our trip count, otherwise wrap around or other
11381 // things must have happened.
11382 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
11383 if (Range.contains(Val->getValue()))
11384 return SE.getCouldNotCompute(); // Something strange happened
11385
11386 // Ensure that the previous value is in the range. This is a sanity check.
11387 assert(Range.contains(((Range.contains( EvaluateConstantChrecAtConstant(this, ConstantInt
::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
"Linear scev computation is off in a bad way!") ? static_cast
<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!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 11390, __PRETTY_FUNCTION__))
11388 EvaluateConstantChrecAtConstant(this,((Range.contains( EvaluateConstantChrecAtConstant(this, ConstantInt
::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
"Linear scev computation is off in a bad way!") ? static_cast
<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!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 11390, __PRETTY_FUNCTION__))
11389 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&((Range.contains( EvaluateConstantChrecAtConstant(this, ConstantInt
::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
"Linear scev computation is off in a bad way!") ? static_cast
<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!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 11390, __PRETTY_FUNCTION__))
11390 "Linear scev computation is off in a bad way!")((Range.contains( EvaluateConstantChrecAtConstant(this, ConstantInt
::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
"Linear scev computation is off in a bad way!") ? static_cast
<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!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 11390, __PRETTY_FUNCTION__))
;
11391 return SE.getConstant(ExitValue);
11392 }
11393
11394 if (isQuadratic()) {
11395 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
11396 return SE.getConstant(S.getValue());
11397 }
11398
11399 return SE.getCouldNotCompute();
11400}
11401
11402const SCEVAddRecExpr *
11403SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
11404 assert(getNumOperands() > 1 && "AddRec with zero step?")((getNumOperands() > 1 && "AddRec with zero step?"
) ? static_cast<void> (0) : __assert_fail ("getNumOperands() > 1 && \"AddRec with zero step?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 11404, __PRETTY_FUNCTION__))
;
11405 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
11406 // but in this case we cannot guarantee that the value returned will be an
11407 // AddRec because SCEV does not have a fixed point where it stops
11408 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
11409 // may happen if we reach arithmetic depth limit while simplifying. So we
11410 // construct the returned value explicitly.
11411 SmallVector<const SCEV *, 3> Ops;
11412 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
11413 // (this + Step) is {A+B,+,B+C,+...,+,N}.
11414 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
11415 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
11416 // We know that the last operand is not a constant zero (otherwise it would
11417 // have been popped out earlier). This guarantees us that if the result has
11418 // the same last operand, then it will also not be popped out, meaning that
11419 // the returned value will be an AddRec.
11420 const SCEV *Last = getOperand(getNumOperands() - 1);
11421 assert(!Last->isZero() && "Recurrency with zero step?")((!Last->isZero() && "Recurrency with zero step?")
? static_cast<void> (0) : __assert_fail ("!Last->isZero() && \"Recurrency with zero step?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 11421, __PRETTY_FUNCTION__))
;
11422 Ops.push_back(Last);
11423 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
11424 SCEV::FlagAnyWrap));
11425}
11426
11427// Return true when S contains at least an undef value.
11428static inline bool containsUndefs(const SCEV *S) {
11429 return SCEVExprContains(S, [](const SCEV *S) {
11430 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
11431 return isa<UndefValue>(SU->getValue());
11432 return false;
11433 });
11434}
11435
11436namespace {
11437
11438// Collect all steps of SCEV expressions.
11439struct SCEVCollectStrides {
11440 ScalarEvolution &SE;
11441 SmallVectorImpl<const SCEV *> &Strides;
11442
11443 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
11444 : SE(SE), Strides(S) {}
11445
11446 bool follow(const SCEV *S) {
11447 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
11448 Strides.push_back(AR->getStepRecurrence(SE));
11449 return true;
11450 }
11451
11452 bool isDone() const { return false; }
11453};
11454
11455// Collect all SCEVUnknown and SCEVMulExpr expressions.
11456struct SCEVCollectTerms {
11457 SmallVectorImpl<const SCEV *> &Terms;
11458
11459 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
11460
11461 bool follow(const SCEV *S) {
11462 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
11463 isa<SCEVSignExtendExpr>(S)) {
11464 if (!containsUndefs(S))
11465 Terms.push_back(S);
11466
11467 // Stop recursion: once we collected a term, do not walk its operands.
11468 return false;
11469 }
11470
11471 // Keep looking.
11472 return true;
11473 }
11474
11475 bool isDone() const { return false; }
11476};
11477
11478// Check if a SCEV contains an AddRecExpr.
11479struct SCEVHasAddRec {
11480 bool &ContainsAddRec;
11481
11482 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
11483 ContainsAddRec = false;
11484 }
11485
11486 bool follow(const SCEV *S) {
11487 if (isa<SCEVAddRecExpr>(S)) {
11488 ContainsAddRec = true;
11489
11490 // Stop recursion: once we collected a term, do not walk its operands.
11491 return false;
11492 }
11493
11494 // Keep looking.
11495 return true;
11496 }
11497
11498 bool isDone() const { return false; }
11499};
11500
11501// Find factors that are multiplied with an expression that (possibly as a
11502// subexpression) contains an AddRecExpr. In the expression:
11503//
11504// 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
11505//
11506// "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
11507// that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
11508// parameters as they form a product with an induction variable.
11509//
11510// This collector expects all array size parameters to be in the same MulExpr.
11511// It might be necessary to later add support for collecting parameters that are
11512// spread over different nested MulExpr.
11513struct SCEVCollectAddRecMultiplies {
11514 SmallVectorImpl<const SCEV *> &Terms;
11515 ScalarEvolution &SE;
11516
11517 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
11518 : Terms(T), SE(SE) {}
11519
11520 bool follow(const SCEV *S) {
11521 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
11522 bool HasAddRec = false;
11523 SmallVector<const SCEV *, 0> Operands;
11524 for (auto Op : Mul->operands()) {
11525 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
11526 if (Unknown && !isa<CallInst>(Unknown->getValue())) {
11527 Operands.push_back(Op);
11528 } else if (Unknown) {
11529 HasAddRec = true;
11530 } else {
11531 bool ContainsAddRec = false;
11532 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
11533 visitAll(Op, ContiansAddRec);
11534 HasAddRec |= ContainsAddRec;
11535 }
11536 }
11537 if (Operands.size() == 0)
11538 return true;
11539
11540 if (!HasAddRec)
11541 return false;
11542
11543 Terms.push_back(SE.getMulExpr(Operands));
11544 // Stop recursion: once we collected a term, do not walk its operands.
11545 return false;
11546 }
11547
11548 // Keep looking.
11549 return true;
11550 }
11551
11552 bool isDone() const { return false; }
11553};
11554
11555} // end anonymous namespace
11556
11557/// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
11558/// two places:
11559/// 1) The strides of AddRec expressions.
11560/// 2) Unknowns that are multiplied with AddRec expressions.
11561void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
11562 SmallVectorImpl<const SCEV *> &Terms) {
11563 SmallVector<const SCEV *, 4> Strides;
11564 SCEVCollectStrides StrideCollector(*this, Strides);
11565 visitAll(Expr, StrideCollector);
11566
11567 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Strides:\n"; for (
const SCEV *S : Strides) dbgs() << *S << "\n"; };
} } while (false)
11568 dbgs() << "Strides:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Strides:\n"; for (
const SCEV *S : Strides) dbgs() << *S << "\n"; };
} } while (false)
11569 for (const SCEV *S : Strides)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Strides:\n"; for (
const SCEV *S : Strides) dbgs() << *S << "\n"; };
} } while (false)
11570 dbgs() << *S << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Strides:\n"; for (
const SCEV *S : Strides) dbgs() << *S << "\n"; };
} } while (false)
11571 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Strides:\n"; for (
const SCEV *S : Strides) dbgs() << *S << "\n"; };
} } while (false)
;
11572
11573 for (const SCEV *S : Strides) {
11574 SCEVCollectTerms TermCollector(Terms);
11575 visitAll(S, TermCollector);
11576 }
11577
11578 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const
SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while
(false)
11579 dbgs() << "Terms:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const
SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while
(false)
11580 for (const SCEV *T : Terms)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const
SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while
(false)
11581 dbgs() << *T << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const
SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while
(false)
11582 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const
SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while
(false)
;
11583
11584 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
11585 visitAll(Expr, MulCollector);
11586}
11587
11588static bool findArrayDimensionsRec(ScalarEvolution &SE,
11589 SmallVectorImpl<const SCEV *> &Terms,
11590 SmallVectorImpl<const SCEV *> &Sizes) {
11591 int Last = Terms.size() - 1;
11592 const SCEV *Step = Terms[Last];
11593
11594 // End of recursion.
11595 if (Last == 0) {
11596 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
11597 SmallVector<const SCEV *, 2> Qs;
11598 for (const SCEV *Op : M->operands())
11599 if (!isa<SCEVConstant>(Op))
11600 Qs.push_back(Op);
11601
11602 Step = SE.getMulExpr(Qs);
11603 }
11604
11605 Sizes.push_back(Step);
11606 return true;
11607 }
11608
11609 for (const SCEV *&Term : Terms) {
11610 // Normalize the terms before the next call to findArrayDimensionsRec.
11611 const SCEV *Q, *R;
11612 SCEVDivision::divide(SE, Term, Step, &Q, &R);
11613
11614 // Bail out when GCD does not evenly divide one of the terms.
11615 if (!R->isZero())
11616 return false;
11617
11618 Term = Q;
11619 }
11620
11621 // Remove all SCEVConstants.
11622 Terms.erase(
11623 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
11624 Terms.end());
11625
11626 if (Terms.size() > 0)
11627 if (!findArrayDimensionsRec(SE, Terms, Sizes))
11628 return false;
11629
11630 Sizes.push_back(Step);
11631 return true;
11632}
11633
11634// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
11635static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
11636 for (const SCEV *T : Terms)
11637 if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); }))
11638 return true;
11639
11640 return false;
11641}
11642
11643// Return the number of product terms in S.
11644static inline int numberOfTerms(const SCEV *S) {
11645 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
11646 return Expr->getNumOperands();
11647 return 1;
11648}
11649
11650static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
11651 if (isa<SCEVConstant>(T))
11652 return nullptr;
11653
11654 if (isa<SCEVUnknown>(T))
11655 return T;
11656
11657 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
11658 SmallVector<const SCEV *, 2> Factors;
11659 for (const SCEV *Op : M->operands())
11660 if (!isa<SCEVConstant>(Op))
11661 Factors.push_back(Op);
11662
11663 return SE.getMulExpr(Factors);
11664 }
11665
11666 return T;
11667}
11668
11669/// Return the size of an element read or written by Inst.
11670const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
11671 Type *Ty;
11672 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
11673 Ty = Store->getValueOperand()->getType();
11674 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
11675 Ty = Load->getType();
11676 else
11677 return nullptr;
11678
11679 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
11680 return getSizeOfExpr(ETy, Ty);
11681}
11682
11683void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
11684 SmallVectorImpl<const SCEV *> &Sizes,
11685 const SCEV *ElementSize) {
11686 if (Terms.size() < 1 || !ElementSize)
11687 return;
11688
11689 // Early return when Terms do not contain parameters: we do not delinearize
11690 // non parametric SCEVs.
11691 if (!containsParameters(Terms))
11692 return;
11693
11694 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const
SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while
(false)
11695 dbgs() << "Terms:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const
SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while
(false)
11696 for (const SCEV *T : Terms)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const
SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while
(false)
11697 dbgs() << *T << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const
SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while
(false)
11698 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const
SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while
(false)
;
11699
11700 // Remove duplicates.
11701 array_pod_sort(Terms.begin(), Terms.end());
11702 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
11703
11704 // Put larger terms first.
11705 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) {
11706 return numberOfTerms(LHS) > numberOfTerms(RHS);
11707 });
11708
11709 // Try to divide all terms by the element size. If term is not divisible by
11710 // element size, proceed with the original term.
11711 for (const SCEV *&Term : Terms) {
11712 const SCEV *Q, *R;
11713 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
11714 if (!Q->isZero())
11715 Term = Q;
11716 }
11717
11718 SmallVector<const SCEV *, 4> NewTerms;
11719
11720 // Remove constant factors.
11721 for (const SCEV *T : Terms)
11722 if (const SCEV *NewT = removeConstantFactors(*this, T))
11723 NewTerms.push_back(NewT);
11724
11725 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Terms after sorting:\n"
; for (const SCEV *T : NewTerms) dbgs() << *T << "\n"
; }; } } while (false)
11726 dbgs() << "Terms after sorting:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Terms after sorting:\n"
; for (const SCEV *T : NewTerms) dbgs() << *T << "\n"
; }; } } while (false)
11727 for (const SCEV *T : NewTerms)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Terms after sorting:\n"
; for (const SCEV *T : NewTerms) dbgs() << *T << "\n"
; }; } } while (false)
11728 dbgs() << *T << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Terms after sorting:\n"
; for (const SCEV *T : NewTerms) dbgs() << *T << "\n"
; }; } } while (false)
11729 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Terms after sorting:\n"
; for (const SCEV *T : NewTerms) dbgs() << *T << "\n"
; }; } } while (false)
;
11730
11731 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
11732 Sizes.clear();
11733 return;
11734 }
11735
11736 // The last element to be pushed into Sizes is the size of an element.
11737 Sizes.push_back(ElementSize);
11738
11739 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Sizes:\n"; for (const
SCEV *S : Sizes) dbgs() << *S << "\n"; }; } } while
(false)
11740 dbgs() << "Sizes:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Sizes:\n"; for (const
SCEV *S : Sizes) dbgs() << *S << "\n"; }; } } while
(false)
11741 for (const SCEV *S : Sizes)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Sizes:\n"; for (const
SCEV *S : Sizes) dbgs() << *S << "\n"; }; } } while
(false)
11742 dbgs() << *S << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Sizes:\n"; for (const
SCEV *S : Sizes) dbgs() << *S << "\n"; }; } } while
(false)
11743 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Sizes:\n"; for (const
SCEV *S : Sizes) dbgs() << *S << "\n"; }; } } while
(false)
;
11744}
11745
11746void ScalarEvolution::computeAccessFunctions(
11747 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
11748 SmallVectorImpl<const SCEV *> &Sizes) {
11749 // Early exit in case this SCEV is not an affine multivariate function.
11750 if (Sizes.empty())
11751 return;
11752
11753 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
11754 if (!AR->isAffine())
11755 return;
11756
11757 const SCEV *Res = Expr;
11758 int Last = Sizes.size() - 1;
11759 for (int i = Last; i >= 0; i--) {
11760 const SCEV *Q, *R;
11761 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
11762
11763 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Res: " << *Res
<< "\n"; dbgs() << "Sizes[i]: " << *Sizes[
i] << "\n"; dbgs() << "Res divided by Sizes[i]:\n"
; dbgs() << "Quotient: " << *Q << "\n"; dbgs
() << "Remainder: " << *R << "\n"; }; } } while
(false)
11764 dbgs() << "Res: " << *Res << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Res: " << *Res
<< "\n"; dbgs() << "Sizes[i]: " << *Sizes[
i] << "\n"; dbgs() << "Res divided by Sizes[i]:\n"
; dbgs() << "Quotient: " << *Q << "\n"; dbgs
() << "Remainder: " << *R << "\n"; }; } } while
(false)
11765 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Res: " << *Res
<< "\n"; dbgs() << "Sizes[i]: " << *Sizes[
i] << "\n"; dbgs() << "Res divided by Sizes[i]:\n"
; dbgs() << "Quotient: " << *Q << "\n"; dbgs
() << "Remainder: " << *R << "\n"; }; } } while
(false)
11766 dbgs() << "Res divided by Sizes[i]:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Res: " << *Res
<< "\n"; dbgs() << "Sizes[i]: " << *Sizes[
i] << "\n"; dbgs() << "Res divided by Sizes[i]:\n"
; dbgs() << "Quotient: " << *Q << "\n"; dbgs
() << "Remainder: " << *R << "\n"; }; } } while
(false)
11767 dbgs() << "Quotient: " << *Q << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Res: " << *Res
<< "\n"; dbgs() << "Sizes[i]: " << *Sizes[
i] << "\n"; dbgs() << "Res divided by Sizes[i]:\n"
; dbgs() << "Quotient: " << *Q << "\n"; dbgs
() << "Remainder: " << *R << "\n"; }; } } while
(false)
11768 dbgs() << "Remainder: " << *R << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Res: " << *Res
<< "\n"; dbgs() << "Sizes[i]: " << *Sizes[
i] << "\n"; dbgs() << "Res divided by Sizes[i]:\n"
; dbgs() << "Quotient: " << *Q << "\n"; dbgs
() << "Remainder: " << *R << "\n"; }; } } while
(false)
11769 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Res: " << *Res
<< "\n"; dbgs() << "Sizes[i]: " << *Sizes[
i] << "\n"; dbgs() << "Res divided by Sizes[i]:\n"
; dbgs() << "Quotient: " << *Q << "\n"; dbgs
() << "Remainder: " << *R << "\n"; }; } } while
(false)
;
11770
11771 Res = Q;
11772
11773 // Do not record the last subscript corresponding to the size of elements in
11774 // the array.
11775 if (i == Last) {
11776
11777 // Bail out if the remainder is too complex.
11778 if (isa<SCEVAddRecExpr>(R)) {
11779 Subscripts.clear();
11780 Sizes.clear();
11781 return;
11782 }
11783
11784 continue;
11785 }
11786
11787 // Record the access function for the current subscript.
11788 Subscripts.push_back(R);
11789 }
11790
11791 // Also push in last position the remainder of the last division: it will be
11792 // the access function of the innermost dimension.
11793 Subscripts.push_back(Res);
11794
11795 std::reverse(Subscripts.begin(), Subscripts.end());
11796
11797 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Subscripts:\n"; for
(const SCEV *S : Subscripts) dbgs() << *S << "\n"
; }; } } while (false)
11798 dbgs() << "Subscripts:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Subscripts:\n"; for
(const SCEV *S : Subscripts) dbgs() << *S << "\n"
; }; } } while (false)
11799 for (const SCEV *S : Subscripts)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Subscripts:\n"; for
(const SCEV *S : Subscripts) dbgs() << *S << "\n"
; }; } } while (false)
11800 dbgs() << *S << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Subscripts:\n"; for
(const SCEV *S : Subscripts) dbgs() << *S << "\n"
; }; } } while (false)
11801 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "Subscripts:\n"; for
(const SCEV *S : Subscripts) dbgs() << *S << "\n"
; }; } } while (false)
;
11802}
11803
11804/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
11805/// sizes of an array access. Returns the remainder of the delinearization that
11806/// is the offset start of the array. The SCEV->delinearize algorithm computes
11807/// the multiples of SCEV coefficients: that is a pattern matching of sub
11808/// expressions in the stride and base of a SCEV corresponding to the
11809/// computation of a GCD (greatest common divisor) of base and stride. When
11810/// SCEV->delinearize fails, it returns the SCEV unchanged.
11811///
11812/// For example: when analyzing the memory access A[i][j][k] in this loop nest
11813///
11814/// void foo(long n, long m, long o, double A[n][m][o]) {
11815///
11816/// for (long i = 0; i < n; i++)
11817/// for (long j = 0; j < m; j++)
11818/// for (long k = 0; k < o; k++)
11819/// A[i][j][k] = 1.0;
11820/// }
11821///
11822/// the delinearization input is the following AddRec SCEV:
11823///
11824/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
11825///
11826/// From this SCEV, we are able to say that the base offset of the access is %A
11827/// because it appears as an offset that does not divide any of the strides in
11828/// the loops:
11829///
11830/// CHECK: Base offset: %A
11831///
11832/// and then SCEV->delinearize determines the size of some of the dimensions of
11833/// the array as these are the multiples by which the strides are happening:
11834///
11835/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
11836///
11837/// Note that the outermost dimension remains of UnknownSize because there are
11838/// no strides that would help identifying the size of the last dimension: when
11839/// the array has been statically allocated, one could compute the size of that
11840/// dimension by dividing the overall size of the array by the size of the known
11841/// dimensions: %m * %o * 8.
11842///
11843/// Finally delinearize provides the access functions for the array reference
11844/// that does correspond to A[i][j][k] of the above C testcase:
11845///
11846/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
11847///
11848/// The testcases are checking the output of a function pass:
11849/// DelinearizationPass that walks through all loads and stores of a function
11850/// asking for the SCEV of the memory access with respect to all enclosing
11851/// loops, calling SCEV->delinearize on that and printing the results.
11852void ScalarEvolution::delinearize(const SCEV *Expr,
11853 SmallVectorImpl<const SCEV *> &Subscripts,
11854 SmallVectorImpl<const SCEV *> &Sizes,
11855 const SCEV *ElementSize) {
11856 // First step: collect parametric terms.
11857 SmallVector<const SCEV *, 4> Terms;
11858 collectParametricTerms(Expr, Terms);
11859
11860 if (Terms.empty())
11861 return;
11862
11863 // Second step: find subscript sizes.
11864 findArrayDimensions(Terms, Sizes, ElementSize);
11865
11866 if (Sizes.empty())
11867 return;
11868
11869 // Third step: compute the access functions for each subscript.
11870 computeAccessFunctions(Expr, Subscripts, Sizes);
11871
11872 if (Subscripts.empty())
11873 return;
11874
11875 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "succeeded to delinearize "
<< *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]"
; for (const SCEV *S : Sizes) dbgs() << "[" << *S
<< "]"; dbgs() << "\nArrayRef"; for (const SCEV *
S : Subscripts) dbgs() << "[" << *S << "]";
dbgs() << "\n"; }; } } while (false)
11876 dbgs() << "succeeded to delinearize " << *Expr << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "succeeded to delinearize "
<< *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]"
; for (const SCEV *S : Sizes) dbgs() << "[" << *S
<< "]"; dbgs() << "\nArrayRef"; for (const SCEV *
S : Subscripts) dbgs() << "[" << *S << "]";
dbgs() << "\n"; }; } } while (false)
11877 dbgs() << "ArrayDecl[UnknownSize]";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "succeeded to delinearize "
<< *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]"
; for (const SCEV *S : Sizes) dbgs() << "[" << *S
<< "]"; dbgs() << "\nArrayRef"; for (const SCEV *
S : Subscripts) dbgs() << "[" << *S << "]";
dbgs() << "\n"; }; } } while (false)
11878 for (const SCEV *S : Sizes)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "succeeded to delinearize "
<< *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]"
; for (const SCEV *S : Sizes) dbgs() << "[" << *S
<< "]"; dbgs() << "\nArrayRef"; for (const SCEV *
S : Subscripts) dbgs() << "[" << *S << "]";
dbgs() << "\n"; }; } } while (false)
11879 dbgs() << "[" << *S << "]";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "succeeded to delinearize "
<< *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]"
; for (const SCEV *S : Sizes) dbgs() << "[" << *S
<< "]"; dbgs() << "\nArrayRef"; for (const SCEV *
S : Subscripts) dbgs() << "[" << *S << "]";
dbgs() << "\n"; }; } } while (false)
11880
11881 dbgs() << "\nArrayRef";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "succeeded to delinearize "
<< *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]"
; for (const SCEV *S : Sizes) dbgs() << "[" << *S
<< "]"; dbgs() << "\nArrayRef"; for (const SCEV *
S : Subscripts) dbgs() << "[" << *S << "]";
dbgs() << "\n"; }; } } while (false)
11882 for (const SCEV *S : Subscripts)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "succeeded to delinearize "
<< *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]"
; for (const SCEV *S : Sizes) dbgs() << "[" << *S
<< "]"; dbgs() << "\nArrayRef"; for (const SCEV *
S : Subscripts) dbgs() << "[" << *S << "]";
dbgs() << "\n"; }; } } while (false)
11883 dbgs() << "[" << *S << "]";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "succeeded to delinearize "
<< *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]"
; for (const SCEV *S : Sizes) dbgs() << "[" << *S
<< "]"; dbgs() << "\nArrayRef"; for (const SCEV *
S : Subscripts) dbgs() << "[" << *S << "]";
dbgs() << "\n"; }; } } while (false)
11884 dbgs() << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "succeeded to delinearize "
<< *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]"
; for (const SCEV *S : Sizes) dbgs() << "[" << *S
<< "]"; dbgs() << "\nArrayRef"; for (const SCEV *
S : Subscripts) dbgs() << "[" << *S << "]";
dbgs() << "\n"; }; } } while (false)
11885 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("scalar-evolution")) { { dbgs() << "succeeded to delinearize "
<< *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]"
; for (const SCEV *S : Sizes) dbgs() << "[" << *S
<< "]"; dbgs() << "\nArrayRef"; for (const SCEV *
S : Subscripts) dbgs() << "[" << *S << "]";
dbgs() << "\n"; }; } } while (false)
;
11886}
11887
11888bool ScalarEvolution::getIndexExpressionsFromGEP(
11889 const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts,
11890 SmallVectorImpl<int> &Sizes) {
11891 assert(Subscripts.empty() && Sizes.empty() &&((Subscripts.empty() && Sizes.empty() && "Expected output lists to be empty on entry to this function."
) ? static_cast<void> (0) : __assert_fail ("Subscripts.empty() && Sizes.empty() && \"Expected output lists to be empty on entry to this function.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 11892, __PRETTY_FUNCTION__))
11892 "Expected output lists to be empty on entry to this function.")((Subscripts.empty() && Sizes.empty() && "Expected output lists to be empty on entry to this function."
) ? static_cast<void> (0) : __assert_fail ("Subscripts.empty() && Sizes.empty() && \"Expected output lists to be empty on entry to this function.\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 11892, __PRETTY_FUNCTION__))
;
11893 assert(GEP && "getIndexExpressionsFromGEP called with a null GEP")((GEP && "getIndexExpressionsFromGEP called with a null GEP"
) ? static_cast<void> (0) : __assert_fail ("GEP && \"getIndexExpressionsFromGEP called with a null GEP\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 11893, __PRETTY_FUNCTION__))
;
11894 Type *Ty = GEP->getPointerOperandType();
11895 bool DroppedFirstDim = false;
11896 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
11897 const SCEV *Expr = getSCEV(GEP->getOperand(i));
11898 if (i == 1) {
11899 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
11900 Ty = PtrTy->getElementType();
11901 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
11902 Ty = ArrayTy->getElementType();
11903 } else {
11904 Subscripts.clear();
11905 Sizes.clear();
11906 return false;
11907 }
11908 if (auto *Const = dyn_cast<SCEVConstant>(Expr))
11909 if (Const->getValue()->isZero()) {
11910 DroppedFirstDim = true;
11911 continue;
11912 }
11913 Subscripts.push_back(Expr);
11914 continue;
11915 }
11916
11917 auto *ArrayTy = dyn_cast<ArrayType>(Ty);
11918 if (!ArrayTy) {
11919 Subscripts.clear();
11920 Sizes.clear();
11921 return false;
11922 }
11923
11924 Subscripts.push_back(Expr);
11925 if (!(DroppedFirstDim && i == 2))
11926 Sizes.push_back(ArrayTy->getNumElements());
11927
11928 Ty = ArrayTy->getElementType();
11929 }
11930 return !Subscripts.empty();
11931}
11932
11933//===----------------------------------------------------------------------===//
11934// SCEVCallbackVH Class Implementation
11935//===----------------------------------------------------------------------===//
11936
11937void ScalarEvolution::SCEVCallbackVH::deleted() {
11938 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!")((SE && "SCEVCallbackVH called with a null ScalarEvolution!"
) ? static_cast<void> (0) : __assert_fail ("SE && \"SCEVCallbackVH called with a null ScalarEvolution!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 11938, __PRETTY_FUNCTION__))
;
11939 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
11940 SE->ConstantEvolutionLoopExitValue.erase(PN);
11941 SE->eraseValueFromMap(getValPtr());
11942 // this now dangles!
11943}
11944
11945void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
11946 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!")((SE && "SCEVCallbackVH called with a null ScalarEvolution!"
) ? static_cast<void> (0) : __assert_fail ("SE && \"SCEVCallbackVH called with a null ScalarEvolution!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 11946, __PRETTY_FUNCTION__))
;
11947
11948 // Forget all the expressions associated with users of the old value,
11949 // so that future queries will recompute the expressions using the new
11950 // value.
11951 Value *Old = getValPtr();
11952 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
11953 SmallPtrSet<User *, 8> Visited;
11954 while (!Worklist.empty()) {
11955 User *U = Worklist.pop_back_val();
11956 // Deleting the Old value will cause this to dangle. Postpone
11957 // that until everything else is done.
11958 if (U == Old)
11959 continue;
11960 if (!Visited.insert(U).second)
11961 continue;
11962 if (PHINode *PN = dyn_cast<PHINode>(U))
11963 SE->ConstantEvolutionLoopExitValue.erase(PN);
11964 SE->eraseValueFromMap(U);
11965 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
11966 }
11967 // Delete the Old value.
11968 if (PHINode *PN = dyn_cast<PHINode>(Old))
11969 SE->ConstantEvolutionLoopExitValue.erase(PN);
11970 SE->eraseValueFromMap(Old);
11971 // this now dangles!
11972}
11973
11974ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
11975 : CallbackVH(V), SE(se) {}
11976
11977//===----------------------------------------------------------------------===//
11978// ScalarEvolution Class Implementation
11979//===----------------------------------------------------------------------===//
11980
11981ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
11982 AssumptionCache &AC, DominatorTree &DT,
11983 LoopInfo &LI)
11984 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
11985 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
11986 LoopDispositions(64), BlockDispositions(64) {
11987 // To use guards for proving predicates, we need to scan every instruction in
11988 // relevant basic blocks, and not just terminators. Doing this is a waste of
11989 // time if the IR does not actually contain any calls to
11990 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
11991 //
11992 // This pessimizes the case where a pass that preserves ScalarEvolution wants
11993 // to _add_ guards to the module when there weren't any before, and wants
11994 // ScalarEvolution to optimize based on those guards. For now we prefer to be
11995 // efficient in lieu of being smart in that rather obscure case.
11996
11997 auto *GuardDecl = F.getParent()->getFunction(
11998 Intrinsic::getName(Intrinsic::experimental_guard));
11999 HasGuards = GuardDecl && !GuardDecl->use_empty();
12000}
12001
12002ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
12003 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
12004 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
12005 ValueExprMap(std::move(Arg.ValueExprMap)),
12006 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
12007 PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
12008 PendingMerges(std::move(Arg.PendingMerges)),
12009 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
12010 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
12011 PredicatedBackedgeTakenCounts(
12012 std::move(Arg.PredicatedBackedgeTakenCounts)),
12013 ConstantEvolutionLoopExitValue(
12014 std::move(Arg.ConstantEvolutionLoopExitValue)),
12015 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
12016 LoopDispositions(std::move(Arg.LoopDispositions)),
12017 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
12018 BlockDispositions(std::move(Arg.BlockDispositions)),
12019 UnsignedRanges(std::move(Arg.UnsignedRanges)),
12020 SignedRanges(std::move(Arg.SignedRanges)),
12021 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
12022 UniquePreds(std::move(Arg.UniquePreds)),
12023 SCEVAllocator(std::move(Arg.SCEVAllocator)),
12024 LoopUsers(std::move(Arg.LoopUsers)),
12025 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
12026 FirstUnknown(Arg.FirstUnknown) {
12027 Arg.FirstUnknown = nullptr;
12028}
12029
12030ScalarEvolution::~ScalarEvolution() {
12031 // Iterate through all the SCEVUnknown instances and call their
12032 // destructors, so that they release their references to their values.
12033 for (SCEVUnknown *U = FirstUnknown; U;) {
12034 SCEVUnknown *Tmp = U;
12035 U = U->Next;
12036 Tmp->~SCEVUnknown();
12037 }
12038 FirstUnknown = nullptr;
12039
12040 ExprValueMap.clear();
12041 ValueExprMap.clear();
12042 HasRecMap.clear();
12043
12044 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
12045 // that a loop had multiple computable exits.
12046 for (auto &BTCI : BackedgeTakenCounts)
12047 BTCI.second.clear();
12048 for (auto &BTCI : PredicatedBackedgeTakenCounts)
12049 BTCI.second.clear();
12050
12051 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage")((PendingLoopPredicates.empty() && "isImpliedCond garbage"
) ? static_cast<void> (0) : __assert_fail ("PendingLoopPredicates.empty() && \"isImpliedCond garbage\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12051, __PRETTY_FUNCTION__))
;
12052 assert(PendingPhiRanges.empty() && "getRangeRef garbage")((PendingPhiRanges.empty() && "getRangeRef garbage") ?
static_cast<void> (0) : __assert_fail ("PendingPhiRanges.empty() && \"getRangeRef garbage\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12052, __PRETTY_FUNCTION__))
;
12053 assert(PendingMerges.empty() && "isImpliedViaMerge garbage")((PendingMerges.empty() && "isImpliedViaMerge garbage"
) ? static_cast<void> (0) : __assert_fail ("PendingMerges.empty() && \"isImpliedViaMerge garbage\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12053, __PRETTY_FUNCTION__))
;
12054 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!")((!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"
) ? static_cast<void> (0) : __assert_fail ("!WalkingBEDominatingConds && \"isLoopBackedgeGuardedByCond garbage!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12054, __PRETTY_FUNCTION__))
;
12055 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!")((!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"
) ? static_cast<void> (0) : __assert_fail ("!ProvingSplitPredicate && \"ProvingSplitPredicate garbage!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12055, __PRETTY_FUNCTION__))
;
12056}
12057
12058bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
12059 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
12060}
12061
12062static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
12063 const Loop *L) {
12064 // Print all inner loops first
12065 for (Loop *I : *L)
12066 PrintLoopInfo(OS, SE, I);
12067
12068 OS << "Loop ";
12069 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12070 OS << ": ";
12071
12072 SmallVector<BasicBlock *, 8> ExitingBlocks;
12073 L->getExitingBlocks(ExitingBlocks);
12074 if (ExitingBlocks.size() != 1)
12075 OS << "<multiple exits> ";
12076
12077 if (SE->hasLoopInvariantBackedgeTakenCount(L))
12078 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
12079 else
12080 OS << "Unpredictable backedge-taken count.\n";
12081
12082 if (ExitingBlocks.size() > 1)
12083 for (BasicBlock *ExitingBlock : ExitingBlocks) {
12084 OS << " exit count for " << ExitingBlock->getName() << ": "
12085 << *SE->getExitCount(L, ExitingBlock) << "\n";
12086 }
12087
12088 OS << "Loop ";
12089 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12090 OS << ": ";
12091
12092 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
12093 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
12094 if (SE->isBackedgeTakenCountMaxOrZero(L))
12095 OS << ", actual taken count either this or zero.";
12096 } else {
12097 OS << "Unpredictable max backedge-taken count. ";
12098 }
12099
12100 OS << "\n"
12101 "Loop ";
12102 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12103 OS << ": ";
12104
12105 SCEVUnionPredicate Pred;
12106 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
12107 if (!isa<SCEVCouldNotCompute>(PBT)) {
12108 OS << "Predicated backedge-taken count is " << *PBT << "\n";
12109 OS << " Predicates:\n";
12110 Pred.print(OS, 4);
12111 } else {
12112 OS << "Unpredictable predicated backedge-taken count. ";
12113 }
12114 OS << "\n";
12115
12116 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
12117 OS << "Loop ";
12118 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12119 OS << ": ";
12120 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
12121 }
12122}
12123
12124static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
12125 switch (LD) {
12126 case ScalarEvolution::LoopVariant:
12127 return "Variant";
12128 case ScalarEvolution::LoopInvariant:
12129 return "Invariant";
12130 case ScalarEvolution::LoopComputable:
12131 return "Computable";
12132 }
12133 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!")::llvm::llvm_unreachable_internal("Unknown ScalarEvolution::LoopDisposition kind!"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12133)
;
12134}
12135
12136void ScalarEvolution::print(raw_ostream &OS) const {
12137 // ScalarEvolution's implementation of the print method is to print
12138 // out SCEV values of all instructions that are interesting. Doing
12139 // this potentially causes it to create new SCEV objects though,
12140 // which technically conflicts with the const qualifier. This isn't
12141 // observable from outside the class though, so casting away the
12142 // const isn't dangerous.
12143 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12144
12145 if (ClassifyExpressions) {
12146 OS << "Classifying expressions for: ";
12147 F.printAsOperand(OS, /*PrintType=*/false);
12148 OS << "\n";
12149 for (Instruction &I : instructions(F))
12150 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
12151 OS << I << '\n';
12152 OS << " --> ";
12153 const SCEV *SV = SE.getSCEV(&I);
12154 SV->print(OS);
12155 if (!isa<SCEVCouldNotCompute>(SV)) {
12156 OS << " U: ";
12157 SE.getUnsignedRange(SV).print(OS);
12158 OS << " S: ";
12159 SE.getSignedRange(SV).print(OS);
12160 }
12161
12162 const Loop *L = LI.getLoopFor(I.getParent());
12163
12164 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
12165 if (AtUse != SV) {
12166 OS << " --> ";
12167 AtUse->print(OS);
12168 if (!isa<SCEVCouldNotCompute>(AtUse)) {
12169 OS << " U: ";
12170 SE.getUnsignedRange(AtUse).print(OS);
12171 OS << " S: ";
12172 SE.getSignedRange(AtUse).print(OS);
12173 }
12174 }
12175
12176 if (L) {
12177 OS << "\t\t" "Exits: ";
12178 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
12179 if (!SE.isLoopInvariant(ExitValue, L)) {
12180 OS << "<<Unknown>>";
12181 } else {
12182 OS << *ExitValue;
12183 }
12184
12185 bool First = true;
12186 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
12187 if (First) {
12188 OS << "\t\t" "LoopDispositions: { ";
12189 First = false;
12190 } else {
12191 OS << ", ";
12192 }
12193
12194 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12195 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
12196 }
12197
12198 for (auto *InnerL : depth_first(L)) {
12199 if (InnerL == L)
12200 continue;
12201 if (First) {
12202 OS << "\t\t" "LoopDispositions: { ";
12203 First = false;
12204 } else {
12205 OS << ", ";
12206 }
12207
12208 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
12209 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
12210 }
12211
12212 OS << " }";
12213 }
12214
12215 OS << "\n";
12216 }
12217 }
12218
12219 OS << "Determining loop execution counts for: ";
12220 F.printAsOperand(OS, /*PrintType=*/false);
12221 OS << "\n";
12222 for (Loop *I : LI)
12223 PrintLoopInfo(OS, &SE, I);
12224}
12225
12226ScalarEvolution::LoopDisposition
12227ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
12228 auto &Values = LoopDispositions[S];
12229 for (auto &V : Values) {
12230 if (V.getPointer() == L)
12231 return V.getInt();
12232 }
12233 Values.emplace_back(L, LoopVariant);
12234 LoopDisposition D = computeLoopDisposition(S, L);
12235 auto &Values2 = LoopDispositions[S];
12236 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12237 if (V.getPointer() == L) {
12238 V.setInt(D);
12239 break;
12240 }
12241 }
12242 return D;
12243}
12244
12245ScalarEvolution::LoopDisposition
12246ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
12247 switch (S->getSCEVType()) {
12248 case scConstant:
12249 return LoopInvariant;
12250 case scPtrToInt:
12251 case scTruncate:
12252 case scZeroExtend:
12253 case scSignExtend:
12254 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
12255 case scAddRecExpr: {
12256 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12257
12258 // If L is the addrec's loop, it's computable.
12259 if (AR->getLoop() == L)
12260 return LoopComputable;
12261
12262 // Add recurrences are never invariant in the function-body (null loop).
12263 if (!L)
12264 return LoopVariant;
12265
12266 // Everything that is not defined at loop entry is variant.
12267 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
12268 return LoopVariant;
12269 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"((!L->contains(AR->getLoop()) && "Containing loop's header does not"
" dominate the contained loop's header?") ? static_cast<void
> (0) : __assert_fail ("!L->contains(AR->getLoop()) && \"Containing loop's header does not\" \" dominate the contained loop's header?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12270, __PRETTY_FUNCTION__))
12270 " dominate the contained loop's header?")((!L->contains(AR->getLoop()) && "Containing loop's header does not"
" dominate the contained loop's header?") ? static_cast<void
> (0) : __assert_fail ("!L->contains(AR->getLoop()) && \"Containing loop's header does not\" \" dominate the contained loop's header?\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12270, __PRETTY_FUNCTION__))
;
12271
12272 // This recurrence is invariant w.r.t. L if AR's loop contains L.
12273 if (AR->getLoop()->contains(L))
12274 return LoopInvariant;
12275
12276 // This recurrence is variant w.r.t. L if any of its operands
12277 // are variant.
12278 for (auto *Op : AR->operands())
12279 if (!isLoopInvariant(Op, L))
12280 return LoopVariant;
12281
12282 // Otherwise it's loop-invariant.
12283 return LoopInvariant;
12284 }
12285 case scAddExpr:
12286 case scMulExpr:
12287 case scUMaxExpr:
12288 case scSMaxExpr:
12289 case scUMinExpr:
12290 case scSMinExpr: {
12291 bool HasVarying = false;
12292 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
12293 LoopDisposition D = getLoopDisposition(Op, L);
12294 if (D == LoopVariant)
12295 return LoopVariant;
12296 if (D == LoopComputable)
12297 HasVarying = true;
12298 }
12299 return HasVarying ? LoopComputable : LoopInvariant;
12300 }
12301 case scUDivExpr: {
12302 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12303 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
12304 if (LD == LoopVariant)
12305 return LoopVariant;
12306 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
12307 if (RD == LoopVariant)
12308 return LoopVariant;
12309 return (LD == LoopInvariant && RD == LoopInvariant) ?
12310 LoopInvariant : LoopComputable;
12311 }
12312 case scUnknown:
12313 // All non-instruction values are loop invariant. All instructions are loop
12314 // invariant if they are not contained in the specified loop.
12315 // Instructions are never considered invariant in the function body
12316 // (null loop) because they are defined within the "loop".
12317 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
12318 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
12319 return LoopInvariant;
12320 case scCouldNotCompute:
12321 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12321)
;
12322 }
12323 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12323)
;
12324}
12325
12326bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
12327 return getLoopDisposition(S, L) == LoopInvariant;
2
Assuming the condition is false
3
Returning zero, which participates in a condition later
7
Assuming the condition is true
8
Returning the value 1, which participates in a condition later
12328}
12329
12330bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
12331 return getLoopDisposition(S, L) == LoopComputable;
12332}
12333
12334ScalarEvolution::BlockDisposition
12335ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12336 auto &Values = BlockDispositions[S];
12337 for (auto &V : Values) {
12338 if (V.getPointer() == BB)
12339 return V.getInt();
12340 }
12341 Values.emplace_back(BB, DoesNotDominateBlock);
12342 BlockDisposition D = computeBlockDisposition(S, BB);
12343 auto &Values2 = BlockDispositions[S];
12344 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
12345 if (V.getPointer() == BB) {
12346 V.setInt(D);
12347 break;
12348 }
12349 }
12350 return D;
12351}
12352
12353ScalarEvolution::BlockDisposition
12354ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
12355 switch (S->getSCEVType()) {
12356 case scConstant:
12357 return ProperlyDominatesBlock;
12358 case scPtrToInt:
12359 case scTruncate:
12360 case scZeroExtend:
12361 case scSignExtend:
12362 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
12363 case scAddRecExpr: {
12364 // This uses a "dominates" query instead of "properly dominates" query
12365 // to test for proper dominance too, because the instruction which
12366 // produces the addrec's value is a PHI, and a PHI effectively properly
12367 // dominates its entire containing block.
12368 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
12369 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
12370 return DoesNotDominateBlock;
12371
12372 // Fall through into SCEVNAryExpr handling.
12373 LLVM_FALLTHROUGH[[gnu::fallthrough]];
12374 }
12375 case scAddExpr:
12376 case scMulExpr:
12377 case scUMaxExpr:
12378 case scSMaxExpr:
12379 case scUMinExpr:
12380 case scSMinExpr: {
12381 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
12382 bool Proper = true;
12383 for (const SCEV *NAryOp : NAry->operands()) {
12384 BlockDisposition D = getBlockDisposition(NAryOp, BB);
12385 if (D == DoesNotDominateBlock)
12386 return DoesNotDominateBlock;
12387 if (D == DominatesBlock)
12388 Proper = false;
12389 }
12390 return Proper ? ProperlyDominatesBlock : DominatesBlock;
12391 }
12392 case scUDivExpr: {
12393 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
12394 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
12395 BlockDisposition LD = getBlockDisposition(LHS, BB);
12396 if (LD == DoesNotDominateBlock)
12397 return DoesNotDominateBlock;
12398 BlockDisposition RD = getBlockDisposition(RHS, BB);
12399 if (RD == DoesNotDominateBlock)
12400 return DoesNotDominateBlock;
12401 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
12402 ProperlyDominatesBlock : DominatesBlock;
12403 }
12404 case scUnknown:
12405 if (Instruction *I =
12406 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
12407 if (I->getParent() == BB)
12408 return DominatesBlock;
12409 if (DT.properlyDominates(I->getParent(), BB))
12410 return ProperlyDominatesBlock;
12411 return DoesNotDominateBlock;
12412 }
12413 return ProperlyDominatesBlock;
12414 case scCouldNotCompute:
12415 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12415)
;
12416 }
12417 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12417)
;
12418}
12419
12420bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
12421 return getBlockDisposition(S, BB) >= DominatesBlock;
12422}
12423
12424bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
12425 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
12426}
12427
12428bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
12429 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
12430}
12431
12432bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
12433 auto IsS = [&](const SCEV *X) { return S == X; };
12434 auto ContainsS = [&](const SCEV *X) {
12435 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
12436 };
12437 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
12438}
12439
12440void
12441ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
12442 ValuesAtScopes.erase(S);
12443 LoopDispositions.erase(S);
12444 BlockDispositions.erase(S);
12445 UnsignedRanges.erase(S);
12446 SignedRanges.erase(S);
12447 ExprValueMap.erase(S);
12448 HasRecMap.erase(S);
12449 MinTrailingZerosCache.erase(S);
12450
12451 for (auto I = PredicatedSCEVRewrites.begin();
12452 I != PredicatedSCEVRewrites.end();) {
12453 std::pair<const SCEV *, const Loop *> Entry = I->first;
12454 if (Entry.first == S)
12455 PredicatedSCEVRewrites.erase(I++);
12456 else
12457 ++I;
12458 }
12459
12460 auto RemoveSCEVFromBackedgeMap =
12461 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
12462 for (auto I = Map.begin(), E = Map.end(); I != E;) {
12463 BackedgeTakenInfo &BEInfo = I->second;
12464 if (BEInfo.hasOperand(S, this)) {
12465 BEInfo.clear();
12466 Map.erase(I++);
12467 } else
12468 ++I;
12469 }
12470 };
12471
12472 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
12473 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
12474}
12475
12476void
12477ScalarEvolution::getUsedLoops(const SCEV *S,
12478 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
12479 struct FindUsedLoops {
12480 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
12481 : LoopsUsed(LoopsUsed) {}
12482 SmallPtrSetImpl<const Loop *> &LoopsUsed;
12483 bool follow(const SCEV *S) {
12484 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
12485 LoopsUsed.insert(AR->getLoop());
12486 return true;
12487 }
12488
12489 bool isDone() const { return false; }
12490 };
12491
12492 FindUsedLoops F(LoopsUsed);
12493 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
12494}
12495
12496void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
12497 SmallPtrSet<const Loop *, 8> LoopsUsed;
12498 getUsedLoops(S, LoopsUsed);
12499 for (auto *L : LoopsUsed)
12500 LoopUsers[L].push_back(S);
12501}
12502
12503void ScalarEvolution::verify() const {
12504 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
12505 ScalarEvolution SE2(F, TLI, AC, DT, LI);
12506
12507 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
12508
12509 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
12510 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
12511 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
12512
12513 const SCEV *visitConstant(const SCEVConstant *Constant) {
12514 return SE.getConstant(Constant->getAPInt());
12515 }
12516
12517 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12518 return SE.getUnknown(Expr->getValue());
12519 }
12520
12521 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
12522 return SE.getCouldNotCompute();
12523 }
12524 };
12525
12526 SCEVMapper SCM(SE2);
12527
12528 while (!LoopStack.empty()) {
12529 auto *L = LoopStack.pop_back_val();
12530 LoopStack.insert(LoopStack.end(), L->begin(), L->end());
12531
12532 auto *CurBECount = SCM.visit(
12533 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
12534 auto *NewBECount = SE2.getBackedgeTakenCount(L);
12535
12536 if (CurBECount == SE2.getCouldNotCompute() ||
12537 NewBECount == SE2.getCouldNotCompute()) {
12538 // NB! This situation is legal, but is very suspicious -- whatever pass
12539 // change the loop to make a trip count go from could not compute to
12540 // computable or vice-versa *should have* invalidated SCEV. However, we
12541 // choose not to assert here (for now) since we don't want false
12542 // positives.
12543 continue;
12544 }
12545
12546 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
12547 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
12548 // not propagate undef aggressively). This means we can (and do) fail
12549 // verification in cases where a transform makes the trip count of a loop
12550 // go from "undef" to "undef+1" (say). The transform is fine, since in
12551 // both cases the loop iterates "undef" times, but SCEV thinks we
12552 // increased the trip count of the loop by 1 incorrectly.
12553 continue;
12554 }
12555
12556 if (SE.getTypeSizeInBits(CurBECount->getType()) >
12557 SE.getTypeSizeInBits(NewBECount->getType()))
12558 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
12559 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
12560 SE.getTypeSizeInBits(NewBECount->getType()))
12561 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
12562
12563 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
12564
12565 // Unless VerifySCEVStrict is set, we only compare constant deltas.
12566 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
12567 dbgs() << "Trip Count for " << *L << " Changed!\n";
12568 dbgs() << "Old: " << *CurBECount << "\n";
12569 dbgs() << "New: " << *NewBECount << "\n";
12570 dbgs() << "Delta: " << *Delta << "\n";
12571 std::abort();
12572 }
12573 }
12574
12575 // Collect all valid loops currently in LoopInfo.
12576 SmallPtrSet<Loop *, 32> ValidLoops;
12577 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
12578 while (!Worklist.empty()) {
12579 Loop *L = Worklist.pop_back_val();
12580 if (ValidLoops.contains(L))
12581 continue;
12582 ValidLoops.insert(L);
12583 Worklist.append(L->begin(), L->end());
12584 }
12585 // Check for SCEV expressions referencing invalid/deleted loops.
12586 for (auto &KV : ValueExprMap) {
12587 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second);
12588 if (!AR)
12589 continue;
12590 assert(ValidLoops.contains(AR->getLoop()) &&((ValidLoops.contains(AR->getLoop()) && "AddRec references invalid loop"
) ? static_cast<void> (0) : __assert_fail ("ValidLoops.contains(AR->getLoop()) && \"AddRec references invalid loop\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12591, __PRETTY_FUNCTION__))
12591 "AddRec references invalid loop")((ValidLoops.contains(AR->getLoop()) && "AddRec references invalid loop"
) ? static_cast<void> (0) : __assert_fail ("ValidLoops.contains(AR->getLoop()) && \"AddRec references invalid loop\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12591, __PRETTY_FUNCTION__))
;
12592 }
12593}
12594
12595bool ScalarEvolution::invalidate(
12596 Function &F, const PreservedAnalyses &PA,
12597 FunctionAnalysisManager::Invalidator &Inv) {
12598 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
12599 // of its dependencies is invalidated.
12600 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
12601 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
12602 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
12603 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
12604 Inv.invalidate<LoopAnalysis>(F, PA);
12605}
12606
12607AnalysisKey ScalarEvolutionAnalysis::Key;
12608
12609ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
12610 FunctionAnalysisManager &AM) {
12611 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
12612 AM.getResult<AssumptionAnalysis>(F),
12613 AM.getResult<DominatorTreeAnalysis>(F),
12614 AM.getResult<LoopAnalysis>(F));
12615}
12616
12617PreservedAnalyses
12618ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
12619 AM.getResult<ScalarEvolutionAnalysis>(F).verify();
12620 return PreservedAnalyses::all();
12621}
12622
12623PreservedAnalyses
12624ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
12625 // For compatibility with opt's -analyze feature under legacy pass manager
12626 // which was not ported to NPM. This keeps tests using
12627 // update_analyze_test_checks.py working.
12628 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
12629 << F.getName() << "':\n";
12630 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
12631 return PreservedAnalyses::all();
12632}
12633
12634INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",static void *initializeScalarEvolutionWrapperPassPassOnce(PassRegistry
&Registry) {
12635 "Scalar Evolution Analysis", false, true)static void *initializeScalarEvolutionWrapperPassPassOnce(PassRegistry
&Registry) {
12636INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry);
12637INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)initializeLoopInfoWrapperPassPass(Registry);
12638INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)initializeDominatorTreeWrapperPassPass(Registry);
12639INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
12640INITIALIZE_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
)); }
12641 "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
)); }
12642
12643char ScalarEvolutionWrapperPass::ID = 0;
12644
12645ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
12646 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
12647}
12648
12649bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
12650 SE.reset(new ScalarEvolution(
12651 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
12652 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
12653 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
12654 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
12655 return false;
12656}
12657
12658void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
12659
12660void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
12661 SE->print(OS);
12662}
12663
12664void ScalarEvolutionWrapperPass::verifyAnalysis() const {
12665 if (!VerifySCEV)
12666 return;
12667
12668 SE->verify();
12669}
12670
12671void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
12672 AU.setPreservesAll();
12673 AU.addRequiredTransitive<AssumptionCacheTracker>();
12674 AU.addRequiredTransitive<LoopInfoWrapperPass>();
12675 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
12676 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
12677}
12678
12679const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
12680 const SCEV *RHS) {
12681 FoldingSetNodeID ID;
12682 assert(LHS->getType() == RHS->getType() &&((LHS->getType() == RHS->getType() && "Type mismatch between LHS and RHS"
) ? static_cast<void> (0) : __assert_fail ("LHS->getType() == RHS->getType() && \"Type mismatch between LHS and RHS\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12683, __PRETTY_FUNCTION__))
12683 "Type mismatch between LHS and RHS")((LHS->getType() == RHS->getType() && "Type mismatch between LHS and RHS"
) ? static_cast<void> (0) : __assert_fail ("LHS->getType() == RHS->getType() && \"Type mismatch between LHS and RHS\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12683, __PRETTY_FUNCTION__))
;
12684 // Unique this node based on the arguments
12685 ID.AddInteger(SCEVPredicate::P_Equal);
12686 ID.AddPointer(LHS);
12687 ID.AddPointer(RHS);
12688 void *IP = nullptr;
12689 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12690 return S;
12691 SCEVEqualPredicate *Eq = new (SCEVAllocator)
12692 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
12693 UniquePreds.InsertNode(Eq, IP);
12694 return Eq;
12695}
12696
12697const SCEVPredicate *ScalarEvolution::getWrapPredicate(
12698 const SCEVAddRecExpr *AR,
12699 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12700 FoldingSetNodeID ID;
12701 // Unique this node based on the arguments
12702 ID.AddInteger(SCEVPredicate::P_Wrap);
12703 ID.AddPointer(AR);
12704 ID.AddInteger(AddedFlags);
12705 void *IP = nullptr;
12706 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12707 return S;
12708 auto *OF = new (SCEVAllocator)
12709 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
12710 UniquePreds.InsertNode(OF, IP);
12711 return OF;
12712}
12713
12714namespace {
12715
12716class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
12717public:
12718
12719 /// Rewrites \p S in the context of a loop L and the SCEV predication
12720 /// infrastructure.
12721 ///
12722 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
12723 /// equivalences present in \p Pred.
12724 ///
12725 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
12726 /// \p NewPreds such that the result will be an AddRecExpr.
12727 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
12728 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12729 SCEVUnionPredicate *Pred) {
12730 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
12731 return Rewriter.visit(S);
12732 }
12733
12734 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12735 if (Pred) {
12736 auto ExprPreds = Pred->getPredicatesForExpr(Expr);
12737 for (auto *Pred : ExprPreds)
12738 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
12739 if (IPred->getLHS() == Expr)
12740 return IPred->getRHS();
12741 }
12742 return convertToAddRecWithPreds(Expr);
12743 }
12744
12745 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
12746 const SCEV *Operand = visit(Expr->getOperand());
12747 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12748 if (AR && AR->getLoop() == L && AR->isAffine()) {
12749 // This couldn't be folded because the operand didn't have the nuw
12750 // flag. Add the nusw flag as an assumption that we could make.
12751 const SCEV *Step = AR->getStepRecurrence(SE);
12752 Type *Ty = Expr->getType();
12753 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
12754 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
12755 SE.getSignExtendExpr(Step, Ty), L,
12756 AR->getNoWrapFlags());
12757 }
12758 return SE.getZeroExtendExpr(Operand, Expr->getType());
12759 }
12760
12761 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
12762 const SCEV *Operand = visit(Expr->getOperand());
12763 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12764 if (AR && AR->getLoop() == L && AR->isAffine()) {
12765 // This couldn't be folded because the operand didn't have the nsw
12766 // flag. Add the nssw flag as an assumption that we could make.
12767 const SCEV *Step = AR->getStepRecurrence(SE);
12768 Type *Ty = Expr->getType();
12769 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
12770 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
12771 SE.getSignExtendExpr(Step, Ty), L,
12772 AR->getNoWrapFlags());
12773 }
12774 return SE.getSignExtendExpr(Operand, Expr->getType());
12775 }
12776
12777private:
12778 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
12779 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12780 SCEVUnionPredicate *Pred)
12781 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
12782
12783 bool addOverflowAssumption(const SCEVPredicate *P) {
12784 if (!NewPreds) {
12785 // Check if we've already made this assumption.
12786 return Pred && Pred->implies(P);
12787 }
12788 NewPreds->insert(P);
12789 return true;
12790 }
12791
12792 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
12793 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12794 auto *A = SE.getWrapPredicate(AR, AddedFlags);
12795 return addOverflowAssumption(A);
12796 }
12797
12798 // If \p Expr represents a PHINode, we try to see if it can be represented
12799 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
12800 // to add this predicate as a runtime overflow check, we return the AddRec.
12801 // If \p Expr does not meet these conditions (is not a PHI node, or we
12802 // couldn't create an AddRec for it, or couldn't add the predicate), we just
12803 // return \p Expr.
12804 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
12805 if (!isa<PHINode>(Expr->getValue()))
12806 return Expr;
12807 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
12808 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
12809 if (!PredicatedRewrite)
12810 return Expr;
12811 for (auto *P : PredicatedRewrite->second){
12812 // Wrap predicates from outer loops are not supported.
12813 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
12814 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
12815 if (L != AR->getLoop())
12816 return Expr;
12817 }
12818 if (!addOverflowAssumption(P))
12819 return Expr;
12820 }
12821 return PredicatedRewrite->first;
12822 }
12823
12824 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
12825 SCEVUnionPredicate *Pred;
12826 const Loop *L;
12827};
12828
12829} // end anonymous namespace
12830
12831const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
12832 SCEVUnionPredicate &Preds) {
12833 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
12834}
12835
12836const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
12837 const SCEV *S, const Loop *L,
12838 SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
12839 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
12840 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
12841 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
12842
12843 if (!AddRec)
12844 return nullptr;
12845
12846 // Since the transformation was successful, we can now transfer the SCEV
12847 // predicates.
12848 for (auto *P : TransformPreds)
12849 Preds.insert(P);
12850
12851 return AddRec;
12852}
12853
12854/// SCEV predicates
12855SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
12856 SCEVPredicateKind Kind)
12857 : FastID(ID), Kind(Kind) {}
12858
12859SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
12860 const SCEV *LHS, const SCEV *RHS)
12861 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
12862 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match")((LHS->getType() == RHS->getType() && "LHS and RHS types don't match"
) ? static_cast<void> (0) : __assert_fail ("LHS->getType() == RHS->getType() && \"LHS and RHS types don't match\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12862, __PRETTY_FUNCTION__))
;
12863 assert(LHS != RHS && "LHS and RHS are the same SCEV")((LHS != RHS && "LHS and RHS are the same SCEV") ? static_cast
<void> (0) : __assert_fail ("LHS != RHS && \"LHS and RHS are the same SCEV\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12863, __PRETTY_FUNCTION__))
;
12864}
12865
12866bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
12867 const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
12868
12869 if (!Op)
12870 return false;
12871
12872 return Op->LHS == LHS && Op->RHS == RHS;
12873}
12874
12875bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
12876
12877const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
12878
12879void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
12880 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
12881}
12882
12883SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
12884 const SCEVAddRecExpr *AR,
12885 IncrementWrapFlags Flags)
12886 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
12887
12888const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
12889
12890bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
12891 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
12892
12893 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
12894}
12895
12896bool SCEVWrapPredicate::isAlwaysTrue() const {
12897 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
12898 IncrementWrapFlags IFlags = Flags;
12899
12900 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
12901 IFlags = clearFlags(IFlags, IncrementNSSW);
12902
12903 return IFlags == IncrementAnyWrap;
12904}
12905
12906void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
12907 OS.indent(Depth) << *getExpr() << " Added Flags: ";
12908 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
12909 OS << "<nusw>";
12910 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
12911 OS << "<nssw>";
12912 OS << "\n";
12913}
12914
12915SCEVWrapPredicate::IncrementWrapFlags
12916SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
12917 ScalarEvolution &SE) {
12918 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
12919 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
12920
12921 // We can safely transfer the NSW flag as NSSW.
12922 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
12923 ImpliedFlags = IncrementNSSW;
12924
12925 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
12926 // If the increment is positive, the SCEV NUW flag will also imply the
12927 // WrapPredicate NUSW flag.
12928 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
12929 if (Step->getValue()->getValue().isNonNegative())
12930 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
12931 }
12932
12933 return ImpliedFlags;
12934}
12935
12936/// Union predicates don't get cached so create a dummy set ID for it.
12937SCEVUnionPredicate::SCEVUnionPredicate()
12938 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
12939
12940bool SCEVUnionPredicate::isAlwaysTrue() const {
12941 return all_of(Preds,
12942 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
12943}
12944
12945ArrayRef<const SCEVPredicate *>
12946SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
12947 auto I = SCEVToPreds.find(Expr);
12948 if (I == SCEVToPreds.end())
12949 return ArrayRef<const SCEVPredicate *>();
12950 return I->second;
12951}
12952
12953bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
12954 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
12955 return all_of(Set->Preds,
12956 [this](const SCEVPredicate *I) { return this->implies(I); });
12957
12958 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
12959 if (ScevPredsIt == SCEVToPreds.end())
12960 return false;
12961 auto &SCEVPreds = ScevPredsIt->second;
12962
12963 return any_of(SCEVPreds,
12964 [N](const SCEVPredicate *I) { return I->implies(N); });
12965}
12966
12967const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
12968
12969void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
12970 for (auto Pred : Preds)
12971 Pred->print(OS, Depth);
12972}
12973
12974void SCEVUnionPredicate::add(const SCEVPredicate *N) {
12975 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
12976 for (auto Pred : Set->Preds)
12977 add(Pred);
12978 return;
12979 }
12980
12981 if (implies(N))
12982 return;
12983
12984 const SCEV *Key = N->getExpr();
12985 assert(Key && "Only SCEVUnionPredicate doesn't have an "((Key && "Only SCEVUnionPredicate doesn't have an " " associated expression!"
) ? static_cast<void> (0) : __assert_fail ("Key && \"Only SCEVUnionPredicate doesn't have an \" \" associated expression!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12986, __PRETTY_FUNCTION__))
12986 " associated expression!")((Key && "Only SCEVUnionPredicate doesn't have an " " associated expression!"
) ? static_cast<void> (0) : __assert_fail ("Key && \"Only SCEVUnionPredicate doesn't have an \" \" associated expression!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 12986, __PRETTY_FUNCTION__))
;
12987
12988 SCEVToPreds[Key].push_back(N);
12989 Preds.push_back(N);
12990}
12991
12992PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
12993 Loop &L)
12994 : SE(SE), L(L) {}
12995
12996const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
12997 const SCEV *Expr = SE.getSCEV(V);
12998 RewriteEntry &Entry = RewriteMap[Expr];
12999
13000 // If we already have an entry and the version matches, return it.
13001 if (Entry.second && Generation == Entry.first)
13002 return Entry.second;
13003
13004 // We found an entry but it's stale. Rewrite the stale entry
13005 // according to the current predicate.
13006 if (Entry.second)
13007 Expr = Entry.second;
13008
13009 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
13010 Entry = {Generation, NewSCEV};
13011
13012 return NewSCEV;
13013}
13014
13015const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
13016 if (!BackedgeCount) {
13017 SCEVUnionPredicate BackedgePred;
13018 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
13019 addPredicate(BackedgePred);
13020 }
13021 return BackedgeCount;
13022}
13023
13024void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
13025 if (Preds.implies(&Pred))
13026 return;
13027 Preds.add(&Pred);
13028 updateGeneration();
13029}
13030
13031const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
13032 return Preds;
13033}
13034
13035void PredicatedScalarEvolution::updateGeneration() {
13036 // If the generation number wrapped recompute everything.
13037 if (++Generation == 0) {
13038 for (auto &II : RewriteMap) {
13039 const SCEV *Rewritten = II.second.second;
13040 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
13041 }
13042 }
13043}
13044
13045void PredicatedScalarEvolution::setNoOverflow(
13046 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13047 const SCEV *Expr = getSCEV(V);
13048 const auto *AR = cast<SCEVAddRecExpr>(Expr);
13049
13050 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
13051
13052 // Clear the statically implied flags.
13053 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
13054 addPredicate(*SE.getWrapPredicate(AR, Flags));
13055
13056 auto II = FlagsMap.insert({V, Flags});
13057 if (!II.second)
13058 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
13059}
13060
13061bool PredicatedScalarEvolution::hasNoOverflow(
13062 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
13063 const SCEV *Expr = getSCEV(V);
13064 const auto *AR = cast<SCEVAddRecExpr>(Expr);
13065
13066 Flags = SCEVWrapPredicate::clearFlags(
13067 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
13068
13069 auto II = FlagsMap.find(V);
13070
13071 if (II != FlagsMap.end())
13072 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
13073
13074 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
13075}
13076
13077const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
13078 const SCEV *Expr = this->getSCEV(V);
13079 SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
13080 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
13081
13082 if (!New)
13083 return nullptr;
13084
13085 for (auto *P : NewPreds)
13086 Preds.add(P);
13087
13088 updateGeneration();
13089 RewriteMap[SE.getSCEV(V)] = {Generation, New};
13090 return New;
13091}
13092
13093PredicatedScalarEvolution::PredicatedScalarEvolution(
13094 const PredicatedScalarEvolution &Init)
13095 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
13096 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
13097 for (auto I : Init.FlagsMap)
13098 FlagsMap.insert(I);
13099}
13100
13101void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
13102 // For each block.
13103 for (auto *BB : L.getBlocks())
13104 for (auto &I : *BB) {
13105 if (!SE.isSCEVable(I.getType()))
13106 continue;
13107
13108 auto *Expr = SE.getSCEV(&I);
13109 auto II = RewriteMap.find(Expr);
13110
13111 if (II == RewriteMap.end())
13112 continue;
13113
13114 // Don't print things that are not interesting.
13115 if (II->second.second == Expr)
13116 continue;
13117
13118 OS.indent(Depth) << "[PSE]" << I << ":\n";
13119 OS.indent(Depth + 2) << *Expr << "\n";
13120 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
13121 }
13122}
13123
13124// Match the mathematical pattern A - (A / B) * B, where A and B can be
13125// arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
13126// for URem with constant power-of-2 second operands.
13127// It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
13128// 4, A / B becomes X / 8).
13129bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
13130 const SCEV *&RHS) {
13131 // Try to match 'zext (trunc A to iB) to iY', which is used
13132 // for URem with constant power-of-2 second operands. Make sure the size of
13133 // the operand A matches the size of the whole expressions.
13134 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
13135 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
13136 LHS = Trunc->getOperand();
13137 if (LHS->getType() != Expr->getType())
13138 LHS = getZeroExtendExpr(LHS, Expr->getType());
13139 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
13140 << getTypeSizeInBits(Trunc->getType()));
13141 return true;
13142 }
13143 const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
13144 if (Add == nullptr || Add->getNumOperands() != 2)
13145 return false;
13146
13147 const SCEV *A = Add->getOperand(1);
13148 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
13149
13150 if (Mul == nullptr)
13151 return false;
13152
13153 const auto MatchURemWithDivisor = [&](const SCEV *B) {
13154 // (SomeExpr + (-(SomeExpr / B) * B)).
13155 if (Expr == getURemExpr(A, B)) {
13156 LHS = A;
13157 RHS = B;
13158 return true;
13159 }
13160 return false;
13161 };
13162
13163 // (SomeExpr + (-1 * (SomeExpr / B) * B)).
13164 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
13165 return MatchURemWithDivisor(Mul->getOperand(1)) ||
13166 MatchURemWithDivisor(Mul->getOperand(2));
13167
13168 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
13169 if (Mul->getNumOperands() == 2)
13170 return MatchURemWithDivisor(Mul->getOperand(1)) ||
13171 MatchURemWithDivisor(Mul->getOperand(0)) ||
13172 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
13173 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
13174 return false;
13175}
13176
13177const SCEV *
13178ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
13179 SmallVector<BasicBlock*, 16> ExitingBlocks;
13180 L->getExitingBlocks(ExitingBlocks);
13181
13182 // Form an expression for the maximum exit count possible for this loop. We
13183 // merge the max and exact information to approximate a version of
13184 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
13185 SmallVector<const SCEV*, 4> ExitCounts;
13186 for (BasicBlock *ExitingBB : ExitingBlocks) {
13187 const SCEV *ExitCount = getExitCount(L, ExitingBB);
13188 if (isa<SCEVCouldNotCompute>(ExitCount))
13189 ExitCount = getExitCount(L, ExitingBB,
13190 ScalarEvolution::ConstantMaximum);
13191 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
13192 assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&((DT.dominates(ExitingBB, L->getLoopLatch()) && "We should only have known counts for exiting blocks that "
"dominate latch!") ? static_cast<void> (0) : __assert_fail
("DT.dominates(ExitingBB, L->getLoopLatch()) && \"We should only have known counts for exiting blocks that \" \"dominate latch!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 13194, __PRETTY_FUNCTION__))
13193 "We should only have known counts for exiting blocks that "((DT.dominates(ExitingBB, L->getLoopLatch()) && "We should only have known counts for exiting blocks that "
"dominate latch!") ? static_cast<void> (0) : __assert_fail
("DT.dominates(ExitingBB, L->getLoopLatch()) && \"We should only have known counts for exiting blocks that \" \"dominate latch!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 13194, __PRETTY_FUNCTION__))
13194 "dominate latch!")((DT.dominates(ExitingBB, L->getLoopLatch()) && "We should only have known counts for exiting blocks that "
"dominate latch!") ? static_cast<void> (0) : __assert_fail
("DT.dominates(ExitingBB, L->getLoopLatch()) && \"We should only have known counts for exiting blocks that \" \"dominate latch!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/lib/Analysis/ScalarEvolution.cpp"
, 13194, __PRETTY_FUNCTION__))
;
13195 ExitCounts.push_back(ExitCount);
13196 }
13197 }
13198 if (ExitCounts.empty())
13199 return getCouldNotCompute();
13200 return getUMinFromMismatchedTypes(ExitCounts);
13201}
13202
13203/// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown
13204/// components following the Map (Value -> SCEV)), but skips AddRecExpr because
13205/// we cannot guarantee that the replacement is loop invariant in the loop of
13206/// the AddRec.
13207class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
13208 ValueToSCEVMapTy &Map;
13209
13210public:
13211 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M)
13212 : SCEVRewriteVisitor(SE), Map(M) {}
13213
13214 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
13215
13216 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
13217 auto I = Map.find(Expr->getValue());
13218 if (I == Map.end())
13219 return Expr;
13220 return I->second;
13221 }
13222};
13223
13224const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
13225 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
13226 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) {
13227 if (!isa<SCEVUnknown>(LHS)) {
13228 std::swap(LHS, RHS);
13229 Predicate = CmpInst::getSwappedPredicate(Predicate);
13230 }
13231
13232 // For now, limit to conditions that provide information about unknown
13233 // expressions.
13234 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS);
13235 if (!LHSUnknown)
13236 return;
13237
13238 // TODO: use information from more predicates.
13239 switch (Predicate) {
13240 case CmpInst::ICMP_ULT: {
13241 if (!containsAddRecurrence(RHS)) {
13242 const SCEV *Base = LHS;
13243 auto I = RewriteMap.find(LHSUnknown->getValue());
13244 if (I != RewriteMap.end())
13245 Base = I->second;
13246
13247 RewriteMap[LHSUnknown->getValue()] =
13248 getUMinExpr(Base, getMinusSCEV(RHS, getOne(RHS->getType())));
13249 }
13250 break;
13251 }
13252 case CmpInst::ICMP_ULE: {
13253 if (!containsAddRecurrence(RHS)) {
13254 const SCEV *Base = LHS;
13255 auto I = RewriteMap.find(LHSUnknown->getValue());
13256 if (I != RewriteMap.end())
13257 Base = I->second;
13258 RewriteMap[LHSUnknown->getValue()] = getUMinExpr(Base, RHS);
13259 }
13260 break;
13261 }
13262 case CmpInst::ICMP_EQ:
13263 if (isa<SCEVConstant>(RHS))
13264 RewriteMap[LHSUnknown->getValue()] = RHS;
13265 break;
13266 case CmpInst::ICMP_NE:
13267 if (isa<SCEVConstant>(RHS) &&
13268 cast<SCEVConstant>(RHS)->getValue()->isNullValue())
13269 RewriteMap[LHSUnknown->getValue()] =
13270 getUMaxExpr(LHS, getOne(RHS->getType()));
13271 break;
13272 default:
13273 break;
13274 }
13275 };
13276 // Starting at the loop predecessor, climb up the predecessor chain, as long
13277 // as there are predecessors that can be found that have unique successors
13278 // leading to the original header.
13279 // TODO: share this logic with isLoopEntryGuardedByCond.
13280 ValueToSCEVMapTy RewriteMap;
13281 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
13282 L->getLoopPredecessor(), L->getHeader());
13283 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
13284
13285 const BranchInst *LoopEntryPredicate =
13286 dyn_cast<BranchInst>(Pair.first->getTerminator());
13287 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
13288 continue;
13289
13290 // TODO: use information from more complex conditions, e.g. AND expressions.
13291 auto *Cmp = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
13292 if (!Cmp)
13293 continue;
13294
13295 auto Predicate = Cmp->getPredicate();
13296 if (LoopEntryPredicate->getSuccessor(1) == Pair.second)
13297 Predicate = CmpInst::getInversePredicate(Predicate);
13298 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)),
13299 getSCEV(Cmp->getOperand(1)), RewriteMap);
13300 }
13301
13302 // Also collect information from assumptions dominating the loop.
13303 for (auto &AssumeVH : AC.assumptions()) {
13304 if (!AssumeVH)
13305 continue;
13306 auto *AssumeI = cast<CallInst>(AssumeVH);
13307 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0));
13308 if (!Cmp || !DT.dominates(AssumeI, L->getHeader()))
13309 continue;
13310 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)),
13311 getSCEV(Cmp->getOperand(1)), RewriteMap);
13312 }
13313
13314 if (RewriteMap.empty())
13315 return Expr;
13316 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
13317 return Rewriter.visit(Expr);
13318}

/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/Analysis/ScalarEvolutionExpressions.h

1//===- llvm/Analysis/ScalarEvolutionExpressions.h - SCEV Exprs --*- C++ -*-===//
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 defines the classes used to represent and build scalar expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ANALYSIS_SCALAREVOLUTIONEXPRESSIONS_H
14#define LLVM_ANALYSIS_SCALAREVOLUTIONEXPRESSIONS_H
15
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/FoldingSet.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/iterator_range.h"
21#include "llvm/Analysis/ScalarEvolution.h"
22#include "llvm/IR/Constants.h"
23#include "llvm/IR/Value.h"
24#include "llvm/IR/ValueHandle.h"
25#include "llvm/Support/Casting.h"
26#include "llvm/Support/ErrorHandling.h"
27#include <cassert>
28#include <cstddef>
29
30namespace llvm {
31
32class APInt;
33class Constant;
34class ConstantRange;
35class Loop;
36class Type;
37
38 enum SCEVTypes : unsigned short {
39 // These should be ordered in terms of increasing complexity to make the
40 // folders simpler.
41 scConstant, scTruncate, scZeroExtend, scSignExtend, scAddExpr, scMulExpr,
42 scUDivExpr, scAddRecExpr, scUMaxExpr, scSMaxExpr, scUMinExpr, scSMinExpr,
43 scPtrToInt, scUnknown, scCouldNotCompute
44 };
45
46 /// This class represents a constant integer value.
47 class SCEVConstant : public SCEV {
48 friend class ScalarEvolution;
49
50 ConstantInt *V;
51
52 SCEVConstant(const FoldingSetNodeIDRef ID, ConstantInt *v) :
53 SCEV(ID, scConstant, 1), V(v) {}
54
55 public:
56 ConstantInt *getValue() const { return V; }
57 const APInt &getAPInt() const { return getValue()->getValue(); }
58
59 Type *getType() const { return V->getType(); }
60
61 /// Methods for support type inquiry through isa, cast, and dyn_cast:
62 static bool classof(const SCEV *S) {
63 return S->getSCEVType() == scConstant;
64 }
65 };
66
67 inline unsigned short computeExpressionSize(ArrayRef<const SCEV *> Args) {
68 APInt Size(16, 1);
69 for (auto *Arg : Args)
70 Size = Size.uadd_sat(APInt(16, Arg->getExpressionSize()));
71 return (unsigned short)Size.getZExtValue();
72 }
73
74 /// This is the base class for unary cast operator classes.
75 class SCEVCastExpr : public SCEV {
76 protected:
77 std::array<const SCEV *, 1> Operands;
78 Type *Ty;
79
80 SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, const SCEV *op,
81 Type *ty);
82
83 public:
84 const SCEV *getOperand() const { return Operands[0]; }
85 const SCEV *getOperand(unsigned i) const {
86 assert(i == 0 && "Operand index out of range!")((i == 0 && "Operand index out of range!") ? static_cast
<void> (0) : __assert_fail ("i == 0 && \"Operand index out of range!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/Analysis/ScalarEvolutionExpressions.h"
, 86, __PRETTY_FUNCTION__))
;
87 return Operands[0];
88 }
89 using op_iterator = std::array<const SCEV *, 1>::const_iterator;
90 using op_range = iterator_range<op_iterator>;
91
92 op_range operands() const {
93 return make_range(Operands.begin(), Operands.end());
94 }
95 size_t getNumOperands() const { return 1; }
96 Type *getType() const { return Ty; }
97
98 /// Methods for support type inquiry through isa, cast, and dyn_cast:
99 static bool classof(const SCEV *S) {
100 return S->getSCEVType() == scPtrToInt || S->getSCEVType() == scTruncate ||
101 S->getSCEVType() == scZeroExtend ||
102 S->getSCEVType() == scSignExtend;
103 }
104 };
105
106 /// This class represents a cast from a pointer to a pointer-sized integer
107 /// value.
108 class SCEVPtrToIntExpr : public SCEVCastExpr {
109 friend class ScalarEvolution;
110
111 SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, Type *ITy);
112
113 public:
114 /// Methods for support type inquiry through isa, cast, and dyn_cast:
115 static bool classof(const SCEV *S) {
116 return S->getSCEVType() == scPtrToInt;
117 }
118 };
119
120 /// This is the base class for unary integral cast operator classes.
121 class SCEVIntegralCastExpr : public SCEVCastExpr {
122 protected:
123 SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
124 const SCEV *op, Type *ty);
125
126 public:
127 /// Methods for support type inquiry through isa, cast, and dyn_cast:
128 static bool classof(const SCEV *S) {
129 return S->getSCEVType() == scTruncate ||
130 S->getSCEVType() == scZeroExtend ||
131 S->getSCEVType() == scSignExtend;
132 }
133 };
134
135 /// This class represents a truncation of an integer value to a
136 /// smaller integer value.
137 class SCEVTruncateExpr : public SCEVIntegralCastExpr {
138 friend class ScalarEvolution;
139
140 SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
141 const SCEV *op, Type *ty);
142
143 public:
144 /// Methods for support type inquiry through isa, cast, and dyn_cast:
145 static bool classof(const SCEV *S) {
146 return S->getSCEVType() == scTruncate;
147 }
148 };
149
150 /// This class represents a zero extension of a small integer value
151 /// to a larger integer value.
152 class SCEVZeroExtendExpr : public SCEVIntegralCastExpr {
153 friend class ScalarEvolution;
154
155 SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
156 const SCEV *op, Type *ty);
157
158 public:
159 /// Methods for support type inquiry through isa, cast, and dyn_cast:
160 static bool classof(const SCEV *S) {
161 return S->getSCEVType() == scZeroExtend;
162 }
163 };
164
165 /// This class represents a sign extension of a small integer value
166 /// to a larger integer value.
167 class SCEVSignExtendExpr : public SCEVIntegralCastExpr {
168 friend class ScalarEvolution;
169
170 SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
171 const SCEV *op, Type *ty);
172
173 public:
174 /// Methods for support type inquiry through isa, cast, and dyn_cast:
175 static bool classof(const SCEV *S) {
176 return S->getSCEVType() == scSignExtend;
177 }
178 };
179
180 /// This node is a base class providing common functionality for
181 /// n'ary operators.
182 class SCEVNAryExpr : public SCEV {
183 protected:
184 // Since SCEVs are immutable, ScalarEvolution allocates operand
185 // arrays with its SCEVAllocator, so this class just needs a simple
186 // pointer rather than a more elaborate vector-like data structure.
187 // This also avoids the need for a non-trivial destructor.
188 const SCEV *const *Operands;
189 size_t NumOperands;
190
191 SCEVNAryExpr(const FoldingSetNodeIDRef ID, enum SCEVTypes T,
192 const SCEV *const *O, size_t N)
193 : SCEV(ID, T, computeExpressionSize(makeArrayRef(O, N))), Operands(O),
194 NumOperands(N) {}
195
196 public:
197 size_t getNumOperands() const { return NumOperands; }
198
199 const SCEV *getOperand(unsigned i) const {
200 assert(i < NumOperands && "Operand index out of range!")((i < NumOperands && "Operand index out of range!"
) ? static_cast<void> (0) : __assert_fail ("i < NumOperands && \"Operand index out of range!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/Analysis/ScalarEvolutionExpressions.h"
, 200, __PRETTY_FUNCTION__))
;
201 return Operands[i];
202 }
203
204 using op_iterator = const SCEV *const *;
205 using op_range = iterator_range<op_iterator>;
206
207 op_iterator op_begin() const { return Operands; }
208 op_iterator op_end() const { return Operands + NumOperands; }
209 op_range operands() const {
210 return make_range(op_begin(), op_end());
211 }
212
213 Type *getType() const { return getOperand(0)->getType(); }
214
215 NoWrapFlags getNoWrapFlags(NoWrapFlags Mask = NoWrapMask) const {
216 return (NoWrapFlags)(SubclassData & Mask);
217 }
218
219 bool hasNoUnsignedWrap() const {
220 return getNoWrapFlags(FlagNUW) != FlagAnyWrap;
221 }
222
223 bool hasNoSignedWrap() const {
224 return getNoWrapFlags(FlagNSW) != FlagAnyWrap;
30
Assuming the condition is false
31
Returning zero, which participates in a condition later
225 }
226
227 bool hasNoSelfWrap() const {
228 return getNoWrapFlags(FlagNW) != FlagAnyWrap;
45
Assuming the condition is true
46
Returning the value 1, which participates in a condition later
229 }
230
231 /// Methods for support type inquiry through isa, cast, and dyn_cast:
232 static bool classof(const SCEV *S) {
233 return S->getSCEVType() == scAddExpr || S->getSCEVType() == scMulExpr ||
234 S->getSCEVType() == scSMaxExpr || S->getSCEVType() == scUMaxExpr ||
235 S->getSCEVType() == scSMinExpr || S->getSCEVType() == scUMinExpr ||
236 S->getSCEVType() == scAddRecExpr;
237 }
238 };
239
240 /// This node is the base class for n'ary commutative operators.
241 class SCEVCommutativeExpr : public SCEVNAryExpr {
242 protected:
243 SCEVCommutativeExpr(const FoldingSetNodeIDRef ID,
244 enum SCEVTypes T, const SCEV *const *O, size_t N)
245 : SCEVNAryExpr(ID, T, O, N) {}
246
247 public:
248 /// Methods for support type inquiry through isa, cast, and dyn_cast:
249 static bool classof(const SCEV *S) {
250 return S->getSCEVType() == scAddExpr || S->getSCEVType() == scMulExpr ||
251 S->getSCEVType() == scSMaxExpr || S->getSCEVType() == scUMaxExpr ||
252 S->getSCEVType() == scSMinExpr || S->getSCEVType() == scUMinExpr;
253 }
254
255 /// Set flags for a non-recurrence without clearing previously set flags.
256 void setNoWrapFlags(NoWrapFlags Flags) {
257 SubclassData |= Flags;
258 }
259 };
260
261 /// This node represents an addition of some number of SCEVs.
262 class SCEVAddExpr : public SCEVCommutativeExpr {
263 friend class ScalarEvolution;
264
265 Type *Ty;
266
267 SCEVAddExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
268 : SCEVCommutativeExpr(ID, scAddExpr, O, N) {
269 auto *FirstPointerTypedOp = find_if(operands(), [](const SCEV *Op) {
270 return Op->getType()->isPointerTy();
271 });
272 if (FirstPointerTypedOp != operands().end())
273 Ty = (*FirstPointerTypedOp)->getType();
274 else
275 Ty = getOperand(0)->getType();
276 }
277
278 public:
279 Type *getType() const { return Ty; }
280
281 /// Methods for support type inquiry through isa, cast, and dyn_cast:
282 static bool classof(const SCEV *S) {
283 return S->getSCEVType() == scAddExpr;
284 }
285 };
286
287 /// This node represents multiplication of some number of SCEVs.
288 class SCEVMulExpr : public SCEVCommutativeExpr {
289 friend class ScalarEvolution;
290
291 SCEVMulExpr(const FoldingSetNodeIDRef ID,
292 const SCEV *const *O, size_t N)
293 : SCEVCommutativeExpr(ID, scMulExpr, O, N) {}
294
295 public:
296 /// Methods for support type inquiry through isa, cast, and dyn_cast:
297 static bool classof(const SCEV *S) {
298 return S->getSCEVType() == scMulExpr;
299 }
300 };
301
302 /// This class represents a binary unsigned division operation.
303 class SCEVUDivExpr : public SCEV {
304 friend class ScalarEvolution;
305
306 std::array<const SCEV *, 2> Operands;
307
308 SCEVUDivExpr(const FoldingSetNodeIDRef ID, const SCEV *lhs, const SCEV *rhs)
309 : SCEV(ID, scUDivExpr, computeExpressionSize({lhs, rhs})) {
310 Operands[0] = lhs;
311 Operands[1] = rhs;
312 }
313
314 public:
315 const SCEV *getLHS() const { return Operands[0]; }
316 const SCEV *getRHS() const { return Operands[1]; }
317 size_t getNumOperands() const { return 2; }
318 const SCEV *getOperand(unsigned i) const {
319 assert((i == 0 || i == 1) && "Operand index out of range!")(((i == 0 || i == 1) && "Operand index out of range!"
) ? static_cast<void> (0) : __assert_fail ("(i == 0 || i == 1) && \"Operand index out of range!\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/Analysis/ScalarEvolutionExpressions.h"
, 319, __PRETTY_FUNCTION__))
;
320 return i == 0 ? getLHS() : getRHS();
321 }
322
323 using op_iterator = std::array<const SCEV *, 2>::const_iterator;
324 using op_range = iterator_range<op_iterator>;
325 op_range operands() const {
326 return make_range(Operands.begin(), Operands.end());
327 }
328
329 Type *getType() const {
330 // In most cases the types of LHS and RHS will be the same, but in some
331 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
332 // depend on the type for correctness, but handling types carefully can
333 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
334 // a pointer type than the RHS, so use the RHS' type here.
335 return getRHS()->getType();
336 }
337
338 /// Methods for support type inquiry through isa, cast, and dyn_cast:
339 static bool classof(const SCEV *S) {
340 return S->getSCEVType() == scUDivExpr;
341 }
342 };
343
344 /// This node represents a polynomial recurrence on the trip count
345 /// of the specified loop. This is the primary focus of the
346 /// ScalarEvolution framework; all the other SCEV subclasses are
347 /// mostly just supporting infrastructure to allow SCEVAddRecExpr
348 /// expressions to be created and analyzed.
349 ///
350 /// All operands of an AddRec are required to be loop invariant.
351 ///
352 class SCEVAddRecExpr : public SCEVNAryExpr {
353 friend class ScalarEvolution;
354
355 const Loop *L;
356
357 SCEVAddRecExpr(const FoldingSetNodeIDRef ID,
358 const SCEV *const *O, size_t N, const Loop *l)
359 : SCEVNAryExpr(ID, scAddRecExpr, O, N), L(l) {}
360
361 public:
362 const SCEV *getStart() const { return Operands[0]; }
363 const Loop *getLoop() const { return L; }
364
365 /// Constructs and returns the recurrence indicating how much this
366 /// expression steps by. If this is a polynomial of degree N, it
367 /// returns a chrec of degree N-1. We cannot determine whether
368 /// the step recurrence has self-wraparound.
369 const SCEV *getStepRecurrence(ScalarEvolution &SE) const {
370 if (isAffine()) return getOperand(1);
371 return SE.getAddRecExpr(SmallVector<const SCEV *, 3>(op_begin()+1,
372 op_end()),
373 getLoop(), FlagAnyWrap);
374 }
375
376 /// Return true if this represents an expression A + B*x where A
377 /// and B are loop invariant values.
378 bool isAffine() const {
379 // We know that the start value is invariant. This expression is thus
380 // affine iff the step is also invariant.
381 return getNumOperands() == 2;
382 }
383
384 /// Return true if this represents an expression A + B*x + C*x^2
385 /// where A, B and C are loop invariant values. This corresponds
386 /// to an addrec of the form {L,+,M,+,N}
387 bool isQuadratic() const {
388 return getNumOperands() == 3;
389 }
390
391 /// Set flags for a recurrence without clearing any previously set flags.
392 /// For AddRec, either NUW or NSW implies NW. Keep track of this fact here
393 /// to make it easier to propagate flags.
394 void setNoWrapFlags(NoWrapFlags Flags) {
395 if (Flags & (FlagNUW | FlagNSW))
396 Flags = ScalarEvolution::setFlags(Flags, FlagNW);
397 SubclassData |= Flags;
398 }
399
400 /// Return the value of this chain of recurrences at the specified
401 /// iteration number.
402 const SCEV *evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const;
403
404 /// Return the number of iterations of this loop that produce
405 /// values in the specified constant range. Another way of
406 /// looking at this is that it returns the first iteration number
407 /// where the value is not in the condition, thus computing the
408 /// exit count. If the iteration count can't be computed, an
409 /// instance of SCEVCouldNotCompute is returned.
410 const SCEV *getNumIterationsInRange(const ConstantRange &Range,
411 ScalarEvolution &SE) const;
412
413 /// Return an expression representing the value of this expression
414 /// one iteration of the loop ahead.
415 const SCEVAddRecExpr *getPostIncExpr(ScalarEvolution &SE) const;
416
417 /// Methods for support type inquiry through isa, cast, and dyn_cast:
418 static bool classof(const SCEV *S) {
419 return S->getSCEVType() == scAddRecExpr;
420 }
421 };
422
423 /// This node is the base class min/max selections.
424 class SCEVMinMaxExpr : public SCEVCommutativeExpr {
425 friend class ScalarEvolution;
426
427 static bool isMinMaxType(enum SCEVTypes T) {
428 return T == scSMaxExpr || T == scUMaxExpr || T == scSMinExpr ||
429 T == scUMinExpr;
430 }
431
432 protected:
433 /// Note: Constructing subclasses via this constructor is allowed
434 SCEVMinMaxExpr(const FoldingSetNodeIDRef ID, enum SCEVTypes T,
435 const SCEV *const *O, size_t N)
436 : SCEVCommutativeExpr(ID, T, O, N) {
437 assert(isMinMaxType(T))((isMinMaxType(T)) ? static_cast<void> (0) : __assert_fail
("isMinMaxType(T)", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/Analysis/ScalarEvolutionExpressions.h"
, 437, __PRETTY_FUNCTION__))
;
438 // Min and max never overflow
439 setNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW));
440 }
441
442 public:
443 static bool classof(const SCEV *S) {
444 return isMinMaxType(S->getSCEVType());
445 }
446
447 static enum SCEVTypes negate(enum SCEVTypes T) {
448 switch (T) {
449 case scSMaxExpr:
450 return scSMinExpr;
451 case scSMinExpr:
452 return scSMaxExpr;
453 case scUMaxExpr:
454 return scUMinExpr;
455 case scUMinExpr:
456 return scUMaxExpr;
457 default:
458 llvm_unreachable("Not a min or max SCEV type!")::llvm::llvm_unreachable_internal("Not a min or max SCEV type!"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/Analysis/ScalarEvolutionExpressions.h"
, 458)
;
459 }
460 }
461 };
462
463 /// This class represents a signed maximum selection.
464 class SCEVSMaxExpr : public SCEVMinMaxExpr {
465 friend class ScalarEvolution;
466
467 SCEVSMaxExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
468 : SCEVMinMaxExpr(ID, scSMaxExpr, O, N) {}
469
470 public:
471 /// Methods for support type inquiry through isa, cast, and dyn_cast:
472 static bool classof(const SCEV *S) {
473 return S->getSCEVType() == scSMaxExpr;
474 }
475 };
476
477 /// This class represents an unsigned maximum selection.
478 class SCEVUMaxExpr : public SCEVMinMaxExpr {
479 friend class ScalarEvolution;
480
481 SCEVUMaxExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
482 : SCEVMinMaxExpr(ID, scUMaxExpr, O, N) {}
483
484 public:
485 /// Methods for support type inquiry through isa, cast, and dyn_cast:
486 static bool classof(const SCEV *S) {
487 return S->getSCEVType() == scUMaxExpr;
488 }
489 };
490
491 /// This class represents a signed minimum selection.
492 class SCEVSMinExpr : public SCEVMinMaxExpr {
493 friend class ScalarEvolution;
494
495 SCEVSMinExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
496 : SCEVMinMaxExpr(ID, scSMinExpr, O, N) {}
497
498 public:
499 /// Methods for support type inquiry through isa, cast, and dyn_cast:
500 static bool classof(const SCEV *S) {
501 return S->getSCEVType() == scSMinExpr;
502 }
503 };
504
505 /// This class represents an unsigned minimum selection.
506 class SCEVUMinExpr : public SCEVMinMaxExpr {
507 friend class ScalarEvolution;
508
509 SCEVUMinExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
510 : SCEVMinMaxExpr(ID, scUMinExpr, O, N) {}
511
512 public:
513 /// Methods for support type inquiry through isa, cast, and dyn_cast:
514 static bool classof(const SCEV *S) {
515 return S->getSCEVType() == scUMinExpr;
516 }
517 };
518
519 /// This means that we are dealing with an entirely unknown SCEV
520 /// value, and only represent it as its LLVM Value. This is the
521 /// "bottom" value for the analysis.
522 class SCEVUnknown final : public SCEV, private CallbackVH {
523 friend class ScalarEvolution;
524
525 /// The parent ScalarEvolution value. This is used to update the
526 /// parent's maps when the value associated with a SCEVUnknown is
527 /// deleted or RAUW'd.
528 ScalarEvolution *SE;
529
530 /// The next pointer in the linked list of all SCEVUnknown
531 /// instances owned by a ScalarEvolution.
532 SCEVUnknown *Next;
533
534 SCEVUnknown(const FoldingSetNodeIDRef ID, Value *V,
535 ScalarEvolution *se, SCEVUnknown *next) :
536 SCEV(ID, scUnknown, 1), CallbackVH(V), SE(se), Next(next) {}
537
538 // Implement CallbackVH.
539 void deleted() override;
540 void allUsesReplacedWith(Value *New) override;
541
542 public:
543 Value *getValue() const { return getValPtr(); }
544
545 /// @{
546 /// Test whether this is a special constant representing a type
547 /// size, alignment, or field offset in a target-independent
548 /// manner, and hasn't happened to have been folded with other
549 /// operations into something unrecognizable. This is mainly only
550 /// useful for pretty-printing and other situations where it isn't
551 /// absolutely required for these to succeed.
552 bool isSizeOf(Type *&AllocTy) const;
553 bool isAlignOf(Type *&AllocTy) const;
554 bool isOffsetOf(Type *&STy, Constant *&FieldNo) const;
555 /// @}
556
557 Type *getType() const { return getValPtr()->getType(); }
558
559 /// Methods for support type inquiry through isa, cast, and dyn_cast:
560 static bool classof(const SCEV *S) {
561 return S->getSCEVType() == scUnknown;
562 }
563 };
564
565 /// This class defines a simple visitor class that may be used for
566 /// various SCEV analysis purposes.
567 template<typename SC, typename RetVal=void>
568 struct SCEVVisitor {
569 RetVal visit(const SCEV *S) {
570 switch (S->getSCEVType()) {
571 case scConstant:
572 return ((SC*)this)->visitConstant((const SCEVConstant*)S);
573 case scPtrToInt:
574 return ((SC *)this)->visitPtrToIntExpr((const SCEVPtrToIntExpr *)S);
575 case scTruncate:
576 return ((SC*)this)->visitTruncateExpr((const SCEVTruncateExpr*)S);
577 case scZeroExtend:
578 return ((SC*)this)->visitZeroExtendExpr((const SCEVZeroExtendExpr*)S);
579 case scSignExtend:
580 return ((SC*)this)->visitSignExtendExpr((const SCEVSignExtendExpr*)S);
581 case scAddExpr:
582 return ((SC*)this)->visitAddExpr((const SCEVAddExpr*)S);
583 case scMulExpr:
584 return ((SC*)this)->visitMulExpr((const SCEVMulExpr*)S);
585 case scUDivExpr:
586 return ((SC*)this)->visitUDivExpr((const SCEVUDivExpr*)S);
587 case scAddRecExpr:
588 return ((SC*)this)->visitAddRecExpr((const SCEVAddRecExpr*)S);
589 case scSMaxExpr:
590 return ((SC*)this)->visitSMaxExpr((const SCEVSMaxExpr*)S);
591 case scUMaxExpr:
592 return ((SC*)this)->visitUMaxExpr((const SCEVUMaxExpr*)S);
593 case scSMinExpr:
594 return ((SC *)this)->visitSMinExpr((const SCEVSMinExpr *)S);
595 case scUMinExpr:
596 return ((SC *)this)->visitUMinExpr((const SCEVUMinExpr *)S);
597 case scUnknown:
598 return ((SC*)this)->visitUnknown((const SCEVUnknown*)S);
599 case scCouldNotCompute:
600 return ((SC*)this)->visitCouldNotCompute((const SCEVCouldNotCompute*)S);
601 }
602 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/Analysis/ScalarEvolutionExpressions.h"
, 602)
;
603 }
604
605 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *S) {
606 llvm_unreachable("Invalid use of SCEVCouldNotCompute!")::llvm::llvm_unreachable_internal("Invalid use of SCEVCouldNotCompute!"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/Analysis/ScalarEvolutionExpressions.h"
, 606)
;
607 }
608 };
609
610 /// Visit all nodes in the expression tree using worklist traversal.
611 ///
612 /// Visitor implements:
613 /// // return true to follow this node.
614 /// bool follow(const SCEV *S);
615 /// // return true to terminate the search.
616 /// bool isDone();
617 template<typename SV>
618 class SCEVTraversal {
619 SV &Visitor;
620 SmallVector<const SCEV *, 8> Worklist;
621 SmallPtrSet<const SCEV *, 8> Visited;
622
623 void push(const SCEV *S) {
624 if (Visited.insert(S).second && Visitor.follow(S))
625 Worklist.push_back(S);
626 }
627
628 public:
629 SCEVTraversal(SV& V): Visitor(V) {}
630
631 void visitAll(const SCEV *Root) {
632 push(Root);
633 while (!Worklist.empty() && !Visitor.isDone()) {
634 const SCEV *S = Worklist.pop_back_val();
635
636 switch (S->getSCEVType()) {
637 case scConstant:
638 case scUnknown:
639 continue;
640 case scPtrToInt:
641 case scTruncate:
642 case scZeroExtend:
643 case scSignExtend:
644 push(cast<SCEVCastExpr>(S)->getOperand());
645 continue;
646 case scAddExpr:
647 case scMulExpr:
648 case scSMaxExpr:
649 case scUMaxExpr:
650 case scSMinExpr:
651 case scUMinExpr:
652 case scAddRecExpr:
653 for (const auto *Op : cast<SCEVNAryExpr>(S)->operands())
654 push(Op);
655 continue;
656 case scUDivExpr: {
657 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
658 push(UDiv->getLHS());
659 push(UDiv->getRHS());
660 continue;
661 }
662 case scCouldNotCompute:
663 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/Analysis/ScalarEvolutionExpressions.h"
, 663)
;
664 }
665 llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/Analysis/ScalarEvolutionExpressions.h"
, 665)
;
666 }
667 }
668 };
669
670 /// Use SCEVTraversal to visit all nodes in the given expression tree.
671 template<typename SV>
672 void visitAll(const SCEV *Root, SV& Visitor) {
673 SCEVTraversal<SV> T(Visitor);
674 T.visitAll(Root);
675 }
676
677 /// Return true if any node in \p Root satisfies the predicate \p Pred.
678 template <typename PredTy>
679 bool SCEVExprContains(const SCEV *Root, PredTy Pred) {
680 struct FindClosure {
681 bool Found = false;
682 PredTy Pred;
683
684 FindClosure(PredTy Pred) : Pred(Pred) {}
685
686 bool follow(const SCEV *S) {
687 if (!Pred(S))
688 return true;
689
690 Found = true;
691 return false;
692 }
693
694 bool isDone() const { return Found; }
695 };
696
697 FindClosure FC(Pred);
698 visitAll(Root, FC);
699 return FC.Found;
700 }
701
702 /// This visitor recursively visits a SCEV expression and re-writes it.
703 /// The result from each visit is cached, so it will return the same
704 /// SCEV for the same input.
705 template<typename SC>
706 class SCEVRewriteVisitor : public SCEVVisitor<SC, const SCEV *> {
707 protected:
708 ScalarEvolution &SE;
709 // Memoize the result of each visit so that we only compute once for
710 // the same input SCEV. This is to avoid redundant computations when
711 // a SCEV is referenced by multiple SCEVs. Without memoization, this
712 // visit algorithm would have exponential time complexity in the worst
713 // case, causing the compiler to hang on certain tests.
714 DenseMap<const SCEV *, const SCEV *> RewriteResults;
715
716 public:
717 SCEVRewriteVisitor(ScalarEvolution &SE) : SE(SE) {}
718
719 const SCEV *visit(const SCEV *S) {
720 auto It = RewriteResults.find(S);
721 if (It != RewriteResults.end())
722 return It->second;
723 auto* Visited = SCEVVisitor<SC, const SCEV *>::visit(S);
724 auto Result = RewriteResults.try_emplace(S, Visited);
725 assert(Result.second && "Should insert a new entry")((Result.second && "Should insert a new entry") ? static_cast
<void> (0) : __assert_fail ("Result.second && \"Should insert a new entry\""
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/Analysis/ScalarEvolutionExpressions.h"
, 725, __PRETTY_FUNCTION__))
;
726 return Result.first->second;
727 }
728
729 const SCEV *visitConstant(const SCEVConstant *Constant) {
730 return Constant;
731 }
732
733 const SCEV *visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) {
734 const SCEV *Operand = ((SC *)this)->visit(Expr->getOperand());
735 return Operand == Expr->getOperand()
736 ? Expr
737 : SE.getPtrToIntExpr(Operand, Expr->getType());
738 }
739
740 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *Expr) {
741 const SCEV *Operand = ((SC*)this)->visit(Expr->getOperand());
742 return Operand == Expr->getOperand()
743 ? Expr
744 : SE.getTruncateExpr(Operand, Expr->getType());
745 }
746
747 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
748 const SCEV *Operand = ((SC*)this)->visit(Expr->getOperand());
749 return Operand == Expr->getOperand()
750 ? Expr
751 : SE.getZeroExtendExpr(Operand, Expr->getType());
752 }
753
754 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
755 const SCEV *Operand = ((SC*)this)->visit(Expr->getOperand());
756 return Operand == Expr->getOperand()
757 ? Expr
758 : SE.getSignExtendExpr(Operand, Expr->getType());
759 }
760
761 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
762 SmallVector<const SCEV *, 2> Operands;
763 bool Changed = false;
764 for (auto *Op : Expr->operands()) {
765 Operands.push_back(((SC*)this)->visit(Op));
766 Changed |= Op != Operands.back();
767 }
768 return !Changed ? Expr : SE.getAddExpr(Operands);
769 }
770
771 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
772 SmallVector<const SCEV *, 2> Operands;
773 bool Changed = false;
774 for (auto *Op : Expr->operands()) {
775 Operands.push_back(((SC*)this)->visit(Op));
776 Changed |= Op != Operands.back();
777 }
778 return !Changed ? Expr : SE.getMulExpr(Operands);
779 }
780
781 const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) {
782 auto *LHS = ((SC *)this)->visit(Expr->getLHS());
783 auto *RHS = ((SC *)this)->visit(Expr->getRHS());
784 bool Changed = LHS != Expr->getLHS() || RHS != Expr->getRHS();
785 return !Changed ? Expr : SE.getUDivExpr(LHS, RHS);
786 }
787
788 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
789 SmallVector<const SCEV *, 2> Operands;
790 bool Changed = false;
791 for (auto *Op : Expr->operands()) {
792 Operands.push_back(((SC*)this)->visit(Op));
793 Changed |= Op != Operands.back();
794 }
795 return !Changed ? Expr
796 : SE.getAddRecExpr(Operands, Expr->getLoop(),
797 Expr->getNoWrapFlags());
798 }
799
800 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
801 SmallVector<const SCEV *, 2> Operands;
802 bool Changed = false;
803 for (auto *Op : Expr->operands()) {
804 Operands.push_back(((SC *)this)->visit(Op));
805 Changed |= Op != Operands.back();
806 }
807 return !Changed ? Expr : SE.getSMaxExpr(Operands);
808 }
809
810 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) {
811 SmallVector<const SCEV *, 2> Operands;
812 bool Changed = false;
813 for (auto *Op : Expr->operands()) {
814 Operands.push_back(((SC*)this)->visit(Op));
815 Changed |= Op != Operands.back();
816 }
817 return !Changed ? Expr : SE.getUMaxExpr(Operands);
818 }
819
820 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
821 SmallVector<const SCEV *, 2> Operands;
822 bool Changed = false;
823 for (auto *Op : Expr->operands()) {
824 Operands.push_back(((SC *)this)->visit(Op));
825 Changed |= Op != Operands.back();
826 }
827 return !Changed ? Expr : SE.getSMinExpr(Operands);
828 }
829
830 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
831 SmallVector<const SCEV *, 2> Operands;
832 bool Changed = false;
833 for (auto *Op : Expr->operands()) {
834 Operands.push_back(((SC *)this)->visit(Op));
835 Changed |= Op != Operands.back();
836 }
837 return !Changed ? Expr : SE.getUMinExpr(Operands);
838 }
839
840 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
841 return Expr;
842 }
843
844 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
845 return Expr;
846 }
847 };
848
849 using ValueToValueMap = DenseMap<const Value *, Value *>;
850 using ValueToSCEVMapTy = DenseMap<const Value *, const SCEV *>;
851
852 /// The SCEVParameterRewriter takes a scalar evolution expression and updates
853 /// the SCEVUnknown components following the Map (Value -> SCEV).
854 class SCEVParameterRewriter : public SCEVRewriteVisitor<SCEVParameterRewriter> {
855 public:
856 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
857 ValueToSCEVMapTy &Map) {
858 SCEVParameterRewriter Rewriter(SE, Map);
859 return Rewriter.visit(Scev);
860 }
861
862 SCEVParameterRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M)
863 : SCEVRewriteVisitor(SE), Map(M) {}
864
865 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
866 auto I = Map.find(Expr->getValue());
867 if (I == Map.end())
868 return Expr;
869 return I->second;
870 }
871
872 private:
873 ValueToSCEVMapTy &Map;
874 };
875
876 using LoopToScevMapT = DenseMap<const Loop *, const SCEV *>;
877
878 /// The SCEVLoopAddRecRewriter takes a scalar evolution expression and applies
879 /// the Map (Loop -> SCEV) to all AddRecExprs.
880 class SCEVLoopAddRecRewriter
881 : public SCEVRewriteVisitor<SCEVLoopAddRecRewriter> {
882 public:
883 SCEVLoopAddRecRewriter(ScalarEvolution &SE, LoopToScevMapT &M)
884 : SCEVRewriteVisitor(SE), Map(M) {}
885
886 static const SCEV *rewrite(const SCEV *Scev, LoopToScevMapT &Map,
887 ScalarEvolution &SE) {
888 SCEVLoopAddRecRewriter Rewriter(SE, Map);
889 return Rewriter.visit(Scev);
890 }
891
892 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
893 SmallVector<const SCEV *, 2> Operands;
894 for (const SCEV *Op : Expr->operands())
895 Operands.push_back(visit(Op));
896
897 const Loop *L = Expr->getLoop();
898 const SCEV *Res = SE.getAddRecExpr(Operands, L, Expr->getNoWrapFlags());
899
900 if (0 == Map.count(L))
901 return Res;
902
903 const SCEVAddRecExpr *Rec = cast<SCEVAddRecExpr>(Res);
904 return Rec->evaluateAtIteration(Map[L], SE);
905 }
906
907 private:
908 LoopToScevMapT &Map;
909 };
910
911} // end namespace llvm
912
913#endif // LLVM_ANALYSIS_SCALAREVOLUTIONEXPRESSIONS_H

/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/ADT/Optional.h

1//===- Optional.h - Simple variant for passing optional values --*- C++ -*-===//
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 provides Optional, a template class modeled in the spirit of
10// OCaml's 'opt' variant. The idea is to strongly type whether or not
11// a value can be optional.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ADT_OPTIONAL_H
16#define LLVM_ADT_OPTIONAL_H
17
18#include "llvm/ADT/None.h"
19#include "llvm/Support/Compiler.h"
20#include "llvm/Support/type_traits.h"
21#include <cassert>
22#include <memory>
23#include <new>
24#include <utility>
25
26namespace llvm {
27
28class raw_ostream;
29
30namespace optional_detail {
31
32struct in_place_t {};
33
34/// Storage for any type.
35template <typename T, bool = is_trivially_copyable<T>::value>
36class OptionalStorage {
37 union {
38 char empty;
39 T value;
40 };
41 bool hasVal;
42
43public:
44 ~OptionalStorage() { reset(); }
45
46 constexpr OptionalStorage() noexcept : empty(), hasVal(false) {}
47
48 constexpr OptionalStorage(OptionalStorage const &other) : OptionalStorage() {
49 if (other.hasValue()) {
50 emplace(other.value);
51 }
52 }
53 constexpr OptionalStorage(OptionalStorage &&other) : OptionalStorage() {
54 if (other.hasValue()) {
55 emplace(std::move(other.value));
56 }
57 }
58
59 template <class... Args>
60 constexpr explicit OptionalStorage(in_place_t, Args &&... args)
61 : value(std::forward<Args>(args)...), hasVal(true) {}
62
63 void reset() noexcept {
64 if (hasVal) {
65 value.~T();
66 hasVal = false;
67 }
68 }
69
70 constexpr bool hasValue() const noexcept { return hasVal; }
71
72 T &getValue() LLVM_LVALUE_FUNCTION& noexcept {
73 assert(hasVal)((hasVal) ? static_cast<void> (0) : __assert_fail ("hasVal"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/ADT/Optional.h"
, 73, __PRETTY_FUNCTION__))
;
74 return value;
75 }
76 constexpr T const &getValue() const LLVM_LVALUE_FUNCTION& noexcept {
77 assert(hasVal)((hasVal) ? static_cast<void> (0) : __assert_fail ("hasVal"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/ADT/Optional.h"
, 77, __PRETTY_FUNCTION__))
;
78 return value;
79 }
80#if LLVM_HAS_RVALUE_REFERENCE_THIS1
81 T &&getValue() && noexcept {
82 assert(hasVal)((hasVal) ? static_cast<void> (0) : __assert_fail ("hasVal"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/ADT/Optional.h"
, 82, __PRETTY_FUNCTION__))
;
83 return std::move(value);
84 }
85#endif
86
87 template <class... Args> void emplace(Args &&... args) {
88 reset();
89 ::new ((void *)std::addressof(value)) T(std::forward<Args>(args)...);
90 hasVal = true;
91 }
92
93 OptionalStorage &operator=(T const &y) {
94 if (hasValue()) {
95 value = y;
96 } else {
97 ::new ((void *)std::addressof(value)) T(y);
98 hasVal = true;
99 }
100 return *this;
101 }
102 OptionalStorage &operator=(T &&y) {
103 if (hasValue()) {
104 value = std::move(y);
105 } else {
106 ::new ((void *)std::addressof(value)) T(std::move(y));
107 hasVal = true;
108 }
109 return *this;
110 }
111
112 OptionalStorage &operator=(OptionalStorage const &other) {
113 if (other.hasValue()) {
114 if (hasValue()) {
115 value = other.value;
116 } else {
117 ::new ((void *)std::addressof(value)) T(other.value);
118 hasVal = true;
119 }
120 } else {
121 reset();
122 }
123 return *this;
124 }
125
126 OptionalStorage &operator=(OptionalStorage &&other) {
127 if (other.hasValue()) {
128 if (hasValue()) {
129 value = std::move(other.value);
130 } else {
131 ::new ((void *)std::addressof(value)) T(std::move(other.value));
132 hasVal = true;
133 }
134 } else {
135 reset();
136 }
137 return *this;
138 }
139};
140
141template <typename T> class OptionalStorage<T, true> {
142 union {
143 char empty;
144 T value;
145 };
146 bool hasVal = false;
147
148public:
149 ~OptionalStorage() = default;
150
151 constexpr OptionalStorage() noexcept : empty{} {}
152
153 constexpr OptionalStorage(OptionalStorage const &other) = default;
154 constexpr OptionalStorage(OptionalStorage &&other) = default;
155
156 OptionalStorage &operator=(OptionalStorage const &other) = default;
157 OptionalStorage &operator=(OptionalStorage &&other) = default;
158
159 template <class... Args>
160 constexpr explicit OptionalStorage(in_place_t, Args &&... args)
161 : value(std::forward<Args>(args)...), hasVal(true) {}
162
163 void reset() noexcept {
164 if (hasVal) {
165 value.~T();
166 hasVal = false;
167 }
168 }
169
170 constexpr bool hasValue() const noexcept { return hasVal; }
37
Returning the value 1, which participates in a condition later
171
172 T &getValue() LLVM_LVALUE_FUNCTION& noexcept {
173 assert(hasVal)((hasVal) ? static_cast<void> (0) : __assert_fail ("hasVal"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/ADT/Optional.h"
, 173, __PRETTY_FUNCTION__))
;
174 return value;
175 }
176 constexpr T const &getValue() const LLVM_LVALUE_FUNCTION& noexcept {
177 assert(hasVal)((hasVal) ? static_cast<void> (0) : __assert_fail ("hasVal"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/ADT/Optional.h"
, 177, __PRETTY_FUNCTION__))
;
178 return value;
179 }
180#if LLVM_HAS_RVALUE_REFERENCE_THIS1
181 T &&getValue() && noexcept {
182 assert(hasVal)((hasVal) ? static_cast<void> (0) : __assert_fail ("hasVal"
, "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/llvm/include/llvm/ADT/Optional.h"
, 182, __PRETTY_FUNCTION__))
;
183 return std::move(value);
184 }
185#endif
186
187 template <class... Args> void emplace(Args &&... args) {
188 reset();
189 ::new ((void *)std::addressof(value)) T(std::forward<Args>(args)...);
190 hasVal = true;
191 }
192
193 OptionalStorage &operator=(T const &y) {
194 if (hasValue()) {
195 value = y;
196 } else {
197 ::new ((void *)std::addressof(value)) T(y);
198 hasVal = true;
199 }
200 return *this;
201 }
202 OptionalStorage &operator=(T &&y) {
203 if (hasValue()) {
204 value = std::move(y);
205 } else {
206 ::new ((void *)std::addressof(value)) T(std::move(y));
207 hasVal = true;
208 }
209 return *this;
210 }
211};
212
213} // namespace optional_detail
214
215template <typename T> class Optional {
216 optional_detail::OptionalStorage<T> Storage;
217
218public:
219 using value_type = T;
220
221 constexpr Optional() {}
222 constexpr Optional(NoneType) {}
223
224 constexpr Optional(const T &y) : Storage(optional_detail::in_place_t{}, y) {}
225 constexpr Optional(const Optional &O) = default;
226
227 constexpr Optional(T &&y)
228 : Storage(optional_detail::in_place_t{}, std::move(y)) {}
229 constexpr Optional(Optional &&O) = default;
230
231 Optional &operator=(T &&y) {
232 Storage = std::move(y);
233 return *this;
234 }
235 Optional &operator=(Optional &&O) = default;
236
237 /// Create a new object by constructing it in place with the given arguments.
238 template <typename... ArgTypes> void emplace(ArgTypes &&... Args) {
239 Storage.emplace(std::forward<ArgTypes>(Args)...);
240 }
241
242 static constexpr Optional create(const T *y) {
243 return y ? Optional(*y) : Optional();
244 }
245
246 Optional &operator=(const T &y) {
247 Storage = y;
248 return *this;
249 }
250 Optional &operator=(const Optional &O) = default;
251
252 void reset() { Storage.reset(); }
253
254 constexpr const T *getPointer() const { return &Storage.getValue(); }
255 T *getPointer() { return &Storage.getValue(); }
256 constexpr const T &getValue() const LLVM_LVALUE_FUNCTION& {
257 return Storage.getValue();
258 }
259 T &getValue() LLVM_LVALUE_FUNCTION& { return Storage.getValue(); }
260
261 constexpr explicit operator bool() const { return hasValue(); }
35
Calling 'Optional::hasValue'
40
Returning from 'Optional::hasValue'
41
Returning the value 1, which participates in a condition later
262 constexpr bool hasValue() const { return Storage.hasValue(); }
36
Calling 'OptionalStorage::hasValue'
38
Returning from 'OptionalStorage::hasValue'
39
Returning the value 1, which participates in a condition later
263 constexpr const T *operator->() const { return getPointer(); }
264 T *operator->() { return getPointer(); }
265 constexpr const T &operator*() const LLVM_LVALUE_FUNCTION& {
266 return getValue();
267 }
268 T &operator*() LLVM_LVALUE_FUNCTION& { return getValue(); }
269
270 template <typename U>
271 constexpr T getValueOr(U &&value) const LLVM_LVALUE_FUNCTION& {
272 return hasValue() ? getValue() : std::forward<U>(value);
273 }
274
275 /// Apply a function to the value if present; otherwise return None.
276 template <class Function>
277 auto map(const Function &F) const LLVM_LVALUE_FUNCTION&
278 -> Optional<decltype(F(getValue()))> {
279 if (*this) return F(getValue());
280 return None;
281 }
282
283#if LLVM_HAS_RVALUE_REFERENCE_THIS1
284 T &&getValue() && { return std::move(Storage.getValue()); }
285 T &&operator*() && { return std::move(Storage.getValue()); }
286
287 template <typename U>
288 T getValueOr(U &&value) && {
289 return hasValue() ? std::move(getValue()) : std::forward<U>(value);
290 }
291
292 /// Apply a function to the value if present; otherwise return None.
293 template <class Function>
294 auto map(const Function &F) &&
295 -> Optional<decltype(F(std::move(*this).getValue()))> {
296 if (*this) return F(std::move(*this).getValue());
297 return None;
298 }
299#endif
300};
301
302template <typename T, typename U>
303constexpr bool operator==(const Optional<T> &X, const Optional<U> &Y) {
304 if (X && Y)
305 return *X == *Y;
306 return X.hasValue() == Y.hasValue();
307}
308
309template <typename T, typename U>
310constexpr bool operator!=(const Optional<T> &X, const Optional<U> &Y) {
311 return !(X == Y);
312}
313
314template <typename T, typename U>
315constexpr bool operator<(const Optional<T> &X, const Optional<U> &Y) {
316 if (X && Y)
317 return *X < *Y;
318 return X.hasValue() < Y.hasValue();
319}
320
321template <typename T, typename U>
322constexpr bool operator<=(const Optional<T> &X, const Optional<U> &Y) {
323 return !(Y < X);
324}
325
326template <typename T, typename U>
327constexpr bool operator>(const Optional<T> &X, const Optional<U> &Y) {
328 return Y < X;
329}
330
331template <typename T, typename U>
332constexpr bool operator>=(const Optional<T> &X, const Optional<U> &Y) {
333 return !(X < Y);
334}
335
336template <typename T>
337constexpr bool operator==(const Optional<T> &X, NoneType) {
338 return !X;
339}
340
341template <typename T>
342constexpr bool operator==(NoneType, const Optional<T> &X) {
343 return X == None;
344}
345
346template <typename T>
347constexpr bool operator!=(const Optional<T> &X, NoneType) {
348 return !(X == None);
349}
350
351template <typename T>
352constexpr bool operator!=(NoneType, const Optional<T> &X) {
353 return X != None;
354}
355
356template <typename T> constexpr bool operator<(const Optional<T> &X, NoneType) {
357 return false;
358}
359
360template <typename T> constexpr bool operator<(NoneType, const Optional<T> &X) {
361 return X.hasValue();
362}
363
364template <typename T>
365constexpr bool operator<=(const Optional<T> &X, NoneType) {
366 return !(None < X);
367}
368
369template <typename T>
370constexpr bool operator<=(NoneType, const Optional<T> &X) {
371 return !(X < None);
372}
373
374template <typename T> constexpr bool operator>(const Optional<T> &X, NoneType) {
375 return None < X;
376}
377
378template <typename T> constexpr bool operator>(NoneType, const Optional<T> &X) {
379 return X < None;
380}
381
382template <typename T>
383constexpr bool operator>=(const Optional<T> &X, NoneType) {
384 return None <= X;
385}
386
387template <typename T>
388constexpr bool operator>=(NoneType, const Optional<T> &X) {
389 return X <= None;
390}
391
392template <typename T>
393constexpr bool operator==(const Optional<T> &X, const T &Y) {
394 return X && *X == Y;
395}
396
397template <typename T>
398constexpr bool operator==(const T &X, const Optional<T> &Y) {
399 return Y && X == *Y;
400}
401
402template <typename T>
403constexpr bool operator!=(const Optional<T> &X, const T &Y) {
404 return !(X == Y);
405}
406
407template <typename T>
408constexpr bool operator!=(const T &X, const Optional<T> &Y) {
409 return !(X == Y);
410}
411
412template <typename T>
413constexpr bool operator<(const Optional<T> &X, const T &Y) {
414 return !X || *X < Y;
415}
416
417template <typename T>
418constexpr bool operator<(const T &X, const Optional<T> &Y) {
419 return Y && X < *Y;
420}
421
422template <typename T>
423constexpr bool operator<=(const Optional<T> &X, const T &Y) {
424 return !(Y < X);
425}
426
427template <typename T>
428constexpr bool operator<=(const T &X, const Optional<T> &Y) {
429 return !(Y < X);
430}
431
432template <typename T>
433constexpr bool operator>(const Optional<T> &X, const T &Y) {
434 return Y < X;
435}
436
437template <typename T>
438constexpr bool operator>(const T &X, const Optional<T> &Y) {
439 return Y < X;
440}
441
442template <typename T>
443constexpr bool operator>=(const Optional<T> &X, const T &Y) {
444 return !(X < Y);
445}
446
447template <typename T>
448constexpr bool operator>=(const T &X, const Optional<T> &Y) {
449 return !(X < Y);
450}
451
452raw_ostream &operator<<(raw_ostream &OS, NoneType);
453
454template <typename T, typename = decltype(std::declval<raw_ostream &>()
455 << std::declval<const T &>())>
456raw_ostream &operator<<(raw_ostream &OS, const Optional<T> &O) {
457 if (O)
458 OS << *O;
459 else
460 OS << None;
461 return OS;
462}
463
464} // end namespace llvm
465
466#endif // LLVM_ADT_OPTIONAL_H