Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/lib/Analysis/ScalarEvolution.cpp
Warning:line 4536, column 32
Dereference of null pointer (loaded from variable 'PtrOp')

Annotated Source Code

Press '?' to see keyboard shortcuts

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