Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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