Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/lib/Analysis/ScalarEvolution.cpp
Warning:line 4437, column 3
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -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~++20221003111214+1fa2019828ca/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~++20221003111214+1fa2019828ca/llvm/lib/Analysis -I include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/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~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -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~++20221003111214+1fa2019828ca/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -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-10-03-140002-15933-1 -x c++ /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/lib/Analysis/ScalarEvolution.cpp

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