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/FoldingSet.h"
66#include "llvm/ADT/STLExtras.h"
67#include "llvm/ADT/ScopeExit.h"
68#include "llvm/ADT/Sequence.h"
69#include "llvm/ADT/SmallPtrSet.h"
70#include "llvm/ADT/SmallVector.h"
71#include "llvm/ADT/Statistic.h"
72#include "llvm/ADT/StringExtras.h"
73#include "llvm/ADT/StringRef.h"
74#include "llvm/Analysis/AssumptionCache.h"
75#include "llvm/Analysis/ConstantFolding.h"
76#include "llvm/Analysis/InstructionSimplify.h"
77#include "llvm/Analysis/LoopInfo.h"
78#include "llvm/Analysis/MemoryBuiltins.h"
79#include "llvm/Analysis/ScalarEvolutionExpressions.h"
80#include "llvm/Analysis/ScalarEvolutionPatternMatch.h"
81#include "llvm/Analysis/TargetLibraryInfo.h"
82#include "llvm/Analysis/ValueTracking.h"
83#include "llvm/Config/llvm-config.h"
84#include "llvm/IR/Argument.h"
85#include "llvm/IR/BasicBlock.h"
86#include "llvm/IR/CFG.h"
87#include "llvm/IR/Constant.h"
88#include "llvm/IR/ConstantRange.h"
89#include "llvm/IR/Constants.h"
90#include "llvm/IR/DataLayout.h"
91#include "llvm/IR/DerivedTypes.h"
92#include "llvm/IR/Dominators.h"
93#include "llvm/IR/Function.h"
94#include "llvm/IR/GlobalAlias.h"
95#include "llvm/IR/GlobalValue.h"
96#include "llvm/IR/InstIterator.h"
97#include "llvm/IR/InstrTypes.h"
98#include "llvm/IR/Instruction.h"
99#include "llvm/IR/Instructions.h"
100#include "llvm/IR/IntrinsicInst.h"
101#include "llvm/IR/Intrinsics.h"
102#include "llvm/IR/LLVMContext.h"
103#include "llvm/IR/Operator.h"
104#include "llvm/IR/PatternMatch.h"
105#include "llvm/IR/Type.h"
106#include "llvm/IR/Use.h"
107#include "llvm/IR/User.h"
108#include "llvm/IR/Value.h"
109#include "llvm/IR/Verifier.h"
110#include "llvm/InitializePasses.h"
111#include "llvm/Pass.h"
112#include "llvm/Support/Casting.h"
113#include "llvm/Support/CommandLine.h"
114#include "llvm/Support/Compiler.h"
115#include "llvm/Support/Debug.h"
116#include "llvm/Support/ErrorHandling.h"
117#include "llvm/Support/InterleavedRange.h"
118#include "llvm/Support/KnownBits.h"
119#include "llvm/Support/SaveAndRestore.h"
120#include "llvm/Support/raw_ostream.h"
121#include <algorithm>
122#include <cassert>
123#include <climits>
124#include <cstdint>
125#include <cstdlib>
126#include <map>
127#include <memory>
128#include <numeric>
129#include <optional>
130#include <tuple>
131#include <utility>
132#include <vector>
133
134using namespace llvm;
135using namespace PatternMatch;
136using namespace SCEVPatternMatch;
137
138#define DEBUG_TYPE "scalar-evolution"
139
140STATISTIC(NumExitCountsComputed,
141 "Number of loop exits with predictable exit counts");
142STATISTIC(NumExitCountsNotComputed,
143 "Number of loop exits without predictable exit counts");
144STATISTIC(NumBruteForceTripCountsComputed,
145 "Number of loops with trip counts computed by force");
146
147#ifdef EXPENSIVE_CHECKS
148bool llvm::VerifySCEV = true;
149#else
150bool llvm::VerifySCEV = false;
151#endif
152
153static cl::opt<unsigned>
154 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
155 cl::desc("Maximum number of iterations SCEV will "
156 "symbolically execute a constant "
157 "derived loop"),
158 cl::init(Val: 100));
159
160static cl::opt<bool, true> VerifySCEVOpt(
161 "verify-scev", cl::Hidden, cl::location(L&: VerifySCEV),
162 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
163static cl::opt<bool> VerifySCEVStrict(
164 "verify-scev-strict", cl::Hidden,
165 cl::desc("Enable stricter verification with -verify-scev is passed"));
166
167static cl::opt<bool> VerifyIR(
168 "scev-verify-ir", cl::Hidden,
169 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
170 cl::init(Val: false));
171
172static cl::opt<unsigned> MulOpsInlineThreshold(
173 "scev-mulops-inline-threshold", cl::Hidden,
174 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
175 cl::init(Val: 32));
176
177static cl::opt<unsigned> AddOpsInlineThreshold(
178 "scev-addops-inline-threshold", cl::Hidden,
179 cl::desc("Threshold for inlining addition operands into a SCEV"),
180 cl::init(Val: 500));
181
182static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
183 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
184 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
185 cl::init(Val: 2));
186
187static cl::opt<unsigned> MaxValueCompareDepth(
188 "scalar-evolution-max-value-compare-depth", cl::Hidden,
189 cl::desc("Maximum depth of recursive value complexity comparisons"),
190 cl::init(Val: 2));
191
192static cl::opt<unsigned>
193 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
194 cl::desc("Maximum depth of recursive arithmetics"),
195 cl::init(Val: 32));
196
197static cl::opt<unsigned> MaxConstantEvolvingDepth(
198 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
199 cl::desc("Maximum depth of recursive constant evolving"), cl::init(Val: 32));
200
201static cl::opt<unsigned>
202 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
203 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
204 cl::init(Val: 8));
205
206static cl::opt<unsigned>
207 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
208 cl::desc("Max coefficients in AddRec during evolving"),
209 cl::init(Val: 8));
210
211static cl::opt<unsigned>
212 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
213 cl::desc("Size of the expression which is considered huge"),
214 cl::init(Val: 4096));
215
216static cl::opt<unsigned> RangeIterThreshold(
217 "scev-range-iter-threshold", cl::Hidden,
218 cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
219 cl::init(Val: 32));
220
221static cl::opt<unsigned> MaxLoopGuardCollectionDepth(
222 "scalar-evolution-max-loop-guard-collection-depth", cl::Hidden,
223 cl::desc("Maximum depth for recursive loop guard collection"), cl::init(Val: 1));
224
225static cl::opt<bool>
226ClassifyExpressions("scalar-evolution-classify-expressions",
227 cl::Hidden, cl::init(Val: true),
228 cl::desc("When printing analysis, include information on every instruction"));
229
230static cl::opt<bool> UseExpensiveRangeSharpening(
231 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
232 cl::init(Val: false),
233 cl::desc("Use more powerful methods of sharpening expression ranges. May "
234 "be costly in terms of compile time"));
235
236static cl::opt<bool>
237 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
238 cl::desc("Handle <= and >= in finite loops"),
239 cl::init(Val: true));
240
241static cl::opt<bool> UseContextForNoWrapFlagInference(
242 "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
243 cl::desc("Infer nuw/nsw flags using context where suitable"),
244 cl::init(Val: true));
245
246//===----------------------------------------------------------------------===//
247// SCEV class definitions
248//===----------------------------------------------------------------------===//
249
250void SCEV::computeAndSetCanonical(ScalarEvolution &SE) {
251 // Leaf nodes are always their own canonical.
252 switch (getSCEVType()) {
253 case scConstant:
254 case scVScale:
255 case scUnknown:
256 CanonicalSCEV = this;
257 return;
258 default:
259 break;
260 }
261
262 // For all other expressions, check whether any immediate operand has a
263 // different canonical. Since operands are always created before their parent,
264 // their canonical pointers are already set — no recursion needed.
265 if (all_of(Range: operands(), P: [](SCEVUse Op) { return Op.isCanonical(); })) {
266 CanonicalSCEV = this;
267 return;
268 }
269
270 SmallVector<SCEVUse, 4> CanonOps(
271 map_range(C: operands(), F: [](SCEVUse Op) { return Op.getCanonical(); }));
272 // Rebuild the expression from the canonical operands, stripping use flags.
273 CanonicalSCEV = SE.getWithOperands(S: this, NewOps&: CanonOps);
274}
275
276//===----------------------------------------------------------------------===//
277// Implementation of the SCEV class.
278//
279
280#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
281LLVM_DUMP_METHOD void SCEV::dump() const {
282 print(dbgs());
283 dbgs() << '\n';
284}
285#endif
286
287void SCEV::print(raw_ostream &OS) const {
288 switch (getSCEVType()) {
289 case scConstant:
290 cast<SCEVConstant>(Val: this)->getValue()->printAsOperand(O&: OS, PrintType: false);
291 return;
292 case scVScale:
293 OS << "vscale";
294 return;
295 case scPtrToAddr: {
296 const SCEVCastExpr *PtrCast = cast<SCEVCastExpr>(Val: this);
297 SCEVUse Op = PtrCast->getOperand();
298 OS << "(ptrtoaddr " << *Op->getType() << " " << Op << " to "
299 << *PtrCast->getType() << ")";
300 return;
301 }
302 case scTruncate: {
303 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Val: this);
304 SCEVUse Op = Trunc->getOperand();
305 OS << "(trunc " << *Op->getType() << " " << Op << " to "
306 << *Trunc->getType() << ")";
307 return;
308 }
309 case scZeroExtend: {
310 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(Val: this);
311 SCEVUse Op = ZExt->getOperand();
312 OS << "(zext " << *Op->getType() << " " << Op << " to " << *ZExt->getType()
313 << ")";
314 return;
315 }
316 case scSignExtend: {
317 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(Val: this);
318 SCEVUse Op = SExt->getOperand();
319 OS << "(sext " << *Op->getType() << " " << Op << " to " << *SExt->getType()
320 << ")";
321 return;
322 }
323 case scAddRecExpr: {
324 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(Val: this);
325 OS << "{" << AR->getOperand(i: 0);
326 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
327 OS << ",+," << AR->getOperand(i);
328 OS << "}<";
329 if (AR->hasNoUnsignedWrap())
330 OS << "nuw><";
331 if (AR->hasNoSignedWrap())
332 OS << "nsw><";
333 if (AR->hasNoSelfWrap() && !AR->hasNoUnsignedWrap() &&
334 !AR->hasNoSignedWrap())
335 OS << "nw><";
336 AR->getLoop()->getHeader()->printAsOperand(O&: OS, /*PrintType=*/false);
337 OS << ">";
338 return;
339 }
340 case scAddExpr:
341 case scMulExpr:
342 case scUMaxExpr:
343 case scSMaxExpr:
344 case scUMinExpr:
345 case scSMinExpr:
346 case scSequentialUMinExpr: {
347 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(Val: this);
348 const char *OpStr = nullptr;
349 switch (NAry->getSCEVType()) {
350 case scAddExpr: OpStr = " + "; break;
351 case scMulExpr: OpStr = " * "; break;
352 case scUMaxExpr: OpStr = " umax "; break;
353 case scSMaxExpr: OpStr = " smax "; break;
354 case scUMinExpr:
355 OpStr = " umin ";
356 break;
357 case scSMinExpr:
358 OpStr = " smin ";
359 break;
360 case scSequentialUMinExpr:
361 OpStr = " umin_seq ";
362 break;
363 default:
364 llvm_unreachable("There are no other nary expression types.");
365 }
366 OS << "(" << llvm::interleaved(R: NAry->operands(), Separator: OpStr) << ")";
367 switch (NAry->getSCEVType()) {
368 case scAddExpr:
369 case scMulExpr:
370 if (NAry->hasNoUnsignedWrap())
371 OS << "<nuw>";
372 if (NAry->hasNoSignedWrap())
373 OS << "<nsw>";
374 break;
375 default:
376 // Nothing to print for other nary expressions.
377 break;
378 }
379 return;
380 }
381 case scUDivExpr: {
382 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(Val: this);
383 OS << "(" << UDiv->getLHS() << " /u " << UDiv->getRHS() << ")";
384 return;
385 }
386 case scUnknown:
387 cast<SCEVUnknown>(Val: this)->getValue()->printAsOperand(O&: OS, PrintType: false);
388 return;
389 case scCouldNotCompute:
390 OS << "***COULDNOTCOMPUTE***";
391 return;
392 }
393 llvm_unreachable("Unknown SCEV kind!");
394}
395
396ArrayRef<SCEVUse> SCEV::operands() const {
397 switch (getSCEVType()) {
398 case scConstant:
399 case scVScale:
400 case scUnknown:
401 return {};
402 case scPtrToAddr:
403 case scTruncate:
404 case scZeroExtend:
405 case scSignExtend:
406 return cast<SCEVCastExpr>(Val: this)->operands();
407 case scAddRecExpr:
408 case scAddExpr:
409 case scMulExpr:
410 case scUMaxExpr:
411 case scSMaxExpr:
412 case scUMinExpr:
413 case scSMinExpr:
414 case scSequentialUMinExpr:
415 return cast<SCEVNAryExpr>(Val: this)->operands();
416 case scUDivExpr:
417 return cast<SCEVUDivExpr>(Val: this)->operands();
418 case scCouldNotCompute:
419 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
420 }
421 llvm_unreachable("Unknown SCEV kind!");
422}
423
424bool SCEV::isZero() const { return match(S: this, P: m_scev_Zero()); }
425
426bool SCEV::isOne() const { return match(S: this, P: m_scev_One()); }
427
428bool SCEV::isAllOnesValue() const { return match(S: this, P: m_scev_AllOnes()); }
429
430bool SCEV::isNonConstantNegative() const {
431 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Val: this);
432 if (!Mul) return false;
433
434 // If there is a constant factor, it will be first.
435 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Val: Mul->getOperand(i: 0));
436 if (!SC) return false;
437
438 // Return true if the value is negative, this matches things like (-42 * V).
439 return SC->getAPInt().isNegative();
440}
441
442SCEVCouldNotCompute::SCEVCouldNotCompute()
443 : SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0, nullptr) {}
444
445bool SCEVCouldNotCompute::classof(const SCEV *S) {
446 return S->getSCEVType() == scCouldNotCompute;
447}
448
449const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
450 auto &Entry = ConstantSCEVs[V];
451 if (Entry)
452 return Entry;
453
454 FoldingSetNodeID ID;
455 ID.AddInteger(I: scConstant);
456 ID.AddPointer(Ptr: V);
457 FoldingSetInsertToken Token;
458 if (SCEVConstant *S =
459 static_cast<SCEVConstant *>(UniqueSCEVs.lookup(ID, Token)))
460 return Entry = S;
461 SCEVConstant *S =
462 new (SCEVAllocator) SCEVConstant(ID.Intern(Allocator&: SCEVAllocator), V);
463 UniqueSCEVs.insert(N: S, Token);
464 S->computeAndSetCanonical(SE&: *this);
465 return Entry = S;
466}
467
468const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
469 return getConstant(V: ConstantInt::get(Context&: getContext(), V: Val));
470}
471
472const SCEV *
473ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
474 IntegerType *ITy = cast<IntegerType>(Val: getEffectiveSCEVType(Ty));
475 // TODO: Avoid implicit trunc?
476 // See https://github.com/llvm/llvm-project/issues/112510.
477 return getConstant(
478 V: ConstantInt::get(Ty: ITy, V, IsSigned: isSigned, /*ImplicitTrunc=*/true));
479}
480
481const SCEV *ScalarEvolution::getVScale(Type *Ty) {
482 FoldingSetNodeID ID;
483 ID.AddInteger(I: scVScale);
484 ID.AddPointer(Ptr: Ty);
485 FoldingSetInsertToken Token;
486 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
487 return S;
488 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(Allocator&: SCEVAllocator), Ty);
489 UniqueSCEVs.insert(N: S, Token);
490 S->computeAndSetCanonical(SE&: *this);
491 return S;
492}
493
494const SCEV *ScalarEvolution::getElementCount(Type *Ty, ElementCount EC,
495 SCEVFlags Flags) {
496 const SCEV *Res = getConstant(Ty, V: EC.getKnownMinValue());
497 if (EC.isScalable())
498 Res = getMulExpr(LHS: Res, RHS: getVScale(Ty), Flags);
499 return Res;
500}
501
502SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
503 SCEVUse op, Type *ty)
504 : SCEV(ID, SCEVTy, computeExpressionSize(Args: op), ty), Op(op) {}
505
506SCEVPtrToAddrExpr::SCEVPtrToAddrExpr(const FoldingSetNodeIDRef ID,
507 const SCEV *Op, Type *ITy)
508 : SCEVCastExpr(ID, scPtrToAddr, Op, ITy) {
509 assert(getOperand()->getType()->isPointerTy() && getType()->isIntegerTy() &&
510 "Must be a non-bit-width-changing pointer-to-integer cast!");
511}
512
513SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
514 SCEVTypes SCEVTy, SCEVUse op,
515 Type *ty)
516 : SCEVCastExpr(ID, SCEVTy, op, ty) {}
517
518SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
519 Type *ty)
520 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
521 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
522 "Cannot truncate non-integer value!");
523}
524
525SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
526 Type *ty)
527 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
528 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
529 "Cannot zero extend non-integer value!");
530}
531
532SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
533 Type *ty)
534 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
535 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
536 "Cannot sign extend non-integer value!");
537}
538
539void SCEVUnknown::deleted() {
540 // Clear this SCEVUnknown from various maps.
541 SE->forgetMemoizedResults(SCEVs: {this});
542
543 // Remove this SCEVUnknown from the uniquing map.
544 SE->UniqueSCEVs.erase(N: this);
545
546 // Release the value.
547 setValPtr(nullptr);
548}
549
550void SCEVUnknown::allUsesReplacedWith(Value *New) {
551 // Clear this SCEVUnknown from various maps.
552 SE->forgetMemoizedResults(SCEVs: {this});
553
554 // Remove this SCEVUnknown from the uniquing map.
555 SE->UniqueSCEVs.erase(N: this);
556
557 // Replace the value pointer in case someone is still using this SCEVUnknown.
558 setValPtr(New);
559}
560
561//===----------------------------------------------------------------------===//
562// SCEV Utilities
563//===----------------------------------------------------------------------===//
564
565/// Compare the two values \p LV and \p RV in terms of their "complexity" where
566/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
567/// operands in SCEV expressions.
568static int CompareValueComplexity(const LoopInfo *const LI, Value *LV,
569 Value *RV, unsigned Depth) {
570 if (Depth > MaxValueCompareDepth)
571 return 0;
572
573 // Order pointer values after integer values. This helps SCEVExpander form
574 // GEPs.
575 bool LIsPointer = LV->getType()->isPointerTy(),
576 RIsPointer = RV->getType()->isPointerTy();
577 if (LIsPointer != RIsPointer)
578 return (int)LIsPointer - (int)RIsPointer;
579
580 // Compare getValueID values.
581 unsigned LID = LV->getValueID(), RID = RV->getValueID();
582 if (LID != RID)
583 return (int)LID - (int)RID;
584
585 // Sort arguments by their position.
586 if (const auto *LA = dyn_cast<Argument>(Val: LV)) {
587 const auto *RA = cast<Argument>(Val: RV);
588 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
589 return (int)LArgNo - (int)RArgNo;
590 }
591
592 if (const auto *LGV = dyn_cast<GlobalValue>(Val: LV)) {
593 const auto *RGV = cast<GlobalValue>(Val: RV);
594
595 if (auto L = LGV->getLinkage() - RGV->getLinkage())
596 return L;
597
598 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
599 auto LT = GV->getLinkage();
600 return !(GlobalValue::isPrivateLinkage(Linkage: LT) ||
601 GlobalValue::isInternalLinkage(Linkage: LT));
602 };
603
604 // Use the names to distinguish the two values, but only if the
605 // names are semantically important.
606 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
607 return LGV->getName().compare(RHS: RGV->getName());
608 }
609
610 // For instructions, compare their loop depth, and their operand count. This
611 // is pretty loose.
612 if (const auto *LInst = dyn_cast<Instruction>(Val: LV)) {
613 const auto *RInst = cast<Instruction>(Val: RV);
614
615 // Compare loop depths.
616 const BasicBlock *LParent = LInst->getParent(),
617 *RParent = RInst->getParent();
618 if (LParent != RParent) {
619 unsigned LDepth = LI->getLoopDepth(BB: LParent),
620 RDepth = LI->getLoopDepth(BB: RParent);
621 if (LDepth != RDepth)
622 return (int)LDepth - (int)RDepth;
623 }
624
625 // Compare the number of operands.
626 unsigned LNumOps = LInst->getNumOperands(),
627 RNumOps = RInst->getNumOperands();
628 if (LNumOps != RNumOps)
629 return (int)LNumOps - (int)RNumOps;
630
631 for (unsigned Idx : seq(Size: LNumOps)) {
632 int Result = CompareValueComplexity(LI, LV: LInst->getOperand(i: Idx),
633 RV: RInst->getOperand(i: Idx), Depth: Depth + 1);
634 if (Result != 0)
635 return Result;
636 }
637 }
638
639 return 0;
640}
641
642// Return negative, zero, or positive, if LHS is less than, equal to, or greater
643// than RHS, respectively. A three-way result allows recursive comparisons to be
644// more efficient. The result is a total order.
645static int CompareSCEVComplexity(const LoopInfo *const LI, SCEVUse LHS,
646 SCEVUse RHS, DominatorTree &DT) {
647 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
648 if (LHS == RHS)
649 return 0;
650
651 if (LHS.getPointer() == RHS.getPointer())
652 return (int)LHS.getUseNoWrapFlags() - (int)RHS.getUseNoWrapFlags();
653
654 // Primarily, sort the SCEVs by their getSCEVType().
655 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
656 if (LType != RType)
657 return (int)LType - (int)RType;
658
659 // Aside from the getSCEVType() ordering, the particular ordering
660 // isn't very important except that it's beneficial to be consistent,
661 // so that (a + b) and (b + a) don't end up as different expressions.
662 switch (LType) {
663 case scUnknown: {
664 const SCEVUnknown *LU = cast<SCEVUnknown>(Val&: LHS);
665 const SCEVUnknown *RU = cast<SCEVUnknown>(Val&: RHS);
666
667 if (int X = CompareValueComplexity(LI, LV: LU->getValue(), RV: RU->getValue(),
668 /*Depth=*/0))
669 return X;
670 return LU->getOrderID() < RU->getOrderID() ? -1 : 1;
671 }
672
673 case scConstant: {
674 const SCEVConstant *LC = cast<SCEVConstant>(Val&: LHS);
675 const SCEVConstant *RC = cast<SCEVConstant>(Val&: RHS);
676
677 // Compare constant values.
678 const APInt &LA = LC->getAPInt();
679 const APInt &RA = RC->getAPInt();
680 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
681 if (LBitWidth != RBitWidth)
682 return (int)LBitWidth - (int)RBitWidth;
683 return LA.ult(RHS: RA) ? -1 : 1;
684 }
685
686 case scVScale: {
687 const auto *LTy = cast<IntegerType>(Val: cast<SCEVVScale>(Val&: LHS)->getType());
688 const auto *RTy = cast<IntegerType>(Val: cast<SCEVVScale>(Val&: RHS)->getType());
689 return LTy->getBitWidth() - RTy->getBitWidth();
690 }
691
692 case scAddRecExpr: {
693 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(Val&: LHS);
694 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(Val&: RHS);
695
696 // There is always a dominance between two recs that are used by one SCEV,
697 // so we can safely sort recs by loop header dominance. We require such
698 // order in getAddExpr.
699 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
700 if (LLoop != RLoop) {
701 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
702 assert(LHead != RHead && "Two loops share the same header?");
703 if (DT.dominates(A: LHead, B: RHead))
704 return 1;
705 assert(DT.dominates(RHead, LHead) &&
706 "No dominance between recurrences used by one SCEV?");
707 return -1;
708 }
709
710 [[fallthrough]];
711 }
712
713 case scTruncate:
714 case scZeroExtend:
715 case scSignExtend:
716 case scPtrToAddr:
717 case scAddExpr:
718 case scMulExpr:
719 case scUDivExpr:
720 case scSMaxExpr:
721 case scUMaxExpr:
722 case scSMinExpr:
723 case scUMinExpr:
724 case scSequentialUMinExpr: {
725 ArrayRef<SCEVUse> LOps = LHS->operands();
726 ArrayRef<SCEVUse> ROps = RHS->operands();
727
728 // Lexicographically compare n-ary-like expressions.
729 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
730 if (LNumOps != RNumOps)
731 return (int)LNumOps - (int)RNumOps;
732
733 for (unsigned i = 0; i != LNumOps; ++i) {
734 auto X = CompareSCEVComplexity(LI, LHS: LOps[i], RHS: ROps[i], DT);
735 if (X != 0)
736 return X;
737 }
738
739 assert(isa<SCEVCastExpr>(LHS) && "distinct SCEVs compare equal");
740 unsigned LBitWidth = cast<IntegerType>(Val: LHS->getType())->getBitWidth();
741 unsigned RBitWidth = cast<IntegerType>(Val: RHS->getType())->getBitWidth();
742 assert(LBitWidth != RBitWidth && "distinct SCEVs compare equal");
743 return (int)LBitWidth - (int)RBitWidth;
744 }
745
746 case scCouldNotCompute:
747 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
748 }
749 llvm_unreachable("Unknown SCEV kind!");
750}
751
752/// Given a list of SCEV objects, order them by their complexity, and group
753/// objects of the same complexity together by value. When this routine is
754/// finished, we know that any duplicates in the vector are consecutive and that
755/// complexity is monotonically increasing.
756///
757/// Note that we go take special precautions to ensure that we get deterministic
758/// results from this routine. In other words, we don't want the results of
759/// this to depend on where the addresses of various SCEV objects happened to
760/// land in memory.
761static void GroupByComplexity(SmallVectorImpl<SCEVUse> &Ops, LoopInfo *LI,
762 DominatorTree &DT) {
763 if (Ops.size() < 2) return; // Noop
764
765 // Whether LHS has provably less complexity than RHS.
766 auto IsLessComplex = [&](SCEVUse LHS, SCEVUse RHS) {
767 return CompareSCEVComplexity(LI, LHS, RHS, DT) < 0;
768 };
769 if (Ops.size() == 2) {
770 // This is the common case, which also happens to be trivially simple.
771 // Special case it.
772 SCEVUse &LHS = Ops[0], &RHS = Ops[1];
773 if (IsLessComplex(RHS, LHS))
774 std::swap(a&: LHS, b&: RHS);
775 return;
776 }
777
778 llvm::sort(C&: Ops, Comp: IsLessComplex);
779}
780
781/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
782/// least HugeExprThreshold nodes).
783static bool hasHugeExpression(ArrayRef<SCEVUse> Ops) {
784 return any_of(Range&: Ops, P: [](const SCEV *S) {
785 return S->getExpressionSize() >= HugeExprThreshold;
786 });
787}
788
789/// Performs a number of common optimizations on the passed \p Ops. If the
790/// whole expression reduces down to a single operand, it will be returned.
791///
792/// The following optimizations are performed:
793/// * Fold constants using the \p Fold function.
794/// * Remove identity constants satisfying \p IsIdentity.
795/// * If a constant satisfies \p IsAbsorber, return it.
796/// * Sort operands by complexity.
797template <typename FoldT, typename IsIdentityT, typename IsAbsorberT>
798static const SCEV *
799constantFoldAndGroupOps(ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT,
800 SmallVectorImpl<SCEVUse> &Ops, FoldT Fold,
801 IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
802 const SCEVConstant *Folded = nullptr;
803 for (unsigned Idx = 0; Idx < Ops.size();) {
804 const SCEV *Op = Ops[Idx];
805 if (const auto *C = dyn_cast<SCEVConstant>(Val: Op)) {
806 if (!Folded)
807 Folded = C;
808 else
809 Folded = cast<SCEVConstant>(
810 SE.getConstant(Fold(Folded->getAPInt(), C->getAPInt())));
811 Ops.erase(CI: Ops.begin() + Idx);
812 continue;
813 }
814 ++Idx;
815 }
816
817 if (Ops.empty()) {
818 assert(Folded && "Must have folded value");
819 return Folded;
820 }
821
822 if (Folded && IsAbsorber(Folded->getAPInt()))
823 return Folded;
824
825 GroupByComplexity(Ops, LI: &LI, DT);
826 if (Folded && !IsIdentity(Folded->getAPInt()))
827 Ops.insert(I: Ops.begin(), Elt: Folded);
828
829 return Ops.size() == 1 ? Ops[0] : nullptr;
830}
831
832//===----------------------------------------------------------------------===//
833// Simple SCEV method implementations
834//===----------------------------------------------------------------------===//
835
836/// Compute BC(It, K). The result has width W. Assume, K > 0.
837static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
838 ScalarEvolution &SE,
839 Type *ResultTy) {
840 // Handle the simplest case efficiently.
841 if (K == 1)
842 return SE.getTruncateOrZeroExtend(V: It, Ty: ResultTy);
843
844 // We are using the following formula for BC(It, K):
845 //
846 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
847 //
848 // Suppose, W is the bitwidth of the return value. We must be prepared for
849 // overflow. Hence, we must assure that the result of our computation is
850 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
851 // safe in modular arithmetic.
852 //
853 // However, this code doesn't use exactly that formula; the formula it uses
854 // is something like the following, where T is the number of factors of 2 in
855 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
856 // exponentiation:
857 //
858 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
859 //
860 // This formula is trivially equivalent to the previous formula. However,
861 // this formula can be implemented much more efficiently. The trick is that
862 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
863 // arithmetic. To do exact division in modular arithmetic, all we have
864 // to do is multiply by the inverse. Therefore, this step can be done at
865 // width W.
866 //
867 // The next issue is how to safely do the division by 2^T. The way this
868 // is done is by doing the multiplication step at a width of at least W + T
869 // bits. This way, the bottom W+T bits of the product are accurate. Then,
870 // when we perform the division by 2^T (which is equivalent to a right shift
871 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
872 // truncated out after the division by 2^T.
873 //
874 // In comparison to just directly using the first formula, this technique
875 // is much more efficient; using the first formula requires W * K bits,
876 // but this formula less than W + K bits. Also, the first formula requires
877 // a division step, whereas this formula only requires multiplies and shifts.
878 //
879 // It doesn't matter whether the subtraction step is done in the calculation
880 // width or the input iteration count's width; if the subtraction overflows,
881 // the result must be zero anyway. We prefer here to do it in the width of
882 // the induction variable because it helps a lot for certain cases; CodeGen
883 // isn't smart enough to ignore the overflow, which leads to much less
884 // efficient code if the width of the subtraction is wider than the native
885 // register width.
886 //
887 // (It's possible to not widen at all by pulling out factors of 2 before
888 // the multiplication; for example, K=2 can be calculated as
889 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
890 // extra arithmetic, so it's not an obvious win, and it gets
891 // much more complicated for K > 3.)
892
893 // Protection from insane SCEVs; this bound is conservative,
894 // but it probably doesn't matter.
895 if (K > 1000)
896 return SE.getCouldNotCompute();
897
898 unsigned W = SE.getTypeSizeInBits(Ty: ResultTy);
899
900 // Calculate K! / 2^T and T; we divide out the factors of two before
901 // multiplying for calculating K! / 2^T to avoid overflow.
902 // Other overflow doesn't matter because we only care about the bottom
903 // W bits of the result.
904 APInt OddFactorial(W, 1);
905 unsigned T = 1;
906 for (unsigned i = 3; i <= K; ++i) {
907 unsigned TwoFactors = countr_zero(Val: i);
908 T += TwoFactors;
909 OddFactorial *= (i >> TwoFactors);
910 }
911
912 // We need at least W + T bits for the multiplication step
913 unsigned CalculationBits = W + T;
914
915 // Calculate 2^T, at width T+W.
916 APInt DivFactor = APInt::getOneBitSet(numBits: CalculationBits, BitNo: T);
917
918 // Calculate the multiplicative inverse of K! / 2^T;
919 // this multiplication factor will perform the exact division by
920 // K! / 2^T.
921 APInt MultiplyFactor = OddFactorial.multiplicativeInverse();
922
923 // Calculate the product, at width T+W
924 IntegerType *CalculationTy = IntegerType::get(C&: SE.getContext(),
925 NumBits: CalculationBits);
926 const SCEV *Dividend = SE.getTruncateOrZeroExtend(V: It, Ty: CalculationTy);
927 for (unsigned i = 1; i != K; ++i) {
928 const SCEV *S = SE.getMinusSCEV(LHS: It, RHS: SE.getConstant(Ty: It->getType(), V: i));
929 Dividend = SE.getMulExpr(LHS: Dividend,
930 RHS: SE.getTruncateOrZeroExtend(V: S, Ty: CalculationTy));
931 }
932
933 // Divide by 2^T
934 const SCEV *DivResult = SE.getUDivExpr(LHS: Dividend, RHS: SE.getConstant(Val: DivFactor));
935
936 // Truncate the result, and divide by K! / 2^T.
937
938 return SE.getMulExpr(LHS: SE.getConstant(Val: MultiplyFactor),
939 RHS: SE.getTruncateOrZeroExtend(V: DivResult, Ty: ResultTy));
940}
941
942/// Return the value of this chain of recurrences at the specified iteration
943/// number. We can evaluate this recurrence by multiplying each element in the
944/// chain by the binomial coefficient corresponding to it. In other words, we
945/// can evaluate {A,+,B,+,C,+,D} as:
946///
947/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
948///
949/// where BC(It, k) stands for binomial coefficient.
950const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
951 ScalarEvolution &SE) const {
952 return evaluateAtIteration(Operands: operands(), It, SE);
953}
954
955SCEVUse SCEVAddRecExpr::evaluateAtIteration(ArrayRef<SCEVUse> Operands,
956 const SCEV *It, ScalarEvolution &SE,
957 SCEVFlags UseFlags) {
958 assert(Operands.size() > 0);
959 assert((Operands.size() == 2 || UseFlags == SCEV::FlagNone) &&
960 "use-specific flags only supported for affine AddRecs");
961 SCEVUse Result = Operands[0].getPointer();
962 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
963 // The computation is correct in the face of overflow provided that the
964 // multiplication is performed _after_ the evaluation of the binomial
965 // coefficient.
966 const SCEV *Coeff = BinomialCoefficient(It, K: i, SE, ResultTy: Result->getType());
967 if (isa<SCEVCouldNotCompute>(Val: Coeff))
968 return Coeff;
969
970 SCEVUse Mul = SE.getMulExpr(LHS: Operands[i].getPointer(), RHS: Coeff,
971 Flags: {SCEV::FlagNone, UseFlags});
972 Result = SE.getAddExpr(LHS: Result, RHS: Mul, Flags: {SCEV::FlagNone, UseFlags});
973 }
974 return Result;
975}
976
977SCEVUse SCEVAddRecExpr::getExitValue(ScalarEvolution &SE) const {
978 const SCEV *BTC = SE.getBackedgeTakenCount(L: getLoop());
979 if (isa<SCEVCouldNotCompute>(Val: BTC))
980 return BTC;
981 // The loop reaches iteration BTC, so the value this recurrence computes there
982 // is the value it had, and that did not wrap.
983 return evaluateAtIteration(Operands: operands(), It: BTC, SE,
984 UseFlags: isAffine() ? getNoWrapFlags(Mask: SCEV::FlagNUW)
985 : SCEV::FlagNone);
986}
987
988//===----------------------------------------------------------------------===//
989// SCEV Expression folder implementations
990//===----------------------------------------------------------------------===//
991
992/// The SCEVCastSinkingRewriter takes a scalar evolution expression,
993/// which computes a pointer-typed value, and rewrites the whole expression
994/// tree so that *all* the computations are done on integers, and the only
995/// pointer-typed operands in the expression are SCEVUnknown.
996/// The CreatePtrCast callback is invoked to create the actual conversion
997/// (ptrtoint or ptrtoaddr) at the SCEVUnknown leaves.
998class SCEVCastSinkingRewriter
999 : public SCEVRewriteVisitor<SCEVCastSinkingRewriter> {
1000 using Base = SCEVRewriteVisitor<SCEVCastSinkingRewriter>;
1001 using ConversionFn = function_ref<const SCEV *(const SCEVUnknown *)>;
1002 Type *TargetTy;
1003 ConversionFn CreatePtrCast;
1004
1005public:
1006 SCEVCastSinkingRewriter(ScalarEvolution &SE, Type *TargetTy,
1007 ConversionFn CreatePtrCast)
1008 : Base(SE), TargetTy(TargetTy), CreatePtrCast(std::move(CreatePtrCast)) {}
1009
1010 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
1011 Type *TargetTy, ConversionFn CreatePtrCast) {
1012 SCEVCastSinkingRewriter Rewriter(SE, TargetTy, std::move(CreatePtrCast));
1013 return Rewriter.visit(S: Scev);
1014 }
1015
1016 const SCEV *visit(const SCEV *S) {
1017 Type *STy = S->getType();
1018 // If the expression is not pointer-typed, just keep it as-is.
1019 if (!STy->isPointerTy())
1020 return S;
1021 // Else, recursively sink the cast down into it.
1022 return Base::visit(S);
1023 }
1024
1025 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1026 // Preserve wrap flags on rewritten SCEVAddExpr, which the default
1027 // implementation drops.
1028 SmallVector<SCEVUse, 2> Operands;
1029 bool Changed = false;
1030 for (SCEVUse Op : Expr->operands()) {
1031 Operands.push_back(Elt: visit(S: Op.getPointer()));
1032 Changed |= Op.getPointer() != Operands.back();
1033 }
1034 return !Changed ? Expr : SE.getAddExpr(Ops&: Operands, Flags: Expr->getNoWrapFlags());
1035 }
1036
1037 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1038 assert(Expr->getType()->isPointerTy() &&
1039 "Should only reach pointer-typed SCEVUnknown's.");
1040 // Perform some basic constant folding. If the operand of the cast is a
1041 // null pointer, don't create a cast SCEV expression (that will be left
1042 // as-is), but produce a zero constant.
1043 if (isa<ConstantPointerNull>(Val: Expr->getValue()))
1044 return SE.getZero(Ty: TargetTy);
1045 return CreatePtrCast(Expr);
1046 }
1047};
1048
1049const SCEV *ScalarEvolution::getPtrToAddrExpr(const SCEV *Op) {
1050 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
1051
1052 // Treat pointers with unstable representation conservatively, since the
1053 // address bits may change.
1054 if (DL.hasUnstableRepresentation(Ty: Op->getType()))
1055 return getCouldNotCompute();
1056
1057 Type *Ty = DL.getAddressType(PtrTy: Op->getType());
1058
1059 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
1060 // The rewriter handles null pointer constant folding.
1061 const SCEV *IntOp = SCEVCastSinkingRewriter::rewrite(
1062 Scev: Op, SE&: *this, TargetTy: Ty, CreatePtrCast: [this, Ty](const SCEVUnknown *U) {
1063 FoldingSetNodeID ID;
1064 ID.AddInteger(I: scPtrToAddr);
1065 ID.AddPointer(Ptr: U);
1066 ID.AddPointer(Ptr: Ty);
1067 FoldingSetInsertToken Token;
1068 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1069 return S;
1070 SCEV *S = new (SCEVAllocator)
1071 SCEVPtrToAddrExpr(ID.Intern(Allocator&: SCEVAllocator), U, Ty);
1072 UniqueSCEVs.insert(N: S, Token);
1073 S->computeAndSetCanonical(SE&: *this);
1074 registerUser(User: S, Ops: {U});
1075 return static_cast<const SCEV *>(S);
1076 });
1077 assert(IntOp->getType()->isIntegerTy() &&
1078 "We must have succeeded in sinking the cast, "
1079 "and ending up with an integer-typed expression!");
1080 return IntOp;
1081}
1082
1083const SCEV *ScalarEvolution::getTruncateExpr(SCEVUse Op, Type *Ty,
1084 unsigned Depth) {
1085 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1086 "This is not a truncating conversion!");
1087 assert(isSCEVable(Ty) &&
1088 "This is not a conversion to a SCEVable type!");
1089 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1090 Ty = getEffectiveSCEVType(Ty);
1091
1092 FoldingSetNodeID ID;
1093 ID.AddInteger(I: scTruncate);
1094 ID.AddPointer(Ptr: Op.getOpaqueValue());
1095 ID.AddPointer(Ptr: Ty);
1096 FoldingSetInsertToken Token;
1097 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1098 return S;
1099
1100 // Fold if the operand is constant.
1101 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Val&: Op))
1102 return getConstant(
1103 V: cast<ConstantInt>(Val: ConstantExpr::getTrunc(C: SC->getValue(), Ty)));
1104
1105 // trunc(trunc(x)) --> trunc(x)
1106 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Val&: Op))
1107 return getTruncateExpr(Op: ST->getOperand(), Ty, Depth: Depth + 1);
1108
1109 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1110 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Val&: Op))
1111 return getTruncateOrSignExtend(V: SS->getOperand(), Ty, Depth: Depth + 1);
1112
1113 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1114 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Val&: Op))
1115 return getTruncateOrZeroExtend(V: SZ->getOperand(), Ty, Depth: Depth + 1);
1116
1117 if (Depth > MaxCastDepth) {
1118 SCEV *S =
1119 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(Allocator&: SCEVAllocator), Op, Ty);
1120 UniqueSCEVs.insert(N: S, Token);
1121 S->computeAndSetCanonical(SE&: *this);
1122 registerUser(User: S, Ops: Op);
1123 return S;
1124 }
1125
1126 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1127 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1128 // if after transforming we have at most one truncate, not counting truncates
1129 // that replace other casts.
1130 if (isa<SCEVAddExpr>(Val: Op) || isa<SCEVMulExpr>(Val: Op)) {
1131 auto *CommOp = cast<SCEVCommutativeExpr>(Val&: Op);
1132 SmallVector<SCEVUse, 4> Operands;
1133 unsigned numTruncs = 0;
1134 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1135 ++i) {
1136 const SCEV *S = getTruncateExpr(Op: CommOp->getOperand(i), Ty, Depth: Depth + 1);
1137 if (!isa<SCEVIntegralCastExpr>(Val: CommOp->getOperand(i)) &&
1138 isa<SCEVTruncateExpr>(Val: S))
1139 numTruncs++;
1140 Operands.push_back(Elt: S);
1141 }
1142 if (numTruncs < 2) {
1143 if (isa<SCEVAddExpr>(Val: Op))
1144 return getAddExpr(Ops&: Operands);
1145 if (isa<SCEVMulExpr>(Val: Op))
1146 return getMulExpr(Ops&: Operands);
1147 llvm_unreachable("Unexpected SCEV type for Op.");
1148 }
1149 // Although we checked in the beginning that ID is not in the cache, it is
1150 // possible that during recursion and different modification ID was inserted
1151 // into the cache. So if we find it, just return it.
1152 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1153 return S;
1154 }
1155
1156 // If the input value is a chrec scev, truncate the chrec's operands.
1157 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Val&: Op)) {
1158 SmallVector<SCEVUse, 4> Operands;
1159 for (const SCEV *Op : AddRec->operands())
1160 Operands.push_back(Elt: getTruncateExpr(Op, Ty, Depth: Depth + 1));
1161 return getAddRecExpr(Operands, L: AddRec->getLoop(), Flags: SCEV::FlagNone);
1162 }
1163
1164 // Return zero if truncating to known zeros.
1165 uint32_t MinTrailingZeros = getMinTrailingZeros(S: Op);
1166 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1167 return getZero(Ty);
1168
1169 // The cast wasn't folded; create an explicit cast node. We can reuse
1170 // the existing insert position since if we get here, we won't have
1171 // made any changes which would invalidate it.
1172 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(Allocator&: SCEVAllocator),
1173 Op, Ty);
1174 UniqueSCEVs.insert(N: S, Token);
1175 S->computeAndSetCanonical(SE&: *this);
1176 registerUser(User: S, Ops: Op);
1177 return S;
1178}
1179
1180// Get the limit of a recurrence such that incrementing by Step cannot cause
1181// signed overflow as long as the value of the recurrence within the
1182// loop does not exceed this limit before incrementing.
1183static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1184 ICmpInst::Predicate *Pred,
1185 ScalarEvolution *SE) {
1186 unsigned BitWidth = SE->getTypeSizeInBits(Ty: Step->getType());
1187 if (SE->isKnownPositive(S: Step)) {
1188 *Pred = ICmpInst::ICMP_SLT;
1189 return SE->getConstant(Val: APInt::getSignedMinValue(numBits: BitWidth) -
1190 SE->getSignedRangeMax(S: Step));
1191 }
1192 if (SE->isKnownNegative(S: Step)) {
1193 *Pred = ICmpInst::ICMP_SGT;
1194 return SE->getConstant(Val: APInt::getSignedMaxValue(numBits: BitWidth) -
1195 SE->getSignedRangeMin(S: Step));
1196 }
1197 return nullptr;
1198}
1199
1200// Get the limit of a recurrence such that incrementing by Step cannot cause
1201// unsigned overflow as long as the value of the recurrence within the loop does
1202// not exceed this limit before incrementing.
1203static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1204 ICmpInst::Predicate *Pred,
1205 ScalarEvolution *SE) {
1206 unsigned BitWidth = SE->getTypeSizeInBits(Ty: Step->getType());
1207 *Pred = ICmpInst::ICMP_ULT;
1208
1209 return SE->getConstant(Val: APInt::getMinValue(numBits: BitWidth) -
1210 SE->getUnsignedRangeMax(S: Step));
1211}
1212
1213namespace {
1214
1215struct ExtendOpTraitsBase {
1216 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(SCEVUse, Type *,
1217 unsigned);
1218};
1219
1220// Used to make code generic over signed and unsigned overflow.
1221template <typename ExtendOp> struct ExtendOpTraits {
1222 // Members present:
1223 //
1224 // static const SCEVFlags WrapType;
1225 //
1226 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1227 //
1228 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1229 // ICmpInst::Predicate *Pred,
1230 // ScalarEvolution *SE);
1231};
1232
1233template <>
1234struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1235 static const SCEVFlags WrapType = SCEV::FlagNSW;
1236
1237 static const GetExtendExprTy GetExtendExpr;
1238
1239 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1240 ICmpInst::Predicate *Pred,
1241 ScalarEvolution *SE) {
1242 return getSignedOverflowLimitForStep(Step, Pred, SE);
1243 }
1244};
1245
1246const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1247 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1248
1249template <>
1250struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1251 static const SCEVFlags WrapType = SCEV::FlagNUW;
1252
1253 static const GetExtendExprTy GetExtendExpr;
1254
1255 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1256 ICmpInst::Predicate *Pred,
1257 ScalarEvolution *SE) {
1258 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1259 }
1260};
1261
1262const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1263 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1264
1265} // end anonymous namespace
1266
1267// The recurrence AR has been shown to have no signed/unsigned wrap or something
1268// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1269// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1270// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1271// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1272// expression "Step + sext/zext(PreIncAR)" is congruent with
1273// "sext/zext(PostIncAR)"
1274template <typename ExtendOpTy>
1275static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR,
1276 ScalarEvolution *SE, unsigned Depth) {
1277 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1278 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1279
1280 const Loop *L = AR->getLoop();
1281 const SCEV *Start = AR->getStart();
1282 const SCEV *Step = AR->getStepRecurrence(SE&: *SE);
1283
1284 // Check for a simple looking step prior to loop entry.
1285 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Val: Start);
1286 if (!SA)
1287 return nullptr;
1288
1289 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1290 // subtraction is expensive. For this purpose, perform a quick and dirty
1291 // difference, by checking for Step in the operand list. Note, that
1292 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1293 SmallVector<SCEVUse, 4> DiffOps(SA->operands());
1294 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1295 if (*It == Step) {
1296 DiffOps.erase(CI: It);
1297 break;
1298 }
1299
1300 if (DiffOps.size() == SA->getNumOperands())
1301 return nullptr;
1302
1303 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1304 // `Step`:
1305
1306 // 1. NSW/NUW flags on the step increment.
1307 auto PreStartFlags =
1308 ScalarEvolution::maskFlags(Flags: SA->getNoWrapFlags(), Mask: SCEV::FlagNUW);
1309 const SCEV *PreStart = SE->getAddExpr(Ops&: DiffOps, Flags: PreStartFlags);
1310 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1311 Val: SE->getAddRecExpr(Start: PreStart, Step, L, Flags: SCEV::FlagNone));
1312
1313 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1314 // "S+X does not sign/unsign-overflow".
1315 //
1316
1317 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1318 if (PreAR && any(PreAR->getNoWrapFlags(Mask: WrapType)) &&
1319 !isa<SCEVCouldNotCompute>(Val: BECount) && SE->isKnownPositive(S: BECount))
1320 return PreStart;
1321
1322 // 2. Direct overflow check on the step operation's expression.
1323 unsigned BitWidth = SE->getTypeSizeInBits(Ty: AR->getType());
1324 Type *WideTy = IntegerType::get(C&: SE->getContext(), NumBits: BitWidth * 2);
1325 const SCEV *OperandExtendedStart =
1326 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1327 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1328 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1329 if (PreAR && any(AR->getNoWrapFlags(Mask: WrapType))) {
1330 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1331 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1332 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1333 SE->setNoWrapFlags(AddRec: const_cast<SCEVAddRecExpr *>(PreAR), Flags: WrapType);
1334 }
1335 return PreStart;
1336 }
1337
1338 // 3. Loop precondition.
1339 ICmpInst::Predicate Pred;
1340 const SCEV *OverflowLimit =
1341 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1342
1343 if (OverflowLimit &&
1344 SE->isLoopEntryGuardedByCond(L, Pred, LHS: PreStart, RHS: OverflowLimit))
1345 return PreStart;
1346
1347 return nullptr;
1348}
1349
1350// Get the normalized zero or sign extended expression for this AddRec's Start.
1351template <typename ExtendOpTy>
1352static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1353 ScalarEvolution *SE,
1354 unsigned Depth) {
1355 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1356
1357 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, SE, Depth);
1358 if (!PreStart)
1359 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1360
1361 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(SE&: *SE), Ty,
1362 Depth),
1363 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1364}
1365
1366// Try to prove away overflow by looking at "nearby" add recurrences. A
1367// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1368// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1369//
1370// Formally:
1371//
1372// {S,+,X} == {S-T,+,X} + T
1373// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1374//
1375// If ({S-T,+,X} + T) does not overflow ... (1)
1376//
1377// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1378//
1379// If {S-T,+,X} does not overflow ... (2)
1380//
1381// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1382// == {Ext(S-T)+Ext(T),+,Ext(X)}
1383//
1384// If (S-T)+T does not overflow ... (3)
1385//
1386// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1387// == {Ext(S),+,Ext(X)} == LHS
1388//
1389// Thus, if (1), (2) and (3) are true for some T, then
1390// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1391//
1392// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1393// does not overflow" restricted to the 0th iteration. Therefore we only need
1394// to check for (1) and (2).
1395//
1396// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1397// is `Delta` (defined below).
1398template <typename ExtendOpTy>
1399bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1400 const SCEV *Step,
1401 const Loop *L) {
1402 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1403
1404 // We restrict `Start` to a constant to prevent SCEV from spending too much
1405 // time here. It is correct (but more expensive) to continue with a
1406 // non-constant `Start` and do a general SCEV subtraction to compute
1407 // `PreStart` below.
1408 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Val: Start);
1409 if (!StartC)
1410 return false;
1411
1412 APInt StartAI = StartC->getAPInt();
1413
1414 for (unsigned Delta : {-2, -1, 1, 2}) {
1415 const SCEV *PreStart = getConstant(Val: StartAI - Delta);
1416 const auto *PreAR = static_cast<SCEVAddRecExpr *>(
1417 findExistingSCEVInCache(SCEVType: scAddRecExpr, Ops: {PreStart, Step}, L));
1418
1419 // Give up if we don't already have the add recurrence we need because
1420 // actually constructing an add recurrence is relatively expensive.
1421 if (PreAR && any(PreAR->getNoWrapFlags(Mask: WrapType))) { // proves (2)
1422 const SCEV *DeltaS = getConstant(Ty: StartC->getType(), V: Delta);
1423 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1424 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1425 DeltaS, &Pred, this);
1426 if (Limit && isKnownPredicate(Pred, LHS: PreAR, RHS: Limit)) // proves (1)
1427 return true;
1428 }
1429 }
1430
1431 return false;
1432}
1433
1434// Finds an integer D for an expression (C + x + y + ...) such that the top
1435// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1436// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1437// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1438// the (C + x + y + ...) expression is \p WholeAddExpr.
1439static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1440 const SCEVConstant *ConstantTerm,
1441 const SCEVAddExpr *WholeAddExpr) {
1442 const APInt &C = ConstantTerm->getAPInt();
1443 const unsigned BitWidth = C.getBitWidth();
1444 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1445 uint32_t TZ = BitWidth;
1446 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1447 TZ = std::min(a: TZ, b: SE.getMinTrailingZeros(S: WholeAddExpr->getOperand(i: I)));
1448 if (TZ) {
1449 // Set D to be as many least significant bits of C as possible while still
1450 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1451 return TZ < BitWidth ? C.trunc(width: TZ).zext(width: BitWidth) : C;
1452 }
1453 return APInt(BitWidth, 0);
1454}
1455
1456// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1457// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1458// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1459// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1460static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1461 const APInt &ConstantStart,
1462 const SCEV *Step) {
1463 const unsigned BitWidth = ConstantStart.getBitWidth();
1464 const uint32_t TZ = SE.getMinTrailingZeros(S: Step);
1465 if (TZ)
1466 return TZ < BitWidth ? ConstantStart.trunc(width: TZ).zext(width: BitWidth)
1467 : ConstantStart;
1468 return APInt(BitWidth, 0);
1469}
1470
1471static void insertFoldCacheEntry(
1472 const ScalarEvolution::FoldID &ID, const SCEV *S,
1473 DenseMap<ScalarEvolution::FoldID, const SCEV *> &FoldCache,
1474 DenseMap<const SCEV *, SmallVector<ScalarEvolution::FoldID, 2>>
1475 &FoldCacheUser) {
1476 auto I = FoldCache.insert(KV: {ID, S});
1477 if (!I.second) {
1478 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1479 // entry.
1480 auto &UserIDs = FoldCacheUser[I.first->second];
1481 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1482 for (unsigned I = 0; I != UserIDs.size(); ++I)
1483 if (UserIDs[I] == ID) {
1484 std::swap(a&: UserIDs[I], b&: UserIDs.back());
1485 break;
1486 }
1487 UserIDs.pop_back();
1488 I.first->second = S;
1489 }
1490 FoldCacheUser[S].push_back(Elt: ID);
1491}
1492
1493const SCEV *ScalarEvolution::getZeroExtendExpr(SCEVUse Op, Type *Ty,
1494 unsigned Depth) {
1495 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1496 "This is not an extending conversion!");
1497 assert(isSCEVable(Ty) &&
1498 "This is not a conversion to a SCEVable type!");
1499 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1500 Ty = getEffectiveSCEVType(Ty);
1501
1502 FoldID ID(scZeroExtend, Op, Ty);
1503 if (const SCEV *S = FoldCache.lookup(Val: ID))
1504 return S;
1505
1506 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1507 if (!isa<SCEVZeroExtendExpr>(Val: S))
1508 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1509 return S;
1510}
1511
1512const SCEV *ScalarEvolution::getZeroExtendExprImpl(SCEVUse Op, Type *Ty,
1513 unsigned Depth) {
1514 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1515 "This is not an extending conversion!");
1516 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1517 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1518
1519 // Fold if the operand is constant.
1520 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Val&: Op))
1521 return getConstant(Val: SC->getAPInt().zext(width: getTypeSizeInBits(Ty)));
1522
1523 // zext(zext(x)) --> zext(x)
1524 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Val&: Op))
1525 return getZeroExtendExpr(Op: SZ->getOperand(), Ty, Depth: Depth + 1);
1526
1527 // If the operand is an affine AddRec with the no-unsigned-wrap flag, the
1528 // zero-extension distributes over the recurrence.
1529 const SCEV *Start, *Step;
1530 const Loop *L;
1531 if (Depth <= MaxCastDepth &&
1532 match(U: Op, P: m_scev_AffineAddRec(Op0: m_SCEV(V&: Start), Op1: m_SCEV(V&: Step), L: m_Loop(L)))) {
1533 const auto *AR = cast<SCEVAddRecExpr>(Val&: Op);
1534 if (AR->hasNoUnsignedWrap()) {
1535 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, SE: this, Depth: Depth + 1);
1536 Step = getZeroExtendExpr(Op: Step, Ty, Depth: Depth + 1);
1537 return getAddRecExpr(Start, Step, L, Flags: AR->getNoWrapFlags());
1538 }
1539 }
1540
1541 // Before doing any expensive analysis, check to see if we've already
1542 // computed a SCEV for this Op and Ty.
1543 FoldingSetNodeID ID;
1544 ID.AddInteger(I: scZeroExtend);
1545 ID.AddPointer(Ptr: Op.getOpaqueValue());
1546 ID.AddPointer(Ptr: Ty);
1547 FoldingSetInsertToken Token;
1548 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1549 return S;
1550 if (Depth > MaxCastDepth) {
1551 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(Allocator&: SCEVAllocator),
1552 Op, Ty);
1553 UniqueSCEVs.insert(N: S, Token);
1554 S->computeAndSetCanonical(SE&: *this);
1555 registerUser(User: S, Ops: Op);
1556 return S;
1557 }
1558
1559 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1560 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Val&: Op)) {
1561 // It's possible the bits taken off by the truncate were all zero bits. If
1562 // so, we should be able to simplify this further.
1563 const SCEV *X = ST->getOperand();
1564 ConstantRange CR = getUnsignedRange(S: X);
1565 unsigned TruncBits = getTypeSizeInBits(Ty: ST->getType());
1566 unsigned NewBits = getTypeSizeInBits(Ty);
1567 if (CR.truncate(BitWidth: TruncBits).zeroExtend(BitWidth: NewBits).contains(
1568 CR: CR.zextOrTrunc(BitWidth: NewBits)))
1569 return getTruncateOrZeroExtend(V: X, Ty, Depth);
1570 }
1571
1572 // If the input value is a chrec scev, and we can prove that the value
1573 // did not overflow the old, smaller, value, we can zero extend all of the
1574 // operands (often constants). This allows analysis of something like
1575 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1576 if (match(U: Op, P: m_scev_AffineAddRec(Op0: m_SCEV(V&: Start), Op1: m_SCEV(V&: Step), L: m_Loop(L)))) {
1577 const auto *AR = cast<SCEVAddRecExpr>(Val&: Op);
1578 unsigned BitWidth = getTypeSizeInBits(Ty: AR->getType());
1579
1580 // The no-unsigned-wrap case is handled before the uniquing lookup above.
1581
1582 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1583 // Note that this serves two purposes: It filters out loops that are
1584 // simply not analyzable, and it covers the case where this code is
1585 // being called from within backedge-taken count analysis, such that
1586 // attempting to ask for the backedge-taken count would likely result
1587 // in infinite recursion. In the later case, the analysis code will
1588 // cope with a conservative value, and it will take care to purge
1589 // that value once it has finished.
1590 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1591 if (!isa<SCEVCouldNotCompute>(Val: MaxBECount)) {
1592 // Manually compute the final value for AR, checking for overflow.
1593
1594 // Check whether the backedge-taken count can be losslessly casted to
1595 // the addrec's type. The count is always unsigned.
1596 const SCEV *CastedMaxBECount =
1597 getTruncateOrZeroExtend(V: MaxBECount, Ty: Start->getType(), Depth);
1598 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1599 V: CastedMaxBECount, Ty: MaxBECount->getType(), Depth);
1600 if (MaxBECount == RecastedMaxBECount) {
1601 Type *WideTy = IntegerType::get(C&: getContext(), NumBits: BitWidth * 2);
1602 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1603 const SCEV *ZMul =
1604 getMulExpr(LHS: CastedMaxBECount, RHS: Step, Flags: SCEV::FlagNone, Depth: Depth + 1);
1605 const SCEV *ZAdd = getZeroExtendExpr(
1606 Op: getAddExpr(LHS: Start, RHS: ZMul, Flags: SCEV::FlagNone, Depth: Depth + 1), Ty: WideTy,
1607 Depth: Depth + 1);
1608 const SCEV *WideStart = getZeroExtendExpr(Op: Start, Ty: WideTy, Depth: Depth + 1);
1609 const SCEV *WideMaxBECount =
1610 getZeroExtendExpr(Op: CastedMaxBECount, Ty: WideTy, Depth: Depth + 1);
1611 const SCEV *OperandExtendedAdd =
1612 getAddExpr(LHS: WideStart,
1613 RHS: getMulExpr(LHS: WideMaxBECount,
1614 RHS: getZeroExtendExpr(Op: Step, Ty: WideTy, Depth: Depth + 1),
1615 Flags: SCEV::FlagNone, Depth: Depth + 1),
1616 Flags: SCEV::FlagNone, Depth: Depth + 1);
1617 if (ZAdd == OperandExtendedAdd) {
1618 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1619 setNoWrapFlags(AddRec: const_cast<SCEVAddRecExpr *>(AR), Flags: SCEV::FlagNUW);
1620 // Return the expression with the addrec on the outside.
1621 Start =
1622 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, SE: this, Depth: Depth + 1);
1623 Step = getZeroExtendExpr(Op: Step, Ty, Depth: Depth + 1);
1624 return getAddRecExpr(Start, Step, L, Flags: AR->getNoWrapFlags());
1625 }
1626 // Similar to above, only this time treat the step value as signed.
1627 // This covers loops that count down.
1628 OperandExtendedAdd =
1629 getAddExpr(LHS: WideStart,
1630 RHS: getMulExpr(LHS: WideMaxBECount,
1631 RHS: getSignExtendExpr(Op: Step, Ty: WideTy, Depth: Depth + 1),
1632 Flags: SCEV::FlagNone, Depth: Depth + 1),
1633 Flags: SCEV::FlagNone, Depth: Depth + 1);
1634 if (ZAdd == OperandExtendedAdd) {
1635 // Cache knowledge of AR NW, which is propagated to this AddRec.
1636 // Negative step causes unsigned wrap, but it still can't self-wrap.
1637 setNoWrapFlags(AddRec: const_cast<SCEVAddRecExpr *>(AR), Flags: SCEV::FlagNW);
1638 // Return the expression with the addrec on the outside.
1639 Start =
1640 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, SE: this, Depth: Depth + 1);
1641 Step = getSignExtendExpr(Op: Step, Ty, Depth: Depth + 1);
1642 return getAddRecExpr(Start, Step, L, Flags: AR->getNoWrapFlags());
1643 }
1644 }
1645 }
1646
1647 // Normally, in the cases we can prove no-overflow via a
1648 // backedge guarding condition, we can also compute a backedge
1649 // taken count for the loop. The exceptions are assumptions and
1650 // guards present in the loop -- SCEV is not great at exploiting
1651 // these to compute max backedge taken counts, but can still use
1652 // these to prove lack of overflow. Use this fact to avoid
1653 // doing extra work that may not pay off.
1654 if (!isa<SCEVCouldNotCompute>(Val: MaxBECount) || HasGuards ||
1655 !AC.assumptions().empty()) {
1656
1657 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1658 setNoWrapFlags(AddRec: const_cast<SCEVAddRecExpr *>(AR), Flags: NewFlags);
1659 if (AR->hasNoUnsignedWrap()) {
1660 // Same as nuw case above - duplicated here to avoid a compile time
1661 // issue. It's not clear that the order of checks does matter, but
1662 // it's one of two issue possible causes for a change which was
1663 // reverted. Be conservative for the moment.
1664 Start =
1665 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, SE: this, Depth: Depth + 1);
1666 Step = getZeroExtendExpr(Op: Step, Ty, Depth: Depth + 1);
1667 return getAddRecExpr(Start, Step, L, Flags: AR->getNoWrapFlags());
1668 }
1669
1670 // For a negative step, we can extend the operands iff doing so only
1671 // traverses values in the range zext([0,UINT_MAX]).
1672 if (isKnownNegative(S: Step)) {
1673 const SCEV *N =
1674 getConstant(Val: APInt::getMaxValue(numBits: BitWidth) - getSignedRangeMin(S: Step));
1675 if (isLoopBackedgeGuardedByCond(L, Pred: ICmpInst::ICMP_UGT, LHS: AR, RHS: N) ||
1676 isKnownOnEveryIteration(Pred: ICmpInst::ICMP_UGT, LHS: AR, RHS: N)) {
1677 // Cache knowledge of AR NW, which is propagated to this
1678 // AddRec. Negative step causes unsigned wrap, but it
1679 // still can't self-wrap.
1680 setNoWrapFlags(AddRec: const_cast<SCEVAddRecExpr *>(AR), Flags: SCEV::FlagNW);
1681 // Return the expression with the addrec on the outside.
1682 Start =
1683 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, SE: this, Depth: Depth + 1);
1684 Step = getSignExtendExpr(Op: Step, Ty, Depth: Depth + 1);
1685 return getAddRecExpr(Start, Step, L, Flags: AR->getNoWrapFlags());
1686 }
1687 }
1688 }
1689
1690 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1691 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1692 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1693 if (const auto *SC = dyn_cast<SCEVConstant>(Val: Start)) {
1694 const APInt &C = SC->getAPInt();
1695 const APInt &D = extractConstantWithoutWrapping(SE&: *this, ConstantStart: C, Step);
1696 if (D != 0) {
1697 const SCEV *SZExtD = getZeroExtendExpr(Op: getConstant(Val: D), Ty, Depth);
1698 const SCEV *SResidual =
1699 getAddRecExpr(Start: getConstant(Val: C - D), Step, L, Flags: AR->getNoWrapFlags());
1700 const SCEV *SZExtR = getZeroExtendExpr(Op: SResidual, Ty, Depth: Depth + 1);
1701 return getAddExpr(LHS: SZExtD, RHS: SZExtR, Flags: SCEV::FlagNSW | SCEV::FlagNUW,
1702 Depth: Depth + 1);
1703 }
1704 }
1705
1706 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1707 setNoWrapFlags(AddRec: const_cast<SCEVAddRecExpr *>(AR), Flags: SCEV::FlagNUW);
1708 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, SE: this, Depth: Depth + 1);
1709 Step = getZeroExtendExpr(Op: Step, Ty, Depth: Depth + 1);
1710 return getAddRecExpr(Start, Step, L, Flags: AR->getNoWrapFlags());
1711 }
1712 }
1713
1714 // zext(A % B) --> zext(A) % zext(B)
1715 {
1716 const SCEV *LHS;
1717 const SCEV *RHS;
1718 if (match(U: Op, P: m_scev_URem(LHS: m_SCEV(V&: LHS), RHS: m_SCEV(V&: RHS), SE&: *this)))
1719 return getURemExpr(LHS: getZeroExtendExpr(Op: LHS, Ty, Depth: Depth + 1),
1720 RHS: getZeroExtendExpr(Op: RHS, Ty, Depth: Depth + 1));
1721 }
1722
1723 // zext(A / B) --> zext(A) / zext(B).
1724 if (auto *Div = dyn_cast<SCEVUDivExpr>(Val&: Op))
1725 return getUDivExpr(LHS: getZeroExtendExpr(Op: Div->getLHS(), Ty, Depth: Depth + 1),
1726 RHS: getZeroExtendExpr(Op: Div->getRHS(), Ty, Depth: Depth + 1));
1727
1728 if (auto *SA = dyn_cast<SCEVAddExpr>(Val&: Op)) {
1729 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1730 if (SA->hasNoUnsignedWrap()) {
1731 // If the addition does not unsign overflow then we can, by definition,
1732 // commute the zero extension with the addition operation.
1733 SmallVector<SCEVUse, 4> Ops;
1734 for (SCEVUse Op : SA->operands())
1735 Ops.push_back(Elt: getZeroExtendExpr(Op, Ty, Depth: Depth + 1));
1736 return getAddExpr(Ops, Flags: SCEV::FlagNUW, Depth: Depth + 1);
1737 }
1738
1739 const APInt *C, *C2;
1740 // zext (C + A)<nsw> -> (sext(C) + sext(A))<nsw> if zext (C + A)<nsw> >=s 0.
1741 // Currently the non-negative check is done manually, as isKnownNonNegative
1742 // is too expensive.
1743 if (SA->hasNoSignedWrap() &&
1744 match(V: SA, P: m_scev_Add(Op0: m_scev_APInt(C),
1745 Op1: m_scev_SMax(Op0: m_scev_APInt(C&: C2), Op1: m_SCEV()))) &&
1746 C->isNegative() && !C->isMinSignedValue() && C2->sge(RHS: C->abs())) {
1747 assert(isKnownNonNegative(SA) && "incorrectly determined non-negative");
1748 return getAddExpr(LHS: getSignExtendExpr(Op: SA->getOperand(i: 0), Ty, Depth: Depth + 1),
1749 RHS: getSignExtendExpr(Op: SA->getOperand(i: 1), Ty, Depth: Depth + 1),
1750 Flags: SCEV::FlagNSW, Depth: Depth + 1);
1751 }
1752
1753 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1754 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1755 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1756 //
1757 // Often address arithmetics contain expressions like
1758 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1759 // This transformation is useful while proving that such expressions are
1760 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1761 if (const auto *SC = dyn_cast<SCEVConstant>(Val: SA->getOperand(i: 0))) {
1762 const APInt &D = extractConstantWithoutWrapping(SE&: *this, ConstantTerm: SC, WholeAddExpr: SA);
1763 if (D != 0) {
1764 const SCEV *SZExtD = getZeroExtendExpr(Op: getConstant(Val: D), Ty, Depth);
1765 const SCEV *SResidual =
1766 getAddExpr(LHS: getConstant(Val: -D), RHS: SA, Flags: SCEV::FlagNone, Depth);
1767 const SCEV *SZExtR = getZeroExtendExpr(Op: SResidual, Ty, Depth: Depth + 1);
1768 return getAddExpr(LHS: SZExtD, RHS: SZExtR, Flags: (SCEV::FlagNSW | SCEV::FlagNUW),
1769 Depth: Depth + 1);
1770 }
1771 }
1772 }
1773
1774 if (auto *SM = dyn_cast<SCEVMulExpr>(Val&: Op)) {
1775 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1776 if (SM->hasNoUnsignedWrap()) {
1777 // If the multiply does not unsign overflow then we can, by definition,
1778 // commute the zero extension with the multiply operation.
1779 SmallVector<SCEVUse, 4> Ops;
1780 for (SCEVUse Op : SM->operands())
1781 Ops.push_back(Elt: getZeroExtendExpr(Op, Ty, Depth: Depth + 1));
1782 return getMulExpr(Ops, Flags: SCEV::FlagNUW, Depth: Depth + 1);
1783 }
1784
1785 // zext(2^K * (trunc X to iN)) to iM ->
1786 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1787 //
1788 // Proof:
1789 //
1790 // zext(2^K * (trunc X to iN)) to iM
1791 // = zext((trunc X to iN) << K) to iM
1792 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1793 // (because shl removes the top K bits)
1794 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1795 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1796 //
1797 const APInt *C;
1798 const SCEV *TruncRHS;
1799 if (match(V: SM,
1800 P: m_scev_Mul(Op0: m_scev_APInt(C), Op1: m_scev_Trunc(Op0: m_SCEV(V&: TruncRHS)))) &&
1801 C->isPowerOf2()) {
1802 int NewTruncBits =
1803 getTypeSizeInBits(Ty: SM->getOperand(i: 1)->getType()) - C->logBase2();
1804 Type *NewTruncTy = IntegerType::get(C&: getContext(), NumBits: NewTruncBits);
1805 return getMulExpr(
1806 LHS: getZeroExtendExpr(Op: SM->getOperand(i: 0), Ty),
1807 RHS: getZeroExtendExpr(Op: getTruncateExpr(Op: TruncRHS, Ty: NewTruncTy), Ty),
1808 Flags: SCEV::FlagNUW, Depth: Depth + 1);
1809 }
1810 }
1811
1812 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1813 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1814 if (isa<SCEVUMinExpr>(Val: Op) || isa<SCEVUMaxExpr>(Val: Op)) {
1815 auto *MinMax = cast<SCEVMinMaxExpr>(Val&: Op);
1816 SmallVector<SCEVUse, 4> Operands;
1817 for (SCEVUse Operand : MinMax->operands())
1818 Operands.push_back(Elt: getZeroExtendExpr(Op: Operand, Ty));
1819 if (isa<SCEVUMinExpr>(Val: MinMax))
1820 return getUMinExpr(Operands);
1821 return getUMaxExpr(Operands);
1822 }
1823
1824 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1825 if (auto *MinMax = dyn_cast<SCEVSequentialMinMaxExpr>(Val&: Op)) {
1826 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1827 SmallVector<SCEVUse, 4> Operands;
1828 for (SCEVUse Operand : MinMax->operands())
1829 Operands.push_back(Elt: getZeroExtendExpr(Op: Operand, Ty));
1830 return getUMinExpr(Operands, /*Sequential*/ true);
1831 }
1832
1833 // The cast wasn't folded; create an explicit cast node.
1834 // Recompute the insert position, as it may have been invalidated.
1835 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1836 return S;
1837 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(Allocator&: SCEVAllocator),
1838 Op, Ty);
1839 UniqueSCEVs.insert(N: S, Token);
1840 S->computeAndSetCanonical(SE&: *this);
1841 registerUser(User: S, Ops: Op);
1842 return S;
1843}
1844
1845const SCEV *ScalarEvolution::getSignExtendExpr(SCEVUse Op, Type *Ty,
1846 unsigned Depth) {
1847 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1848 "This is not an extending conversion!");
1849 assert(isSCEVable(Ty) &&
1850 "This is not a conversion to a SCEVable type!");
1851 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1852 Ty = getEffectiveSCEVType(Ty);
1853
1854 FoldID ID(scSignExtend, Op, Ty);
1855 if (const SCEV *S = FoldCache.lookup(Val: ID))
1856 return S;
1857
1858 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1859 if (!isa<SCEVSignExtendExpr>(Val: S))
1860 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1861 return S;
1862}
1863
1864const SCEV *ScalarEvolution::getSignExtendExprImpl(SCEVUse Op, Type *Ty,
1865 unsigned Depth) {
1866 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1867 "This is not an extending conversion!");
1868 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1869 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1870 Ty = getEffectiveSCEVType(Ty);
1871
1872 // Fold if the operand is constant.
1873 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Val&: Op))
1874 return getConstant(Val: SC->getAPInt().sext(width: getTypeSizeInBits(Ty)));
1875
1876 // sext(sext(x)) --> sext(x)
1877 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Val&: Op))
1878 return getSignExtendExpr(Op: SS->getOperand(), Ty, Depth: Depth + 1);
1879
1880 // sext(zext(x)) --> zext(x)
1881 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Val&: Op))
1882 return getZeroExtendExpr(Op: SZ->getOperand(), Ty, Depth: Depth + 1);
1883
1884 // If the operand is an affine AddRec with the no-signed-wrap flag, the
1885 // sign-extension distributes over the recurrence.
1886 const SCEV *Start, *Step;
1887 const Loop *L;
1888 if (Depth <= MaxCastDepth &&
1889 match(U: Op, P: m_scev_AffineAddRec(Op0: m_SCEV(V&: Start), Op1: m_SCEV(V&: Step), L: m_Loop(L)))) {
1890 const auto *AR = cast<SCEVAddRecExpr>(Val&: Op);
1891 if (AR->hasNoSignedWrap()) {
1892 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, SE: this, Depth: Depth + 1);
1893 Step = getSignExtendExpr(Op: Step, Ty, Depth: Depth + 1);
1894 return getAddRecExpr(Start, Step, L, Flags: AR->getNoWrapFlags());
1895 }
1896 }
1897
1898 // Before doing any expensive analysis, check to see if we've already
1899 // computed a SCEV for this Op and Ty.
1900 FoldingSetNodeID ID;
1901 ID.AddInteger(I: scSignExtend);
1902 ID.AddPointer(Ptr: Op.getOpaqueValue());
1903 ID.AddPointer(Ptr: Ty);
1904 FoldingSetInsertToken Token;
1905 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1906 return S;
1907 // Limit recursion depth.
1908 if (Depth > MaxCastDepth) {
1909 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(Allocator&: SCEVAllocator),
1910 Op, Ty);
1911 UniqueSCEVs.insert(N: S, Token);
1912 S->computeAndSetCanonical(SE&: *this);
1913 registerUser(User: S, Ops: Op);
1914 return S;
1915 }
1916
1917 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1918 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Val&: Op)) {
1919 // It's possible the bits taken off by the truncate were all sign bits. If
1920 // so, we should be able to simplify this further.
1921 const SCEV *X = ST->getOperand();
1922 ConstantRange CR = getSignedRange(S: X);
1923 unsigned TruncBits = getTypeSizeInBits(Ty: ST->getType());
1924 unsigned NewBits = getTypeSizeInBits(Ty);
1925 if (CR.truncate(BitWidth: TruncBits).signExtend(BitWidth: NewBits).contains(
1926 CR: CR.sextOrTrunc(BitWidth: NewBits)))
1927 return getTruncateOrSignExtend(V: X, Ty, Depth);
1928 }
1929
1930 if (auto *SA = dyn_cast<SCEVAddExpr>(Val&: Op)) {
1931 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1932 if (SA->hasNoSignedWrap()) {
1933 // If the addition does not sign overflow then we can, by definition,
1934 // commute the sign extension with the addition operation.
1935 SmallVector<SCEVUse, 4> Ops;
1936 for (SCEVUse Op : SA->operands())
1937 Ops.push_back(Elt: getSignExtendExpr(Op, Ty, Depth: Depth + 1));
1938 return getAddExpr(Ops, Flags: SCEV::FlagNSW, Depth: Depth + 1);
1939 }
1940
1941 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1942 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1943 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1944 //
1945 // For instance, this will bring two seemingly different expressions:
1946 // 1 + sext(5 + 20 * %x + 24 * %y) and
1947 // sext(6 + 20 * %x + 24 * %y)
1948 // to the same form:
1949 // 2 + sext(4 + 20 * %x + 24 * %y)
1950 if (const auto *SC = dyn_cast<SCEVConstant>(Val: SA->getOperand(i: 0))) {
1951 const APInt &D = extractConstantWithoutWrapping(SE&: *this, ConstantTerm: SC, WholeAddExpr: SA);
1952 if (D != 0) {
1953 const SCEV *SSExtD = getSignExtendExpr(Op: getConstant(Val: D), Ty, Depth);
1954 const SCEV *SResidual =
1955 getAddExpr(LHS: getConstant(Val: -D), RHS: SA, Flags: SCEV::FlagNone, Depth);
1956 const SCEV *SSExtR = getSignExtendExpr(Op: SResidual, Ty, Depth: Depth + 1);
1957 return getAddExpr(LHS: SSExtD, RHS: SSExtR, Flags: (SCEV::FlagNSW | SCEV::FlagNUW),
1958 Depth: Depth + 1);
1959 }
1960 }
1961 }
1962 // If the input value is a chrec scev, and we can prove that the value
1963 // did not overflow the old, smaller, value, we can sign extend all of the
1964 // operands (often constants). This allows analysis of something like
1965 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1966 if (match(U: Op, P: m_scev_AffineAddRec(Op0: m_SCEV(V&: Start), Op1: m_SCEV(V&: Step), L: m_Loop(L)))) {
1967 const auto *AR = cast<SCEVAddRecExpr>(Val&: Op);
1968 unsigned BitWidth = getTypeSizeInBits(Ty: AR->getType());
1969
1970 // The no-signed-wrap case is handled before the uniquing lookup above.
1971
1972 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1973 // Note that this serves two purposes: It filters out loops that are
1974 // simply not analyzable, and it covers the case where this code is
1975 // being called from within backedge-taken count analysis, such that
1976 // attempting to ask for the backedge-taken count would likely result
1977 // in infinite recursion. In the later case, the analysis code will
1978 // cope with a conservative value, and it will take care to purge
1979 // that value once it has finished.
1980 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1981 if (!isa<SCEVCouldNotCompute>(Val: MaxBECount)) {
1982 // Manually compute the final value for AR, checking for
1983 // overflow.
1984
1985 // Check whether the backedge-taken count can be losslessly casted to
1986 // the addrec's type. The count is always unsigned.
1987 const SCEV *CastedMaxBECount =
1988 getTruncateOrZeroExtend(V: MaxBECount, Ty: Start->getType(), Depth);
1989 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1990 V: CastedMaxBECount, Ty: MaxBECount->getType(), Depth);
1991 if (MaxBECount == RecastedMaxBECount) {
1992 Type *WideTy = IntegerType::get(C&: getContext(), NumBits: BitWidth * 2);
1993 // Check whether Start+Step*MaxBECount has no signed overflow.
1994 const SCEV *SMul =
1995 getMulExpr(LHS: CastedMaxBECount, RHS: Step, Flags: SCEV::FlagNone, Depth: Depth + 1);
1996 const SCEV *SAdd = getSignExtendExpr(
1997 Op: getAddExpr(LHS: Start, RHS: SMul, Flags: SCEV::FlagNone, Depth: Depth + 1), Ty: WideTy,
1998 Depth: Depth + 1);
1999 const SCEV *WideStart = getSignExtendExpr(Op: Start, Ty: WideTy, Depth: Depth + 1);
2000 const SCEV *WideMaxBECount =
2001 getZeroExtendExpr(Op: CastedMaxBECount, Ty: WideTy, Depth: Depth + 1);
2002 const SCEV *OperandExtendedAdd =
2003 getAddExpr(LHS: WideStart,
2004 RHS: getMulExpr(LHS: WideMaxBECount,
2005 RHS: getSignExtendExpr(Op: Step, Ty: WideTy, Depth: Depth + 1),
2006 Flags: SCEV::FlagNone, Depth: Depth + 1),
2007 Flags: SCEV::FlagNone, Depth: Depth + 1);
2008 if (SAdd == OperandExtendedAdd) {
2009 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2010 setNoWrapFlags(AddRec: const_cast<SCEVAddRecExpr *>(AR), Flags: SCEV::FlagNSW);
2011 // Return the expression with the addrec on the outside.
2012 Start =
2013 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, SE: this, Depth: Depth + 1);
2014 Step = getSignExtendExpr(Op: Step, Ty, Depth: Depth + 1);
2015 return getAddRecExpr(Start, Step, L, Flags: AR->getNoWrapFlags());
2016 }
2017 // Similar to above, only this time treat the step value as unsigned.
2018 // This covers loops that count up with an unsigned step.
2019 OperandExtendedAdd =
2020 getAddExpr(LHS: WideStart,
2021 RHS: getMulExpr(LHS: WideMaxBECount,
2022 RHS: getZeroExtendExpr(Op: Step, Ty: WideTy, Depth: Depth + 1),
2023 Flags: SCEV::FlagNone, Depth: Depth + 1),
2024 Flags: SCEV::FlagNone, Depth: Depth + 1);
2025 if (SAdd == OperandExtendedAdd) {
2026 // If AR wraps around then
2027 //
2028 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2029 // => SAdd != OperandExtendedAdd
2030 //
2031 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2032 // (SAdd == OperandExtendedAdd => AR is NW)
2033
2034 setNoWrapFlags(AddRec: const_cast<SCEVAddRecExpr *>(AR), Flags: SCEV::FlagNW);
2035
2036 // Return the expression with the addrec on the outside.
2037 Start =
2038 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, SE: this, Depth: Depth + 1);
2039 Step = getZeroExtendExpr(Op: Step, Ty, Depth: Depth + 1);
2040 return getAddRecExpr(Start, Step, L, Flags: AR->getNoWrapFlags());
2041 }
2042 }
2043 }
2044
2045 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2046 setNoWrapFlags(AddRec: const_cast<SCEVAddRecExpr *>(AR), Flags: NewFlags);
2047 if (AR->hasNoSignedWrap()) {
2048 // Same as nsw case above - duplicated here to avoid a compile time
2049 // issue. It's not clear that the order of checks does matter, but
2050 // it's one of two issue possible causes for a change which was
2051 // reverted. Be conservative for the moment.
2052 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, SE: this, Depth: Depth + 1);
2053 Step = getSignExtendExpr(Op: Step, Ty, Depth: Depth + 1);
2054 return getAddRecExpr(Start, Step, L, Flags: AR->getNoWrapFlags());
2055 }
2056
2057 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2058 // if D + (C - D + Step * n) could be proven to not signed wrap
2059 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2060 if (const auto *SC = dyn_cast<SCEVConstant>(Val: Start)) {
2061 const APInt &C = SC->getAPInt();
2062 const APInt &D = extractConstantWithoutWrapping(SE&: *this, ConstantStart: C, Step);
2063 if (D != 0) {
2064 const SCEV *SSExtD = getSignExtendExpr(Op: getConstant(Val: D), Ty, Depth);
2065 const SCEV *SResidual =
2066 getAddRecExpr(Start: getConstant(Val: C - D), Step, L, Flags: AR->getNoWrapFlags());
2067 const SCEV *SSExtR = getSignExtendExpr(Op: SResidual, Ty, Depth: Depth + 1);
2068 return getAddExpr(LHS: SSExtD, RHS: SSExtR, Flags: (SCEV::FlagNSW | SCEV::FlagNUW),
2069 Depth: Depth + 1);
2070 }
2071 }
2072
2073 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2074 setNoWrapFlags(AddRec: const_cast<SCEVAddRecExpr *>(AR), Flags: SCEV::FlagNSW);
2075 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, SE: this, Depth: Depth + 1);
2076 Step = getSignExtendExpr(Op: Step, Ty, Depth: Depth + 1);
2077 return getAddRecExpr(Start, Step, L, Flags: AR->getNoWrapFlags());
2078 }
2079 }
2080
2081 // If the input value is provably positive and we could not simplify
2082 // away the sext build a zext instead.
2083 if (isKnownNonNegative(S: Op))
2084 return getZeroExtendExpr(Op, Ty, Depth: Depth + 1);
2085
2086 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2087 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2088 if (isa<SCEVSMinExpr>(Val: Op) || isa<SCEVSMaxExpr>(Val: Op)) {
2089 auto *MinMax = cast<SCEVMinMaxExpr>(Val&: Op);
2090 SmallVector<SCEVUse, 4> Operands;
2091 for (SCEVUse Operand : MinMax->operands())
2092 Operands.push_back(Elt: getSignExtendExpr(Op: Operand, Ty));
2093 if (isa<SCEVSMinExpr>(Val: MinMax))
2094 return getSMinExpr(Operands);
2095 return getSMaxExpr(Operands);
2096 }
2097
2098 // The cast wasn't folded; create an explicit cast node.
2099 // Recompute the insert position, as it may have been invalidated.
2100 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
2101 return S;
2102 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(Allocator&: SCEVAllocator),
2103 Op, Ty);
2104 UniqueSCEVs.insert(N: S, Token);
2105 S->computeAndSetCanonical(SE&: *this);
2106 registerUser(User: S, Ops: Op);
2107 return S;
2108}
2109
2110const SCEV *ScalarEvolution::getCastExpr(SCEVTypes Kind, SCEVUse Op, Type *Ty) {
2111 switch (Kind) {
2112 case scTruncate:
2113 return getTruncateExpr(Op, Ty);
2114 case scZeroExtend:
2115 return getZeroExtendExpr(Op, Ty);
2116 case scSignExtend:
2117 return getSignExtendExpr(Op, Ty);
2118 case scPtrToAddr: {
2119 const SCEV *Expr = getPtrToAddrExpr(Op);
2120 assert(Expr->getType() == Ty && "requested type must match");
2121 return Expr;
2122 }
2123 default:
2124 llvm_unreachable("Not a SCEV cast expression!");
2125 }
2126}
2127
2128/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2129/// unspecified bits out to the given type.
2130const SCEV *ScalarEvolution::getAnyExtendExpr(SCEVUse Op, Type *Ty) {
2131 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2132 "This is not an extending conversion!");
2133 assert(isSCEVable(Ty) &&
2134 "This is not a conversion to a SCEVable type!");
2135 Ty = getEffectiveSCEVType(Ty);
2136
2137 // Sign-extend negative constants.
2138 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Val&: Op))
2139 if (SC->getAPInt().isNegative())
2140 return getSignExtendExpr(Op, Ty);
2141
2142 // Peel off a truncate cast.
2143 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Val&: Op)) {
2144 const SCEV *NewOp = T->getOperand();
2145 if (getTypeSizeInBits(Ty: NewOp->getType()) < getTypeSizeInBits(Ty))
2146 return getAnyExtendExpr(Op: NewOp, Ty);
2147 return getTruncateOrNoop(V: NewOp, Ty);
2148 }
2149
2150 // Next try a zext cast. If the cast is folded, use it.
2151 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2152 if (!isa<SCEVZeroExtendExpr>(Val: ZExt))
2153 return ZExt;
2154
2155 // Next try a sext cast. If the cast is folded, use it.
2156 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2157 if (!isa<SCEVSignExtendExpr>(Val: SExt))
2158 return SExt;
2159
2160 // Force the cast to be folded into the operands of an addrec.
2161 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Val&: Op)) {
2162 SmallVector<SCEVUse, 4> Ops;
2163 for (const SCEV *Op : AR->operands())
2164 Ops.push_back(Elt: getAnyExtendExpr(Op, Ty));
2165 return getAddRecExpr(Operands&: Ops, L: AR->getLoop(), Flags: SCEV::FlagNW);
2166 }
2167
2168 // If the expression is obviously signed, use the sext cast value.
2169 if (isa<SCEVSMaxExpr>(Val: Op))
2170 return SExt;
2171
2172 // Absent any other information, use the zext cast value.
2173 return ZExt;
2174}
2175
2176/// Process the given Ops list, which is a list of operands to be added under
2177/// the given scale, update the given map. This is a helper function for
2178/// getAddRecExpr. As an example of what it does, given a sequence of operands
2179/// that would form an add expression like this:
2180///
2181/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2182///
2183/// where A and B are constants, update the map with these values:
2184///
2185/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2186///
2187/// and add 13 + A*B*29 to AccumulatedConstant.
2188/// This will allow getAddRecExpr to produce this:
2189///
2190/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2191///
2192/// This form often exposes folding opportunities that are hidden in
2193/// the original operand list.
2194///
2195/// Return true iff it appears that any interesting folding opportunities
2196/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2197/// the common case where no interesting opportunities are present, and
2198/// is also used as a check to avoid infinite recursion.
2199static bool
2200CollectAddOperandsWithScales(SmallDenseMap<const SCEV *, APInt, 16> &M,
2201 SmallVectorImpl<SCEVUse> &NewOps,
2202 APInt &AccumulatedConstant, ArrayRef<SCEVUse> Ops,
2203 const APInt &Scale, ScalarEvolution &SE) {
2204 bool Interesting = false;
2205
2206 // Iterate over the add operands. They are sorted, with constants first.
2207 unsigned i = 0;
2208 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Val: Ops[i])) {
2209 ++i;
2210 // Pull a buried constant out to the outside.
2211 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2212 Interesting = true;
2213 AccumulatedConstant += Scale * C->getAPInt();
2214 }
2215
2216 // Next comes everything else. We're especially interested in multiplies
2217 // here, but they're in the middle, so just visit the rest with one loop.
2218 for (; i != Ops.size(); ++i) {
2219 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Val: Ops[i]);
2220 if (Mul && isa<SCEVConstant>(Val: Mul->getOperand(i: 0))) {
2221 APInt NewScale =
2222 Scale * cast<SCEVConstant>(Val: Mul->getOperand(i: 0))->getAPInt();
2223 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Val: Mul->getOperand(i: 1))) {
2224 // A multiplication of a constant with another add; recurse.
2225 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Val: Mul->getOperand(i: 1));
2226 Interesting |= CollectAddOperandsWithScales(
2227 M, NewOps, AccumulatedConstant, Ops: Add->operands(), Scale: NewScale, SE);
2228 } else {
2229 // A multiplication of a constant with some other value. Update
2230 // the map.
2231 SmallVector<SCEVUse, 4> MulOps(drop_begin(RangeOrContainer: Mul->operands()));
2232 const SCEV *Key = SE.getMulExpr(Ops&: MulOps)->getCanonical();
2233 auto Pair = M.insert(KV: {Key, NewScale});
2234 if (Pair.second) {
2235 NewOps.push_back(Elt: Pair.first->first);
2236 } else {
2237 Pair.first->second += NewScale;
2238 // The map already had an entry for this value, which may indicate
2239 // a folding opportunity.
2240 Interesting = true;
2241 }
2242 }
2243 } else {
2244 // An ordinary operand. Update the map.
2245 auto Pair = M.insert(KV: {Ops[i]->getCanonical(), Scale});
2246 if (Pair.second) {
2247 NewOps.push_back(Elt: Pair.first->first);
2248 } else {
2249 Pair.first->second += Scale;
2250 // The map already had an entry for this value, which may indicate
2251 // a folding opportunity.
2252 Interesting = true;
2253 }
2254 }
2255 }
2256
2257 return Interesting;
2258}
2259
2260bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
2261 const SCEV *LHS, const SCEV *RHS,
2262 const Instruction *CtxI) {
2263 auto Operation = [this, BinOp](SCEVUse L, SCEVUse R) -> const SCEV * {
2264 switch (BinOp) {
2265 default:
2266 llvm_unreachable("Unsupported binary op");
2267 case Instruction::Add:
2268 return getAddExpr(LHS: L, RHS: R);
2269 case Instruction::Sub:
2270 return getMinusSCEV(LHS: L, RHS: R);
2271 case Instruction::Mul:
2272 return getMulExpr(LHS: L, RHS: R);
2273 }
2274 };
2275
2276 const SCEV *(ScalarEvolution::*Extension)(SCEVUse, Type *, unsigned) =
2277 Signed ? &ScalarEvolution::getSignExtendExpr
2278 : &ScalarEvolution::getZeroExtendExpr;
2279
2280 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2281 auto *NarrowTy = cast<IntegerType>(Val: LHS->getType());
2282 auto *WideTy =
2283 IntegerType::get(C&: NarrowTy->getContext(), NumBits: NarrowTy->getBitWidth() * 2);
2284
2285 const SCEV *A = (this->*Extension)(Operation(LHS, RHS), WideTy, 0);
2286 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2287 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2288 const SCEV *B = Operation(LHSB, RHSB);
2289 if (A == B)
2290 return true;
2291 // Can we use context to prove the fact we need?
2292 if (!CtxI)
2293 return false;
2294 // TODO: Support mul.
2295 if (BinOp == Instruction::Mul)
2296 return false;
2297 auto *RHSC = dyn_cast<SCEVConstant>(Val: RHS);
2298 // TODO: Lift this limitation.
2299 if (!RHSC)
2300 return false;
2301 APInt C = RHSC->getAPInt();
2302 unsigned NumBits = C.getBitWidth();
2303 bool IsSub = (BinOp == Instruction::Sub);
2304 bool IsNegativeConst = (Signed && C.isNegative());
2305 // Compute the direction and magnitude by which we need to check overflow.
2306 bool OverflowDown = IsSub ^ IsNegativeConst;
2307 APInt Magnitude = C;
2308 if (IsNegativeConst) {
2309 if (C == APInt::getSignedMinValue(numBits: NumBits))
2310 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2311 // want to deal with that.
2312 return false;
2313 Magnitude = -C;
2314 }
2315
2316 ICmpInst::Predicate Pred = Signed ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
2317 if (OverflowDown) {
2318 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2319 APInt Min = Signed ? APInt::getSignedMinValue(numBits: NumBits)
2320 : APInt::getMinValue(numBits: NumBits);
2321 APInt Limit = Min + Magnitude;
2322 return isKnownPredicateAt(Pred, LHS: getConstant(Val: Limit), RHS: LHS, CtxI);
2323 } else {
2324 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2325 APInt Max = Signed ? APInt::getSignedMaxValue(numBits: NumBits)
2326 : APInt::getMaxValue(numBits: NumBits);
2327 APInt Limit = Max - Magnitude;
2328 return isKnownPredicateAt(Pred, LHS, RHS: getConstant(Val: Limit), CtxI);
2329 }
2330}
2331
2332std::optional<SCEVFlags> ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp(
2333 const OverflowingBinaryOperator *OBO) {
2334 // It cannot be done any better.
2335 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2336 return std::nullopt;
2337
2338 SCEVFlags Flags = SCEVFlags::FlagNone;
2339
2340 if (OBO->hasNoUnsignedWrap())
2341 Flags = ScalarEvolution::setFlags(Flags, OnFlags: SCEV::FlagNUW);
2342 if (OBO->hasNoSignedWrap())
2343 Flags = ScalarEvolution::setFlags(Flags, OnFlags: SCEV::FlagNSW);
2344
2345 bool Deduced = false;
2346
2347 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)OBO->getOpcode();
2348 const SCEV *LHS = getSCEV(V: OBO->getOperand(i_nocapture: 0));
2349 const SCEV *RHS = getSCEV(V: OBO->getOperand(i_nocapture: 1));
2350
2351 bool CanUseNSW = true;
2352 const APInt *ShiftAmt;
2353 // Treat `shl %a, C` as `mul %a, 1 << C`.
2354 if (match(V: OBO, P: m_Shl(L: m_Value(), R: m_APInt(Res&: ShiftAmt)))) {
2355 unsigned BitWidth = ShiftAmt->getBitWidth();
2356 if (ShiftAmt->uge(RHS: BitWidth))
2357 return std::nullopt;
2358 // NSW only transfers if the shift amount is < BitWidth - 1, as INT_MIN * -1
2359 // overflows.
2360 CanUseNSW = ShiftAmt->ult(RHS: BitWidth - 1);
2361 Opcode = Instruction::Mul;
2362 RHS = getConstant(Val: APInt::getOneBitSet(numBits: BitWidth, BitNo: ShiftAmt->getZExtValue()));
2363 } else if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
2364 Opcode != Instruction::Mul) {
2365 return std::nullopt;
2366 }
2367
2368 const Instruction *CtxI =
2369 UseContextForNoWrapFlagInference ? dyn_cast<Instruction>(Val: OBO) : nullptr;
2370 if (!OBO->hasNoUnsignedWrap() &&
2371 willNotOverflow(BinOp: Opcode, /* Signed */ false, LHS, RHS, CtxI)) {
2372 Flags = ScalarEvolution::setFlags(Flags, OnFlags: SCEV::FlagNUW);
2373 Deduced = true;
2374 }
2375
2376 if (CanUseNSW && !OBO->hasNoSignedWrap() &&
2377 willNotOverflow(BinOp: Opcode, /* Signed */ true, LHS, RHS, CtxI)) {
2378 Flags = ScalarEvolution::setFlags(Flags, OnFlags: SCEV::FlagNSW);
2379 Deduced = true;
2380 }
2381
2382 if (Deduced)
2383 return Flags;
2384 return std::nullopt;
2385}
2386
2387// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2388// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2389// can't-overflow flags for the operation if possible.
2390static SCEVFlags StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2391 ArrayRef<SCEVUse> Ops, SCEVFlags Flags) {
2392 using namespace std::placeholders;
2393
2394 using OBO = OverflowingBinaryOperator;
2395
2396 bool CanAnalyze =
2397 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2398 (void)CanAnalyze;
2399 assert(CanAnalyze && "don't call from other places!");
2400
2401 SCEVFlags SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2402 SCEVFlags SignOrUnsignWrap =
2403 ScalarEvolution::maskFlags(Flags, Mask: SignOrUnsignMask);
2404
2405 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2406 auto IsKnownNonNegative = [&](SCEVUse U) {
2407 return SE->isKnownNonNegative(S: U);
2408 };
2409
2410 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Range&: Ops, P: IsKnownNonNegative))
2411 Flags = ScalarEvolution::setFlags(Flags, OnFlags: SignOrUnsignMask);
2412
2413 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, Mask: SignOrUnsignMask);
2414
2415 if (SignOrUnsignWrap != SignOrUnsignMask &&
2416 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2417 isa<SCEVConstant>(Val: Ops[0])) {
2418
2419 auto Opcode = [&] {
2420 switch (Type) {
2421 case scAddExpr:
2422 return Instruction::Add;
2423 case scMulExpr:
2424 return Instruction::Mul;
2425 default:
2426 llvm_unreachable("Unexpected SCEV op.");
2427 }
2428 }();
2429
2430 const APInt &C = cast<SCEVConstant>(Val: Ops[0])->getAPInt();
2431
2432 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2433 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2434 auto NSWRegion =
2435 ConstantRange::makeExactNoWrapRegion(BinOp: Opcode, Other: C, NoWrapKind: OBO::NoSignedWrap);
2436 if (NSWRegion.contains(CR: SE->getSignedRange(S: Ops[1])))
2437 Flags = ScalarEvolution::setFlags(Flags, OnFlags: SCEV::FlagNSW);
2438 }
2439
2440 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2441 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2442 auto NUWRegion =
2443 ConstantRange::makeExactNoWrapRegion(BinOp: Opcode, Other: C, NoWrapKind: OBO::NoUnsignedWrap);
2444 if (NUWRegion.contains(CR: SE->getUnsignedRange(S: Ops[1])))
2445 Flags = ScalarEvolution::setFlags(Flags, OnFlags: SCEV::FlagNUW);
2446 }
2447 }
2448
2449 // <0,+,nonnegative><nw> is also nuw
2450 // TODO: Add corresponding nsw case
2451 if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, TestFlags: SCEV::FlagNW) &&
2452 !ScalarEvolution::hasFlags(Flags, TestFlags: SCEV::FlagNUW) && Ops.size() == 2 &&
2453 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2454 Flags = ScalarEvolution::setFlags(Flags, OnFlags: SCEV::FlagNUW);
2455
2456 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2457 if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, TestFlags: SCEV::FlagNUW) &&
2458 Ops.size() == 2) {
2459 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Val: Ops[0]))
2460 if (UDiv->getOperand(i: 1) == Ops[1])
2461 Flags = ScalarEvolution::setFlags(Flags, OnFlags: SCEV::FlagNUW);
2462 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Val: Ops[1]))
2463 if (UDiv->getOperand(i: 1) == Ops[0])
2464 Flags = ScalarEvolution::setFlags(Flags, OnFlags: SCEV::FlagNUW);
2465 }
2466
2467 return Flags;
2468}
2469
2470bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2471 return isLoopInvariant(S, L) && properlyDominates(S, BB: L->getHeader());
2472}
2473
2474/// Get a canonical add expression, or something simpler if possible.
2475SCEVUse ScalarEvolution::getAddExpr(SmallVectorImpl<SCEVUse> &Ops,
2476 SCEVFlagsPair Flags, unsigned Depth) {
2477 SCEVFlags ExprFlags = Flags.ExprFlags;
2478 SCEVFlags UseFlags = Flags.UseFlags;
2479 assert(!(ExprFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2480 "only nuw or nsw allowed");
2481 assert(!(UseFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2482 "only nuw or nsw allowed");
2483 assert(!Ops.empty() && "Cannot get empty add!");
2484 if (Ops.size() == 1) return Ops[0];
2485#ifndef NDEBUG
2486 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2487 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2488 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2489 "SCEVAddExpr operand types don't match!");
2490 unsigned NumPtrs = count_if(
2491 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2492 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2493#endif
2494
2495 const SCEV *Folded = constantFoldAndGroupOps(
2496 SE&: *this, LI, DT, Ops,
2497 Fold: [](const APInt &C1, const APInt &C2) { return C1 + C2; },
2498 IsIdentity: [](const APInt &C) { return C.isZero(); }, // identity
2499 IsAbsorber: [](const APInt &C) { return false; }); // absorber
2500 if (Folded)
2501 return Folded;
2502
2503#ifndef NDEBUG
2504 // Keep track of operands after constant folding, for verification when adding
2505 // use-specific flags.
2506 const SmallVector<SCEVUse, 8> OrigOps(Ops.begin(), Ops.end());
2507#endif
2508
2509 unsigned Idx = isa<SCEVConstant>(Val: Ops[0]) ? 1 : 0;
2510
2511 // Delay expensive flag strengthening until necessary.
2512 auto ComputeFlags = [this, ExprFlags](ArrayRef<SCEVUse> Ops) {
2513 return StrengthenNoWrapFlags(SE: this, Type: scAddExpr, Ops, Flags: ExprFlags);
2514 };
2515
2516 // Limit recursion calls depth.
2517 if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2518 return {getOrCreateAddExpr(Ops, Flags: ComputeFlags(Ops)), UseFlags};
2519
2520 if (SCEV *S = findExistingSCEVInCache(SCEVType: scAddExpr, Ops)) {
2521 // Don't strengthen flags if we have no new information.
2522 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2523 if (Add->getNoWrapFlags(Mask: ExprFlags) != ExprFlags)
2524 Add->setNoWrapFlags(ComputeFlags(Ops));
2525 return {S, UseFlags};
2526 }
2527
2528 // Okay, check to see if the same value occurs in the operand list more than
2529 // once. If so, merge them together into an multiply expression. Since we
2530 // sorted the list, these values are required to be adjacent.
2531 Type *Ty = Ops[0]->getType();
2532 bool FoundMatch = false;
2533 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2534 if (SCEVUse Op = SCEVUse::getCommon(A: Ops[i], B: Ops[i + 1])) {
2535 // X + Y + Y --> X + Y*2
2536 // Scan ahead to count how many equal operands there are.
2537 unsigned Count = 2;
2538 for (; i + Count != e; ++Count) {
2539 SCEVUse Common = SCEVUse::getCommon(A: Op, B: Ops[i + Count]);
2540 if (!Common)
2541 break;
2542 Op = Common;
2543 }
2544 // Merge the values into a multiply.
2545 SCEVUse Scale = getConstant(Ty, V: Count);
2546 SCEVUse Mul = getMulExpr(LHS: Scale, RHS: Op, Flags: SCEV::FlagNone, Depth: Depth + 1);
2547 if (Ops.size() == Count)
2548 return Mul;
2549 Ops[i] = Mul;
2550 Ops.erase(CS: Ops.begin()+i+1, CE: Ops.begin()+i+Count);
2551 --i; e -= Count - 1;
2552 FoundMatch = true;
2553 }
2554 if (FoundMatch)
2555 return getAddExpr(Ops, Flags: ExprFlags, Depth: Depth + 1);
2556
2557 // Check for truncates. If all the operands are truncated from the same
2558 // type, see if factoring out the truncate would permit the result to be
2559 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2560 // if the contents of the resulting outer trunc fold to something simple.
2561 auto FindTruncSrcType = [&]() -> Type * {
2562 // We're ultimately looking to fold an addrec of truncs and muls of only
2563 // constants and truncs, so if we find any other types of SCEV
2564 // as operands of the addrec then we bail and return nullptr here.
2565 // Otherwise, we return the type of the operand of a trunc that we find.
2566 if (auto *T = dyn_cast<SCEVTruncateExpr>(Val&: Ops[Idx]))
2567 return T->getOperand()->getType();
2568 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Val&: Ops[Idx])) {
2569 SCEVUse LastOp = Mul->getOperand(i: Mul->getNumOperands() - 1);
2570 if (const auto *T = dyn_cast<SCEVTruncateExpr>(Val&: LastOp))
2571 return T->getOperand()->getType();
2572 }
2573 return nullptr;
2574 };
2575 if (auto *SrcType = FindTruncSrcType()) {
2576 SmallVector<SCEVUse, 8> LargeOps;
2577 bool Ok = true;
2578 // Check all the operands to see if they can be represented in the
2579 // source type of the truncate.
2580 for (const SCEV *Op : Ops) {
2581 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Val: Op)) {
2582 if (T->getOperand()->getType() != SrcType) {
2583 Ok = false;
2584 break;
2585 }
2586 LargeOps.push_back(Elt: T->getOperand());
2587 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Val: Op)) {
2588 LargeOps.push_back(Elt: getAnyExtendExpr(Op: C, Ty: SrcType));
2589 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Val: Op)) {
2590 SmallVector<SCEVUse, 8> LargeMulOps;
2591 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2592 if (const SCEVTruncateExpr *T =
2593 dyn_cast<SCEVTruncateExpr>(Val: M->getOperand(i: j))) {
2594 if (T->getOperand()->getType() != SrcType) {
2595 Ok = false;
2596 break;
2597 }
2598 LargeMulOps.push_back(Elt: T->getOperand());
2599 } else if (const auto *C = dyn_cast<SCEVConstant>(Val: M->getOperand(i: j))) {
2600 LargeMulOps.push_back(Elt: getAnyExtendExpr(Op: C, Ty: SrcType));
2601 } else {
2602 Ok = false;
2603 break;
2604 }
2605 }
2606 if (Ok)
2607 LargeOps.push_back(
2608 Elt: getMulExpr(Ops&: LargeMulOps, Flags: SCEV::FlagNone, Depth: Depth + 1));
2609 } else {
2610 Ok = false;
2611 break;
2612 }
2613 }
2614 if (Ok) {
2615 // Evaluate the expression in the larger type.
2616 const SCEV *Fold = getAddExpr(Ops&: LargeOps, Flags: SCEV::FlagNone, Depth: Depth + 1);
2617 // If it folds to something simple, use it. Otherwise, don't.
2618 if (isa<SCEVConstant>(Val: Fold) || isa<SCEVUnknown>(Val: Fold))
2619 return getTruncateExpr(Op: Fold, Ty);
2620 }
2621 }
2622
2623 if (Ops.size() == 2) {
2624 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2625 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2626 // C1).
2627 const SCEV *A = Ops[0];
2628 const SCEV *B = Ops[1];
2629 auto *AddExpr = dyn_cast<SCEVAddExpr>(Val: B);
2630 auto *C = dyn_cast<SCEVConstant>(Val: A);
2631 if (AddExpr && C && isa<SCEVConstant>(Val: AddExpr->getOperand(i: 0))) {
2632 auto C1 = cast<SCEVConstant>(Val: AddExpr->getOperand(i: 0))->getAPInt();
2633 auto C2 = C->getAPInt();
2634 SCEVFlags PreservedFlags = SCEV::FlagNone;
2635
2636 APInt ConstAdd = C1 + C2;
2637 auto AddFlags = AddExpr->getNoWrapFlags();
2638 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2639 if (ScalarEvolution::hasFlags(Flags: AddFlags, TestFlags: SCEV::FlagNUW) &&
2640 ConstAdd.ule(RHS: C1)) {
2641 PreservedFlags =
2642 ScalarEvolution::setFlags(Flags: PreservedFlags, OnFlags: SCEV::FlagNUW);
2643 }
2644
2645 // Adding a constant with the same sign and small magnitude is NSW, if the
2646 // original AddExpr was NSW.
2647 if (ScalarEvolution::hasFlags(Flags: AddFlags, TestFlags: SCEV::FlagNSW) &&
2648 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2649 ConstAdd.abs().ule(RHS: C1.abs())) {
2650 PreservedFlags =
2651 ScalarEvolution::setFlags(Flags: PreservedFlags, OnFlags: SCEV::FlagNSW);
2652 }
2653
2654 if (PreservedFlags != SCEV::FlagNone) {
2655 SmallVector<SCEVUse, 4> NewOps(AddExpr->operands());
2656 NewOps[0] = getConstant(Val: ConstAdd);
2657 return getAddExpr(Ops&: NewOps, Flags: PreservedFlags);
2658 }
2659 }
2660
2661 // Try to push the constant operand into a ZExt: A + zext (-A + B) -> zext
2662 // (B), if trunc (A) + -A + B does not unsigned-wrap.
2663 const SCEVAddExpr *InnerAdd;
2664 if (match(S: B, P: m_scev_ZExt(Op0: m_scev_Add(V&: InnerAdd)))) {
2665 const SCEV *NarrowA = getTruncateExpr(Op: A, Ty: InnerAdd->getType());
2666 if (NarrowA == getNegativeSCEV(V: InnerAdd->getOperand(i: 0)) &&
2667 getZeroExtendExpr(Op: NarrowA, Ty: B->getType()) == A &&
2668 hasFlags(Flags: StrengthenNoWrapFlags(SE: this, Type: scAddExpr, Ops: {NarrowA, InnerAdd},
2669 Flags: SCEV::FlagNone),
2670 TestFlags: SCEV::FlagNUW)) {
2671 return getZeroExtendExpr(Op: getAddExpr(LHS: NarrowA, RHS: InnerAdd), Ty: B->getType());
2672 }
2673 }
2674 }
2675
2676 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2677 const SCEV *Y;
2678 if (Ops.size() == 2 &&
2679 match(U: Ops[0],
2680 P: m_scev_Mul(Op0: m_scev_AllOnes(),
2681 Op1: m_scev_URem(LHS: m_scev_Specific(S: Ops[1]), RHS: m_SCEV(V&: Y), SE&: *this))))
2682 return getMulExpr(LHS: Y, RHS: getUDivExpr(LHS: Ops[1], RHS: Y));
2683
2684 // Skip past any other cast SCEVs.
2685 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2686 ++Idx;
2687
2688 // If there are add operands they would be next.
2689 if (Idx < Ops.size()) {
2690 bool DeletedAdd = false;
2691 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2692 // common NUW flag for expression after inlining. Other flags cannot be
2693 // preserved, because they may depend on the original order of operations.
2694 SCEVFlags CommonFlags = maskFlags(Flags: ExprFlags, Mask: SCEV::FlagNUW);
2695 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Val&: Ops[Idx])) {
2696 if (Ops.size() > AddOpsInlineThreshold ||
2697 Add->getNumOperands() > AddOpsInlineThreshold)
2698 break;
2699 // If we have an add, expand the add operands onto the end of the operands
2700 // list.
2701 Ops.erase(CI: Ops.begin()+Idx);
2702 append_range(C&: Ops, R: Add->operands());
2703 DeletedAdd = true;
2704 CommonFlags = maskFlags(Flags: CommonFlags, Mask: Add->getNoWrapFlags());
2705 }
2706
2707 // If we deleted at least one add, we added operands to the end of the list,
2708 // and they are not necessarily sorted. Recurse to resort and resimplify
2709 // any operands we just acquired.
2710 if (DeletedAdd)
2711 return getAddExpr(Ops, Flags: CommonFlags, Depth: Depth + 1);
2712 }
2713
2714 // Skip over the add expression until we get to a multiply.
2715 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2716 ++Idx;
2717
2718 // Check to see if there are any folding opportunities present with
2719 // operands multiplied by constant values.
2720 if (Idx < Ops.size() && isa<SCEVMulExpr>(Val: Ops[Idx])) {
2721 uint64_t BitWidth = getTypeSizeInBits(Ty);
2722 SmallDenseMap<const SCEV *, APInt, 16> M;
2723 SmallVector<SCEVUse, 8> NewOps;
2724 APInt AccumulatedConstant(BitWidth, 0);
2725 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2726 Ops, Scale: APInt(BitWidth, 1), SE&: *this)) {
2727 struct APIntCompare {
2728 bool operator()(const APInt &LHS, const APInt &RHS) const {
2729 return LHS.ult(RHS);
2730 }
2731 };
2732
2733 // Some interesting folding opportunity is present, so its worthwhile to
2734 // re-generate the operands list. Group the operands by constant scale,
2735 // to avoid multiplying by the same constant scale multiple times.
2736 std::map<APInt, SmallVector<SCEVUse, 4>, APIntCompare> MulOpLists;
2737 for (SCEVUse NewOp : NewOps)
2738 MulOpLists[M.find(Val: NewOp)->second].push_back(Elt: NewOp);
2739 // Re-generate the operands list.
2740 Ops.clear();
2741 if (AccumulatedConstant != 0)
2742 Ops.push_back(Elt: getConstant(Val: AccumulatedConstant));
2743 for (auto &MulOp : MulOpLists) {
2744 if (MulOp.first == 1) {
2745 Ops.push_back(Elt: getAddExpr(Ops&: MulOp.second, Flags: SCEV::FlagNone, Depth: Depth + 1));
2746 } else if (MulOp.first != 0) {
2747 Ops.push_back(
2748 Elt: getMulExpr(LHS: getConstant(Val: MulOp.first),
2749 RHS: getAddExpr(Ops&: MulOp.second, Flags: SCEV::FlagNone, Depth: Depth + 1),
2750 Flags: SCEV::FlagNone, Depth: Depth + 1));
2751 }
2752 }
2753 if (Ops.empty())
2754 return getZero(Ty);
2755 if (Ops.size() == 1)
2756 return Ops[0];
2757 return getAddExpr(Ops, Flags: SCEV::FlagNone, Depth: Depth + 1);
2758 }
2759 }
2760
2761 // Given a SCEVMulExpr and an operand index, return the product of all
2762 // operands except the one at OpIdx.
2763 auto StripFactor = [&](const SCEVMulExpr *M, unsigned OpIdx) -> SCEVUse {
2764 if (M->getNumOperands() == 2)
2765 return M->getOperand(i: OpIdx == 0);
2766 SmallVector<SCEVUse, 4> Remaining(M->operands().take_front(N: OpIdx));
2767 append_range(C&: Remaining, R: M->operands().drop_front(N: OpIdx + 1));
2768 return getMulExpr(Ops&: Remaining, Flags: SCEV::FlagNone, Depth: Depth + 1);
2769 };
2770
2771 // If we are adding something to a multiply expression, make sure the
2772 // something is not already an operand of the multiply. If so, merge it into
2773 // the multiply.
2774 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Val: Ops[Idx]); ++Idx) {
2775 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Val&: Ops[Idx]);
2776 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2777 // Scan all terms to find every occurrence of common factor MulOpSCEV
2778 // and fold them in one shot:
2779 // A1*X + A2*X + ... + An*X --> X * (A1 + A2 + ... + An)
2780 SCEVUse MulOpSCEV = Mul->getOperand(i: MulOp);
2781 if (isa<SCEVConstant>(Val: MulOpSCEV))
2782 continue;
2783
2784 // Cofactors: 1 for bare addends matching MulOpSCEV, or the
2785 // remaining product for multiply terms containing MulOpSCEV.
2786 SmallVector<SCEVUse, 4> Cofactors;
2787 SmallVector<unsigned, 4> DeadIndices;
2788 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) {
2789 if (SCEVUse Common = SCEVUse::getCommon(A: MulOpSCEV, B: Ops[AddOp])) {
2790 // W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2791 MulOpSCEV = Common;
2792 Cofactors.push_back(Elt: getOne(Ty));
2793 DeadIndices.push_back(Elt: AddOp);
2794 continue;
2795 }
2796
2797 if (AddOp <= Idx || !isa<SCEVMulExpr>(Val: Ops[AddOp]))
2798 continue;
2799
2800 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Val&: Ops[AddOp]);
2801 for (unsigned OMulOp = 0, OE = OtherMul->getNumOperands(); OMulOp != OE;
2802 ++OMulOp) {
2803 if (SCEVUse Common =
2804 SCEVUse::getCommon(A: MulOpSCEV, B: OtherMul->getOperand(i: OMulOp))) {
2805 // (A*B*C) + (A*D*E) --> A * (B*C + D*E)
2806 MulOpSCEV = Common;
2807 Cofactors.push_back(Elt: StripFactor(OtherMul, OMulOp));
2808 DeadIndices.push_back(Elt: AddOp);
2809 break;
2810 }
2811 }
2812 }
2813
2814 // Fold all collected cofactors with the anchor multiply's cofactor:
2815 // MulOpSCEV * (Cofactor_1 + ... + Cofactor_n + AnchorCofactor)
2816 if (!Cofactors.empty()) {
2817 Cofactors.push_back(Elt: StripFactor(Mul, MulOp));
2818
2819 SCEVUse InnerSum = getAddExpr(Ops&: Cofactors, Flags: SCEV::FlagNone, Depth: Depth + 1);
2820 SCEVUse OuterMul =
2821 getMulExpr(LHS: MulOpSCEV, RHS: InnerSum, Flags: SCEV::FlagNone, Depth: Depth + 1);
2822
2823 // DeadIndices does not include Idx (the anchor), hence +1.
2824 if (Ops.size() == DeadIndices.size() + 1)
2825 return OuterMul;
2826
2827 // Erase Ops[Idx] first, then erase DeadIndices in reverse order.
2828 // The -1 adjustment accounts for the shift from removing Idx;
2829 // reverse order means each erasure only shifts later positions,
2830 // which have already been processed.
2831 Ops.erase(CI: Ops.begin() + Idx);
2832 for (unsigned Dead : reverse(C&: DeadIndices))
2833 Ops.erase(CI: Ops.begin() + (Dead > Idx ? Dead - 1 : Dead));
2834
2835 Ops.push_back(Elt: OuterMul);
2836 return getAddExpr(Ops, Flags: SCEV::FlagNone, Depth: Depth + 1);
2837 }
2838 }
2839 }
2840
2841 // If there are any add recurrences in the operands list, see if any other
2842 // added values are loop invariant. If so, we can fold them into the
2843 // recurrence.
2844 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2845 ++Idx;
2846
2847 // Scan over all recurrences, trying to fold loop invariants into them.
2848 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Val: Ops[Idx]); ++Idx) {
2849 // Scan all of the other operands to this add and add them to the vector if
2850 // they are loop invariant w.r.t. the recurrence.
2851 SmallVector<SCEVUse, 8> LIOps;
2852 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Val&: Ops[Idx]);
2853 const Loop *AddRecLoop = AddRec->getLoop();
2854 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2855 if (isAvailableAtLoopEntry(S: Ops[i], L: AddRecLoop)) {
2856 LIOps.push_back(Elt: Ops[i]);
2857 Ops.erase(CI: Ops.begin()+i);
2858 --i; --e;
2859 }
2860
2861 // If we found some loop invariants, fold them into the recurrence.
2862 if (!LIOps.empty()) {
2863 // Compute nowrap flags for the addition of the loop-invariant ops and
2864 // the addrec. Temporarily push it as an operand for that purpose. These
2865 // flags are valid in the scope of the addrec only.
2866 LIOps.push_back(Elt: AddRec);
2867 SCEVFlags Flags = ComputeFlags(LIOps);
2868 LIOps.pop_back();
2869
2870 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2871 LIOps.push_back(Elt: AddRec->getStart());
2872
2873 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2874
2875 // It is not in general safe to propagate flags valid on an add within
2876 // the addrec scope to one outside it. We must prove that the inner
2877 // scope is guaranteed to execute if the outer one does to be able to
2878 // safely propagate. We know the program is undefined if poison is
2879 // produced on the inner scoped addrec. We also know that *for this use*
2880 // the outer scoped add can't overflow (because of the flags we just
2881 // computed for the inner scoped add) without the program being undefined.
2882 // Proving that entry to the outer scope neccesitates entry to the inner
2883 // scope, thus proves the program undefined if the flags would be violated
2884 // in the outer scope.
2885 SCEVFlags AddFlags = Flags;
2886 if (AddFlags != SCEV::FlagNone) {
2887 auto *DefI = getDefiningScopeBound(Ops: LIOps);
2888 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2889 if (!isGuaranteedToTransferExecutionTo(A: DefI, B: ReachI))
2890 AddFlags = SCEV::FlagNone;
2891 }
2892 AddRecOps[0] = getAddExpr(Ops&: LIOps, Flags: AddFlags, Depth: Depth + 1);
2893
2894 // Build the new addrec. Propagate the NUW and NSW flags if both the
2895 // outer add and the inner addrec are guaranteed to have no overflow.
2896 // Always propagate NW.
2897 Flags = AddRec->getNoWrapFlags(Mask: setFlags(Flags, OnFlags: SCEV::FlagNW));
2898 const SCEV *NewRec = getAddRecExpr(Operands&: AddRecOps, L: AddRecLoop, Flags);
2899
2900 // If all of the other operands were loop invariant, we are done.
2901 if (Ops.size() == 1) return NewRec;
2902
2903 // Otherwise, add the folded AddRec by the non-invariant parts.
2904 for (unsigned i = 0;; ++i)
2905 if (Ops[i] == AddRec) {
2906 Ops[i] = NewRec;
2907 break;
2908 }
2909 return getAddExpr(Ops, Flags: SCEV::FlagNone, Depth: Depth + 1);
2910 }
2911
2912 // Okay, if there weren't any loop invariants to be folded, check to see if
2913 // there are multiple AddRec's with the same loop induction variable being
2914 // added together. If so, we can fold them.
2915 for (unsigned OtherIdx = Idx+1;
2916 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Val: Ops[OtherIdx]);
2917 ++OtherIdx) {
2918 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2919 // so that the 1st found AddRecExpr is dominated by all others.
2920 assert(DT.dominates(
2921 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2922 AddRec->getLoop()->getHeader()) &&
2923 "AddRecExprs are not sorted in reverse dominance order?");
2924 if (AddRecLoop == cast<SCEVAddRecExpr>(Val&: Ops[OtherIdx])->getLoop()) {
2925 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2926 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2927 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Val: Ops[OtherIdx]);
2928 ++OtherIdx) {
2929 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Val&: Ops[OtherIdx]);
2930 if (OtherAddRec->getLoop() == AddRecLoop) {
2931 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2932 i != e; ++i) {
2933 if (i >= AddRecOps.size()) {
2934 append_range(C&: AddRecOps, R: OtherAddRec->operands().drop_front(N: i));
2935 break;
2936 }
2937 AddRecOps[i] =
2938 getAddExpr(LHS: AddRecOps[i], RHS: OtherAddRec->getOperand(i),
2939 Flags: SCEV::FlagNone, Depth: Depth + 1);
2940 }
2941 Ops.erase(CI: Ops.begin() + OtherIdx); --OtherIdx;
2942 }
2943 }
2944 // Step size has changed, so we cannot guarantee no self-wraparound.
2945 Ops[Idx] = getAddRecExpr(Operands&: AddRecOps, L: AddRecLoop, Flags: SCEV::FlagNone);
2946 return getAddExpr(Ops, Flags: SCEV::FlagNone, Depth: Depth + 1);
2947 }
2948 }
2949
2950 // Otherwise couldn't fold anything into this recurrence. Move onto the
2951 // next one.
2952 }
2953
2954 // Okay, it looks like we really DO need an add expr. Check to see if we
2955 // already have one, otherwise create a new one.
2956 assert((UseFlags == SCEV::FlagNone || equal(OrigOps, Ops)) &&
2957 "Tried to add SCEVUse flags after operands changed");
2958 return {getOrCreateAddExpr(Ops, Flags: ComputeFlags(Ops)), UseFlags};
2959}
2960
2961const SCEV *ScalarEvolution::getOrCreateAddExpr(ArrayRef<SCEVUse> Ops,
2962 SCEVFlags Flags) {
2963 FoldingSetNodeID ID;
2964 ID.AddInteger(I: scAddExpr);
2965 for (SCEVUse Op : Ops)
2966 ID.AddPointer(Ptr: Op.getOpaqueValue());
2967 FoldingSetInsertToken Token;
2968 SCEVAddExpr *S = static_cast<SCEVAddExpr *>(UniqueSCEVs.lookup(ID, Token));
2969 if (!S) {
2970 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Num: Ops.size());
2971 llvm::uninitialized_copy(Src&: Ops, Dst: O);
2972 S = new (SCEVAllocator)
2973 SCEVAddExpr(ID.Intern(Allocator&: SCEVAllocator), O, Ops.size());
2974 UniqueSCEVs.insert(N: S, Token);
2975 S->computeAndSetCanonical(SE&: *this);
2976 registerUser(User: S, Ops);
2977 }
2978 S->setNoWrapFlags(Flags);
2979 return S;
2980}
2981
2982const SCEV *ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops,
2983 const Loop *L,
2984 SCEVFlags Flags) {
2985 FoldingSetNodeID ID;
2986 ID.AddInteger(I: scAddRecExpr);
2987 for (SCEVUse Op : Ops)
2988 ID.AddPointer(Ptr: Op.getOpaqueValue());
2989 ID.AddPointer(Ptr: L);
2990 FoldingSetInsertToken Token;
2991 SCEVAddRecExpr *S =
2992 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.lookup(ID, Token));
2993 if (!S) {
2994 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Num: Ops.size());
2995 llvm::uninitialized_copy(Src&: Ops, Dst: O);
2996 S = new (SCEVAllocator)
2997 SCEVAddRecExpr(ID.Intern(Allocator&: SCEVAllocator), O, Ops.size(), L);
2998 UniqueSCEVs.insert(N: S, Token);
2999 S->computeAndSetCanonical(SE&: *this);
3000 LoopUsers[L].push_back(Elt: S);
3001 registerUser(User: S, Ops);
3002 }
3003 setNoWrapFlags(AddRec: S, Flags);
3004 return S;
3005}
3006
3007const SCEV *ScalarEvolution::getOrCreateMulExpr(ArrayRef<SCEVUse> Ops,
3008 SCEVFlags Flags) {
3009 FoldingSetNodeID ID;
3010 ID.AddInteger(I: scMulExpr);
3011 for (SCEVUse Op : Ops)
3012 ID.AddPointer(Ptr: Op.getOpaqueValue());
3013 FoldingSetInsertToken Token;
3014 SCEVMulExpr *S = static_cast<SCEVMulExpr *>(UniqueSCEVs.lookup(ID, Token));
3015 if (!S) {
3016 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Num: Ops.size());
3017 llvm::uninitialized_copy(Src&: Ops, Dst: O);
3018 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(Allocator&: SCEVAllocator),
3019 O, Ops.size());
3020 UniqueSCEVs.insert(N: S, Token);
3021 S->computeAndSetCanonical(SE&: *this);
3022 registerUser(User: S, Ops);
3023 }
3024 S->setNoWrapFlags(Flags);
3025 return S;
3026}
3027
3028const SCEV *ScalarEvolution::getOrCreateUDivExpr(SCEVUse LHS, SCEVUse RHS) {
3029 FoldingSetNodeID ID;
3030 ID.AddInteger(I: scUDivExpr);
3031 ID.AddPointer(Ptr: LHS.getOpaqueValue());
3032 ID.AddPointer(Ptr: RHS.getOpaqueValue());
3033 FoldingSetInsertToken Token;
3034 SCEV *S = UniqueSCEVs.lookup(ID, Token);
3035 if (!S) {
3036 S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(Allocator&: SCEVAllocator), LHS, RHS);
3037 UniqueSCEVs.insert(N: S, Token);
3038 S->computeAndSetCanonical(SE&: *this);
3039 registerUser(User: S, Ops: {LHS, RHS});
3040 }
3041 return S;
3042}
3043
3044static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3045 uint64_t k = i*j;
3046 if (j > 1 && k / j != i) Overflow = true;
3047 return k;
3048}
3049
3050/// Compute the result of "n choose k", the binomial coefficient. If an
3051/// intermediate computation overflows, Overflow will be set and the return will
3052/// be garbage. Overflow is not cleared on absence of overflow.
3053static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3054 // We use the multiplicative formula:
3055 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3056 // At each iteration, we take the n-th term of the numeral and divide by the
3057 // (k-n)th term of the denominator. This division will always produce an
3058 // integral result, and helps reduce the chance of overflow in the
3059 // intermediate computations. However, we can still overflow even when the
3060 // final result would fit.
3061
3062 if (n == 0 || n == k) return 1;
3063 if (k > n) return 0;
3064
3065 if (k > n/2)
3066 k = n-k;
3067
3068 uint64_t r = 1;
3069 for (uint64_t i = 1; i <= k; ++i) {
3070 r = umul_ov(i: r, j: n-(i-1), Overflow);
3071 r /= i;
3072 }
3073 return r;
3074}
3075
3076/// Determine if any of the operands in this SCEV are a constant or if
3077/// any of the add or multiply expressions in this SCEV contain a constant.
3078static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3079 struct FindConstantInAddMulChain {
3080 bool FoundConstant = false;
3081
3082 bool follow(const SCEV *S) {
3083 FoundConstant |= isa<SCEVConstant>(Val: S);
3084 return isa<SCEVAddExpr>(Val: S) || isa<SCEVMulExpr>(Val: S);
3085 }
3086
3087 bool isDone() const {
3088 return FoundConstant;
3089 }
3090 };
3091
3092 FindConstantInAddMulChain F;
3093 SCEVTraversal<FindConstantInAddMulChain> ST(F);
3094 ST.visitAll(Root: StartExpr);
3095 return F.FoundConstant;
3096}
3097
3098/// Get a canonical multiply expression, or something simpler if possible.
3099SCEVUse ScalarEvolution::getMulExpr(SmallVectorImpl<SCEVUse> &Ops,
3100 SCEVFlagsPair Flags, unsigned Depth) {
3101 SCEVFlags ExprFlags = Flags.ExprFlags;
3102 SCEVFlags UseFlags = Flags.UseFlags;
3103 assert(ExprFlags == maskFlags(ExprFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3104 "only nuw or nsw allowed");
3105 assert(UseFlags == maskFlags(UseFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3106 "only nuw or nsw allowed");
3107 assert(!Ops.empty() && "Cannot get empty mul!");
3108 if (Ops.size() == 1) return Ops[0];
3109#ifndef NDEBUG
3110 Type *ETy = Ops[0]->getType();
3111 assert(!ETy->isPointerTy());
3112 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3113 assert(Ops[i]->getType() == ETy &&
3114 "SCEVMulExpr operand types don't match!");
3115#endif
3116
3117 const SCEV *Folded = constantFoldAndGroupOps(
3118 SE&: *this, LI, DT, Ops,
3119 Fold: [](const APInt &C1, const APInt &C2) { return C1 * C2; },
3120 IsIdentity: [](const APInt &C) { return C.isOne(); }, // identity
3121 IsAbsorber: [](const APInt &C) { return C.isZero(); }); // absorber
3122 if (Folded)
3123 return Folded;
3124
3125#ifndef NDEBUG
3126 // Keep track of operands after constant folding, for verification when adding
3127 // use-specific flags.
3128 const SmallVector<SCEVUse, 8> OrigOps(Ops.begin(), Ops.end());
3129#endif
3130
3131 // Delay expensive flag strengthening until necessary.
3132 auto ComputeFlags = [this, ExprFlags](const ArrayRef<SCEVUse> Ops) {
3133 return StrengthenNoWrapFlags(SE: this, Type: scMulExpr, Ops, Flags: ExprFlags);
3134 };
3135
3136 // Limit recursion calls depth.
3137 if (Depth > MaxArithDepth || hasHugeExpression(Ops))
3138 return {getOrCreateMulExpr(Ops, Flags: ComputeFlags(Ops)), UseFlags};
3139
3140 if (SCEV *S = findExistingSCEVInCache(SCEVType: scMulExpr, Ops)) {
3141 // Don't strengthen flags if we have no new information.
3142 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3143 if (Mul->getNoWrapFlags(Mask: ExprFlags) != ExprFlags)
3144 Mul->setNoWrapFlags(ComputeFlags(Ops));
3145 return {S, UseFlags};
3146 }
3147
3148 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Val&: Ops[0])) {
3149 if (Ops.size() == 2) {
3150 // C1*(C2+V) -> C1*C2 + C1*V
3151 // If any of Add's ops are Adds or Muls with a constant, apply this
3152 // transformation as well.
3153 //
3154 // TODO: There are some cases where this transformation is not
3155 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3156 // this transformation should be narrowed down.
3157 const SCEV *Op0, *Op1;
3158 if (match(U: Ops[1], P: m_scev_Add(Op0: m_SCEV(V&: Op0), Op1: m_SCEV(V&: Op1))) &&
3159 containsConstantInAddMulChain(StartExpr: Ops[1])) {
3160 const SCEV *LHS = getMulExpr(LHS: LHSC, RHS: Op0, Flags: SCEV::FlagNone, Depth: Depth + 1);
3161 const SCEV *RHS = getMulExpr(LHS: LHSC, RHS: Op1, Flags: SCEV::FlagNone, Depth: Depth + 1);
3162 return getAddExpr(LHS, RHS, Flags: SCEV::FlagNone, Depth: Depth + 1);
3163 }
3164
3165 if (Ops[0]->isAllOnesValue()) {
3166 // If we have a mul by -1 of an add, try distributing the -1 among the
3167 // add operands.
3168 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Val&: Ops[1])) {
3169 SmallVector<SCEVUse, 4> NewOps;
3170 bool AnyFolded = false;
3171 for (const SCEV *AddOp : Add->operands()) {
3172 const SCEV *Mul =
3173 getMulExpr(LHS: Ops[0], RHS: SCEVUse(AddOp), Flags: SCEV::FlagNone, Depth: Depth + 1);
3174 if (!isa<SCEVMulExpr>(Val: Mul)) AnyFolded = true;
3175 NewOps.push_back(Elt: Mul);
3176 }
3177 if (AnyFolded)
3178 return getAddExpr(Ops&: NewOps, Flags: SCEV::FlagNone, Depth: Depth + 1);
3179 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Val&: Ops[1])) {
3180 // Negation preserves a recurrence's no self-wrap property.
3181 SmallVector<SCEVUse, 4> Operands;
3182 for (const SCEV *AddRecOp : AddRec->operands())
3183 Operands.push_back(Elt: getMulExpr(LHS: Ops[0], RHS: SCEVUse(AddRecOp),
3184 Flags: SCEV::FlagNone, Depth: Depth + 1));
3185 // Let M be the minimum representable signed value. AddRec with nsw
3186 // multiplied by -1 can have signed overflow if and only if it takes a
3187 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3188 // maximum signed value. In all other cases signed overflow is
3189 // impossible.
3190 auto FlagsMask = SCEV::FlagNW;
3191 if (AddRec->hasNoSignedWrap()) {
3192 auto MinInt =
3193 APInt::getSignedMinValue(numBits: getTypeSizeInBits(Ty: AddRec->getType()));
3194 if (getSignedRangeMin(S: AddRec) != MinInt)
3195 FlagsMask = setFlags(Flags: FlagsMask, OnFlags: SCEV::FlagNSW);
3196 }
3197 return getAddRecExpr(Operands, L: AddRec->getLoop(),
3198 Flags: AddRec->getNoWrapFlags(Mask: FlagsMask));
3199 }
3200 }
3201
3202 // Try to push the constant operand into a ZExt: C * zext (A + B) ->
3203 // zext (C*A + C*B) if trunc (C) * (A + B) does not unsigned-wrap.
3204 const SCEVAddExpr *InnerAdd;
3205 if (match(U: Ops[1], P: m_scev_ZExt(Op0: m_scev_Add(V&: InnerAdd)))) {
3206 const SCEV *NarrowC = getTruncateExpr(Op: LHSC, Ty: InnerAdd->getType());
3207 if (isa<SCEVConstant>(Val: InnerAdd->getOperand(i: 0)) &&
3208 getZeroExtendExpr(Op: NarrowC, Ty: Ops[1]->getType()) == LHSC &&
3209 hasFlags(Flags: StrengthenNoWrapFlags(SE: this, Type: scMulExpr, Ops: {NarrowC, InnerAdd},
3210 Flags: SCEV::FlagNone),
3211 TestFlags: SCEV::FlagNUW)) {
3212 const SCEV *Res =
3213 getMulExpr(LHS: NarrowC, RHS: InnerAdd, Flags: SCEV::FlagNUW, Depth: Depth + 1);
3214 return getZeroExtendExpr(Op: Res, Ty: Ops[1]->getType(), Depth: Depth + 1);
3215 };
3216 }
3217
3218 // Try to fold (C1 * D /u C2) -> C1/C2 * D, if C1 and C2 are powers-of-2,
3219 // D is a multiple of C2, and C1 is a multiple of C2. If C2 is a multiple
3220 // of C1, fold to (D /u (C2 /u C1)).
3221 const SCEV *D;
3222 APInt C1V = LHSC->getAPInt();
3223 // (C1 * D /u C2) == -1 * -C1 * D /u C2 when C1 != INT_MIN. Don't treat -1
3224 // as -1 * 1, as it won't enable additional folds.
3225 if (C1V.isNegative() && !C1V.isMinSignedValue() && !C1V.isAllOnes())
3226 C1V = C1V.abs();
3227 const SCEVConstant *C2;
3228 if (C1V.isPowerOf2() &&
3229 match(U: Ops[1], P: m_scev_UDiv(Op0: m_SCEV(V&: D), Op1: m_SCEVConstant(V&: C2))) &&
3230 C2->getAPInt().isPowerOf2() &&
3231 C1V.logBase2() <= getMinTrailingZeros(S: D)) {
3232 const SCEV *NewMul = nullptr;
3233 if (C1V.uge(RHS: C2->getAPInt())) {
3234 NewMul = getMulExpr(LHS: getUDivExpr(LHS: getConstant(Val: C1V), RHS: C2), RHS: D);
3235 } else if (C2->getAPInt().logBase2() <= getMinTrailingZeros(S: D)) {
3236 assert(C1V.ugt(1) && "C1 <= 1 should have been folded earlier");
3237 NewMul = getUDivExpr(LHS: D, RHS: getUDivExpr(LHS: C2, RHS: getConstant(Val: C1V)));
3238 }
3239 if (NewMul)
3240 return C1V == LHSC->getAPInt() ? NewMul : getNegativeSCEV(V: NewMul);
3241 }
3242 }
3243 }
3244
3245 // Skip over the add expression until we get to a multiply.
3246 unsigned Idx = 0;
3247 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3248 ++Idx;
3249
3250 // If there are mul operands inline them all into this expression.
3251 if (Idx < Ops.size()) {
3252 bool DeletedMul = false;
3253 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Val&: Ops[Idx])) {
3254 if (Ops.size() > MulOpsInlineThreshold)
3255 break;
3256 // If we have an mul, expand the mul operands onto the end of the
3257 // operands list.
3258 Ops.erase(CI: Ops.begin()+Idx);
3259 append_range(C&: Ops, R: Mul->operands());
3260 DeletedMul = true;
3261 }
3262
3263 // If we deleted at least one mul, we added operands to the end of the
3264 // list, and they are not necessarily sorted. Recurse to resort and
3265 // resimplify any operands we just acquired.
3266 if (DeletedMul)
3267 return getMulExpr(Ops, Flags: SCEV::FlagNone, Depth: Depth + 1);
3268 }
3269
3270 // If there are any add recurrences in the operands list, see if any other
3271 // added values are loop invariant. If so, we can fold them into the
3272 // recurrence.
3273 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3274 ++Idx;
3275
3276 // Scan over all recurrences, trying to fold loop invariants into them.
3277 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Val: Ops[Idx]); ++Idx) {
3278 // Scan all of the other operands to this mul and add them to the vector
3279 // if they are loop invariant w.r.t. the recurrence.
3280 SmallVector<SCEVUse, 8> LIOps;
3281 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Val&: Ops[Idx]);
3282 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3283 if (isAvailableAtLoopEntry(S: Ops[i], L: AddRec->getLoop())) {
3284 LIOps.push_back(Elt: Ops[i]);
3285 Ops.erase(CI: Ops.begin()+i);
3286 --i; --e;
3287 }
3288
3289 // If we found some loop invariants, fold them into the recurrence.
3290 if (!LIOps.empty()) {
3291 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3292 SmallVector<SCEVUse, 4> NewOps;
3293 NewOps.reserve(N: AddRec->getNumOperands());
3294 const SCEV *Scale = getMulExpr(Ops&: LIOps, Flags: SCEV::FlagNone, Depth: Depth + 1);
3295
3296 // If both the mul and addrec are nuw, we can preserve nuw.
3297 // If both the mul and addrec are nsw, we can only preserve nsw if either
3298 // a) they are also nuw, or
3299 // b) all multiplications of addrec operands with scale are nsw.
3300 SCEVFlags Flags = AddRec->getNoWrapFlags(Mask: ComputeFlags({Scale, AddRec}));
3301
3302 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3303 NewOps.push_back(Elt: getMulExpr(LHS: Scale, RHS: AddRec->getOperand(i),
3304 Flags: SCEV::FlagNone, Depth: Depth + 1));
3305
3306 if (hasFlags(Flags, TestFlags: SCEV::FlagNSW) && !hasFlags(Flags, TestFlags: SCEV::FlagNUW)) {
3307 ConstantRange NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3308 BinOp: Instruction::Mul, Other: getSignedRange(S: Scale),
3309 NoWrapKind: OverflowingBinaryOperator::NoSignedWrap);
3310 if (!NSWRegion.contains(CR: getSignedRange(S: AddRec->getOperand(i))))
3311 Flags = clearFlags(Flags, OffFlags: SCEV::FlagNSW);
3312 }
3313 }
3314
3315 const SCEV *NewRec = getAddRecExpr(Operands&: NewOps, L: AddRec->getLoop(), Flags);
3316
3317 // If all of the other operands were loop invariant, we are done.
3318 if (Ops.size() == 1) return NewRec;
3319
3320 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3321 for (unsigned i = 0;; ++i)
3322 if (Ops[i] == AddRec) {
3323 Ops[i] = NewRec;
3324 break;
3325 }
3326 return getMulExpr(Ops, Flags: SCEV::FlagNone, Depth: Depth + 1);
3327 }
3328
3329 // Okay, if there weren't any loop invariants to be folded, check to see
3330 // if there are multiple AddRec's with the same loop induction variable
3331 // being multiplied together. If so, we can fold them.
3332
3333 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3334 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3335 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3336 // ]]],+,...up to x=2n}.
3337 // Note that the arguments to choose() are always integers with values
3338 // known at compile time, never SCEV objects.
3339 //
3340 // The implementation avoids pointless extra computations when the two
3341 // addrec's are of different length (mathematically, it's equivalent to
3342 // an infinite stream of zeros on the right).
3343 bool OpsModified = false;
3344 for (unsigned OtherIdx = Idx+1;
3345 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Val: Ops[OtherIdx]);
3346 ++OtherIdx) {
3347 const SCEVAddRecExpr *OtherAddRec =
3348 dyn_cast<SCEVAddRecExpr>(Val&: Ops[OtherIdx]);
3349 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3350 continue;
3351
3352 // Limit max number of arguments to avoid creation of unreasonably big
3353 // SCEVAddRecs with very complex operands.
3354 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3355 MaxAddRecSize || hasHugeExpression(Ops: {AddRec, OtherAddRec}))
3356 continue;
3357
3358 bool Overflow = false;
3359 Type *Ty = AddRec->getType();
3360 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3361 SmallVector<SCEVUse, 7> AddRecOps;
3362 for (int x = 0, xe = AddRec->getNumOperands() +
3363 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3364 SmallVector<SCEVUse, 7> SumOps;
3365 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3366 uint64_t Coeff1 = Choose(n: x, k: 2*x - y, Overflow);
3367 for (int z = std::max(a: y-x, b: y-(int)AddRec->getNumOperands()+1),
3368 ze = std::min(a: x+1, b: (int)OtherAddRec->getNumOperands());
3369 z < ze && !Overflow; ++z) {
3370 uint64_t Coeff2 = Choose(n: 2*x - y, k: x-z, Overflow);
3371 uint64_t Coeff;
3372 if (LargerThan64Bits)
3373 Coeff = umul_ov(i: Coeff1, j: Coeff2, Overflow);
3374 else
3375 Coeff = Coeff1*Coeff2;
3376 const SCEV *CoeffTerm = getConstant(Ty, V: Coeff);
3377 const SCEV *Term1 = AddRec->getOperand(i: y-z);
3378 const SCEV *Term2 = OtherAddRec->getOperand(i: z);
3379 SumOps.push_back(
3380 Elt: getMulExpr(Op0: CoeffTerm, Op1: Term1, Op2: Term2, Flags: SCEV::FlagNone, Depth: Depth + 1));
3381 }
3382 }
3383 if (SumOps.empty())
3384 SumOps.push_back(Elt: getZero(Ty));
3385 AddRecOps.push_back(Elt: getAddExpr(Ops&: SumOps, Flags: SCEV::FlagNone, Depth: Depth + 1));
3386 }
3387 if (!Overflow) {
3388 const SCEV *NewAddRec =
3389 getAddRecExpr(Operands&: AddRecOps, L: AddRec->getLoop(), Flags: SCEV::FlagNone);
3390 if (Ops.size() == 2) return NewAddRec;
3391 Ops[Idx] = NewAddRec;
3392 Ops.erase(CI: Ops.begin() + OtherIdx); --OtherIdx;
3393 OpsModified = true;
3394 AddRec = dyn_cast<SCEVAddRecExpr>(Val: NewAddRec);
3395 if (!AddRec)
3396 break;
3397 }
3398 }
3399 if (OpsModified)
3400 return getMulExpr(Ops, Flags: SCEV::FlagNone, Depth: Depth + 1);
3401
3402 // Otherwise couldn't fold anything into this recurrence. Move onto the
3403 // next one.
3404 }
3405
3406 // Okay, it looks like we really DO need an mul expr. Check to see if we
3407 // already have one, otherwise create a new one.
3408 assert((UseFlags == SCEV::FlagNone || equal(OrigOps, Ops)) &&
3409 "Tried to add SCEVUse flags after operands changed");
3410 return {getOrCreateMulExpr(Ops, Flags: ComputeFlags(Ops)), UseFlags};
3411}
3412
3413/// Represents an unsigned remainder expression based on unsigned division.
3414const SCEV *ScalarEvolution::getURemExpr(SCEVUse LHS, SCEVUse RHS) {
3415 assert(getEffectiveSCEVType(LHS->getType()) ==
3416 getEffectiveSCEVType(RHS->getType()) &&
3417 "SCEVURemExpr operand types don't match!");
3418
3419 // Short-circuit easy cases
3420 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Val&: RHS)) {
3421 // If constant is one, the result is trivial
3422 if (RHSC->getValue()->isOne())
3423 return getZero(Ty: LHS->getType()); // X urem 1 --> 0
3424
3425 // If constant is a power of two, fold into a zext(trunc(LHS)).
3426 if (RHSC->getAPInt().isPowerOf2()) {
3427 Type *FullTy = LHS->getType();
3428 Type *TruncTy =
3429 IntegerType::get(C&: getContext(), NumBits: RHSC->getAPInt().logBase2());
3430 return getZeroExtendExpr(Op: getTruncateExpr(Op: LHS, Ty: TruncTy), Ty: FullTy);
3431 }
3432 }
3433
3434 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3435 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3436 const SCEV *Mult = getMulExpr(LHS: UDiv, RHS, Flags: SCEV::FlagNUW);
3437 return getMinusSCEV(LHS, RHS: Mult, Flags: SCEV::FlagNUW);
3438}
3439
3440/// Get a canonical unsigned division expression, or something simpler if
3441/// possible.
3442const SCEV *ScalarEvolution::getUDivExpr(SCEVUse LHS, SCEVUse RHS) {
3443 assert(!LHS->getType()->isPointerTy() &&
3444 "SCEVUDivExpr operand can't be pointer!");
3445 assert(LHS->getType() == RHS->getType() &&
3446 "SCEVUDivExpr operand types don't match!");
3447
3448 if (SCEV *S = findExistingSCEVInCache(SCEVType: scUDivExpr, Ops: {LHS, RHS}))
3449 return S;
3450
3451 // 0 udiv Y == 0
3452 if (match(U: LHS, P: m_scev_Zero()))
3453 return LHS;
3454
3455 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Val&: RHS)) {
3456 if (RHSC->getValue()->isOne())
3457 return LHS; // X udiv 1 --> x
3458 // If the denominator is zero, the result of the udiv is undefined. Don't
3459 // try to analyze it, because the resolution chosen here may differ from
3460 // the resolution chosen in other parts of the compiler.
3461 if (!RHSC->getValue()->isZero()) {
3462 // Determine if the division can be folded into the operands of
3463 // its operands.
3464 // TODO: Generalize this to non-constants by using known-bits information.
3465 Type *Ty = LHS->getType();
3466 unsigned LZ = RHSC->getAPInt().countl_zero();
3467 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3468 // For non-power-of-two values, effectively round the value up to the
3469 // nearest power of two.
3470 if (!RHSC->getAPInt().isPowerOf2())
3471 ++MaxShiftAmt;
3472 IntegerType *ExtTy =
3473 IntegerType::get(C&: getContext(), NumBits: getTypeSizeInBits(Ty) + MaxShiftAmt);
3474 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Val&: LHS))
3475 if (const SCEVConstant *Step =
3476 dyn_cast<SCEVConstant>(Val: AR->getStepRecurrence(SE&: *this))) {
3477 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3478 const APInt &StepInt = Step->getAPInt();
3479 const APInt &DivInt = RHSC->getAPInt();
3480 if (!StepInt.urem(RHS: DivInt) &&
3481 getZeroExtendExpr(Op: AR, Ty: ExtTy) ==
3482 getAddRecExpr(Start: getZeroExtendExpr(Op: AR->getStart(), Ty: ExtTy),
3483 Step: getZeroExtendExpr(Op: Step, Ty: ExtTy), L: AR->getLoop(),
3484 Flags: SCEV::FlagNone)) {
3485 SmallVector<SCEVUse, 4> Operands;
3486 for (const SCEV *Op : AR->operands())
3487 Operands.push_back(Elt: getUDivExpr(LHS: Op, RHS));
3488 return getAddRecExpr(Operands, L: AR->getLoop(), Flags: SCEV::FlagNW);
3489 }
3490 /// Get a canonical UDivExpr for a recurrence.
3491 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3492 const APInt *StartRem;
3493 if (!DivInt.urem(RHS: StepInt) && match(S: getURemExpr(LHS: AR->getStart(), RHS: Step),
3494 P: m_scev_APInt(C&: StartRem))) {
3495 bool NoWrap =
3496 getZeroExtendExpr(Op: AR, Ty: ExtTy) ==
3497 getAddRecExpr(Start: getZeroExtendExpr(Op: AR->getStart(), Ty: ExtTy),
3498 Step: getZeroExtendExpr(Op: Step, Ty: ExtTy), L: AR->getLoop(),
3499 Flags: SCEV::FlagNone);
3500
3501 // With N <= C and both N, C as powers-of-2, the transformation
3502 // {X,+,N}/C => {(X - X%N),+,N}/C preserves division results even
3503 // if wrapping occurs, as the division results remain equivalent for
3504 // all offsets in [[(X - X%N), X).
3505 bool CanFoldWithWrap = StepInt.ule(RHS: DivInt) && // N <= C
3506 StepInt.isPowerOf2() && DivInt.isPowerOf2();
3507 // Only fold if the subtraction can be folded in the start
3508 // expression.
3509 const SCEV *NewStart =
3510 getMinusSCEV(LHS: AR->getStart(), RHS: getConstant(Val: *StartRem));
3511 if (*StartRem != 0 && (NoWrap || CanFoldWithWrap) &&
3512 !isa<SCEVAddExpr>(Val: NewStart)) {
3513 const SCEV *NewLHS =
3514 getAddRecExpr(Start: NewStart, Step, L: AR->getLoop(),
3515 Flags: NoWrap ? SCEV::FlagNW : SCEV::FlagNone);
3516 if (LHS != NewLHS)
3517 return getUDivExpr(LHS: NewLHS, RHS);
3518 }
3519 }
3520 }
3521 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3522 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Val&: LHS)) {
3523 if (M->hasNoUnsignedWrap()) {
3524 // Find an operand that's safely divisible.
3525 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3526 const SCEV *Op = M->getOperand(i);
3527 const SCEV *Div = getUDivExpr(LHS: Op, RHS: RHSC);
3528 if (!isa<SCEVUDivExpr>(Val: Div) && getMulExpr(LHS: Div, RHS: RHSC) == Op) {
3529 SmallVector<SCEVUse, 4> Operands(M->operands());
3530 Operands[i] = Div;
3531 return getMulExpr(Ops&: Operands);
3532 }
3533 }
3534
3535 // Even if it's not divisible, try to remove a common factor.
3536 if (const auto *LHSC = dyn_cast<SCEVConstant>(Val: M->getOperand(i: 0))) {
3537 APInt Factor = APIntOps::GreatestCommonDivisor(A: LHSC->getAPInt(),
3538 B: RHSC->getAPInt());
3539 if (!Factor.isIntN(N: 1)) {
3540 SmallVector<SCEVUse, 2> NewOperands;
3541 NewOperands.push_back(Elt: getConstant(Val: LHSC->getAPInt().udiv(RHS: Factor)));
3542 append_range(C&: NewOperands, R: M->operands().drop_front());
3543 const SCEV *NewMul = getMulExpr(Ops&: NewOperands);
3544 return getUDivExpr(LHS: NewMul,
3545 RHS: getConstant(Val: RHSC->getAPInt().udiv(RHS: Factor)));
3546 }
3547 }
3548 }
3549 }
3550
3551 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3552 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(Val&: LHS)) {
3553 if (auto *DivisorConstant =
3554 dyn_cast<SCEVConstant>(Val: OtherDiv->getRHS())) {
3555 bool Overflow = false;
3556 APInt NewRHS =
3557 DivisorConstant->getAPInt().umul_ov(RHS: RHSC->getAPInt(), Overflow);
3558 if (Overflow) {
3559 return getConstant(Ty: RHSC->getType(), V: 0, isSigned: false);
3560 }
3561 return getUDivExpr(LHS: OtherDiv->getLHS(), RHS: getConstant(Val: NewRHS));
3562 }
3563 }
3564
3565 // (A+B)/C --> (A/C + B/C) if the add does not unsigned wrap and A/C and
3566 // B/C can be folded.
3567 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Val&: LHS)) {
3568 if (A->hasNoUnsignedWrap()) {
3569 SmallVector<SCEVUse, 4> Operands;
3570 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3571 const SCEV *Op = getUDivExpr(LHS: A->getOperand(i), RHS);
3572 if (isa<SCEVUDivExpr>(Val: Op) ||
3573 getMulExpr(LHS: Op, RHS) != A->getOperand(i))
3574 break;
3575 Operands.push_back(Elt: Op);
3576 }
3577 if (Operands.size() == A->getNumOperands())
3578 return getAddExpr(Ops&: Operands);
3579 }
3580 }
3581
3582 // ((N - M) + (M * A)) / N --> ((N - 1) + (M * A)) / N
3583 // This is an idiom for rounding A up to the next multiple of N, where A
3584 // is aready known to be a multiple of M. In this case, instcombine can
3585 // see that some low bits of the added constant are unused, so can clear
3586 // them, but we want to canonicalise to set the low bits. This makes the
3587 // pattern easier to match, without needing to check for known bits in
3588 // A*M.
3589 const APInt &N = RHSC->getAPInt();
3590 const APInt *NMinusM, *M;
3591 const SCEV *A;
3592 if (match(U: LHS, P: m_scev_Add(Op0: m_scev_APInt(C&: NMinusM),
3593 Op1: m_scev_Mul(Op0: m_scev_APInt(C&: M), Op1: m_SCEV(V&: A))))) {
3594 if (N.isPowerOf2() && M->isPowerOf2() && M->ult(RHS: N) &&
3595 *NMinusM == N - *M) {
3596 return getUDivExpr(
3597 LHS: getAddExpr(LHS: getConstant(Val: N - 1), RHS: getMulExpr(LHS: getConstant(Val: *M), RHS: A)),
3598 RHS);
3599 }
3600 }
3601
3602 // Fold if both operands are constant.
3603 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Val&: LHS))
3604 return getConstant(Val: LHSC->getAPInt().udiv(RHS: RHSC->getAPInt()));
3605 }
3606 }
3607
3608 // ((-C + (C smax %x)) /u %x) evaluates to zero, for any positive constant C.
3609 const APInt *NegC, *C;
3610 if (match(U: LHS,
3611 P: m_scev_Add(Op0: m_scev_APInt(C&: NegC),
3612 Op1: m_scev_SMax(Op0: m_scev_APInt(C), Op1: m_scev_Specific(S: RHS)))) &&
3613 NegC->isNegative() && !NegC->isMinSignedValue() && *C == -*NegC)
3614 return getZero(Ty: LHS->getType());
3615
3616 // (%a * %b)<nuw> / %b -> %a
3617 const auto *Mul = dyn_cast<SCEVMulExpr>(Val&: LHS);
3618 if (Mul && Mul->hasNoUnsignedWrap()) {
3619 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3620 if (Mul->getOperand(i) == RHS) {
3621 SmallVector<SCEVUse, 2> Operands;
3622 append_range(C&: Operands, R: Mul->operands().take_front(N: i));
3623 append_range(C&: Operands, R: Mul->operands().drop_front(N: i + 1));
3624 return getMulExpr(Ops&: Operands);
3625 }
3626 }
3627 }
3628
3629 // TODO: Generalize to handle any common factors.
3630 // udiv (mul nuw a, vscale), (mul nuw b, vscale) --> udiv a, b
3631 const SCEV *NewLHS, *NewRHS;
3632 if (match(U: LHS, P: m_scev_c_NUWMul(Op0: m_SCEV(V&: NewLHS), Op1: m_SCEVVScale())) &&
3633 match(U: RHS, P: m_scev_c_NUWMul(Op0: m_SCEV(V&: NewRHS), Op1: m_SCEVVScale())))
3634 return getUDivExpr(LHS: NewLHS, RHS: NewRHS);
3635
3636 return getOrCreateUDivExpr(LHS, RHS);
3637}
3638
3639/// Get a canonical unsigned division expression, or something simpler if
3640/// possible. There is no representation for an exact udiv in SCEV IR, but we
3641/// can attempt to optimize it prior to construction.
3642const SCEV *ScalarEvolution::getUDivExactExpr(SCEVUse LHS, SCEVUse RHS) {
3643 // Currently there is no exact specific logic.
3644
3645 return getUDivExpr(LHS, RHS);
3646}
3647
3648/// Get an add recurrence expression for the specified loop. Simplify the
3649/// expression as much as possible.
3650SCEVUse ScalarEvolution::getAddRecExpr(SCEVUse Start, SCEVUse Step,
3651 const Loop *L, SCEVFlagsPair Flags) {
3652 SmallVector<SCEVUse, 4> Operands;
3653 Operands.push_back(Elt: Start);
3654 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Val&: Step))
3655 if (StepChrec->getLoop() == L) {
3656 append_range(C&: Operands, R: StepChrec->operands());
3657 // The use flags describe the two-operand recurrence, not the flattened
3658 // one built here, so drop them just like the expression's NUW/NSW.
3659 return getAddRecExpr(Operands, L,
3660 Flags: maskFlags(Flags: Flags.ExprFlags, Mask: SCEV::FlagNW));
3661 }
3662
3663 Operands.push_back(Elt: Step);
3664 return getAddRecExpr(Operands, L, Flags);
3665}
3666
3667/// Get an add recurrence expression for the specified loop. Simplify the
3668/// expression as much as possible.
3669SCEVUse ScalarEvolution::getAddRecExpr(SmallVectorImpl<SCEVUse> &Operands,
3670 const Loop *L, SCEVFlagsPair NWFlags) {
3671 SCEVFlags ExprFlags = NWFlags.ExprFlags;
3672 SCEVFlags UseFlags = NWFlags.UseFlags;
3673 assert(!(UseFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
3674 "only nuw or nsw allowed");
3675 if (Operands.size() == 1) return Operands[0];
3676#ifndef NDEBUG
3677 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3678 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3679 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3680 "SCEVAddRecExpr operand types don't match!");
3681 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3682 }
3683 for (const SCEV *Op : Operands)
3684 assert(isAvailableAtLoopEntry(Op, L) &&
3685 "SCEVAddRecExpr operand is not available at loop entry!");
3686
3687 // Keep track of the original operands, for verification when adding
3688 // use-specific flags.
3689 const SmallVector<SCEVUse, 4> OrigOperands(Operands.begin(), Operands.end());
3690#endif
3691
3692 if (Operands.back()->isZero()) {
3693 Operands.pop_back();
3694 return getAddRecExpr(Operands, L, NWFlags: SCEV::FlagNone); // {X,+,0} --> X
3695 }
3696
3697 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3698 // use that information to infer NUW and NSW flags. However, computing a
3699 // BE count requires calling getAddRecExpr, so we may not yet have a
3700 // meaningful BE count at this point (and if we don't, we'd be stuck
3701 // with a SCEVCouldNotCompute as the cached BE count).
3702
3703 ExprFlags = StrengthenNoWrapFlags(SE: this, Type: scAddRecExpr, Ops: Operands, Flags: ExprFlags);
3704
3705 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3706 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Val&: Operands[0])) {
3707 const Loop *NestedLoop = NestedAR->getLoop();
3708 if (L->contains(L: NestedLoop)
3709 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3710 : (!NestedLoop->contains(L) &&
3711 DT.dominates(A: L->getHeader(), B: NestedLoop->getHeader()))) {
3712 SmallVector<SCEVUse, 4> NestedOperands(NestedAR->operands());
3713 Operands[0] = NestedAR->getStart();
3714 // AddRecs require their operands be loop-invariant with respect to their
3715 // loops. Don't perform this transformation if it would break this
3716 // requirement.
3717 bool AllInvariant = all_of(
3718 Range&: Operands, P: [&](const SCEV *Op) { return isLoopInvariant(S: Op, L); });
3719
3720 if (AllInvariant) {
3721 // Create a recurrence for the outer loop with the same step size.
3722 //
3723 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3724 // inner recurrence has the same property.
3725 SCEVFlags OuterFlags =
3726 maskFlags(Flags: ExprFlags, Mask: SCEV::FlagNW | NestedAR->getNoWrapFlags());
3727
3728 NestedOperands[0] = getAddRecExpr(Operands, L, NWFlags: OuterFlags);
3729 AllInvariant = all_of(Range&: NestedOperands, P: [&](const SCEV *Op) {
3730 return isLoopInvariant(S: Op, L: NestedLoop);
3731 });
3732
3733 if (AllInvariant) {
3734 // Ok, both add recurrences are valid after the transformation.
3735 //
3736 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3737 // the outer recurrence has the same property.
3738 SCEVFlags InnerFlags =
3739 maskFlags(Flags: NestedAR->getNoWrapFlags(), Mask: SCEV::FlagNW | ExprFlags);
3740 return getAddRecExpr(Operands&: NestedOperands, L: NestedLoop, NWFlags: InnerFlags);
3741 }
3742 }
3743 // Reset Operands to its original state.
3744 Operands[0] = NestedAR;
3745 }
3746 }
3747
3748 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3749 // already have one, otherwise create a new one.
3750 assert((UseFlags == SCEV::FlagNone || equal(OrigOperands, Operands)) &&
3751 "Tried to add SCEVUse flags after operands changed");
3752 return {getOrCreateAddRecExpr(Ops: Operands, L, Flags: ExprFlags), UseFlags};
3753}
3754
3755const SCEV *ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3756 ArrayRef<SCEVUse> IndexExprs) {
3757 const SCEV *BaseExpr = getSCEV(V: GEP->getPointerOperand());
3758 // getSCEV(Base)->getType() has the same address space as Base->getType()
3759 // because SCEV::getType() preserves the address space.
3760 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
3761 if (NW != GEPNoWrapFlags::none()) {
3762 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3763 // but to do that, we have to ensure that said flag is valid in the entire
3764 // defined scope of the SCEV.
3765 // TODO: non-instructions have global scope. We might be able to prove
3766 // some global scope cases
3767 auto *GEPI = dyn_cast<Instruction>(Val: GEP);
3768 if (!GEPI || !isSCEVExprNeverPoison(I: GEPI))
3769 NW = GEPNoWrapFlags::none();
3770 }
3771
3772 return getGEPExpr(BaseExpr, IndexExprs, SrcElementTy: GEP->getSourceElementType(), NW);
3773}
3774
3775const SCEV *ScalarEvolution::getGEPExpr(SCEVUse BaseExpr,
3776 ArrayRef<SCEVUse> IndexExprs,
3777 Type *SrcElementTy, GEPNoWrapFlags NW) {
3778 SCEVFlags OffsetWrap = SCEV::FlagNone;
3779 if (NW.hasNoUnsignedSignedWrap())
3780 OffsetWrap = setFlags(Flags: OffsetWrap, OnFlags: SCEV::FlagNSW);
3781 if (NW.hasNoUnsignedWrap())
3782 OffsetWrap = setFlags(Flags: OffsetWrap, OnFlags: SCEV::FlagNUW);
3783
3784 Type *CurTy = BaseExpr->getType();
3785 Type *IntIdxTy = getEffectiveSCEVType(Ty: BaseExpr->getType());
3786 bool FirstIter = true;
3787 SmallVector<SCEVUse, 4> Offsets;
3788 for (SCEVUse IndexExpr : IndexExprs) {
3789 // Compute the (potentially symbolic) offset in bytes for this index.
3790 if (StructType *STy = dyn_cast<StructType>(Val: CurTy)) {
3791 // For a struct, add the member offset.
3792 ConstantInt *Index = cast<SCEVConstant>(Val&: IndexExpr)->getValue();
3793 unsigned FieldNo = Index->getZExtValue();
3794 const SCEV *FieldOffset = getOffsetOfExpr(IntTy: IntIdxTy, STy, FieldNo);
3795 Offsets.push_back(Elt: FieldOffset);
3796
3797 // Update CurTy to the type of the field at Index.
3798 CurTy = STy->getTypeAtIndex(V: Index);
3799 } else {
3800 // Update CurTy to its element type.
3801 if (FirstIter) {
3802 assert(isa<PointerType>(CurTy) &&
3803 "The first index of a GEP indexes a pointer");
3804 CurTy = SrcElementTy;
3805 FirstIter = false;
3806 } else {
3807 CurTy = GetElementPtrInst::getTypeAtIndex(Ty: CurTy, Idx: (uint64_t)0);
3808 }
3809 // For an array, add the element offset, explicitly scaled.
3810 const SCEV *ElementSize = getSizeOfExpr(IntTy: IntIdxTy, AllocTy: CurTy);
3811 // Getelementptr indices are signed.
3812 IndexExpr = getTruncateOrSignExtend(V: IndexExpr, Ty: IntIdxTy);
3813
3814 // Multiply the index by the element size to compute the element offset.
3815 const SCEV *LocalOffset = getMulExpr(LHS: IndexExpr, RHS: ElementSize, Flags: OffsetWrap);
3816 Offsets.push_back(Elt: LocalOffset);
3817 }
3818 }
3819
3820 // Handle degenerate case of GEP without offsets.
3821 if (Offsets.empty())
3822 return BaseExpr;
3823
3824 // Add the offsets together, assuming nsw if inbounds.
3825 const SCEV *Offset = getAddExpr(Ops&: Offsets, Flags: OffsetWrap);
3826 // Add the base address and the offset. We cannot use the nsw flag, as the
3827 // base address is unsigned. However, if we know that the offset is
3828 // non-negative, we can use nuw.
3829 bool NUW = NW.hasNoUnsignedWrap() ||
3830 (NW.hasNoUnsignedSignedWrap() && isKnownNonNegative(S: Offset));
3831 SCEVFlags BaseWrap = NUW ? SCEV::FlagNUW : SCEV::FlagNone;
3832 const SCEV *GEPExpr = getAddExpr(LHS: BaseExpr, RHS: Offset, Flags: BaseWrap);
3833 assert(BaseExpr->getType() == GEPExpr->getType() &&
3834 "GEP should not change type mid-flight.");
3835 return GEPExpr;
3836}
3837
3838SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3839 ArrayRef<SCEVUse> Ops,
3840 const Loop *L) {
3841 assert((SCEVType != scAddRecExpr || L) &&
3842 "L must be passed to find existing AddRecs");
3843 FoldingSetNodeID ID;
3844 ID.AddInteger(I: SCEVType);
3845 for (SCEVUse Op : Ops)
3846 ID.AddPointer(Ptr: Op.getOpaqueValue());
3847 if (L)
3848 ID.AddPointer(Ptr: L);
3849 FoldingSetInsertToken Token;
3850 return UniqueSCEVs.lookup(ID, Token);
3851}
3852
3853const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3854 SCEVFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagNone;
3855 return getSMaxExpr(LHS: Op, RHS: getNegativeSCEV(V: Op, Flags));
3856}
3857
3858const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
3859 SmallVectorImpl<SCEVUse> &Ops) {
3860 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3861 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3862 if (Ops.size() == 1) return Ops[0];
3863#ifndef NDEBUG
3864 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3865 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3866 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3867 "Operand types don't match!");
3868 assert(Ops[0]->getType()->isPointerTy() ==
3869 Ops[i]->getType()->isPointerTy() &&
3870 "min/max should be consistently pointerish");
3871 }
3872#endif
3873
3874 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3875 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3876
3877 const SCEV *Folded = constantFoldAndGroupOps(
3878 SE&: *this, LI, DT, Ops,
3879 Fold: [&](const APInt &C1, const APInt &C2) {
3880 switch (Kind) {
3881 case scSMaxExpr:
3882 return APIntOps::smax(A: C1, B: C2);
3883 case scSMinExpr:
3884 return APIntOps::smin(A: C1, B: C2);
3885 case scUMaxExpr:
3886 return APIntOps::umax(A: C1, B: C2);
3887 case scUMinExpr:
3888 return APIntOps::umin(A: C1, B: C2);
3889 default:
3890 llvm_unreachable("Unknown SCEV min/max opcode");
3891 }
3892 },
3893 IsIdentity: [&](const APInt &C) {
3894 // identity
3895 if (IsMax)
3896 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3897 else
3898 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3899 },
3900 IsAbsorber: [&](const APInt &C) {
3901 // absorber
3902 if (IsMax)
3903 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3904 else
3905 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3906 });
3907 if (Folded)
3908 return Folded;
3909
3910 // Check if we have created the same expression before.
3911 if (const SCEV *S = findExistingSCEVInCache(SCEVType: Kind, Ops)) {
3912 return S;
3913 }
3914
3915 // Find the first operation of the same kind
3916 unsigned Idx = 0;
3917 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3918 ++Idx;
3919
3920 // Check to see if one of the operands is of the same kind. If so, expand its
3921 // operands onto our operand list, and recurse to simplify.
3922 if (Idx < Ops.size()) {
3923 bool DeletedAny = false;
3924 while (Ops[Idx]->getSCEVType() == Kind) {
3925 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Val&: Ops[Idx]);
3926 Ops.erase(CI: Ops.begin()+Idx);
3927 append_range(C&: Ops, R: SMME->operands());
3928 DeletedAny = true;
3929 }
3930
3931 if (DeletedAny)
3932 return getMinMaxExpr(Kind, Ops);
3933 }
3934
3935 // Okay, check to see if the same value occurs in the operand list twice. If
3936 // so, delete one. Since we sorted the list, these values are required to
3937 // be adjacent.
3938 llvm::CmpInst::Predicate GEPred =
3939 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3940 llvm::CmpInst::Predicate LEPred =
3941 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3942 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3943 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3944 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3945 if (SCEVUse Common = SCEVUse::getCommon(A: Ops[i], B: Ops[i + 1]))
3946 Ops[i] = Ops[i + 1] = Common;
3947 if (Ops[i] == Ops[i + 1] ||
3948 isKnownViaNonRecursiveReasoning(Pred: FirstPred, LHS: Ops[i], RHS: Ops[i + 1])) {
3949 // X op Y op Y --> X op Y
3950 // X op Y --> X, if we know X, Y are ordered appropriately
3951 Ops.erase(CS: Ops.begin() + i + 1, CE: Ops.begin() + i + 2);
3952 --i;
3953 --e;
3954 } else if (isKnownViaNonRecursiveReasoning(Pred: SecondPred, LHS: Ops[i],
3955 RHS: Ops[i + 1])) {
3956 // X op Y --> Y, if we know X, Y are ordered appropriately
3957 Ops.erase(CS: Ops.begin() + i, CE: Ops.begin() + i + 1);
3958 --i;
3959 --e;
3960 }
3961 }
3962
3963 if (Ops.size() == 1) return Ops[0];
3964
3965 assert(!Ops.empty() && "Reduced smax down to nothing!");
3966
3967 // Okay, it looks like we really DO need an expr. Check to see if we
3968 // already have one, otherwise create a new one.
3969 FoldingSetNodeID ID;
3970 ID.AddInteger(I: Kind);
3971 for (SCEVUse Op : Ops)
3972 ID.AddPointer(Ptr: Op.getOpaqueValue());
3973 FoldingSetInsertToken Token;
3974 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
3975 if (ExistingSCEV)
3976 return ExistingSCEV;
3977 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Num: Ops.size());
3978 llvm::uninitialized_copy(Src&: Ops, Dst: O);
3979 SCEV *S = new (SCEVAllocator)
3980 SCEVMinMaxExpr(ID.Intern(Allocator&: SCEVAllocator), Kind, O, Ops.size());
3981
3982 UniqueSCEVs.insert(N: S, Token);
3983 S->computeAndSetCanonical(SE&: *this);
3984 registerUser(User: S, Ops);
3985 return S;
3986}
3987
3988namespace {
3989
3990class SCEVSequentialMinMaxDeduplicatingVisitor final
3991 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3992 std::optional<const SCEV *>> {
3993 using RetVal = std::optional<const SCEV *>;
3994
3995 ScalarEvolution &SE;
3996 const SCEVTypes RootKind; // Must be a sequential min/max expression.
3997 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3998 SmallPtrSet<const SCEV *, 16> SeenOps;
3999
4000 bool canRecurseInto(SCEVTypes Kind) const {
4001 // We can only recurse into the SCEV expression of the same effective type
4002 // as the type of our root SCEV expression.
4003 return RootKind == Kind || NonSequentialRootKind == Kind;
4004 };
4005
4006 RetVal visit(const SCEV *S) {
4007 // Has the whole operand been seen already?
4008 if (!SeenOps.insert(Ptr: S).second)
4009 return std::nullopt;
4010 if (isa<SCEVMinMaxExpr, SCEVSequentialMinMaxExpr>(Val: S)) {
4011 SCEVTypes Kind = S->getSCEVType();
4012
4013 if (!canRecurseInto(Kind))
4014 return S;
4015
4016 auto *NAry = cast<SCEVNAryExpr>(Val: S);
4017 SmallVector<SCEVUse> NewOps;
4018 bool Changed = visit(Kind, OrigOps: NAry->operands(), NewOps);
4019
4020 if (!Changed)
4021 return S;
4022 if (NewOps.empty())
4023 return std::nullopt;
4024
4025 return isa<SCEVSequentialMinMaxExpr>(Val: S)
4026 ? SE.getSequentialMinMaxExpr(Kind, Operands&: NewOps)
4027 : SE.getMinMaxExpr(Kind, Ops&: NewOps);
4028 }
4029 return S;
4030 }
4031
4032public:
4033 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4034 SCEVTypes RootKind)
4035 : SE(SE), RootKind(RootKind),
4036 NonSequentialRootKind(
4037 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4038 Ty: RootKind)) {}
4039
4040 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
4041 SmallVectorImpl<SCEVUse> &NewOps) {
4042 bool Changed = false;
4043 SmallVector<SCEVUse> Ops;
4044 Ops.reserve(N: OrigOps.size());
4045
4046 for (const SCEV *Op : OrigOps) {
4047 RetVal NewOp = visit(S: Op);
4048 if (NewOp != Op)
4049 Changed = true;
4050 if (NewOp)
4051 Ops.emplace_back(Args&: *NewOp);
4052 }
4053
4054 if (Changed)
4055 NewOps = std::move(Ops);
4056 return Changed;
4057 }
4058};
4059
4060} // namespace
4061
4062static bool scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind) {
4063 switch (Kind) {
4064 case scConstant:
4065 case scVScale:
4066 case scTruncate:
4067 case scZeroExtend:
4068 case scSignExtend:
4069 case scPtrToAddr:
4070 case scAddExpr:
4071 case scMulExpr:
4072 case scUDivExpr:
4073 case scAddRecExpr:
4074 case scUMaxExpr:
4075 case scSMaxExpr:
4076 case scUMinExpr:
4077 case scSMinExpr:
4078 case scUnknown:
4079 // If any operand is poison, the whole expression is poison.
4080 return true;
4081 case scSequentialUMinExpr:
4082 // FIXME: if the *first* operand is poison, the whole expression is poison.
4083 return false; // Pessimistically, say that it does not propagate poison.
4084 case scCouldNotCompute:
4085 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4086 }
4087 llvm_unreachable("Unknown SCEV kind!");
4088}
4089
4090namespace {
4091// The only way poison may be introduced in a SCEV expression is from a
4092// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4093// not SCEVConstant). Notably, SCEVFlags on SCEV nodes can *not*
4094// introduce poison -- they encode guaranteed, non-speculated knowledge.
4095//
4096// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4097// with the notable exception of umin_seq, where only poison from the first
4098// operand is (unconditionally) propagated.
4099struct SCEVPoisonCollector {
4100 bool LookThroughMaybePoisonBlocking;
4101 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4102 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4103 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4104
4105 bool follow(const SCEV *S) {
4106 if (!LookThroughMaybePoisonBlocking &&
4107 !scevUnconditionallyPropagatesPoisonFromOperands(Kind: S->getSCEVType()))
4108 return false;
4109
4110 if (auto *SU = dyn_cast<SCEVUnknown>(Val: S)) {
4111 if (!isGuaranteedNotToBePoison(V: SU->getValue()))
4112 MaybePoison.insert(Ptr: SU);
4113 }
4114 return true;
4115 }
4116 bool isDone() const { return false; }
4117};
4118} // namespace
4119
4120/// Return true if V is poison given that AssumedPoison is already poison.
4121static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4122 // First collect all SCEVs that might result in AssumedPoison to be poison.
4123 // We need to look through potentially poison-blocking operations here,
4124 // because we want to find all SCEVs that *might* result in poison, not only
4125 // those that are *required* to.
4126 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4127 visitAll(Root: AssumedPoison, Visitor&: PC1);
4128
4129 // AssumedPoison is never poison. As the assumption is false, the implication
4130 // is true. Don't bother walking the other SCEV in this case.
4131 if (PC1.MaybePoison.empty())
4132 return true;
4133
4134 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4135 // as well. We cannot look through potentially poison-blocking operations
4136 // here, as their arguments only *may* make the result poison.
4137 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4138 visitAll(Root: S, Visitor&: PC2);
4139
4140 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4141 // it will also make S poison by being part of PC2.MaybePoison.
4142 return llvm::set_is_subset(S1: PC1.MaybePoison, S2: PC2.MaybePoison);
4143}
4144
4145void ScalarEvolution::getPoisonGeneratingValues(
4146 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4147 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4148 visitAll(Root: S, Visitor&: PC);
4149 for (const SCEVUnknown *SU : PC.MaybePoison)
4150 Result.insert(Ptr: SU->getValue());
4151}
4152
4153bool ScalarEvolution::canReuseInstruction(
4154 const SCEV *S, Instruction *I,
4155 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4156 // If the instruction cannot be poison, it's always safe to reuse.
4157 if (programUndefinedIfPoison(Inst: I))
4158 return true;
4159
4160 // Otherwise, it is possible that I is more poisonous that S. Collect the
4161 // poison-contributors of S, and then check whether I has any additional
4162 // poison-contributors. Poison that is contributed through poison-generating
4163 // flags is handled by dropping those flags instead.
4164 SmallPtrSet<const Value *, 8> PoisonVals;
4165 getPoisonGeneratingValues(Result&: PoisonVals, S);
4166
4167 SmallVector<Value *> Worklist;
4168 SmallPtrSet<Value *, 8> Visited;
4169 Worklist.push_back(Elt: I);
4170 unsigned NumVisitedInsts = 0;
4171 const unsigned InstLimit = std::max<unsigned>(a: 16, b: S->getExpressionSize());
4172 while (!Worklist.empty()) {
4173 Value *V = Worklist.pop_back_val();
4174 if (!Visited.insert(Ptr: V).second)
4175 continue;
4176
4177 // Either the value can't be poison, or the S would also be poison if it
4178 // is.
4179 if (PoisonVals.contains(Ptr: V) || ::isGuaranteedNotToBePoison(V))
4180 continue;
4181
4182 // Avoid walking large instruction graphs.
4183 if (++NumVisitedInsts > InstLimit)
4184 return false;
4185
4186 auto *I = dyn_cast<Instruction>(Val: V);
4187 if (!I)
4188 return false;
4189
4190 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4191 // can't replace an arbitrary add with disjoint or, even if we drop the
4192 // flag. We would need to convert the or into an add.
4193 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(Val: I))
4194 if (PDI->isDisjoint())
4195 return false;
4196
4197 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4198 // because SCEV currently assumes it can't be poison. Remove this special
4199 // case once we proper model when vscale can be poison.
4200 if (auto *II = dyn_cast<IntrinsicInst>(Val: I);
4201 II && II->getIntrinsicID() == Intrinsic::vscale)
4202 continue;
4203
4204 if (canCreatePoison(Op: cast<Operator>(Val: I), /*ConsiderFlagsAndMetadata*/ false))
4205 return false;
4206
4207 // If the instruction can't create poison, we can recurse to its operands.
4208 if (I->hasPoisonGeneratingAnnotations())
4209 DropPoisonGeneratingInsts.push_back(Elt: I);
4210
4211 llvm::append_range(C&: Worklist, R: I->operands());
4212 }
4213 return true;
4214}
4215
4216const SCEV *
4217ScalarEvolution::getSequentialMinMaxExpr(SCEVTypes Kind,
4218 SmallVectorImpl<SCEVUse> &Ops) {
4219 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4220 "Not a SCEVSequentialMinMaxExpr!");
4221 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4222 if (Ops.size() == 1)
4223 return Ops[0];
4224#ifndef NDEBUG
4225 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4226 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4227 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4228 "Operand types don't match!");
4229 assert(Ops[0]->getType()->isPointerTy() ==
4230 Ops[i]->getType()->isPointerTy() &&
4231 "min/max should be consistently pointerish");
4232 }
4233#endif
4234
4235 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4236 // so we can *NOT* do any kind of sorting of the expressions!
4237
4238 // Check if we have created the same expression before.
4239 if (const SCEV *S = findExistingSCEVInCache(SCEVType: Kind, Ops))
4240 return S;
4241
4242 // FIXME: there are *some* simplifications that we can do here.
4243
4244 // Keep only the first instance of an operand.
4245 {
4246 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4247 bool Changed = Deduplicator.visit(Kind, OrigOps: Ops, NewOps&: Ops);
4248 if (Changed)
4249 return getSequentialMinMaxExpr(Kind, Ops);
4250 }
4251
4252 // Check to see if one of the operands is of the same kind. If so, expand its
4253 // operands onto our operand list, and recurse to simplify.
4254 {
4255 unsigned Idx = 0;
4256 bool DeletedAny = false;
4257 while (Idx < Ops.size()) {
4258 if (Ops[Idx]->getSCEVType() != Kind) {
4259 ++Idx;
4260 continue;
4261 }
4262 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Val&: Ops[Idx]);
4263 Ops.erase(CI: Ops.begin() + Idx);
4264 Ops.insert(I: Ops.begin() + Idx, From: SMME->operands().begin(),
4265 To: SMME->operands().end());
4266 DeletedAny = true;
4267 }
4268
4269 if (DeletedAny)
4270 return getSequentialMinMaxExpr(Kind, Ops);
4271 }
4272
4273 const SCEV *SaturationPoint;
4274 ICmpInst::Predicate Pred;
4275 switch (Kind) {
4276 case scSequentialUMinExpr:
4277 SaturationPoint = getZero(Ty: Ops[0]->getType());
4278 Pred = ICmpInst::ICMP_ULE;
4279 break;
4280 default:
4281 llvm_unreachable("Not a sequential min/max type.");
4282 }
4283
4284 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4285 if (!isGuaranteedNotToCauseUB(Op: Ops[i]))
4286 continue;
4287 // We can replace %x umin_seq %y with %x umin %y if either:
4288 // * %y being poison implies %x is also poison.
4289 // * %x cannot be the saturating value (e.g. zero for umin).
4290 if (::impliesPoison(AssumedPoison: Ops[i], S: Ops[i - 1]) ||
4291 isKnownViaNonRecursiveReasoning(Pred: ICmpInst::ICMP_NE, LHS: Ops[i - 1],
4292 RHS: SaturationPoint)) {
4293 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4294 Ops[i - 1] = getMinMaxExpr(
4295 Kind: SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Ty: Kind),
4296 Ops&: SeqOps);
4297 Ops.erase(CI: Ops.begin() + i);
4298 return getSequentialMinMaxExpr(Kind, Ops);
4299 }
4300 // Fold %x umin_seq %y to %x if %x ule %y.
4301 // TODO: We might be able to prove the predicate for a later operand.
4302 if (isKnownViaNonRecursiveReasoning(Pred, LHS: Ops[i - 1], RHS: Ops[i])) {
4303 Ops.erase(CI: Ops.begin() + i);
4304 return getSequentialMinMaxExpr(Kind, Ops);
4305 }
4306 }
4307
4308 // Okay, it looks like we really DO need an expr. Check to see if we
4309 // already have one, otherwise create a new one.
4310 FoldingSetNodeID ID;
4311 ID.AddInteger(I: Kind);
4312 for (SCEVUse Op : Ops)
4313 ID.AddPointer(Ptr: Op.getOpaqueValue());
4314 FoldingSetInsertToken Token;
4315 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
4316 if (ExistingSCEV)
4317 return ExistingSCEV;
4318
4319 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Num: Ops.size());
4320 llvm::uninitialized_copy(Src&: Ops, Dst: O);
4321 SCEV *S = new (SCEVAllocator)
4322 SCEVSequentialMinMaxExpr(ID.Intern(Allocator&: SCEVAllocator), Kind, O, Ops.size());
4323
4324 UniqueSCEVs.insert(N: S, Token);
4325 S->computeAndSetCanonical(SE&: *this);
4326 registerUser(User: S, Ops);
4327 return S;
4328}
4329
4330const SCEV *ScalarEvolution::getSMaxExpr(SCEVUse LHS, SCEVUse RHS) {
4331 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4332 return getMinMaxExpr(Kind: scSMaxExpr, Ops);
4333}
4334
4335const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<SCEVUse> &Ops) {
4336 return getMinMaxExpr(Kind: scSMaxExpr, Ops);
4337}
4338
4339const SCEV *ScalarEvolution::getUMaxExpr(SCEVUse LHS, SCEVUse RHS) {
4340 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4341 return getMinMaxExpr(Kind: scUMaxExpr, Ops);
4342}
4343
4344const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<SCEVUse> &Ops) {
4345 return getMinMaxExpr(Kind: scUMaxExpr, Ops);
4346}
4347
4348const SCEV *ScalarEvolution::getSMinExpr(SCEVUse LHS, SCEVUse RHS) {
4349 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4350 return getMinMaxExpr(Kind: scSMinExpr, Ops);
4351}
4352
4353const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<SCEVUse> &Ops) {
4354 return getMinMaxExpr(Kind: scSMinExpr, Ops);
4355}
4356
4357const SCEV *ScalarEvolution::getUMinExpr(SCEVUse LHS, SCEVUse RHS,
4358 bool Sequential) {
4359 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4360 return getUMinExpr(Operands&: Ops, Sequential);
4361}
4362
4363const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<SCEVUse> &Ops,
4364 bool Sequential) {
4365 return Sequential ? getSequentialMinMaxExpr(Kind: scSequentialUMinExpr, Ops)
4366 : getMinMaxExpr(Kind: scUMinExpr, Ops);
4367}
4368
4369const SCEV *
4370ScalarEvolution::getSizeOfExpr(Type *IntTy, TypeSize Size) {
4371 const SCEV *Res = getConstant(Ty: IntTy, V: Size.getKnownMinValue());
4372 if (Size.isScalable())
4373 Res = getMulExpr(LHS: Res, RHS: getVScale(Ty: IntTy));
4374 return Res;
4375}
4376
4377const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
4378 return getSizeOfExpr(IntTy, Size: getDataLayout().getTypeAllocSize(Ty: AllocTy));
4379}
4380
4381const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
4382 return getSizeOfExpr(IntTy, Size: getDataLayout().getTypeStoreSize(Ty: StoreTy));
4383}
4384
4385const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
4386 StructType *STy,
4387 unsigned FieldNo) {
4388 // We can bypass creating a target-independent constant expression and then
4389 // folding it back into a ConstantInt. This is just a compile-time
4390 // optimization.
4391 const StructLayout *SL = getDataLayout().getStructLayout(Ty: STy);
4392 assert(!SL->getSizeInBits().isScalable() &&
4393 "Cannot get offset for structure containing scalable vector types");
4394 return getConstant(Ty: IntTy, V: SL->getElementOffset(Idx: FieldNo));
4395}
4396
4397const SCEV *ScalarEvolution::getUnknown(Value *V) {
4398 // Don't attempt to do anything other than create a SCEVUnknown object
4399 // here. createSCEV only calls getUnknown after checking for all other
4400 // interesting possibilities, and any other code that calls getUnknown
4401 // is doing so in order to hide a value from SCEV canonicalization.
4402
4403 FoldingSetNodeID ID;
4404 ID.AddInteger(I: scUnknown);
4405 ID.AddPointer(Ptr: V);
4406 FoldingSetInsertToken Token;
4407 if (SCEV *S = UniqueSCEVs.lookup(ID, Token)) {
4408 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4409 "Stale SCEVUnknown in uniquing map!");
4410 return S;
4411 }
4412 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(Allocator&: SCEVAllocator), V, this,
4413 FirstUnknown, NextUnknownOrderID++);
4414 FirstUnknown = cast<SCEVUnknown>(Val: S);
4415 UniqueSCEVs.insert(N: S, Token);
4416 S->computeAndSetCanonical(SE&: *this);
4417 return S;
4418}
4419
4420//===----------------------------------------------------------------------===//
4421// Basic SCEV Analysis and PHI Idiom Recognition Code
4422//
4423
4424/// Test if values of the given type are analyzable within the SCEV
4425/// framework. This primarily includes integer types, and it can optionally
4426/// include pointer types if the ScalarEvolution class has access to
4427/// target-specific information.
4428bool ScalarEvolution::isSCEVable(Type *Ty) const {
4429 // Integers and pointers are always SCEVable.
4430 return Ty->isIntOrPtrTy();
4431}
4432
4433/// Return the size in bits of the specified type, for which isSCEVable must
4434/// return true.
4435uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
4436 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4437 if (Ty->isPointerTy())
4438 return getDataLayout().getIndexTypeSizeInBits(Ty);
4439 return getDataLayout().getTypeSizeInBits(Ty);
4440}
4441
4442/// Return a type with the same bitwidth as the given type and which represents
4443/// how SCEV will treat the given type, for which isSCEVable must return
4444/// true. For pointer types, this is the pointer index sized integer type.
4445Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
4446 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4447
4448 if (Ty->isIntegerTy())
4449 return Ty;
4450
4451 // The only other support type is pointer.
4452 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4453 return getDataLayout().getIndexType(PtrTy: Ty);
4454}
4455
4456Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
4457 return getTypeSizeInBits(Ty: T1) >= getTypeSizeInBits(Ty: T2) ? T1 : T2;
4458}
4459
4460bool ScalarEvolution::instructionCouldExistWithOperands(const SCEV *A,
4461 const SCEV *B) {
4462 /// For a valid use point to exist, the defining scope of one operand
4463 /// must dominate the other.
4464 bool PreciseA, PreciseB;
4465 auto *ScopeA = getDefiningScopeBound(Ops: {A}, Precise&: PreciseA);
4466 auto *ScopeB = getDefiningScopeBound(Ops: {B}, Precise&: PreciseB);
4467 if (!PreciseA || !PreciseB)
4468 // Can't tell.
4469 return false;
4470 return (ScopeA == ScopeB) || DT.dominates(Def: ScopeA, User: ScopeB) ||
4471 DT.dominates(Def: ScopeB, User: ScopeA);
4472}
4473
4474const SCEV *ScalarEvolution::getCouldNotCompute() {
4475 return CouldNotCompute.get();
4476}
4477
4478bool ScalarEvolution::checkValidity(const SCEV *S) const {
4479 bool ContainsNulls = SCEVExprContains(Root: S, Pred: [](const SCEV *S) {
4480 auto *SU = dyn_cast<SCEVUnknown>(Val: S);
4481 return SU && SU->getValue() == nullptr;
4482 });
4483
4484 return !ContainsNulls;
4485}
4486
4487bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
4488 HasRecMapType::iterator I = HasRecMap.find(Val: S);
4489 if (I != HasRecMap.end())
4490 return I->second;
4491
4492 bool FoundAddRec =
4493 SCEVExprContains(Root: S, Pred: [](const SCEV *S) { return isa<SCEVAddRecExpr>(Val: S); });
4494 HasRecMap.insert(KV: {S, FoundAddRec});
4495 return FoundAddRec;
4496}
4497
4498/// Return the ValueOffsetPair set for \p S. \p S can be represented
4499/// by the value and offset from any ValueOffsetPair in the set.
4500ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4501 ExprValueMapType::iterator SI = ExprValueMap.find_as(Val: S);
4502 if (SI == ExprValueMap.end())
4503 return {};
4504 return SI->second.getArrayRef();
4505}
4506
4507/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4508/// cannot be used separately. eraseValueFromMap should be used to remove
4509/// V from ValueExprMap and ExprValueMap at the same time.
4510void ScalarEvolution::eraseValueFromMap(Value *V) {
4511 ValueExprMapType::iterator I = ValueExprMap.find_as(Val: V);
4512 if (I != ValueExprMap.end()) {
4513 auto EVIt = ExprValueMap.find(Val: I->second);
4514 bool Removed = EVIt->second.remove(X: V);
4515 (void) Removed;
4516 assert(Removed && "Value not in ExprValueMap?");
4517 ValueExprMap.erase(I);
4518 }
4519}
4520
4521void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4522 // A recursive query may have already computed the SCEV. It should be
4523 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4524 // inferred nowrap flags.
4525 auto It = ValueExprMap.find_as(Val: V);
4526 if (It == ValueExprMap.end()) {
4527 ValueExprMap.insert(KV: {SCEVCallbackVH(V, this), S});
4528 ExprValueMap[S].insert(X: V);
4529 }
4530}
4531
4532/// Return an existing SCEV if it exists, otherwise analyze the expression and
4533/// create a new one.
4534const SCEV *ScalarEvolution::getSCEV(Value *V) {
4535 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4536
4537 if (const SCEV *S = getExistingSCEV(V))
4538 return S;
4539 return createSCEVIter(V);
4540}
4541
4542const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
4543 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4544
4545 ValueExprMapType::iterator I = ValueExprMap.find_as(Val: V);
4546 if (I != ValueExprMap.end()) {
4547 const SCEV *S = I->second;
4548 assert(checkValidity(S) &&
4549 "existing SCEV has not been properly invalidated");
4550 return S;
4551 }
4552 return nullptr;
4553}
4554
4555/// Return a SCEV corresponding to -V = -1*V
4556const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, SCEVFlags Flags) {
4557 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(Val: V))
4558 return getConstant(
4559 V: cast<ConstantInt>(Val: ConstantExpr::getNeg(C: VC->getValue())));
4560
4561 Type *Ty = V->getType();
4562 Ty = getEffectiveSCEVType(Ty);
4563 return getMulExpr(LHS: V, RHS: getMinusOne(Ty), Flags);
4564}
4565
4566/// If Expr computes ~A, return A else return nullptr
4567static const SCEV *MatchNotExpr(const SCEV *Expr) {
4568 const SCEV *MulOp;
4569 if (match(S: Expr, P: m_scev_Add(Op0: m_scev_AllOnes(),
4570 Op1: m_scev_Mul(Op0: m_scev_AllOnes(), Op1: m_SCEV(V&: MulOp)))))
4571 return MulOp;
4572 return nullptr;
4573}
4574
4575/// Return a SCEV corresponding to ~V = -1-V
4576const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
4577 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4578
4579 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(Val: V))
4580 return getConstant(
4581 V: cast<ConstantInt>(Val: ConstantExpr::getNot(C: VC->getValue())));
4582
4583 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4584 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(Val: V)) {
4585 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4586 SmallVector<SCEVUse, 2> MatchedOperands;
4587 for (const SCEV *Operand : MME->operands()) {
4588 const SCEV *Matched = MatchNotExpr(Expr: Operand);
4589 if (!Matched)
4590 return (const SCEV *)nullptr;
4591 MatchedOperands.push_back(Elt: Matched);
4592 }
4593 return getMinMaxExpr(Kind: SCEVMinMaxExpr::negate(T: MME->getSCEVType()),
4594 Ops&: MatchedOperands);
4595 };
4596 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4597 return Replaced;
4598 }
4599
4600 Type *Ty = V->getType();
4601 Ty = getEffectiveSCEVType(Ty);
4602 return getMinusSCEV(LHS: getMinusOne(Ty), RHS: V);
4603}
4604
4605const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) {
4606 assert(P->getType()->isPointerTy());
4607
4608 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Val: P)) {
4609 // The base of an AddRec is the first operand.
4610 SmallVector<SCEVUse> Ops{AddRec->operands()};
4611 Ops[0] = removePointerBase(P: Ops[0]);
4612 // Don't try to transfer nowrap flags for now. We could in some cases
4613 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4614 return getAddRecExpr(Operands&: Ops, L: AddRec->getLoop(), NWFlags: SCEV::FlagNone);
4615 }
4616 if (auto *Add = dyn_cast<SCEVAddExpr>(Val: P)) {
4617 // The base of an Add is the pointer operand.
4618 SmallVector<SCEVUse> Ops{Add->operands()};
4619 SCEVUse *PtrOp = nullptr;
4620 for (SCEVUse &AddOp : Ops) {
4621 if (AddOp->getType()->isPointerTy()) {
4622 assert(!PtrOp && "Cannot have multiple pointer ops");
4623 PtrOp = &AddOp;
4624 }
4625 }
4626 *PtrOp = removePointerBase(P: *PtrOp);
4627 // Don't try to transfer nowrap flags for now. We could in some cases
4628 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4629 return getAddExpr(Ops);
4630 }
4631 // Any other expression must be a pointer base.
4632 return getZero(Ty: P->getType());
4633}
4634
4635const SCEV *ScalarEvolution::getMinusSCEV(SCEVUse LHS, SCEVUse RHS,
4636 SCEVFlags Flags, unsigned Depth) {
4637 // Fast path: X - X --> 0.
4638 if (SCEVUse::getCommon(A: LHS, B: RHS))
4639 return getZero(Ty: LHS->getType());
4640
4641 // If we subtract two pointers with different pointer bases, bail.
4642 // Eventually, we're going to add an assertion to getMulExpr that we
4643 // can't multiply by a pointer.
4644 if (RHS->getType()->isPointerTy()) {
4645 if (!LHS->getType()->isPointerTy() ||
4646 getPointerBase(V: LHS) != getPointerBase(V: RHS))
4647 return getCouldNotCompute();
4648 LHS = removePointerBase(P: LHS);
4649 RHS = removePointerBase(P: RHS);
4650 }
4651
4652 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4653 // makes it so that we cannot make much use of NUW.
4654 auto AddFlags = SCEV::FlagNone;
4655 const bool RHSIsNotMinSigned =
4656 !getSignedRangeMin(S: RHS).isMinSignedValue();
4657 if (hasFlags(Flags, TestFlags: SCEV::FlagNSW)) {
4658 // Let M be the minimum representable signed value. Then (-1)*RHS
4659 // signed-wraps if and only if RHS is M. That can happen even for
4660 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4661 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4662 // (-1)*RHS, we need to prove that RHS != M.
4663 //
4664 // If LHS is non-negative and we know that LHS - RHS does not
4665 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4666 // either by proving that RHS > M or that LHS >= 0.
4667 if (RHSIsNotMinSigned || isKnownNonNegative(S: LHS)) {
4668 AddFlags = SCEV::FlagNSW;
4669 }
4670 }
4671
4672 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4673 // RHS is NSW and LHS >= 0.
4674 //
4675 // The difficulty here is that the NSW flag may have been proven
4676 // relative to a loop that is to be found in a recurrence in LHS and
4677 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4678 // larger scope than intended.
4679 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagNone;
4680
4681 return getAddExpr(LHS, RHS: getNegativeSCEV(V: RHS, Flags: NegFlags), Flags: AddFlags, Depth);
4682}
4683
4684const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4685 unsigned Depth) {
4686 Type *SrcTy = V->getType();
4687 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4688 "Cannot truncate or zero extend with non-integer arguments!");
4689 if (getTypeSizeInBits(Ty: SrcTy) == getTypeSizeInBits(Ty))
4690 return V; // No conversion
4691 if (getTypeSizeInBits(Ty: SrcTy) > getTypeSizeInBits(Ty))
4692 return getTruncateExpr(Op: V, Ty, Depth);
4693 return getZeroExtendExpr(Op: V, Ty, Depth);
4694}
4695
4696const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4697 unsigned Depth) {
4698 Type *SrcTy = V->getType();
4699 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4700 "Cannot truncate or zero extend with non-integer arguments!");
4701 if (getTypeSizeInBits(Ty: SrcTy) == getTypeSizeInBits(Ty))
4702 return V; // No conversion
4703 if (getTypeSizeInBits(Ty: SrcTy) > getTypeSizeInBits(Ty))
4704 return getTruncateExpr(Op: V, Ty, Depth);
4705 return getSignExtendExpr(Op: V, Ty, Depth);
4706}
4707
4708const SCEV *ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4709 Type *SrcTy = V->getType();
4710 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4711 "Cannot noop or zero extend with non-integer arguments!");
4712 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4713 "getNoopOrZeroExtend cannot truncate!");
4714 if (getTypeSizeInBits(Ty: SrcTy) == getTypeSizeInBits(Ty))
4715 return V; // No conversion
4716 return getZeroExtendExpr(Op: V, Ty);
4717}
4718
4719const SCEV *ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4720 Type *SrcTy = V->getType();
4721 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4722 "Cannot noop or sign extend with non-integer arguments!");
4723 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4724 "getNoopOrSignExtend cannot truncate!");
4725 if (getTypeSizeInBits(Ty: SrcTy) == getTypeSizeInBits(Ty))
4726 return V; // No conversion
4727 return getSignExtendExpr(Op: V, Ty);
4728}
4729
4730const SCEV *ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4731 Type *SrcTy = V->getType();
4732 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4733 "Cannot noop or any extend with non-integer arguments!");
4734 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4735 "getNoopOrAnyExtend cannot truncate!");
4736 if (getTypeSizeInBits(Ty: SrcTy) == getTypeSizeInBits(Ty))
4737 return V; // No conversion
4738 return getAnyExtendExpr(Op: V, Ty);
4739}
4740
4741const SCEV *ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4742 Type *SrcTy = V->getType();
4743 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4744 "Cannot truncate or noop with non-integer arguments!");
4745 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4746 "getTruncateOrNoop cannot extend!");
4747 if (getTypeSizeInBits(Ty: SrcTy) == getTypeSizeInBits(Ty))
4748 return V; // No conversion
4749 return getTruncateExpr(Op: V, Ty);
4750}
4751
4752const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4753 const SCEV *RHS) {
4754 const SCEV *PromotedLHS = LHS;
4755 const SCEV *PromotedRHS = RHS;
4756
4757 if (getTypeSizeInBits(Ty: LHS->getType()) > getTypeSizeInBits(Ty: RHS->getType()))
4758 PromotedRHS = getZeroExtendExpr(Op: RHS, Ty: LHS->getType());
4759 else
4760 PromotedLHS = getNoopOrZeroExtend(V: LHS, Ty: RHS->getType());
4761
4762 return getUMaxExpr(LHS: PromotedLHS, RHS: PromotedRHS);
4763}
4764
4765const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4766 const SCEV *RHS,
4767 bool Sequential) {
4768 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4769 return getUMinFromMismatchedTypes(Ops, Sequential);
4770}
4771
4772const SCEV *
4773ScalarEvolution::getUMinFromMismatchedTypes(SmallVectorImpl<SCEVUse> &Ops,
4774 bool Sequential) {
4775 assert(!Ops.empty() && "At least one operand must be!");
4776 // Trivial case.
4777 if (Ops.size() == 1)
4778 return Ops[0];
4779
4780 // Find the max type first.
4781 Type *MaxType = nullptr;
4782 for (SCEVUse S : Ops)
4783 if (MaxType)
4784 MaxType = getWiderType(T1: MaxType, T2: S->getType());
4785 else
4786 MaxType = S->getType();
4787 assert(MaxType && "Failed to find maximum type!");
4788
4789 // Extend all ops to max type.
4790 SmallVector<SCEVUse, 2> PromotedOps;
4791 for (SCEVUse S : Ops)
4792 PromotedOps.push_back(Elt: getNoopOrZeroExtend(V: S, Ty: MaxType));
4793
4794 // Generate umin.
4795 return getUMinExpr(Ops&: PromotedOps, Sequential);
4796}
4797
4798const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4799 // A pointer operand may evaluate to a nonpointer expression, such as null.
4800 if (!V->getType()->isPointerTy())
4801 return V;
4802
4803 while (true) {
4804 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Val: V)) {
4805 V = AddRec->getStart();
4806 } else if (auto *Add = dyn_cast<SCEVAddExpr>(Val: V)) {
4807 const SCEV *PtrOp = nullptr;
4808 for (const SCEV *AddOp : Add->operands()) {
4809 if (AddOp->getType()->isPointerTy()) {
4810 assert(!PtrOp && "Cannot have multiple pointer ops");
4811 PtrOp = AddOp;
4812 }
4813 }
4814 assert(PtrOp && "Must have pointer op");
4815 V = PtrOp;
4816 } else // Not something we can look further into.
4817 return V;
4818 }
4819}
4820
4821/// Push users of the given Instruction onto the given Worklist.
4822static void PushDefUseChildren(Instruction *I,
4823 SmallVectorImpl<Instruction *> &Worklist,
4824 SmallPtrSetImpl<Instruction *> &Visited) {
4825 // Push the def-use children onto the Worklist stack.
4826 for (User *U : I->users()) {
4827 auto *UserInsn = cast<Instruction>(Val: U);
4828 if (Visited.insert(Ptr: UserInsn).second)
4829 Worklist.push_back(Elt: UserInsn);
4830 }
4831}
4832
4833namespace {
4834
4835/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4836/// expression in case its Loop is L. If it is not L then
4837/// if IgnoreOtherLoops is true then use AddRec itself
4838/// otherwise rewrite cannot be done.
4839/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4840class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4841public:
4842 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4843 bool IgnoreOtherLoops = true) {
4844 SCEVInitRewriter Rewriter(L, SE);
4845 const SCEV *Result = Rewriter.visit(S);
4846 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4847 return SE.getCouldNotCompute();
4848 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4849 ? SE.getCouldNotCompute()
4850 : Result;
4851 }
4852
4853 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4854 if (!SE.isLoopInvariant(S: Expr, L))
4855 SeenLoopVariantSCEVUnknown = true;
4856 return Expr;
4857 }
4858
4859 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4860 // Only re-write AddRecExprs for this loop.
4861 if (Expr->getLoop() == L)
4862 return Expr->getStart();
4863 SeenOtherLoops = true;
4864 return Expr;
4865 }
4866
4867 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4868
4869 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4870
4871private:
4872 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4873 : SCEVRewriteVisitor(SE), L(L) {}
4874
4875 const Loop *L;
4876 bool SeenLoopVariantSCEVUnknown = false;
4877 bool SeenOtherLoops = false;
4878};
4879
4880/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4881/// increment expression in case its Loop is L. If it is not L then
4882/// use AddRec itself.
4883/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4884class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4885public:
4886 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4887 SCEVPostIncRewriter Rewriter(L, SE);
4888 const SCEV *Result = Rewriter.visit(S);
4889 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4890 ? SE.getCouldNotCompute()
4891 : Result;
4892 }
4893
4894 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4895 if (!SE.isLoopInvariant(S: Expr, L))
4896 SeenLoopVariantSCEVUnknown = true;
4897 return Expr;
4898 }
4899
4900 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4901 // Only re-write AddRecExprs for this loop.
4902 if (Expr->getLoop() == L)
4903 return Expr->getPostIncExpr(SE);
4904 SeenOtherLoops = true;
4905 return Expr;
4906 }
4907
4908 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4909
4910 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4911
4912private:
4913 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4914 : SCEVRewriteVisitor(SE), L(L) {}
4915
4916 const Loop *L;
4917 bool SeenLoopVariantSCEVUnknown = false;
4918 bool SeenOtherLoops = false;
4919};
4920
4921/// This class evaluates the compare condition by matching it against the
4922/// condition of loop latch. If there is a match we assume a true value
4923/// for the condition while building SCEV nodes.
4924class SCEVBackedgeConditionFolder
4925 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4926public:
4927 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4928 ScalarEvolution &SE) {
4929 bool IsPosBECond = false;
4930 Value *BECond = nullptr;
4931 if (BasicBlock *Latch = L->getLoopLatch()) {
4932 if (CondBrInst *BI = dyn_cast<CondBrInst>(Val: Latch->getTerminator())) {
4933 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4934 "Both outgoing branches should not target same header!");
4935 BECond = BI->getCondition();
4936 IsPosBECond = BI->getSuccessor(i: 0) == L->getHeader();
4937 } else {
4938 return S;
4939 }
4940 }
4941 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4942 return Rewriter.visit(S);
4943 }
4944
4945 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4946 const SCEV *Result = Expr;
4947 bool InvariantF = SE.isLoopInvariant(S: Expr, L);
4948
4949 if (!InvariantF) {
4950 Instruction *I = cast<Instruction>(Val: Expr->getValue());
4951 switch (I->getOpcode()) {
4952 case Instruction::Select: {
4953 SelectInst *SI = cast<SelectInst>(Val: I);
4954 std::optional<const SCEV *> Res =
4955 compareWithBackedgeCondition(IC: SI->getCondition());
4956 if (Res) {
4957 bool IsOne = cast<SCEVConstant>(Val: *Res)->getValue()->isOne();
4958 Result = SE.getSCEV(V: IsOne ? SI->getTrueValue() : SI->getFalseValue());
4959 }
4960 break;
4961 }
4962 default: {
4963 std::optional<const SCEV *> Res = compareWithBackedgeCondition(IC: I);
4964 if (Res)
4965 Result = *Res;
4966 break;
4967 }
4968 }
4969 }
4970 return Result;
4971 }
4972
4973private:
4974 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4975 bool IsPosBECond, ScalarEvolution &SE)
4976 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4977 IsPositiveBECond(IsPosBECond) {}
4978
4979 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4980
4981 const Loop *L;
4982 /// Loop back condition.
4983 Value *BackedgeCond = nullptr;
4984 /// Set to true if loop back is on positive branch condition.
4985 bool IsPositiveBECond;
4986};
4987
4988std::optional<const SCEV *>
4989SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4990
4991 // If value matches the backedge condition for loop latch,
4992 // then return a constant evolution node based on loopback
4993 // branch taken.
4994 if (BackedgeCond == IC)
4995 return IsPositiveBECond ? SE.getOne(Ty: Type::getInt1Ty(C&: SE.getContext()))
4996 : SE.getZero(Ty: Type::getInt1Ty(C&: SE.getContext()));
4997 return std::nullopt;
4998}
4999
5000class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
5001public:
5002 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5003 ScalarEvolution &SE) {
5004 SCEVShiftRewriter Rewriter(L, SE);
5005 const SCEV *Result = Rewriter.visit(S);
5006 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
5007 }
5008
5009 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5010 // Only allow AddRecExprs for this loop.
5011 if (!SE.isLoopInvariant(S: Expr, L))
5012 Valid = false;
5013 return Expr;
5014 }
5015
5016 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5017 if (Expr->getLoop() == L && Expr->isAffine())
5018 return SE.getMinusSCEV(LHS: Expr, RHS: Expr->getStepRecurrence(SE));
5019 Valid = false;
5020 return Expr;
5021 }
5022
5023 bool isValid() { return Valid; }
5024
5025private:
5026 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5027 : SCEVRewriteVisitor(SE), L(L) {}
5028
5029 const Loop *L;
5030 bool Valid = true;
5031};
5032
5033} // end anonymous namespace
5034
5035void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5036 if (!AR->isAffine())
5037 return;
5038
5039 // Force computation of ranges, which will also perform range-based flag
5040 // inference.
5041 if (!AR->hasNoSignedWrap())
5042 (void)getSignedRange(S: AR);
5043
5044 if (!AR->hasNoUnsignedWrap())
5045 (void)getUnsignedRange(S: AR);
5046
5047 if (!AR->hasNoSelfWrap()) {
5048 const SCEV *BECount = getConstantMaxBackedgeTakenCount(L: AR->getLoop());
5049 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(Val: BECount)) {
5050 ConstantRange StepCR = getSignedRange(S: AR->getStepRecurrence(SE&: *this));
5051 const APInt &BECountAP = BECountMax->getAPInt();
5052 unsigned NoOverflowBitWidth =
5053 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5054 if (NoOverflowBitWidth <= getTypeSizeInBits(Ty: AR->getType()))
5055 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
5056 }
5057 }
5058}
5059
5060SCEVFlags
5061ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5062 SCEVFlags Result = AR->getNoWrapFlags();
5063
5064 if (AR->hasNoSignedWrap())
5065 return Result;
5066
5067 if (!AR->isAffine())
5068 return Result;
5069
5070 // This function can be expensive, only try to prove NSW once per AddRec.
5071 if (!SignedWrapViaInductionTried.insert(Ptr: AR).second)
5072 return Result;
5073
5074 const SCEV *Step = AR->getStepRecurrence(SE&: *this);
5075 const Loop *L = AR->getLoop();
5076
5077 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5078 // Note that this serves two purposes: It filters out loops that are
5079 // simply not analyzable, and it covers the case where this code is
5080 // being called from within backedge-taken count analysis, such that
5081 // attempting to ask for the backedge-taken count would likely result
5082 // in infinite recursion. In the later case, the analysis code will
5083 // cope with a conservative value, and it will take care to purge
5084 // that value once it has finished.
5085 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5086
5087 // Normally, in the cases we can prove no-overflow via a
5088 // backedge guarding condition, we can also compute a backedge
5089 // taken count for the loop. The exceptions are assumptions and
5090 // guards present in the loop -- SCEV is not great at exploiting
5091 // these to compute max backedge taken counts, but can still use
5092 // these to prove lack of overflow. Use this fact to avoid
5093 // doing extra work that may not pay off.
5094
5095 if (isa<SCEVCouldNotCompute>(Val: MaxBECount) && !HasGuards &&
5096 AC.assumptions().empty())
5097 return Result;
5098
5099 // If the backedge is guarded by a comparison with the pre-inc value the
5100 // addrec is safe. Also, if the entry is guarded by a comparison with the
5101 // start value and the backedge is guarded by a comparison with the post-inc
5102 // value, the addrec is safe.
5103 ICmpInst::Predicate Pred;
5104 const SCEV *OverflowLimit =
5105 getSignedOverflowLimitForStep(Step, Pred: &Pred, SE: this);
5106 if (OverflowLimit &&
5107 (isLoopBackedgeGuardedByCond(L, Pred, LHS: AR, RHS: OverflowLimit) ||
5108 isKnownOnEveryIteration(Pred, LHS: AR, RHS: OverflowLimit))) {
5109 Result = setFlags(Flags: Result, OnFlags: SCEV::FlagNSW);
5110 }
5111 return Result;
5112}
5113SCEVFlags
5114ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5115 SCEVFlags Result = AR->getNoWrapFlags();
5116
5117 if (AR->hasNoUnsignedWrap())
5118 return Result;
5119
5120 if (!AR->isAffine())
5121 return Result;
5122
5123 // This function can be expensive, only try to prove NUW once per AddRec.
5124 if (!UnsignedWrapViaInductionTried.insert(Ptr: AR).second)
5125 return Result;
5126
5127 const SCEV *Step = AR->getStepRecurrence(SE&: *this);
5128 const Loop *L = AR->getLoop();
5129
5130 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5131 // Note that this serves two purposes: It filters out loops that are
5132 // simply not analyzable, and it covers the case where this code is
5133 // being called from within backedge-taken count analysis, such that
5134 // attempting to ask for the backedge-taken count would likely result
5135 // in infinite recursion. In the later case, the analysis code will
5136 // cope with a conservative value, and it will take care to purge
5137 // that value once it has finished.
5138 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5139
5140 // Normally, in the cases we can prove no-overflow via a
5141 // backedge guarding condition, we can also compute a backedge
5142 // taken count for the loop. The exceptions are assumptions and
5143 // guards present in the loop -- SCEV is not great at exploiting
5144 // these to compute max backedge taken counts, but can still use
5145 // these to prove lack of overflow. Use this fact to avoid
5146 // doing extra work that may not pay off.
5147
5148 if (isa<SCEVCouldNotCompute>(Val: MaxBECount) && !HasGuards &&
5149 AC.assumptions().empty())
5150 return Result;
5151
5152 // If the backedge is guarded by a comparison with the pre-inc value the
5153 // addrec is safe. Also, if the entry is guarded by a comparison with the
5154 // start value and the backedge is guarded by a comparison with the post-inc
5155 // value, the addrec is safe.
5156 if (isKnownPositive(S: Step)) {
5157 ICmpInst::Predicate Pred;
5158 const SCEV *OverflowLimit =
5159 getUnsignedOverflowLimitForStep(Step, Pred: &Pred, SE: this);
5160 if (isLoopBackedgeGuardedByCond(L, Pred, LHS: AR, RHS: OverflowLimit) ||
5161 isKnownOnEveryIteration(Pred, LHS: AR, RHS: OverflowLimit))
5162 Result = setFlags(Flags: Result, OnFlags: SCEV::FlagNUW);
5163 }
5164 return Result;
5165}
5166
5167namespace {
5168
5169/// Represents an abstract binary operation. This may exist as a
5170/// normal instruction or constant expression, or may have been
5171/// derived from an expression tree.
5172struct BinaryOp {
5173 unsigned Opcode;
5174 Value *LHS;
5175 Value *RHS;
5176 bool IsNSW = false;
5177 bool IsNUW = false;
5178
5179 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5180 /// constant expression.
5181 Operator *Op = nullptr;
5182
5183 explicit BinaryOp(Operator *Op)
5184 : Opcode(Op->getOpcode()), LHS(Op->getOperand(i: 0)), RHS(Op->getOperand(i: 1)),
5185 Op(Op) {
5186 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Val: Op)) {
5187 IsNSW = OBO->hasNoSignedWrap();
5188 IsNUW = OBO->hasNoUnsignedWrap();
5189 }
5190 }
5191
5192 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5193 bool IsNUW = false)
5194 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5195};
5196
5197} // end anonymous namespace
5198
5199/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5200static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5201 AssumptionCache &AC,
5202 const DominatorTree &DT,
5203 const Instruction *CtxI) {
5204 auto *Op = dyn_cast<Operator>(Val: V);
5205 if (!Op)
5206 return std::nullopt;
5207
5208 // Implementation detail: all the cleverness here should happen without
5209 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5210 // SCEV expressions when possible, and we should not break that.
5211
5212 switch (Op->getOpcode()) {
5213 case Instruction::Add:
5214 case Instruction::Sub:
5215 case Instruction::Mul:
5216 case Instruction::UDiv:
5217 case Instruction::URem:
5218 case Instruction::And:
5219 case Instruction::AShr:
5220 case Instruction::Shl:
5221 return BinaryOp(Op);
5222
5223 case Instruction::Or: {
5224 // Convert or disjoint into add nuw nsw.
5225 if (cast<PossiblyDisjointInst>(Val: Op)->isDisjoint()) {
5226 BinaryOp BinOp(Instruction::Add, Op->getOperand(i: 0), Op->getOperand(i: 1),
5227 /*IsNSW=*/true, /*IsNUW=*/true);
5228 // Keep the reference to the original instruction so that we can later
5229 // check whether it can produce poison value or not.
5230 BinOp.Op = Op;
5231 return BinOp;
5232 }
5233 return BinaryOp(Op);
5234 }
5235
5236 case Instruction::Xor:
5237 if (auto *RHSC = dyn_cast<ConstantInt>(Val: Op->getOperand(i: 1)))
5238 // If the RHS of the xor is a signmask, then this is just an add.
5239 // Instcombine turns add of signmask into xor as a strength reduction step.
5240 if (RHSC->getValue().isSignMask())
5241 return BinaryOp(Instruction::Add, Op->getOperand(i: 0), Op->getOperand(i: 1));
5242 // Binary `xor` is a bit-wise `add`.
5243 if (V->getType()->isIntegerTy(BitWidth: 1))
5244 return BinaryOp(Instruction::Add, Op->getOperand(i: 0), Op->getOperand(i: 1));
5245 return BinaryOp(Op);
5246
5247 case Instruction::LShr:
5248 // Turn logical shift right of a constant into a unsigned divide.
5249 if (ConstantInt *SA = dyn_cast<ConstantInt>(Val: Op->getOperand(i: 1))) {
5250 uint32_t BitWidth = cast<IntegerType>(Val: Op->getType())->getBitWidth();
5251
5252 // If the shift count is not less than the bitwidth, the result of
5253 // the shift is undefined. Don't try to analyze it, because the
5254 // resolution chosen here may differ from the resolution chosen in
5255 // other parts of the compiler.
5256 if (SA->getValue().ult(RHS: BitWidth)) {
5257 Constant *X =
5258 ConstantInt::get(Context&: SA->getContext(),
5259 V: APInt::getOneBitSet(numBits: BitWidth, BitNo: SA->getZExtValue()));
5260 return BinaryOp(Instruction::UDiv, Op->getOperand(i: 0), X);
5261 }
5262 }
5263 return BinaryOp(Op);
5264
5265 case Instruction::ExtractValue: {
5266 auto *EVI = cast<ExtractValueInst>(Val: Op);
5267 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5268 break;
5269
5270 auto *WO = dyn_cast<WithOverflowInst>(Val: EVI->getAggregateOperand());
5271 if (!WO)
5272 break;
5273
5274 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5275 bool Signed = WO->isSigned();
5276 // TODO: Should add nuw/nsw flags for mul as well.
5277 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5278 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5279
5280 // Now that we know that all uses of the arithmetic-result component of
5281 // CI are guarded by the overflow check, we can go ahead and pretend
5282 // that the arithmetic is non-overflowing.
5283 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5284 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5285 }
5286
5287 default:
5288 break;
5289 }
5290
5291 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5292 // semantics as a Sub, return a binary sub expression.
5293 if (auto *II = dyn_cast<IntrinsicInst>(Val: V))
5294 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5295 return BinaryOp(Instruction::Sub, II->getOperand(i_nocapture: 0), II->getOperand(i_nocapture: 1));
5296
5297 return std::nullopt;
5298}
5299
5300/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5301/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5302/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5303/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5304/// follows one of the following patterns:
5305/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5306/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5307/// If the SCEV expression of \p Op conforms with one of the expected patterns
5308/// we return the type of the truncation operation, and indicate whether the
5309/// truncated type should be treated as signed/unsigned by setting
5310/// \p Signed to true/false, respectively.
5311static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5312 bool &Signed, ScalarEvolution &SE) {
5313 // The case where Op == SymbolicPHI (that is, with no type conversions on
5314 // the way) is handled by the regular add recurrence creating logic and
5315 // would have already been triggered in createAddRecForPHI. Reaching it here
5316 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5317 // because one of the other operands of the SCEVAddExpr updating this PHI is
5318 // not invariant).
5319 //
5320 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5321 // this case predicates that allow us to prove that Op == SymbolicPHI will
5322 // be added.
5323 if (Op == SymbolicPHI)
5324 return nullptr;
5325
5326 unsigned SourceBits = SE.getTypeSizeInBits(Ty: SymbolicPHI->getType());
5327 unsigned NewBits = SE.getTypeSizeInBits(Ty: Op->getType());
5328 if (SourceBits != NewBits)
5329 return nullptr;
5330
5331 if (match(S: Op, P: m_scev_SExt(Op0: m_scev_Trunc(Op0: m_scev_Specific(S: SymbolicPHI))))) {
5332 Signed = true;
5333 return cast<SCEVCastExpr>(Val: Op)->getOperand()->getType();
5334 }
5335 if (match(S: Op, P: m_scev_ZExt(Op0: m_scev_Trunc(Op0: m_scev_Specific(S: SymbolicPHI))))) {
5336 Signed = false;
5337 return cast<SCEVCastExpr>(Val: Op)->getOperand()->getType();
5338 }
5339 return nullptr;
5340}
5341
5342static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5343 if (!PN->getType()->isIntegerTy())
5344 return nullptr;
5345 const Loop *L = LI.getLoopFor(BB: PN->getParent());
5346 if (!L || L->getHeader() != PN->getParent())
5347 return nullptr;
5348 return L;
5349}
5350
5351// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5352// computation that updates the phi follows the following pattern:
5353// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5354// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5355// If so, try to see if it can be rewritten as an AddRecExpr under some
5356// Predicates. If successful, return them as a pair. Also cache the results
5357// of the analysis.
5358//
5359// Example usage scenario:
5360// Say the Rewriter is called for the following SCEV:
5361// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5362// where:
5363// %X = phi i64 (%Start, %BEValue)
5364// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5365// and call this function with %SymbolicPHI = %X.
5366//
5367// The analysis will find that the value coming around the backedge has
5368// the following SCEV:
5369// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5370// Upon concluding that this matches the desired pattern, the function
5371// will return the pair {NewAddRec, SmallPredsVec} where:
5372// NewAddRec = {%Start,+,%Step}
5373// SmallPredsVec = {P1, P2, P3} as follows:
5374// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5375// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5376// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5377// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5378// under the predicates {P1,P2,P3}.
5379// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5380// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5381//
5382// TODO's:
5383//
5384// 1) Extend the Induction descriptor to also support inductions that involve
5385// casts: When needed (namely, when we are called in the context of the
5386// vectorizer induction analysis), a Set of cast instructions will be
5387// populated by this method, and provided back to isInductionPHI. This is
5388// needed to allow the vectorizer to properly record them to be ignored by
5389// the cost model and to avoid vectorizing them (otherwise these casts,
5390// which are redundant under the runtime overflow checks, will be
5391// vectorized, which can be costly).
5392//
5393// 2) Support additional induction/PHISCEV patterns: We also want to support
5394// inductions where the sext-trunc / zext-trunc operations (partly) occur
5395// after the induction update operation (the induction increment):
5396//
5397// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5398// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5399//
5400// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5401// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5402//
5403// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5404std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5405ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5406 SmallVector<const SCEVPredicate *, 3> Predicates;
5407
5408 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5409 // return an AddRec expression under some predicate.
5410
5411 auto *PN = cast<PHINode>(Val: SymbolicPHI->getValue());
5412 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5413 assert(L && "Expecting an integer loop header phi");
5414
5415 // The loop may have multiple entrances or multiple exits; we can analyze
5416 // this phi as an addrec if it has a unique entry value and a unique
5417 // backedge value.
5418 Value *BEValueV = nullptr, *StartValueV = nullptr;
5419 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5420 Value *V = PN->getIncomingValue(i);
5421 if (L->contains(BB: PN->getIncomingBlock(i))) {
5422 if (!BEValueV) {
5423 BEValueV = V;
5424 } else if (BEValueV != V) {
5425 BEValueV = nullptr;
5426 break;
5427 }
5428 } else if (!StartValueV) {
5429 StartValueV = V;
5430 } else if (StartValueV != V) {
5431 StartValueV = nullptr;
5432 break;
5433 }
5434 }
5435 if (!BEValueV || !StartValueV)
5436 return std::nullopt;
5437
5438 const SCEV *BEValue = getSCEV(V: BEValueV);
5439
5440 // If the value coming around the backedge is an add with the symbolic
5441 // value we just inserted, possibly with casts that we can ignore under
5442 // an appropriate runtime guard, then we found a simple induction variable!
5443 const auto *Add = dyn_cast<SCEVAddExpr>(Val: BEValue);
5444 if (!Add)
5445 return std::nullopt;
5446
5447 // If there is a single occurrence of the symbolic value, possibly
5448 // casted, replace it with a recurrence.
5449 unsigned FoundIndex = Add->getNumOperands();
5450 Type *TruncTy = nullptr;
5451 bool Signed;
5452 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5453 if ((TruncTy =
5454 isSimpleCastedPHI(Op: Add->getOperand(i), SymbolicPHI, Signed, SE&: *this)))
5455 if (FoundIndex == e) {
5456 FoundIndex = i;
5457 break;
5458 }
5459
5460 if (FoundIndex == Add->getNumOperands())
5461 return std::nullopt;
5462
5463 // Create an add with everything but the specified operand.
5464 SmallVector<SCEVUse, 8> Ops;
5465 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5466 if (i != FoundIndex)
5467 Ops.push_back(Elt: Add->getOperand(i));
5468 const SCEV *Accum = getAddExpr(Ops);
5469
5470 // The runtime checks will not be valid if the step amount is
5471 // varying inside the loop.
5472 if (!isLoopInvariant(S: Accum, L))
5473 return std::nullopt;
5474
5475 // *** Part2: Create the predicates
5476
5477 // Analysis was successful: we have a phi-with-cast pattern for which we
5478 // can return an AddRec expression under the following predicates:
5479 //
5480 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5481 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5482 // P2: An Equal predicate that guarantees that
5483 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5484 // P3: An Equal predicate that guarantees that
5485 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5486 //
5487 // As we next prove, the above predicates guarantee that:
5488 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5489 //
5490 //
5491 // More formally, we want to prove that:
5492 // Expr(i+1) = Start + (i+1) * Accum
5493 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5494 //
5495 // Given that:
5496 // 1) Expr(0) = Start
5497 // 2) Expr(1) = Start + Accum
5498 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5499 // 3) Induction hypothesis (step i):
5500 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5501 //
5502 // Proof:
5503 // Expr(i+1) =
5504 // = Start + (i+1)*Accum
5505 // = (Start + i*Accum) + Accum
5506 // = Expr(i) + Accum
5507 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5508 // :: from step i
5509 //
5510 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5511 //
5512 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5513 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5514 // + Accum :: from P3
5515 //
5516 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5517 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5518 //
5519 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5520 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5521 //
5522 // By induction, the same applies to all iterations 1<=i<n:
5523 //
5524
5525 // Create a truncated addrec for which we will add a no overflow check (P1).
5526 const SCEV *StartVal = getSCEV(V: StartValueV);
5527 const SCEV *PHISCEV =
5528 getAddRecExpr(Start: getTruncateExpr(Op: StartVal, Ty: TruncTy),
5529 Step: getTruncateExpr(Op: Accum, Ty: TruncTy), L, Flags: SCEV::FlagNone);
5530
5531 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5532 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5533 // will be constant.
5534 //
5535 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5536 // add P1.
5537 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(Val: PHISCEV)) {
5538 SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
5539 Signed ? SCEVWrapPredicate::IncrementNSSW
5540 : SCEVWrapPredicate::IncrementNUSW;
5541 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5542 Predicates.push_back(Elt: AddRecPred);
5543 }
5544
5545 // Create the Equal Predicates P2,P3:
5546
5547 // It is possible that the predicates P2 and/or P3 are computable at
5548 // compile time due to StartVal and/or Accum being constants.
5549 // If either one is, then we can check that now and escape if either P2
5550 // or P3 is false.
5551
5552 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5553 // for each of StartVal and Accum
5554 auto getExtendedExpr = [&](const SCEV *Expr,
5555 bool CreateSignExtend) -> const SCEV * {
5556 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5557 const SCEV *TruncatedExpr = getTruncateExpr(Op: Expr, Ty: TruncTy);
5558 const SCEV *ExtendedExpr =
5559 CreateSignExtend ? getSignExtendExpr(Op: TruncatedExpr, Ty: Expr->getType())
5560 : getZeroExtendExpr(Op: TruncatedExpr, Ty: Expr->getType());
5561 return ExtendedExpr;
5562 };
5563
5564 // Given:
5565 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5566 // = getExtendedExpr(Expr)
5567 // Determine whether the predicate P: Expr == ExtendedExpr
5568 // is known to be false at compile time
5569 auto PredIsKnownFalse = [&](const SCEV *Expr,
5570 const SCEV *ExtendedExpr) -> bool {
5571 return Expr != ExtendedExpr &&
5572 isKnownPredicate(Pred: ICmpInst::ICMP_NE, LHS: Expr, RHS: ExtendedExpr);
5573 };
5574
5575 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5576 if (PredIsKnownFalse(StartVal, StartExtended)) {
5577 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5578 return std::nullopt;
5579 }
5580
5581 // The Step is always Signed (because the overflow checks are either
5582 // NSSW or NUSW)
5583 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5584 if (PredIsKnownFalse(Accum, AccumExtended)) {
5585 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5586 return std::nullopt;
5587 }
5588
5589 auto AppendPredicate = [&](const SCEV *Expr,
5590 const SCEV *ExtendedExpr) -> void {
5591 if (Expr != ExtendedExpr &&
5592 !isKnownPredicate(Pred: ICmpInst::ICMP_EQ, LHS: Expr, RHS: ExtendedExpr)) {
5593 const SCEVPredicate *Pred = getEqualPredicate(LHS: Expr, RHS: ExtendedExpr);
5594 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5595 Predicates.push_back(Elt: Pred);
5596 }
5597 };
5598
5599 AppendPredicate(StartVal, StartExtended);
5600 AppendPredicate(Accum, AccumExtended);
5601
5602 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5603 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5604 // into NewAR if it will also add the runtime overflow checks specified in
5605 // Predicates.
5606 const SCEV *NewAR = getAddRecExpr(Start: StartVal, Step: Accum, L, Flags: SCEV::FlagNone);
5607
5608 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5609 std::make_pair(x&: NewAR, y&: Predicates);
5610 // Remember the result of the analysis for this SCEV at this locayyytion.
5611 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5612 return PredRewrite;
5613}
5614
5615std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5616ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
5617 auto *PN = cast<PHINode>(Val: SymbolicPHI->getValue());
5618 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5619 if (!L)
5620 return std::nullopt;
5621
5622 // Check to see if we already analyzed this PHI.
5623 auto I = PredicatedSCEVRewrites.find(Val: {SymbolicPHI, L});
5624 if (I != PredicatedSCEVRewrites.end()) {
5625 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5626 I->second;
5627 // Analysis was done before and failed to create an AddRec:
5628 if (Rewrite.first == SymbolicPHI)
5629 return std::nullopt;
5630 // Analysis was done before and succeeded to create an AddRec under
5631 // a predicate:
5632 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5633 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5634 return Rewrite;
5635 }
5636
5637 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5638 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5639
5640 // Record in the cache that the analysis failed
5641 if (!Rewrite) {
5642 SmallVector<const SCEVPredicate *, 3> Predicates;
5643 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5644 return std::nullopt;
5645 }
5646
5647 return Rewrite;
5648}
5649
5650// FIXME: This utility is currently required because the Rewriter currently
5651// does not rewrite this expression:
5652// {0, +, (sext ix (trunc iy to ix) to iy)}
5653// into {0, +, %step},
5654// even when the following Equal predicate exists:
5655// "%step == (sext ix (trunc iy to ix) to iy)".
5656bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
5657 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5658 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5659 if (AR1 == AR2)
5660 return true;
5661
5662 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5663 SCEVUnionPredicate AllPreds = Preds->getUnionWith(N: &NoWrapUnionPred, SE);
5664 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5665 if (Expr1 != Expr2 &&
5666 !AllPreds.implies(N: SE.getEqualPredicate(LHS: Expr1, RHS: Expr2), SE) &&
5667 !AllPreds.implies(N: SE.getEqualPredicate(LHS: Expr2, RHS: Expr1), SE))
5668 return false;
5669 return true;
5670 };
5671
5672 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5673 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5674 return false;
5675 return true;
5676}
5677
5678static SCEVFlags getNoWrapFlagsForGEP(GEPOperator *GEP, const SCEV *Accum,
5679 ScalarEvolution &SE) {
5680 SCEVFlags Flags = SCEV::FlagNone;
5681 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
5682 // If the increment has any nowrap flags, then we know the address
5683 // space cannot be wrapped around.
5684 if (NW != GEPNoWrapFlags::none())
5685 Flags = ScalarEvolution::setFlags(Flags, OnFlags: SCEV::FlagNW);
5686 // If the GEP is nuw or nusw with non-negative offset, we know that
5687 // no unsigned wrap occurs. We cannot set the nsw flag as only the
5688 // offset is treated as signed, while the base is unsigned.
5689 if (NW.hasNoUnsignedWrap() ||
5690 (NW.hasNoUnsignedSignedWrap() && SE.isKnownNonNegative(S: Accum)))
5691 Flags = ScalarEvolution::setFlags(Flags, OnFlags: SCEV::FlagNUW);
5692
5693 return Flags;
5694}
5695
5696/// A helper function for createAddRecFromPHI to handle simple cases.
5697///
5698/// This function tries to find an AddRec expression for the simplest (yet most
5699/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5700/// If it fails, createAddRecFromPHI will use a more general, but slow,
5701/// technique for finding the AddRec expression.
5702const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5703 Value *BEValueV,
5704 Value *StartValueV) {
5705 const Loop *L = LI.getLoopFor(BB: PN->getParent());
5706 assert(L && L->getHeader() == PN->getParent());
5707 assert(BEValueV && StartValueV);
5708
5709 const SCEV *Accum = nullptr;
5710 SCEVFlags Flags = SCEV::FlagNone;
5711 if (auto BO = MatchBinaryOp(V: BEValueV, DL: getDataLayout(), AC, DT, CtxI: PN)) {
5712 if (BO->Opcode != Instruction::Add)
5713 return nullptr;
5714
5715 if (BO->LHS == PN && L->isLoopInvariant(V: BO->RHS))
5716 Accum = getSCEV(V: BO->RHS);
5717 else if (BO->RHS == PN && L->isLoopInvariant(V: BO->LHS))
5718 Accum = getSCEV(V: BO->LHS);
5719
5720 if (!Accum)
5721 return nullptr;
5722
5723 if (BO->IsNUW)
5724 Flags = setFlags(Flags, OnFlags: SCEV::FlagNUW);
5725 if (BO->IsNSW)
5726 Flags = setFlags(Flags, OnFlags: SCEV::FlagNSW);
5727 } else {
5728 // Handle pointer induction variable: PN = PHI(Start, gep PN,
5729 // LoopInvariant).
5730 auto *GEP = dyn_cast<GEPOperator>(Val: BEValueV);
5731 if (!GEP || GEP->getPointerOperand() != PN || GEP->getNumIndices() != 1)
5732 return nullptr;
5733 Value *Idx = *GEP->idx_begin();
5734 if (!L->isLoopInvariant(V: Idx))
5735 return nullptr;
5736
5737 Type *IntIdxTy = getEffectiveSCEVType(Ty: GEP->getType());
5738 Accum = getMulExpr(LHS: getTruncateOrSignExtend(V: getSCEV(V: Idx), Ty: IntIdxTy),
5739 RHS: getSizeOfExpr(IntTy: IntIdxTy, AllocTy: GEP->getSourceElementType()));
5740 Flags = getNoWrapFlagsForGEP(GEP, Accum, SE&: *this);
5741 }
5742
5743 const SCEV *StartVal = getSCEV(V: StartValueV);
5744 const SCEV *PHISCEV = getAddRecExpr(Start: StartVal, Step: Accum, L, Flags);
5745 insertValueToMap(V: PN, S: PHISCEV);
5746
5747 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Val: PHISCEV))
5748 inferNoWrapViaConstantRanges(AR);
5749
5750 // We can add Flags to the post-inc expression only if we
5751 // know that it is *undefined behavior* for BEValueV to
5752 // overflow.
5753 if (auto *BEInst = dyn_cast<Instruction>(Val: BEValueV)) {
5754 assert(isLoopInvariant(Accum, L) &&
5755 "Accum is defined outside L, but is not invariant?");
5756 if (isAddRecNeverPoison(I: BEInst, L))
5757 (void)getAddRecExpr(Start: getAddExpr(LHS: StartVal, RHS: Accum), Step: Accum, L, Flags);
5758 }
5759
5760 return PHISCEV;
5761}
5762
5763const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5764 const Loop *L = LI.getLoopFor(BB: PN->getParent());
5765 if (!L || L->getHeader() != PN->getParent())
5766 return nullptr;
5767
5768 // The loop may have multiple entrances or multiple exits; we can analyze
5769 // this phi as an addrec if it has a unique entry value and a unique
5770 // backedge value.
5771 Value *BEValueV = nullptr, *StartValueV = nullptr;
5772 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5773 Value *V = PN->getIncomingValue(i);
5774 if (L->contains(BB: PN->getIncomingBlock(i))) {
5775 if (!BEValueV) {
5776 BEValueV = V;
5777 } else if (BEValueV != V) {
5778 BEValueV = nullptr;
5779 break;
5780 }
5781 } else if (!StartValueV) {
5782 StartValueV = V;
5783 } else if (StartValueV != V) {
5784 StartValueV = nullptr;
5785 break;
5786 }
5787 }
5788 if (!BEValueV || !StartValueV)
5789 return nullptr;
5790
5791 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5792 "PHI node already processed?");
5793
5794 // First, try to find AddRec expression without creating a fictituos symbolic
5795 // value for PN.
5796 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5797 return S;
5798
5799 // Handle PHI node value symbolically.
5800 const SCEV *SymbolicName = getUnknown(V: PN);
5801 insertValueToMap(V: PN, S: SymbolicName);
5802
5803 // Using this symbolic name for the PHI, analyze the value coming around
5804 // the back-edge.
5805 const SCEV *BEValue = getSCEV(V: BEValueV);
5806
5807 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5808 // has a special value for the first iteration of the loop.
5809
5810 // If the value coming around the backedge is an add with the symbolic
5811 // value we just inserted, then we found a simple induction variable!
5812 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Val: BEValue)) {
5813 // If there is a single occurrence of the symbolic value, replace it
5814 // with a recurrence.
5815 unsigned FoundIndex = Add->getNumOperands();
5816 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5817 if (Add->getOperand(i) == SymbolicName)
5818 if (FoundIndex == e) {
5819 FoundIndex = i;
5820 break;
5821 }
5822
5823 if (FoundIndex != Add->getNumOperands()) {
5824 // Create an add with everything but the specified operand.
5825 SmallVector<SCEVUse, 8> Ops;
5826 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5827 if (i != FoundIndex)
5828 Ops.push_back(Elt: SCEVBackedgeConditionFolder::rewrite(S: Add->getOperand(i),
5829 L, SE&: *this));
5830 const SCEV *Accum = getAddExpr(Ops);
5831
5832 // This is not a valid addrec if the step amount is varying each
5833 // loop iteration, but is not itself an addrec in this loop.
5834 if (isLoopInvariant(S: Accum, L) ||
5835 (isa<SCEVAddRecExpr>(Val: Accum) &&
5836 cast<SCEVAddRecExpr>(Val: Accum)->getLoop() == L)) {
5837 SCEVFlags Flags = SCEV::FlagNone;
5838
5839 if (auto BO = MatchBinaryOp(V: BEValueV, DL: getDataLayout(), AC, DT, CtxI: PN)) {
5840 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5841 if (BO->IsNUW)
5842 Flags = setFlags(Flags, OnFlags: SCEV::FlagNUW);
5843 if (BO->IsNSW)
5844 Flags = setFlags(Flags, OnFlags: SCEV::FlagNSW);
5845 }
5846 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(Val: BEValueV)) {
5847 if (GEP->getOperand(i_nocapture: 0) == PN)
5848 Flags = getNoWrapFlagsForGEP(GEP, Accum, SE&: *this);
5849
5850 // We cannot transfer nuw and nsw flags from subtraction
5851 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5852 // for instance.
5853 }
5854
5855 const SCEV *StartVal = getSCEV(V: StartValueV);
5856 const SCEV *PHISCEV = getAddRecExpr(Start: StartVal, Step: Accum, L, Flags);
5857
5858 // Okay, for the entire analysis of this edge we assumed the PHI
5859 // to be symbolic. We now need to go back and purge all of the
5860 // entries for the scalars that use the symbolic expression.
5861 forgetMemoizedResults(SCEVs: {SymbolicName});
5862 insertValueToMap(V: PN, S: PHISCEV);
5863
5864 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Val: PHISCEV))
5865 inferNoWrapViaConstantRanges(AR);
5866
5867 // We can add Flags to the post-inc expression only if we
5868 // know that it is *undefined behavior* for BEValueV to
5869 // overflow.
5870 if (auto *BEInst = dyn_cast<Instruction>(Val: BEValueV))
5871 if (isLoopInvariant(S: Accum, L) && isAddRecNeverPoison(I: BEInst, L))
5872 (void)getAddRecExpr(Start: getAddExpr(LHS: StartVal, RHS: Accum), Step: Accum, L, Flags);
5873
5874 return PHISCEV;
5875 }
5876 }
5877 } else {
5878 // Otherwise, this could be a loop like this:
5879 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5880 // In this case, j = {1,+,1} and BEValue is j.
5881 // Because the other in-value of i (0) fits the evolution of BEValue
5882 // i really is an addrec evolution.
5883 //
5884 // We can generalize this saying that i is the shifted value of BEValue
5885 // by one iteration:
5886 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5887
5888 // Do not allow refinement in rewriting of BEValue.
5889 const SCEV *Shifted = SCEVShiftRewriter::rewrite(S: BEValue, L, SE&: *this);
5890 const SCEV *Start = SCEVInitRewriter::rewrite(S: Shifted, L, SE&: *this, IgnoreOtherLoops: false);
5891 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
5892 isGuaranteedNotToCauseUB(Op: Shifted) && ::impliesPoison(AssumedPoison: Shifted, S: Start)) {
5893 const SCEV *StartVal = getSCEV(V: StartValueV);
5894 if (Start == StartVal) {
5895 // Okay, for the entire analysis of this edge we assumed the PHI
5896 // to be symbolic. We now need to go back and purge all of the
5897 // entries for the scalars that use the symbolic expression.
5898 forgetMemoizedResults(SCEVs: {SymbolicName});
5899 insertValueToMap(V: PN, S: Shifted);
5900 return Shifted;
5901 }
5902 }
5903 }
5904
5905 // Remove the temporary PHI node SCEV that has been inserted while intending
5906 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5907 // as it will prevent later (possibly simpler) SCEV expressions to be added
5908 // to the ValueExprMap.
5909 eraseValueFromMap(V: PN);
5910
5911 return nullptr;
5912}
5913
5914// Try to match a control flow sequence that branches out at BI and merges back
5915// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5916// match.
5917static bool BrPHIToSelect(DominatorTree &DT, CondBrInst *BI, PHINode *Merge,
5918 Value *&C, Value *&LHS, Value *&RHS) {
5919 C = BI->getCondition();
5920
5921 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(i: 0));
5922 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(i: 1));
5923
5924 Use &LeftUse = Merge->getOperandUse(i: 0);
5925 Use &RightUse = Merge->getOperandUse(i: 1);
5926
5927 if (DT.dominates(BBE: LeftEdge, U: LeftUse) && DT.dominates(BBE: RightEdge, U: RightUse)) {
5928 LHS = LeftUse;
5929 RHS = RightUse;
5930 return true;
5931 }
5932
5933 if (DT.dominates(BBE: LeftEdge, U: RightUse) && DT.dominates(BBE: RightEdge, U: LeftUse)) {
5934 LHS = RightUse;
5935 RHS = LeftUse;
5936 return true;
5937 }
5938
5939 return false;
5940}
5941
5942static bool getOperandsForSelectLikePHI(DominatorTree &DT, PHINode *PN,
5943 Value *&Cond, Value *&LHS,
5944 Value *&RHS) {
5945 auto IsReachable =
5946 [&](BasicBlock *BB) { return DT.isReachableFromEntry(A: BB); };
5947 if (PN->getNumIncomingValues() == 2 && all_of(Range: PN->blocks(), P: IsReachable)) {
5948 // Try to match
5949 //
5950 // br %cond, label %left, label %right
5951 // left:
5952 // br label %merge
5953 // right:
5954 // br label %merge
5955 // merge:
5956 // V = phi [ %x, %left ], [ %y, %right ]
5957 //
5958 // as "select %cond, %x, %y"
5959
5960 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5961 assert(IDom && "At least the entry block should dominate PN");
5962
5963 auto *BI = dyn_cast<CondBrInst>(Val: IDom->getTerminator());
5964 return BI && BrPHIToSelect(DT, BI, Merge: PN, C&: Cond, LHS, RHS);
5965 }
5966 return false;
5967}
5968
5969const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5970 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5971 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
5972 properlyDominates(S: getSCEV(V: LHS), BB: PN->getParent()) &&
5973 properlyDominates(S: getSCEV(V: RHS), BB: PN->getParent()))
5974 return createNodeForSelectOrPHI(V: PN, Cond, TrueVal: LHS, FalseVal: RHS);
5975
5976 return nullptr;
5977}
5978
5979static BinaryOperator *getCommonInstForPHI(PHINode *PN) {
5980 BinaryOperator *CommonInst = nullptr;
5981 // Check if instructions are identical.
5982 for (Value *Incoming : PN->incoming_values()) {
5983 auto *IncomingInst = dyn_cast<BinaryOperator>(Val: Incoming);
5984 if (!IncomingInst)
5985 return nullptr;
5986 if (CommonInst) {
5987 if (!CommonInst->isIdenticalToWhenDefined(I: IncomingInst))
5988 return nullptr; // Not identical, give up
5989 } else {
5990 // Remember binary operator
5991 CommonInst = IncomingInst;
5992 }
5993 }
5994 return CommonInst;
5995}
5996
5997/// Returns SCEV for the first operand of a phi if all phi operands have
5998/// identical opcodes and operands
5999/// eg.
6000/// a: %add = %a + %b
6001/// br %c
6002/// b: %add1 = %a + %b
6003/// br %c
6004/// c: %phi = phi [%add, a], [%add1, b]
6005/// scev(%phi) => scev(%add)
6006const SCEV *
6007ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
6008 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
6009 if (!CommonInst)
6010 return nullptr;
6011
6012 // Check if SCEV exprs for instructions are identical.
6013 const SCEV *CommonSCEV = getSCEV(V: CommonInst);
6014 bool SCEVExprsIdentical =
6015 all_of(Range: drop_begin(RangeOrContainer: PN->incoming_values()),
6016 P: [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
6017 return SCEVExprsIdentical ? CommonSCEV : nullptr;
6018}
6019
6020const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
6021 if (const SCEV *S = createAddRecFromPHI(PN))
6022 return S;
6023
6024 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
6025 // phi node for X.
6026 if (Value *V = simplifyInstruction(
6027 I: PN, Q: {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
6028 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
6029 return getSCEV(V);
6030
6031 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
6032 return S;
6033
6034 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6035 return S;
6036
6037 // If it's not a loop phi, we can't handle it yet.
6038 return getUnknown(V: PN);
6039}
6040
6041bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6042 SCEVTypes RootKind) {
6043 struct FindClosure {
6044 const SCEV *OperandToFind;
6045 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6046 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6047
6048 bool Found = false;
6049
6050 bool canRecurseInto(SCEVTypes Kind) const {
6051 // We can only recurse into the SCEV expression of the same effective type
6052 // as the type of our root SCEV expression, and into zero-extensions.
6053 return RootKind == Kind || NonSequentialRootKind == Kind ||
6054 scZeroExtend == Kind;
6055 };
6056
6057 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6058 : OperandToFind(OperandToFind), RootKind(RootKind),
6059 NonSequentialRootKind(
6060 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
6061 Ty: RootKind)) {}
6062
6063 bool follow(const SCEV *S) {
6064 Found = S == OperandToFind;
6065
6066 return !isDone() && canRecurseInto(Kind: S->getSCEVType());
6067 }
6068
6069 bool isDone() const { return Found; }
6070 };
6071
6072 FindClosure FC(OperandToFind, RootKind);
6073 visitAll(Root, Visitor&: FC);
6074 return FC.Found;
6075}
6076
6077std::optional<const SCEV *>
6078ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6079 ICmpInst *Cond,
6080 Value *TrueVal,
6081 Value *FalseVal) {
6082 // Try to match some simple smax or umax patterns.
6083 auto *ICI = Cond;
6084
6085 Value *LHS = ICI->getOperand(i_nocapture: 0);
6086 Value *RHS = ICI->getOperand(i_nocapture: 1);
6087
6088 switch (ICI->getPredicate()) {
6089 case ICmpInst::ICMP_SLT:
6090 case ICmpInst::ICMP_SLE:
6091 case ICmpInst::ICMP_ULT:
6092 case ICmpInst::ICMP_ULE:
6093 std::swap(a&: LHS, b&: RHS);
6094 [[fallthrough]];
6095 case ICmpInst::ICMP_SGT:
6096 case ICmpInst::ICMP_SGE:
6097 case ICmpInst::ICMP_UGT:
6098 case ICmpInst::ICMP_UGE:
6099 // a > b ? a+x : b+x -> max(a, b)+x
6100 // a > b ? b+x : a+x -> min(a, b)+x
6101 if (getTypeSizeInBits(Ty: LHS->getType()) <= getTypeSizeInBits(Ty)) {
6102 bool Signed = ICI->isSigned();
6103 const SCEV *LA = getSCEV(V: TrueVal);
6104 const SCEV *RA = getSCEV(V: FalseVal);
6105 const SCEV *LS = getSCEV(V: LHS);
6106 const SCEV *RS = getSCEV(V: RHS);
6107 if (LA->getType()->isPointerTy()) {
6108 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6109 // Need to make sure we can't produce weird expressions involving
6110 // negated pointers.
6111 if (LA == LS && RA == RS)
6112 return Signed ? getSMaxExpr(LHS: LS, RHS: RS) : getUMaxExpr(LHS: LS, RHS: RS);
6113 if (LA == RS && RA == LS)
6114 return Signed ? getSMinExpr(LHS: LS, RHS: RS) : getUMinExpr(LHS: LS, RHS: RS);
6115 }
6116 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6117 if (Op->getType()->isPointerTy()) {
6118 Op = getPtrToAddrExpr(Op);
6119 if (isa<SCEVCouldNotCompute>(Val: Op))
6120 return Op;
6121 }
6122 if (Signed)
6123 Op = getNoopOrSignExtend(V: Op, Ty);
6124 else
6125 Op = getNoopOrZeroExtend(V: Op, Ty);
6126 return Op;
6127 };
6128 LS = CoerceOperand(LS);
6129 RS = CoerceOperand(RS);
6130 if (isa<SCEVCouldNotCompute>(Val: LS) || isa<SCEVCouldNotCompute>(Val: RS))
6131 break;
6132 const SCEV *LDiff = getMinusSCEV(LHS: LA, RHS: LS);
6133 const SCEV *RDiff = getMinusSCEV(LHS: RA, RHS: RS);
6134 if (LDiff == RDiff)
6135 return getAddExpr(LHS: Signed ? getSMaxExpr(LHS: LS, RHS: RS) : getUMaxExpr(LHS: LS, RHS: RS),
6136 RHS: LDiff);
6137 LDiff = getMinusSCEV(LHS: LA, RHS: RS);
6138 RDiff = getMinusSCEV(LHS: RA, RHS: LS);
6139 if (LDiff == RDiff)
6140 return getAddExpr(LHS: Signed ? getSMinExpr(LHS: LS, RHS: RS) : getUMinExpr(LHS: LS, RHS: RS),
6141 RHS: LDiff);
6142 }
6143 break;
6144 case ICmpInst::ICMP_NE:
6145 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6146 std::swap(a&: TrueVal, b&: FalseVal);
6147 [[fallthrough]];
6148 case ICmpInst::ICMP_EQ:
6149 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6150 if (getTypeSizeInBits(Ty: LHS->getType()) <= getTypeSizeInBits(Ty) &&
6151 isa<ConstantInt>(Val: RHS) && cast<ConstantInt>(Val: RHS)->isZero()) {
6152 const SCEV *X = getNoopOrZeroExtend(V: getSCEV(V: LHS), Ty);
6153 const SCEV *TrueValExpr = getSCEV(V: TrueVal); // C+y
6154 const SCEV *FalseValExpr = getSCEV(V: FalseVal); // x+y
6155 const SCEV *Y = getMinusSCEV(LHS: FalseValExpr, RHS: X); // y = (x+y)-x
6156 const SCEV *C = getMinusSCEV(LHS: TrueValExpr, RHS: Y); // C = (C+y)-y
6157 if (isa<SCEVConstant>(Val: C) && cast<SCEVConstant>(Val: C)->getAPInt().ule(RHS: 1))
6158 return getAddExpr(LHS: getUMaxExpr(LHS: X, RHS: C), RHS: Y);
6159 }
6160 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6161 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6162 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6163 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6164 if (isa<ConstantInt>(Val: RHS) && cast<ConstantInt>(Val: RHS)->isZero() &&
6165 isa<ConstantInt>(Val: TrueVal) && cast<ConstantInt>(Val: TrueVal)->isZero()) {
6166 const SCEV *X = getSCEV(V: LHS);
6167 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Val: X))
6168 X = ZExt->getOperand();
6169 if (getTypeSizeInBits(Ty: X->getType()) <= getTypeSizeInBits(Ty)) {
6170 const SCEV *FalseValExpr = getSCEV(V: FalseVal);
6171 if (SCEVMinMaxExprContains(Root: FalseValExpr, OperandToFind: X, RootKind: scSequentialUMinExpr))
6172 return getUMinExpr(LHS: getNoopOrZeroExtend(V: X, Ty), RHS: FalseValExpr,
6173 /*Sequential=*/true);
6174 }
6175 }
6176 break;
6177 default:
6178 break;
6179 }
6180
6181 return std::nullopt;
6182}
6183
6184static std::optional<const SCEV *>
6185createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr,
6186 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6187 assert(CondExpr->getType()->isIntegerTy(1) &&
6188 TrueExpr->getType() == FalseExpr->getType() &&
6189 TrueExpr->getType()->isIntegerTy(1) &&
6190 "Unexpected operands of a select.");
6191
6192 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6193 // --> C + (umin_seq cond, x - C)
6194 //
6195 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6196 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6197 // --> C + (umin_seq ~cond, x - C)
6198
6199 // FIXME: while we can't legally model the case where both of the hands
6200 // are fully variable, we only require that the *difference* is constant.
6201 if (!isa<SCEVConstant>(Val: TrueExpr) && !isa<SCEVConstant>(Val: FalseExpr))
6202 return std::nullopt;
6203
6204 const SCEV *X, *C;
6205 if (isa<SCEVConstant>(Val: TrueExpr)) {
6206 CondExpr = SE->getNotSCEV(V: CondExpr);
6207 X = FalseExpr;
6208 C = TrueExpr;
6209 } else {
6210 X = TrueExpr;
6211 C = FalseExpr;
6212 }
6213 return SE->getAddExpr(LHS: C, RHS: SE->getUMinExpr(LHS: CondExpr, RHS: SE->getMinusSCEV(LHS: X, RHS: C),
6214 /*Sequential=*/true));
6215}
6216
6217static std::optional<const SCEV *>
6218createNodeForSelectViaUMinSeq(ScalarEvolution *SE, Value *Cond, Value *TrueVal,
6219 Value *FalseVal) {
6220 if (!isa<ConstantInt>(Val: TrueVal) && !isa<ConstantInt>(Val: FalseVal))
6221 return std::nullopt;
6222
6223 const auto *SECond = SE->getSCEV(V: Cond);
6224 const auto *SETrue = SE->getSCEV(V: TrueVal);
6225 const auto *SEFalse = SE->getSCEV(V: FalseVal);
6226 return createNodeForSelectViaUMinSeq(SE, CondExpr: SECond, TrueExpr: SETrue, FalseExpr: SEFalse);
6227}
6228
6229const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6230 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6231 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6232 assert(TrueVal->getType() == FalseVal->getType() &&
6233 V->getType() == TrueVal->getType() &&
6234 "Types of select hands and of the result must match.");
6235
6236 // For now, only deal with i1-typed `select`s.
6237 if (!V->getType()->isIntegerTy(BitWidth: 1))
6238 return getUnknown(V);
6239
6240 if (std::optional<const SCEV *> S =
6241 createNodeForSelectViaUMinSeq(SE: this, Cond, TrueVal, FalseVal))
6242 return *S;
6243
6244 return getUnknown(V);
6245}
6246
6247const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6248 Value *TrueVal,
6249 Value *FalseVal) {
6250 // Handle "constant" branch or select. This can occur for instance when a
6251 // loop pass transforms an inner loop and moves on to process the outer loop.
6252 if (auto *CI = dyn_cast<ConstantInt>(Val: Cond))
6253 return getSCEV(V: CI->isOne() ? TrueVal : FalseVal);
6254
6255 if (auto *I = dyn_cast<Instruction>(Val: V)) {
6256 if (auto *ICI = dyn_cast<ICmpInst>(Val: Cond)) {
6257 if (std::optional<const SCEV *> S =
6258 createNodeForSelectOrPHIInstWithICmpInstCond(Ty: I->getType(), Cond: ICI,
6259 TrueVal, FalseVal))
6260 return *S;
6261 }
6262 }
6263
6264 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6265}
6266
6267/// Expand GEP instructions into add and multiply operations. This allows them
6268/// to be analyzed by regular SCEV code.
6269const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6270 assert(GEP->getSourceElementType()->isSized() &&
6271 "GEP source element type must be sized");
6272
6273 SmallVector<SCEVUse, 4> IndexExprs;
6274 for (Value *Index : GEP->indices())
6275 IndexExprs.push_back(Elt: getSCEV(V: Index));
6276 return getGEPExpr(GEP, IndexExprs);
6277}
6278
6279APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6280 const Instruction *CtxI) {
6281 uint64_t BitWidth = getTypeSizeInBits(Ty: S->getType());
6282 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6283 return TrailingZeros >= BitWidth
6284 ? APInt::getZero(numBits: BitWidth)
6285 : APInt::getOneBitSet(numBits: BitWidth, BitNo: TrailingZeros);
6286 };
6287 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6288 // The result is GCD of all operands results.
6289 APInt Res = getConstantMultiple(S: N->getOperand(i: 0), CtxI);
6290 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6291 Res = APIntOps::GreatestCommonDivisor(
6292 A: Res, B: getConstantMultiple(S: N->getOperand(i: I), CtxI));
6293 return Res;
6294 };
6295
6296 switch (S->getSCEVType()) {
6297 case scConstant:
6298 return cast<SCEVConstant>(Val: S)->getAPInt();
6299 case scPtrToAddr:
6300 return getConstantMultiple(S: cast<SCEVCastExpr>(Val: S)->getOperand());
6301 case scUDivExpr:
6302 case scVScale:
6303 return APInt(BitWidth, 1);
6304 case scTruncate: {
6305 // Only multiples that are a power of 2 will hold after truncation.
6306 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(Val: S);
6307 uint32_t TZ = getMinTrailingZeros(S: T->getOperand(), CtxI);
6308 return GetShiftedByZeros(TZ);
6309 }
6310 case scZeroExtend: {
6311 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(Val: S);
6312 return getConstantMultiple(S: Z->getOperand(), CtxI).zext(width: BitWidth);
6313 }
6314 case scSignExtend: {
6315 // Only multiples that are a power of 2 will hold after sext.
6316 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(Val: S);
6317 uint32_t TZ = getMinTrailingZeros(S: E->getOperand(), CtxI);
6318 return GetShiftedByZeros(TZ);
6319 }
6320 case scMulExpr: {
6321 const SCEVMulExpr *M = cast<SCEVMulExpr>(Val: S);
6322 if (M->hasNoUnsignedWrap()) {
6323 // The result is the product of all operand results.
6324 APInt Res = getConstantMultiple(S: M->getOperand(i: 0), CtxI);
6325 for (const SCEV *Operand : M->operands().drop_front())
6326 Res = Res * getConstantMultiple(S: Operand, CtxI);
6327 return Res;
6328 }
6329
6330 // If there are no wrap guarentees, find the trailing zeros, which is the
6331 // sum of trailing zeros for all its operands.
6332 uint32_t TZ = 0;
6333 for (const SCEV *Operand : M->operands())
6334 TZ += getMinTrailingZeros(S: Operand, CtxI);
6335 return GetShiftedByZeros(TZ);
6336 }
6337 case scAddExpr:
6338 case scAddRecExpr: {
6339 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(Val: S);
6340 if (N->hasNoUnsignedWrap())
6341 return GetGCDMultiple(N);
6342 // Find the trailing bits, which is the minimum of its operands.
6343 uint32_t TZ = getMinTrailingZeros(S: N->getOperand(i: 0), CtxI);
6344 for (const SCEV *Operand : N->operands().drop_front())
6345 TZ = std::min(a: TZ, b: getMinTrailingZeros(S: Operand, CtxI));
6346 return GetShiftedByZeros(TZ);
6347 }
6348 case scUMaxExpr:
6349 case scSMaxExpr:
6350 case scUMinExpr:
6351 case scSMinExpr:
6352 case scSequentialUMinExpr:
6353 return GetGCDMultiple(cast<SCEVNAryExpr>(Val: S));
6354 case scUnknown: {
6355 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6356 // the point their underlying IR instruction has been defined. If CtxI was
6357 // not provided, use:
6358 // * the first instruction in the entry block if it is an argument
6359 // * the instruction itself otherwise.
6360 const SCEVUnknown *U = cast<SCEVUnknown>(Val: S);
6361 if (!CtxI) {
6362 if (isa<Argument>(Val: U->getValue()))
6363 CtxI = &*F.getEntryBlock().begin();
6364 else if (auto *I = dyn_cast<Instruction>(Val: U->getValue()))
6365 CtxI = I;
6366 }
6367 unsigned Known =
6368 computeKnownBits(V: U->getValue(),
6369 Q: SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6370 .allowEphemerals(AllowEphemerals: true))
6371 .countMinTrailingZeros();
6372 return GetShiftedByZeros(Known);
6373 }
6374 case scCouldNotCompute:
6375 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6376 }
6377 llvm_unreachable("Unknown SCEV kind!");
6378}
6379
6380APInt ScalarEvolution::getConstantMultiple(const SCEV *S,
6381 const Instruction *CtxI) {
6382 // Skip looking up and updating the cache if there is a context instruction,
6383 // as the result will only be valid in the specified context.
6384 if (CtxI)
6385 return getConstantMultipleImpl(S, CtxI);
6386
6387 auto I = ConstantMultipleCache.find(Val: S);
6388 if (I != ConstantMultipleCache.end())
6389 return I->second;
6390
6391 APInt Result = getConstantMultipleImpl(S, CtxI);
6392 auto InsertPair = ConstantMultipleCache.insert(KV: {S, Result});
6393 assert(InsertPair.second && "Should insert a new key");
6394 return InsertPair.first->second;
6395}
6396
6397APInt ScalarEvolution::getNonZeroConstantMultiple(const SCEV *S) {
6398 APInt Multiple = getConstantMultiple(S);
6399 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6400}
6401
6402uint32_t ScalarEvolution::getMinTrailingZeros(const SCEV *S,
6403 const Instruction *CtxI) {
6404 return std::min(a: getConstantMultiple(S, CtxI).countTrailingZeros(),
6405 b: (unsigned)getTypeSizeInBits(Ty: S->getType()));
6406}
6407
6408/// Helper method to assign a range to V from metadata present in the IR.
6409static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6410 if (Instruction *I = dyn_cast<Instruction>(Val: V)) {
6411 if (MDNode *MD = I->getMetadata(KindID: LLVMContext::MD_range))
6412 return getConstantRangeFromMetadata(RangeMD: *MD);
6413 if (const auto *CB = dyn_cast<CallBase>(Val: V))
6414 if (std::optional<ConstantRange> Range = CB->getRange())
6415 return Range;
6416 }
6417 if (auto *A = dyn_cast<Argument>(Val: V))
6418 if (std::optional<ConstantRange> Range = A->getRange())
6419 return Range;
6420
6421 return std::nullopt;
6422}
6423
6424void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, SCEVFlags Flags) {
6425 SCEVFlags NWFlags = Flags & SCEV::FlagsNoWrapMask;
6426 if (AddRec->getNoWrapFlags(Mask: NWFlags) != NWFlags) {
6427 AddRec->setNoWrapFlags(NWFlags);
6428 UnsignedRanges.erase(Val: AddRec);
6429 SignedRanges.erase(Val: AddRec);
6430 ConstantMultipleCache.erase(Val: AddRec);
6431 }
6432}
6433
6434ConstantRange ScalarEvolution::
6435getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6436 const DataLayout &DL = getDataLayout();
6437
6438 unsigned BitWidth = getTypeSizeInBits(Ty: U->getType());
6439 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6440
6441 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6442 // use information about the trip count to improve our available range. Note
6443 // that the trip count independent cases are already handled by known bits.
6444 // WARNING: The definition of recurrence used here is subtly different than
6445 // the one used by AddRec (and thus most of this file). Step is allowed to
6446 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6447 // and other addrecs in the same loop (for non-affine addrecs). The code
6448 // below intentionally handles the case where step is not loop invariant.
6449 auto *P = dyn_cast<PHINode>(Val: U->getValue());
6450 if (!P)
6451 return FullSet;
6452
6453 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6454 // even the values that are not available in these blocks may come from them,
6455 // and this leads to false-positive recurrence test.
6456 for (auto *Pred : predecessors(BB: P->getParent()))
6457 if (!DT.isReachableFromEntry(A: Pred))
6458 return FullSet;
6459
6460 BinaryOperator *BO;
6461 Value *Start, *Step;
6462 if (!matchSimpleRecurrence(P, BO, Start, Step))
6463 return FullSet;
6464
6465 // If we found a recurrence in reachable code, we must be in a loop. Note
6466 // that BO might be in some subloop of L, and that's completely okay.
6467 auto *L = LI.getLoopFor(BB: P->getParent());
6468 assert(L && L->getHeader() == P->getParent());
6469 if (!L->contains(BB: BO->getParent()))
6470 // NOTE: This bailout should be an assert instead. However, asserting
6471 // the condition here exposes a case where LoopFusion is querying SCEV
6472 // with malformed loop information during the midst of the transform.
6473 // There doesn't appear to be an obvious fix, so for the moment bailout
6474 // until the caller issue can be fixed. PR49566 tracks the bug.
6475 return FullSet;
6476
6477 // TODO: Extend to other opcodes such as mul, and div
6478 switch (BO->getOpcode()) {
6479 default:
6480 return FullSet;
6481 case Instruction::AShr:
6482 case Instruction::LShr:
6483 case Instruction::Shl:
6484 break;
6485 };
6486
6487 if (BO->getOperand(i_nocapture: 0) != P)
6488 // TODO: Handle the power function forms some day.
6489 return FullSet;
6490
6491 unsigned TC = getSmallConstantMaxTripCount(L);
6492 if (!TC || TC >= BitWidth)
6493 return FullSet;
6494
6495 auto KnownStart = computeKnownBits(V: Start, DL, AC: &AC, CtxI: nullptr, DT: &DT);
6496 auto KnownStep = computeKnownBits(V: Step, DL, AC: &AC, CtxI: nullptr, DT: &DT);
6497 assert(KnownStart.getBitWidth() == BitWidth &&
6498 KnownStep.getBitWidth() == BitWidth);
6499
6500 // Compute total shift amount, being careful of overflow and bitwidths.
6501 auto MaxShiftAmt = KnownStep.getMaxValue();
6502 APInt TCAP(BitWidth, TC-1);
6503 bool Overflow = false;
6504 auto TotalShift = MaxShiftAmt.umul_ov(RHS: TCAP, Overflow);
6505 if (Overflow)
6506 return FullSet;
6507
6508 switch (BO->getOpcode()) {
6509 default:
6510 llvm_unreachable("filtered out above");
6511 case Instruction::AShr: {
6512 // For each ashr, three cases:
6513 // shift = 0 => unchanged value
6514 // saturation => 0 or -1
6515 // other => a value closer to zero (of the same sign)
6516 // Thus, the end value is closer to zero than the start.
6517 auto KnownEnd = KnownBits::ashr(LHS: KnownStart,
6518 RHS: KnownBits::makeConstant(C: TotalShift));
6519 if (KnownStart.isNonNegative())
6520 // Analogous to lshr (simply not yet canonicalized)
6521 return ConstantRange::getNonEmpty(Lower: KnownEnd.getMinValue(),
6522 Upper: KnownStart.getMaxValue() + 1);
6523 if (KnownStart.isNegative())
6524 // End >=u Start && End <=s Start
6525 return ConstantRange::getNonEmpty(Lower: KnownStart.getMinValue(),
6526 Upper: KnownEnd.getMaxValue() + 1);
6527 break;
6528 }
6529 case Instruction::LShr: {
6530 // For each lshr, three cases:
6531 // shift = 0 => unchanged value
6532 // saturation => 0
6533 // other => a smaller positive number
6534 // Thus, the low end of the unsigned range is the last value produced.
6535 auto KnownEnd = KnownBits::lshr(LHS: KnownStart,
6536 RHS: KnownBits::makeConstant(C: TotalShift));
6537 return ConstantRange::getNonEmpty(Lower: KnownEnd.getMinValue(),
6538 Upper: KnownStart.getMaxValue() + 1);
6539 }
6540 case Instruction::Shl: {
6541 // Iff no bits are shifted out, value increases on every shift.
6542 auto KnownEnd = KnownBits::shl(LHS: KnownStart,
6543 RHS: KnownBits::makeConstant(C: TotalShift));
6544 if (TotalShift.ult(RHS: KnownStart.countMinLeadingZeros()))
6545 return ConstantRange(KnownStart.getMinValue(),
6546 KnownEnd.getMaxValue() + 1);
6547 break;
6548 }
6549 };
6550 return FullSet;
6551}
6552
6553// The goal of this function is to check if recursively visiting the operands
6554// of this PHI might lead to an infinite loop. If we do see such a loop,
6555// there's no good way to break it, so we avoid analyzing such cases.
6556//
6557// getRangeRef previously used a visited set to avoid infinite loops, but this
6558// caused other issues: the result was dependent on the order of getRangeRef
6559// calls, and the interaction with createSCEVIter could cause a stack overflow
6560// in some cases (see issue #148253).
6561//
6562// FIXME: The way this is implemented is overly conservative; this checks
6563// for a few obviously safe patterns, but anything that doesn't lead to
6564// recursion is fine.
6565static bool RangeRefPHIAllowedOperands(DominatorTree &DT, PHINode *PHI) {
6566 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6567 if (getOperandsForSelectLikePHI(DT, PN: PHI, Cond, LHS, RHS))
6568 return true;
6569
6570 if (all_of(Range: PHI->operands(),
6571 P: [&](Value *Operand) { return DT.dominates(Def: Operand, User: PHI); }))
6572 return true;
6573
6574 return false;
6575}
6576
6577const ConstantRange &
6578ScalarEvolution::getRangeRefIter(const SCEV *S,
6579 ScalarEvolution::RangeSignHint SignHint) {
6580 DenseMap<const SCEV *, ConstantRange> &Cache =
6581 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6582 : SignedRanges;
6583 SmallVector<SCEVUse> WorkList;
6584 SmallPtrSet<const SCEV *, 8> Seen;
6585
6586 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6587 // SCEVUnknown PHI node.
6588 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6589 if (!Seen.insert(Ptr: Expr).second)
6590 return;
6591 if (Cache.contains(Val: Expr))
6592 return;
6593 switch (Expr->getSCEVType()) {
6594 case scUnknown:
6595 if (!isa<PHINode>(Val: cast<SCEVUnknown>(Val: Expr)->getValue()))
6596 break;
6597 [[fallthrough]];
6598 case scConstant:
6599 case scVScale:
6600 case scTruncate:
6601 case scZeroExtend:
6602 case scSignExtend:
6603 case scPtrToAddr:
6604 case scAddExpr:
6605 case scMulExpr:
6606 case scUDivExpr:
6607 case scAddRecExpr:
6608 case scUMaxExpr:
6609 case scSMaxExpr:
6610 case scUMinExpr:
6611 case scSMinExpr:
6612 case scSequentialUMinExpr:
6613 WorkList.push_back(Elt: Expr);
6614 break;
6615 case scCouldNotCompute:
6616 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6617 }
6618 };
6619 AddToWorklist(S);
6620
6621 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6622 for (unsigned I = 0; I != WorkList.size(); ++I) {
6623 const SCEV *P = WorkList[I];
6624 auto *UnknownS = dyn_cast<SCEVUnknown>(Val: P);
6625 // If it is not a `SCEVUnknown`, just recurse into operands.
6626 if (!UnknownS) {
6627 for (const SCEV *Op : P->operands())
6628 AddToWorklist(Op);
6629 continue;
6630 }
6631 // `SCEVUnknown`'s require special treatment.
6632 if (PHINode *P = dyn_cast<PHINode>(Val: UnknownS->getValue())) {
6633 if (!RangeRefPHIAllowedOperands(DT, PHI: P))
6634 continue;
6635 for (auto &Op : reverse(C: P->operands()))
6636 AddToWorklist(getSCEV(V: Op));
6637 }
6638 }
6639
6640 if (!WorkList.empty()) {
6641 // Use getRangeRef to compute ranges for items in the worklist in reverse
6642 // order. This will force ranges for earlier operands to be computed before
6643 // their users in most cases.
6644 for (const SCEV *P : reverse(C: drop_begin(RangeOrContainer&: WorkList))) {
6645 getRangeRef(S: P, Hint: SignHint);
6646 }
6647 }
6648
6649 return getRangeRef(S, Hint: SignHint, Depth: 0);
6650}
6651
6652const APInt *ScalarEvolution::getConstantAPIntOrNull(const SCEV *S) {
6653 if (const auto *C = dyn_cast<SCEVConstant>(Val: S))
6654 return &C->getAPInt();
6655 return nullptr;
6656}
6657
6658/// Determine the range for a particular SCEV. If SignHint is
6659/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6660/// with a "cleaner" unsigned (resp. signed) representation.
6661const ConstantRange &ScalarEvolution::getRangeRef(
6662 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6663 DenseMap<const SCEV *, ConstantRange> &Cache =
6664 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6665 : SignedRanges;
6666 ConstantRange::PreferredRangeType RangeType =
6667 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6668 : ConstantRange::Signed;
6669
6670 // See if we've computed this range already.
6671 auto I = Cache.find(Val: S);
6672 if (I != Cache.end())
6673 return I->second;
6674
6675 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Val: S))
6676 return setRange(S: C, Hint: SignHint, CR: ConstantRange(C->getAPInt()));
6677
6678 // Switch to iteratively computing the range for S, if it is part of a deeply
6679 // nested expression.
6680 if (Depth > RangeIterThreshold)
6681 return getRangeRefIter(S, SignHint);
6682
6683 unsigned BitWidth = getTypeSizeInBits(Ty: S->getType());
6684 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6685 using OBO = OverflowingBinaryOperator;
6686
6687 // If the value has known zeros, the maximum value will have those known zeros
6688 // as well.
6689 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6690 APInt Multiple = getNonZeroConstantMultiple(S);
6691 APInt Remainder = APInt::getMaxValue(numBits: BitWidth).urem(RHS: Multiple);
6692 if (!Remainder.isZero())
6693 ConservativeResult =
6694 ConstantRange(APInt::getMinValue(numBits: BitWidth),
6695 APInt::getMaxValue(numBits: BitWidth) - Remainder + 1);
6696 }
6697 else {
6698 uint32_t TZ = getMinTrailingZeros(S);
6699 if (TZ != 0) {
6700 ConservativeResult = ConstantRange(
6701 APInt::getSignedMinValue(numBits: BitWidth),
6702 APInt::getSignedMaxValue(numBits: BitWidth).ashr(ShiftAmt: TZ).shl(shiftAmt: TZ) + 1);
6703 }
6704 }
6705
6706 switch (S->getSCEVType()) {
6707 case scConstant:
6708 llvm_unreachable("Already handled above.");
6709 case scVScale:
6710 return setRange(S, Hint: SignHint, CR: getVScaleRange(F: &F, BitWidth));
6711 case scTruncate: {
6712 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Val: S);
6713 ConstantRange X = getRangeRef(S: Trunc->getOperand(), SignHint, Depth: Depth + 1);
6714 return setRange(
6715 S: Trunc, Hint: SignHint,
6716 CR: ConservativeResult.intersectWith(CR: X.truncate(BitWidth), Type: RangeType));
6717 }
6718 case scZeroExtend: {
6719 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(Val: S);
6720 ConstantRange X = getRangeRef(S: ZExt->getOperand(), SignHint, Depth: Depth + 1);
6721 return setRange(
6722 S: ZExt, Hint: SignHint,
6723 CR: ConservativeResult.intersectWith(CR: X.zeroExtend(BitWidth), Type: RangeType));
6724 }
6725 case scSignExtend: {
6726 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(Val: S);
6727 ConstantRange X = getRangeRef(S: SExt->getOperand(), SignHint, Depth: Depth + 1);
6728 return setRange(
6729 S: SExt, Hint: SignHint,
6730 CR: ConservativeResult.intersectWith(CR: X.signExtend(BitWidth), Type: RangeType));
6731 }
6732 case scPtrToAddr: {
6733 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(Val: S);
6734 ConstantRange X = getRangeRef(S: Cast->getOperand(), SignHint, Depth: Depth + 1);
6735 return setRange(S: Cast, Hint: SignHint, CR: X);
6736 }
6737 case scAddExpr: {
6738 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Val: S);
6739 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6740 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6741 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6742 match(S, P: m_scev_URem(LHS: m_SCEV(V&: URemLHS), RHS: m_SCEV(V&: URemRHS), SE&: *this))) {
6743 ConstantRange LHSRange = getRangeRef(S: URemLHS, SignHint, Depth: Depth + 1);
6744 ConstantRange RHSRange = getRangeRef(S: URemRHS, SignHint, Depth: Depth + 1);
6745 ConservativeResult =
6746 ConservativeResult.intersectWith(CR: LHSRange.urem(Other: RHSRange), Type: RangeType);
6747 }
6748 ConstantRange X = getRangeRef(S: Add->getOperand(i: 0), SignHint, Depth: Depth + 1);
6749 unsigned WrapType = OBO::AnyWrap;
6750 if (Add->hasNoSignedWrap())
6751 WrapType |= OBO::NoSignedWrap;
6752 if (Add->hasNoUnsignedWrap())
6753 WrapType |= OBO::NoUnsignedWrap;
6754 for (const SCEV *Op : drop_begin(RangeOrContainer: Add->operands()))
6755 X = X.addWithNoWrap(Other: getRangeRef(S: Op, SignHint, Depth: Depth + 1), NoWrapKind: WrapType,
6756 RangeType);
6757 return setRange(S: Add, Hint: SignHint,
6758 CR: ConservativeResult.intersectWith(CR: X, Type: RangeType));
6759 }
6760 case scMulExpr: {
6761 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Val: S);
6762 ConstantRange X = getRangeRef(S: Mul->getOperand(i: 0), SignHint, Depth: Depth + 1);
6763 for (const SCEV *Op : drop_begin(RangeOrContainer: Mul->operands()))
6764 X = X.multiply(Other: getRangeRef(S: Op, SignHint, Depth: Depth + 1));
6765 return setRange(S: Mul, Hint: SignHint,
6766 CR: ConservativeResult.intersectWith(CR: X, Type: RangeType));
6767 }
6768 case scUDivExpr: {
6769 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(Val: S);
6770 ConstantRange X = getRangeRef(S: UDiv->getLHS(), SignHint, Depth: Depth + 1);
6771 ConstantRange Y = getRangeRef(S: UDiv->getRHS(), SignHint, Depth: Depth + 1);
6772 return setRange(S: UDiv, Hint: SignHint,
6773 CR: ConservativeResult.intersectWith(CR: X.udiv(Other: Y), Type: RangeType));
6774 }
6775 case scAddRecExpr: {
6776 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Val: S);
6777 // If there's no unsigned wrap, the value will never be less than its
6778 // initial value.
6779 if (AddRec->hasNoUnsignedWrap()) {
6780 APInt UnsignedMinValue = getUnsignedRangeMin(S: AddRec->getStart());
6781 if (!UnsignedMinValue.isZero())
6782 ConservativeResult = ConservativeResult.intersectWith(
6783 CR: ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), Type: RangeType);
6784 }
6785
6786 // If there's no signed wrap, and all the operands except initial value have
6787 // the same sign or zero, the value won't ever be:
6788 // 1: smaller than initial value if operands are non negative,
6789 // 2: bigger than initial value if operands are non positive.
6790 // For both cases, value can not cross signed min/max boundary.
6791 if (AddRec->hasNoSignedWrap()) {
6792 bool AllNonNeg = true;
6793 bool AllNonPos = true;
6794 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6795 if (!isKnownNonNegative(S: AddRec->getOperand(i)))
6796 AllNonNeg = false;
6797 if (!isKnownNonPositive(S: AddRec->getOperand(i)))
6798 AllNonPos = false;
6799 }
6800 if (AllNonNeg)
6801 ConservativeResult = ConservativeResult.intersectWith(
6802 CR: ConstantRange::getNonEmpty(Lower: getSignedRangeMin(S: AddRec->getStart()),
6803 Upper: APInt::getSignedMinValue(numBits: BitWidth)),
6804 Type: RangeType);
6805 else if (AllNonPos)
6806 ConservativeResult = ConservativeResult.intersectWith(
6807 CR: ConstantRange::getNonEmpty(Lower: APInt::getSignedMinValue(numBits: BitWidth),
6808 Upper: getSignedRangeMax(S: AddRec->getStart()) +
6809 1),
6810 Type: RangeType);
6811 }
6812
6813 // TODO: non-affine addrec
6814 if (AddRec->isAffine()) {
6815 const SCEV *MaxBEScev =
6816 getConstantMaxBackedgeTakenCount(L: AddRec->getLoop());
6817 if (!isa<SCEVCouldNotCompute>(Val: MaxBEScev)) {
6818 APInt MaxBECount = cast<SCEVConstant>(Val: MaxBEScev)->getAPInt();
6819
6820 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6821 // MaxBECount's active bits are all <= AddRec's bit width.
6822 if (MaxBECount.getBitWidth() > BitWidth &&
6823 MaxBECount.getActiveBits() <= BitWidth)
6824 MaxBECount = MaxBECount.trunc(width: BitWidth);
6825 else if (MaxBECount.getBitWidth() < BitWidth)
6826 MaxBECount = MaxBECount.zext(width: BitWidth);
6827
6828 if (MaxBECount.getBitWidth() == BitWidth) {
6829 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
6830 Start: AddRec->getStart(), Step: AddRec->getStepRecurrence(SE&: *this), MaxBECount);
6831 ConservativeResult =
6832 ConservativeResult.intersectWith(CR: RangeFromAffine, Type: RangeType);
6833 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
6834
6835 auto RangeFromFactoring = getRangeViaFactoring(
6836 Start: AddRec->getStart(), Step: AddRec->getStepRecurrence(SE&: *this), MaxBECount);
6837 ConservativeResult =
6838 ConservativeResult.intersectWith(CR: RangeFromFactoring, Type: RangeType);
6839 }
6840 }
6841
6842 // Now try symbolic BE count and more powerful methods.
6843 if (UseExpensiveRangeSharpening) {
6844 const SCEV *SymbolicMaxBECount =
6845 getSymbolicMaxBackedgeTakenCount(L: AddRec->getLoop());
6846 if (!isa<SCEVCouldNotCompute>(Val: SymbolicMaxBECount) &&
6847 getTypeSizeInBits(Ty: MaxBEScev->getType()) <= BitWidth &&
6848 AddRec->hasNoSelfWrap()) {
6849 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6850 AddRec, MaxBECount: SymbolicMaxBECount, BitWidth, SignHint);
6851 ConservativeResult =
6852 ConservativeResult.intersectWith(CR: RangeFromAffineNew, Type: RangeType);
6853 }
6854 }
6855 }
6856
6857 return setRange(S: AddRec, Hint: SignHint, CR: std::move(ConservativeResult));
6858 }
6859 case scUMaxExpr:
6860 case scSMaxExpr:
6861 case scUMinExpr:
6862 case scSMinExpr:
6863 case scSequentialUMinExpr: {
6864 Intrinsic::ID ID;
6865 switch (S->getSCEVType()) {
6866 case scUMaxExpr:
6867 ID = Intrinsic::umax;
6868 break;
6869 case scSMaxExpr:
6870 ID = Intrinsic::smax;
6871 break;
6872 case scUMinExpr:
6873 case scSequentialUMinExpr:
6874 ID = Intrinsic::umin;
6875 break;
6876 case scSMinExpr:
6877 ID = Intrinsic::smin;
6878 break;
6879 default:
6880 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6881 }
6882
6883 const auto *NAry = cast<SCEVNAryExpr>(Val: S);
6884 ConstantRange X = getRangeRef(S: NAry->getOperand(i: 0), SignHint, Depth: Depth + 1);
6885 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6886 X = X.intrinsic(
6887 IntrinsicID: ID, Ops: {X, getRangeRef(S: NAry->getOperand(i), SignHint, Depth: Depth + 1)});
6888 return setRange(S, Hint: SignHint,
6889 CR: ConservativeResult.intersectWith(CR: X, Type: RangeType));
6890 }
6891 case scUnknown: {
6892 const SCEVUnknown *U = cast<SCEVUnknown>(Val: S);
6893 Value *V = U->getValue();
6894
6895 // Check if the IR explicitly contains !range metadata.
6896 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6897 if (MDRange)
6898 ConservativeResult =
6899 ConservativeResult.intersectWith(CR: *MDRange, Type: RangeType);
6900
6901 // Use facts about recurrences in the underlying IR. Note that add
6902 // recurrences are AddRecExprs and thus don't hit this path. This
6903 // primarily handles shift recurrences.
6904 auto CR = getRangeForUnknownRecurrence(U);
6905 ConservativeResult = ConservativeResult.intersectWith(CR);
6906
6907 // See if ValueTracking can give us a useful range.
6908 const DataLayout &DL = getDataLayout();
6909 KnownBits Known = computeKnownBits(V, DL, AC: &AC, CtxI: nullptr, DT: &DT);
6910 if (Known.getBitWidth() != BitWidth)
6911 Known = Known.zextOrTrunc(BitWidth);
6912
6913 // ValueTracking may be able to compute a tighter result for the number of
6914 // sign bits than for the value of those sign bits.
6915 unsigned NS = ComputeNumSignBits(Op: V, DL, AC: &AC, CtxI: nullptr, DT: &DT);
6916 if (U->getType()->isPointerTy()) {
6917 // NS counts the sign bits of the whole pointer; drop those above the
6918 // index bits.
6919 unsigned PtrIdxDiff =
6920 DL.getPointerTypeSizeInBits(U->getType()) - BitWidth;
6921 NS = NS > PtrIdxDiff ? NS - PtrIdxDiff : 1;
6922 }
6923
6924 if (NS > 1) {
6925 // If we know any of the sign bits, we know all of the sign bits.
6926 if (!Known.Zero.getHiBits(numBits: NS).isZero())
6927 Known.Zero.setHighBits(NS);
6928 if (!Known.One.getHiBits(numBits: NS).isZero())
6929 Known.One.setHighBits(NS);
6930 }
6931
6932 if (Known.getMinValue() != Known.getMaxValue() + 1)
6933 ConservativeResult = ConservativeResult.intersectWith(
6934 CR: ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6935 Type: RangeType);
6936 if (NS > 1)
6937 ConservativeResult = ConservativeResult.intersectWith(
6938 CR: ConstantRange(APInt::getSignedMinValue(numBits: BitWidth).ashr(ShiftAmt: NS - 1),
6939 APInt::getSignedMaxValue(numBits: BitWidth).ashr(ShiftAmt: NS - 1) + 1),
6940 Type: RangeType);
6941
6942 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6943 // Strengthen the range if the underlying IR value is a
6944 // global/alloca/heap allocation using the size of the object.
6945 bool CanBeNull;
6946 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
6947 DL, CanBeNull, /*CanBeFreed=*/nullptr);
6948 if (DerefBytes > 1 && isUIntN(N: BitWidth, x: DerefBytes)) {
6949 // The highest address the object can start is DerefBytes bytes before
6950 // the end (unsigned max value). If this value is not a multiple of the
6951 // alignment, the last possible start value is the next lowest multiple
6952 // of the alignment. Note: The computations below cannot overflow,
6953 // because if they would there's no possible start address for the
6954 // object.
6955 APInt MaxVal =
6956 APInt::getMaxValue(numBits: BitWidth) - APInt(BitWidth, DerefBytes);
6957 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6958 uint64_t Rem = MaxVal.urem(RHS: Align);
6959 MaxVal -= APInt(BitWidth, Rem);
6960 APInt MinVal = APInt::getZero(numBits: BitWidth);
6961 if (llvm::isKnownNonZero(V, Q: DL))
6962 MinVal = Align;
6963 ConservativeResult = ConservativeResult.intersectWith(
6964 CR: ConstantRange::getNonEmpty(Lower: MinVal, Upper: MaxVal + 1), Type: RangeType);
6965 }
6966 }
6967
6968 // A range of Phi is a subset of union of all ranges of its input.
6969 if (PHINode *Phi = dyn_cast<PHINode>(Val: V)) {
6970 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
6971 // AddRecs; return the range for the corresponding AddRec.
6972 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Val: getSCEV(V)))
6973 return getRangeRef(S: AR, SignHint, Depth: Depth + 1);
6974
6975 // Make sure that we do not run over cycled Phis.
6976 if (RangeRefPHIAllowedOperands(DT, PHI: Phi)) {
6977 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6978
6979 for (const auto &Op : Phi->operands()) {
6980 auto OpRange = getRangeRef(S: getSCEV(V: Op), SignHint, Depth: Depth + 1);
6981 RangeFromOps = RangeFromOps.unionWith(CR: OpRange);
6982 // No point to continue if we already have a full set.
6983 if (RangeFromOps.isFullSet())
6984 break;
6985 }
6986 ConservativeResult =
6987 ConservativeResult.intersectWith(CR: RangeFromOps, Type: RangeType);
6988 }
6989 }
6990
6991 // vscale can't be equal to zero
6992 if (const auto *II = dyn_cast<IntrinsicInst>(Val: V))
6993 if (II->getIntrinsicID() == Intrinsic::vscale) {
6994 ConstantRange Disallowed = APInt::getZero(numBits: BitWidth);
6995 ConservativeResult = ConservativeResult.difference(CR: Disallowed);
6996 }
6997
6998 return setRange(S: U, Hint: SignHint, CR: std::move(ConservativeResult));
6999 }
7000 case scCouldNotCompute:
7001 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
7002 }
7003
7004 return setRange(S, Hint: SignHint, CR: std::move(ConservativeResult));
7005}
7006
7007// Given a StartRange, Step and MaxBECount for an expression compute a range of
7008// values that the expression can take. Initially, the expression has a value
7009// from StartRange and then is changed by Step up to MaxBECount times. Signed
7010// argument defines if we treat Step as signed or unsigned. The second return
7011// value indicates that no wrapping occurred.
7012static std::pair<ConstantRange, bool>
7013getRangeForAffineARHelper(APInt Step, const ConstantRange &StartRange,
7014 const APInt &MaxBECount, bool Signed) {
7015 unsigned BitWidth = Step.getBitWidth();
7016 assert(BitWidth == StartRange.getBitWidth() &&
7017 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
7018 // If either Step or MaxBECount is 0, then the expression won't change, and we
7019 // just need to return the initial range.
7020 if (Step == 0 || MaxBECount == 0)
7021 return {StartRange, true};
7022
7023 // If we don't know anything about the initial value (i.e. StartRange is
7024 // FullRange), then we don't know anything about the final range either.
7025 // Return FullRange.
7026 if (StartRange.isFullSet())
7027 return {ConstantRange::getFull(BitWidth), false};
7028
7029 // If Step is signed and negative, then we use its absolute value, but we also
7030 // note that we're moving in the opposite direction.
7031 bool Descending = Signed && Step.isNegative();
7032
7033 if (Signed)
7034 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
7035 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
7036 // This equations hold true due to the well-defined wrap-around behavior of
7037 // APInt.
7038 Step = Step.abs();
7039
7040 // Check if Offset is more than full span of BitWidth. If it is, the
7041 // expression is guaranteed to overflow.
7042 if (APInt::getMaxValue(numBits: StartRange.getBitWidth()).udiv(RHS: Step).ult(RHS: MaxBECount))
7043 return {ConstantRange::getFull(BitWidth), false};
7044
7045 // Offset is by how much the expression can change. Checks above guarantee no
7046 // overflow here.
7047 APInt Offset = Step * MaxBECount;
7048
7049 // Minimum value of the final range will match the minimal value of StartRange
7050 // if the expression is increasing and will be decreased by Offset otherwise.
7051 // Maximum value of the final range will match the maximal value of StartRange
7052 // if the expression is decreasing and will be increased by Offset otherwise.
7053 APInt StartLower = StartRange.getLower();
7054 APInt StartUpper = StartRange.getUpper() - 1;
7055 bool Overflow;
7056 APInt MovedBoundary;
7057 if (Signed) {
7058 // This does not use sadd_ov, as we want to check overflow for a signed
7059 // start with an unsigned offset.
7060 if (Descending) {
7061 MovedBoundary = StartLower - std::move(Offset);
7062 Overflow = MovedBoundary.sgt(RHS: StartLower) || StartRange.isSignWrappedSet();
7063 } else {
7064 MovedBoundary = StartUpper + std::move(Offset);
7065 Overflow = MovedBoundary.slt(RHS: StartUpper) || StartRange.isSignWrappedSet();
7066 }
7067 } else {
7068 MovedBoundary = StartUpper.uadd_ov(RHS: std::move(Offset), Overflow);
7069 Overflow |= StartRange.isWrappedSet();
7070 }
7071
7072 // It's possible that the new minimum/maximum value will fall into the initial
7073 // range (due to wrap around). This means that the expression can take any
7074 // value in this bitwidth, and we have to return full range.
7075 if (StartRange.contains(Val: MovedBoundary))
7076 return {ConstantRange::getFull(BitWidth), false};
7077
7078 APInt NewLower =
7079 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7080 APInt NewUpper =
7081 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7082 NewUpper += 1;
7083
7084 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7085 return {ConstantRange::getNonEmpty(Lower: std::move(NewLower), Upper: std::move(NewUpper)),
7086 !Overflow};
7087}
7088
7089std::pair<ConstantRange, SCEVFlags>
7090ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
7091 const APInt &MaxBECount) {
7092 assert(getTypeSizeInBits(Start->getType()) ==
7093 getTypeSizeInBits(Step->getType()) &&
7094 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7095 "mismatched bit widths");
7096
7097 // First, consider step signed.
7098 ConstantRange StartSRange = getSignedRange(S: Start);
7099 ConstantRange StepSRange = getSignedRange(S: Step);
7100
7101 // If Step can be both positive and negative, we need to find ranges for the
7102 // maximum absolute step values in both directions and union them.
7103 auto [SR, NSW] = getRangeForAffineARHelper(
7104 Step: StepSRange.getSignedMin(), StartRange: StartSRange, MaxBECount, /*Signed=*/true);
7105 // A singleton step has identical signed bounds, so the second computation
7106 // would produce the same range and no-wrap result.
7107 if (!StepSRange.isSingleElement()) {
7108 auto [SRMax, NSWMax] = getRangeForAffineARHelper(
7109 Step: StepSRange.getSignedMax(), StartRange: StartSRange, MaxBECount, /*Signed=*/true);
7110 SR = SR.unionWith(CR: SRMax);
7111 NSW &= NSWMax;
7112 }
7113
7114 // Next, consider step unsigned.
7115 auto [UR, NUW] = getRangeForAffineARHelper(
7116 Step: getUnsignedRangeMax(S: Step), StartRange: getUnsignedRange(S: Start), MaxBECount,
7117 /*Signed=*/false);
7118
7119 SCEVFlags Flags = SCEV::FlagNone;
7120 if (NUW)
7121 Flags = ScalarEvolution::setFlags(Flags, OnFlags: SCEV::FlagNUW);
7122 if (NSW)
7123 Flags = ScalarEvolution::setFlags(Flags, OnFlags: SCEV::FlagNSW);
7124
7125 // Finally, intersect signed and unsigned ranges.
7126 return {SR.intersectWith(CR: UR, Type: ConstantRange::Smallest), Flags};
7127}
7128
7129ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7130 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7131 ScalarEvolution::RangeSignHint SignHint) {
7132 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7133 assert(AddRec->hasNoSelfWrap() &&
7134 "This only works for non-self-wrapping AddRecs!");
7135 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7136 const SCEV *Step = AddRec->getStepRecurrence(SE&: *this);
7137 // Only deal with constant step to save compile time.
7138 if (!isa<SCEVConstant>(Val: Step))
7139 return ConstantRange::getFull(BitWidth);
7140 // Let's make sure that we can prove that we do not self-wrap during
7141 // MaxBECount iterations. We need this because MaxBECount is a maximum
7142 // iteration count estimate, and we might infer nw from some exit for which we
7143 // do not know max exit count (or any other side reasoning).
7144 // TODO: Turn into assert at some point.
7145 if (getTypeSizeInBits(Ty: MaxBECount->getType()) >
7146 getTypeSizeInBits(Ty: AddRec->getType()))
7147 return ConstantRange::getFull(BitWidth);
7148 MaxBECount = getNoopOrZeroExtend(V: MaxBECount, Ty: AddRec->getType());
7149 const SCEV *RangeWidth = getMinusOne(Ty: AddRec->getType());
7150 const SCEV *StepAbs = getUMinExpr(LHS: Step, RHS: getNegativeSCEV(V: Step));
7151 const SCEV *MaxItersWithoutWrap = getUDivExpr(LHS: RangeWidth, RHS: StepAbs);
7152 if (!isKnownPredicateViaConstantRanges(Pred: ICmpInst::ICMP_ULE, LHS: MaxBECount,
7153 RHS: MaxItersWithoutWrap))
7154 return ConstantRange::getFull(BitWidth);
7155
7156 ICmpInst::Predicate LEPred =
7157 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
7158 ICmpInst::Predicate GEPred =
7159 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
7160 const SCEV *End = AddRec->evaluateAtIteration(It: MaxBECount, SE&: *this);
7161
7162 // We know that there is no self-wrap. Let's take Start and End values and
7163 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7164 // the iteration. They either lie inside the range [Min(Start, End),
7165 // Max(Start, End)] or outside it:
7166 //
7167 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7168 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7169 //
7170 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7171 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7172 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7173 // Start <= End and step is positive, or Start >= End and step is negative.
7174 const SCEV *Start = applyLoopGuards(Expr: AddRec->getStart(), L: AddRec->getLoop());
7175 ConstantRange StartRange = getRangeRef(S: Start, SignHint);
7176 ConstantRange EndRange = getRangeRef(S: End, SignHint);
7177 ConstantRange RangeBetween = StartRange.unionWith(CR: EndRange);
7178 // If they already cover full iteration space, we will know nothing useful
7179 // even if we prove what we want to prove.
7180 if (RangeBetween.isFullSet())
7181 return RangeBetween;
7182 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7183 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7184 : RangeBetween.isWrappedSet();
7185 if (IsWrappedSet)
7186 return ConstantRange::getFull(BitWidth);
7187
7188 if (isKnownPositive(S: Step) &&
7189 isKnownPredicateViaConstantRanges(Pred: LEPred, LHS: Start, RHS: End))
7190 return RangeBetween;
7191 if (isKnownNegative(S: Step) &&
7192 isKnownPredicateViaConstantRanges(Pred: GEPred, LHS: Start, RHS: End))
7193 return RangeBetween;
7194 return ConstantRange::getFull(BitWidth);
7195}
7196
7197ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7198 const SCEV *Step,
7199 const APInt &MaxBECount) {
7200 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7201 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7202
7203 unsigned BitWidth = MaxBECount.getBitWidth();
7204 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7205 getTypeSizeInBits(Step->getType()) == BitWidth &&
7206 "mismatched bit widths");
7207
7208 struct SelectPattern {
7209 Value *Condition = nullptr;
7210 APInt TrueValue;
7211 APInt FalseValue;
7212
7213 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7214 const SCEV *S) {
7215 std::optional<unsigned> CastOp;
7216 APInt Offset(BitWidth, 0);
7217
7218 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
7219 "Should be!");
7220
7221 // Peel off a constant offset. In the future we could consider being
7222 // smarter here and handle {Start+Step,+,Step} too.
7223 const APInt *Off;
7224 if (match(S, P: m_scev_Add(Op0: m_scev_APInt(C&: Off), Op1: m_SCEV(V&: S))))
7225 Offset = *Off;
7226
7227 // Peel off a cast operation
7228 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(Val: S)) {
7229 CastOp = SCast->getSCEVType();
7230 S = SCast->getOperand();
7231 }
7232
7233 using namespace llvm::PatternMatch;
7234
7235 auto *SU = dyn_cast<SCEVUnknown>(Val: S);
7236 const APInt *TrueVal, *FalseVal;
7237 if (!SU ||
7238 !match(V: SU->getValue(), P: m_Select(C: m_Value(V&: Condition), L: m_APInt(Res&: TrueVal),
7239 R: m_APInt(Res&: FalseVal)))) {
7240 Condition = nullptr;
7241 return;
7242 }
7243
7244 TrueValue = *TrueVal;
7245 FalseValue = *FalseVal;
7246
7247 // Re-apply the cast we peeled off earlier
7248 if (CastOp)
7249 switch (*CastOp) {
7250 default:
7251 llvm_unreachable("Unknown SCEV cast type!");
7252
7253 case scTruncate:
7254 TrueValue = TrueValue.trunc(width: BitWidth);
7255 FalseValue = FalseValue.trunc(width: BitWidth);
7256 break;
7257 case scZeroExtend:
7258 TrueValue = TrueValue.zext(width: BitWidth);
7259 FalseValue = FalseValue.zext(width: BitWidth);
7260 break;
7261 case scSignExtend:
7262 TrueValue = TrueValue.sext(width: BitWidth);
7263 FalseValue = FalseValue.sext(width: BitWidth);
7264 break;
7265 }
7266
7267 // Re-apply the constant offset we peeled off earlier
7268 TrueValue += Offset;
7269 FalseValue += Offset;
7270 }
7271
7272 bool isRecognized() { return Condition != nullptr; }
7273 };
7274
7275 SelectPattern StartPattern(*this, BitWidth, Start);
7276 if (!StartPattern.isRecognized())
7277 return ConstantRange::getFull(BitWidth);
7278
7279 SelectPattern StepPattern(*this, BitWidth, Step);
7280 if (!StepPattern.isRecognized())
7281 return ConstantRange::getFull(BitWidth);
7282
7283 if (StartPattern.Condition != StepPattern.Condition) {
7284 // We don't handle this case today; but we could, by considering four
7285 // possibilities below instead of two. I'm not sure if there are cases where
7286 // that will help over what getRange already does, though.
7287 return ConstantRange::getFull(BitWidth);
7288 }
7289
7290 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7291 // construct arbitrary general SCEV expressions here. This function is called
7292 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7293 // say) can end up caching a suboptimal value.
7294
7295 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7296 // C2352 and C2512 (otherwise it isn't needed).
7297
7298 const SCEV *TrueStart = this->getConstant(Val: StartPattern.TrueValue);
7299 const SCEV *TrueStep = this->getConstant(Val: StepPattern.TrueValue);
7300 const SCEV *FalseStart = this->getConstant(Val: StartPattern.FalseValue);
7301 const SCEV *FalseStep = this->getConstant(Val: StepPattern.FalseValue);
7302
7303 ConstantRange TrueRange =
7304 this->getRangeForAffineAR(Start: TrueStart, Step: TrueStep, MaxBECount).first;
7305 ConstantRange FalseRange =
7306 this->getRangeForAffineAR(Start: FalseStart, Step: FalseStep, MaxBECount).first;
7307
7308 return TrueRange.unionWith(CR: FalseRange);
7309}
7310
7311SCEVFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7312 if (isa<ConstantExpr>(Val: V))
7313 return SCEV::FlagNone;
7314 const BinaryOperator *BinOp = cast<BinaryOperator>(Val: V);
7315
7316 // Return early if there are no flags to propagate to the SCEV.
7317 SCEVFlags Flags = SCEV::FlagNone;
7318 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(Val: BinOp);
7319 PDI && PDI->isDisjoint()) {
7320 Flags = ScalarEvolution::setFlags(Flags: SCEV::FlagNUW, OnFlags: SCEV::FlagNSW);
7321 } else {
7322 if (BinOp->hasNoUnsignedWrap())
7323 Flags = ScalarEvolution::setFlags(Flags, OnFlags: SCEV::FlagNUW);
7324 if (BinOp->hasNoSignedWrap())
7325 Flags = ScalarEvolution::setFlags(Flags, OnFlags: SCEV::FlagNSW);
7326 }
7327 if (Flags == SCEV::FlagNone)
7328 return SCEV::FlagNone;
7329
7330 return isSCEVExprNeverPoison(I: BinOp) ? Flags : SCEV::FlagNone;
7331}
7332
7333const Instruction *
7334ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7335 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Val: S))
7336 return &*AddRec->getLoop()->getHeader()->begin();
7337 if (auto *U = dyn_cast<SCEVUnknown>(Val: S))
7338 if (auto *I = dyn_cast<Instruction>(Val: U->getValue()))
7339 return I;
7340 return nullptr;
7341}
7342
7343const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7344 bool &Precise) {
7345 Precise = true;
7346 // Do a bounded search of the def relation of the requested SCEVs.
7347 SmallPtrSet<const SCEV *, 16> Visited;
7348 SmallVector<SCEVUse> Worklist;
7349 auto pushOp = [&](const SCEV *S) {
7350 if (!Visited.insert(Ptr: S).second)
7351 return;
7352 // Threshold of 30 here is arbitrary.
7353 if (Visited.size() > 30) {
7354 Precise = false;
7355 return;
7356 }
7357 Worklist.push_back(Elt: S);
7358 };
7359
7360 for (SCEVUse S : Ops)
7361 pushOp(S);
7362
7363 const Instruction *Bound = nullptr;
7364 while (!Worklist.empty()) {
7365 SCEVUse S = Worklist.pop_back_val();
7366 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7367 if (!Bound || DT.dominates(Def: Bound, User: DefI))
7368 Bound = DefI;
7369 } else {
7370 for (SCEVUse Op : S->operands())
7371 pushOp(Op);
7372 }
7373 }
7374 return Bound ? Bound : &*F.getEntryBlock().begin();
7375}
7376
7377const Instruction *
7378ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7379 bool Discard;
7380 return getDefiningScopeBound(Ops, Precise&: Discard);
7381}
7382
7383bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7384 const Instruction *B) {
7385 if (A->getParent() == B->getParent() &&
7386 isGuaranteedToTransferExecutionToSuccessor(Begin: A->getIterator(),
7387 End: B->getIterator()))
7388 return true;
7389
7390 auto *BLoop = LI.getLoopFor(BB: B->getParent());
7391 if (BLoop && BLoop->getHeader() == B->getParent() &&
7392 BLoop->getLoopPreheader() == A->getParent() &&
7393 isGuaranteedToTransferExecutionToSuccessor(Begin: A->getIterator(),
7394 End: A->getParent()->end()) &&
7395 isGuaranteedToTransferExecutionToSuccessor(Begin: B->getParent()->begin(),
7396 End: B->getIterator()))
7397 return true;
7398 return false;
7399}
7400
7401bool ScalarEvolution::isGuaranteedNotToBePoison(const SCEV *Op) {
7402 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7403 visitAll(Root: Op, Visitor&: PC);
7404 return PC.MaybePoison.empty();
7405}
7406
7407bool ScalarEvolution::isGuaranteedNotToCauseUB(const SCEV *Op) {
7408 return !SCEVExprContains(Root: Op, Pred: [this](const SCEV *S) {
7409 const SCEV *Op1;
7410 bool M = match(S, P: m_scev_UDiv(Op0: m_SCEV(), Op1: m_SCEV(V&: Op1)));
7411 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7412 // is a non-zero constant, we have to assume the UDiv may be UB.
7413 return M && (!isKnownNonZero(S: Op1) || !isGuaranteedNotToBePoison(Op: Op1));
7414 });
7415}
7416
7417bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7418 // Only proceed if we can prove that I does not yield poison.
7419 if (!programUndefinedIfPoison(Inst: I))
7420 return false;
7421
7422 // At this point we know that if I is executed, then it does not wrap
7423 // according to at least one of NSW or NUW. If I is not executed, then we do
7424 // not know if the calculation that I represents would wrap. Multiple
7425 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7426 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7427 // derived from other instructions that map to the same SCEV. We cannot make
7428 // that guarantee for cases where I is not executed. So we need to find a
7429 // upper bound on the defining scope for the SCEV, and prove that I is
7430 // executed every time we enter that scope. When the bounding scope is a
7431 // loop (the common case), this is equivalent to proving I executes on every
7432 // iteration of that loop.
7433 SmallVector<SCEVUse> SCEVOps;
7434 for (const Use &Op : I->operands()) {
7435 // I could be an extractvalue from a call to an overflow intrinsic.
7436 // TODO: We can do better here in some cases.
7437 if (isSCEVable(Ty: Op->getType()))
7438 SCEVOps.push_back(Elt: getSCEV(V: Op));
7439 }
7440 auto *DefI = getDefiningScopeBound(Ops: SCEVOps);
7441 return isGuaranteedToTransferExecutionTo(A: DefI, B: I);
7442}
7443
7444bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7445 // If we know that \c I can never be poison period, then that's enough.
7446 if (isSCEVExprNeverPoison(I))
7447 return true;
7448
7449 // If the loop only has one exit, then we know that, if the loop is entered,
7450 // any instruction dominating that exit will be executed. If any such
7451 // instruction would result in UB, the addrec cannot be poison.
7452 //
7453 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7454 // also handles uses outside the loop header (they just need to dominate the
7455 // single exit).
7456
7457 auto *ExitingBB = L->getExitingBlock();
7458 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7459 return false;
7460
7461 SmallPtrSet<const Value *, 16> KnownPoison;
7462 SmallVector<const Instruction *, 8> Worklist;
7463
7464 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7465 // things that are known to be poison under that assumption go on the
7466 // Worklist.
7467 KnownPoison.insert(Ptr: I);
7468 Worklist.push_back(Elt: I);
7469
7470 while (!Worklist.empty()) {
7471 const Instruction *Poison = Worklist.pop_back_val();
7472
7473 for (const Use &U : Poison->uses()) {
7474 const Instruction *PoisonUser = cast<Instruction>(Val: U.getUser());
7475 if (mustTriggerUB(I: PoisonUser, KnownPoison) &&
7476 DT.dominates(A: PoisonUser->getParent(), B: ExitingBB))
7477 return true;
7478
7479 if (propagatesPoison(PoisonOp: U) && L->contains(Inst: PoisonUser))
7480 if (KnownPoison.insert(Ptr: PoisonUser).second)
7481 Worklist.push_back(Elt: PoisonUser);
7482 }
7483 }
7484
7485 return false;
7486}
7487
7488ScalarEvolution::LoopProperties
7489ScalarEvolution::getLoopProperties(const Loop *L) {
7490 using LoopProperties = ScalarEvolution::LoopProperties;
7491
7492 auto Itr = LoopPropertiesCache.find(Val: L);
7493 if (Itr == LoopPropertiesCache.end()) {
7494 auto HasSideEffects = [](Instruction *I) {
7495 if (auto *SI = dyn_cast<StoreInst>(Val: I))
7496 return !SI->isSimple();
7497
7498 if (I->mayThrow())
7499 return true;
7500
7501 // Non-volatile memset / memcpy do not count as side-effect for forward
7502 // progress.
7503 if (isa<MemIntrinsic>(Val: I) && !I->isVolatile())
7504 return false;
7505
7506 return I->mayWriteToMemory();
7507 };
7508
7509 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7510 /*HasNoSideEffects*/ true};
7511
7512 for (auto *BB : L->getBlocks())
7513 for (auto &I : *BB) {
7514 if (!isGuaranteedToTransferExecutionToSuccessor(I: &I))
7515 LP.HasNoAbnormalExits = false;
7516 if (HasSideEffects(&I))
7517 LP.HasNoSideEffects = false;
7518 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7519 break; // We're already as pessimistic as we can get.
7520 }
7521
7522 auto InsertPair = LoopPropertiesCache.insert(KV: {L, LP});
7523 assert(InsertPair.second && "We just checked!");
7524 Itr = InsertPair.first;
7525 }
7526
7527 return Itr->second;
7528}
7529
7530bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
7531 // A mustprogress loop without side effects must be finite.
7532 // TODO: The check used here is very conservative. It's only *specific*
7533 // side effects which are well defined in infinite loops.
7534 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7535}
7536
7537const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7538 // Worklist item with a Value and a bool indicating whether all operands have
7539 // been visited already.
7540 using PointerTy = PointerIntPair<Value *, 1, bool>;
7541 SmallVector<PointerTy> Stack;
7542
7543 Stack.emplace_back(Args&: V, Args: false);
7544 while (!Stack.empty()) {
7545 auto E = Stack.back();
7546 Value *CurV = E.getPointer();
7547
7548 if (getExistingSCEV(V: CurV)) {
7549 Stack.pop_back();
7550 continue;
7551 }
7552
7553 SmallVector<Value *> Ops;
7554 const SCEV *CreatedSCEV = nullptr;
7555 // If all operands have been visited already, create the SCEV.
7556 if (E.getInt()) {
7557 CreatedSCEV = createSCEV(V: CurV);
7558 } else {
7559 // Otherwise get the operands we need to create SCEV's for before creating
7560 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7561 // just use it.
7562 CreatedSCEV = getOperandsToCreate(V: CurV, Ops);
7563 }
7564
7565 if (CreatedSCEV) {
7566 insertValueToMap(V: CurV, S: CreatedSCEV);
7567 Stack.pop_back();
7568 } else {
7569 Stack.back().setInt(true);
7570 // Queue its operands which need to be constructed.
7571 for (Value *Op : Ops)
7572 Stack.emplace_back(Args&: Op, Args: false);
7573 }
7574 }
7575
7576 return getExistingSCEV(V);
7577}
7578
7579const SCEV *
7580ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7581 if (!isSCEVable(Ty: V->getType()))
7582 return getUnknown(V);
7583
7584 if (Instruction *I = dyn_cast<Instruction>(Val: V)) {
7585 // Don't attempt to analyze instructions in blocks that aren't
7586 // reachable. Such instructions don't matter, and they aren't required
7587 // to obey basic rules for definitions dominating uses which this
7588 // analysis depends on.
7589 if (!DT.isReachableFromEntry(A: I->getParent()))
7590 return getUnknown(V: PoisonValue::get(T: V->getType()));
7591 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: V))
7592 return getConstant(V: CI);
7593 else if (isa<GlobalAlias>(Val: V))
7594 return getUnknown(V);
7595 else if (!isa<ConstantExpr>(Val: V))
7596 return getUnknown(V);
7597
7598 Operator *U = cast<Operator>(Val: V);
7599 if (auto BO =
7600 MatchBinaryOp(V: U, DL: getDataLayout(), AC, DT, CtxI: dyn_cast<Instruction>(Val: V))) {
7601 bool IsConstArg = isa<ConstantInt>(Val: BO->RHS);
7602 switch (BO->Opcode) {
7603 case Instruction::Add:
7604 case Instruction::Mul: {
7605 // For additions and multiplications, traverse add/mul chains for which we
7606 // can potentially create a single SCEV, to reduce the number of
7607 // get{Add,Mul}Expr calls.
7608 do {
7609 if (BO->Op) {
7610 if (BO->Op != V && getExistingSCEV(V: BO->Op)) {
7611 Ops.push_back(Elt: BO->Op);
7612 break;
7613 }
7614 }
7615 Ops.push_back(Elt: BO->RHS);
7616 auto NewBO = MatchBinaryOp(V: BO->LHS, DL: getDataLayout(), AC, DT,
7617 CtxI: dyn_cast<Instruction>(Val: V));
7618 if (!NewBO ||
7619 (BO->Opcode == Instruction::Add &&
7620 (NewBO->Opcode != Instruction::Add &&
7621 NewBO->Opcode != Instruction::Sub)) ||
7622 (BO->Opcode == Instruction::Mul &&
7623 NewBO->Opcode != Instruction::Mul)) {
7624 Ops.push_back(Elt: BO->LHS);
7625 break;
7626 }
7627 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7628 // requires a SCEV for the LHS.
7629 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7630 auto *I = dyn_cast<Instruction>(Val: BO->Op);
7631 if (I && programUndefinedIfPoison(Inst: I)) {
7632 Ops.push_back(Elt: BO->LHS);
7633 break;
7634 }
7635 }
7636 BO = NewBO;
7637 } while (true);
7638 return nullptr;
7639 }
7640 case Instruction::Sub:
7641 case Instruction::UDiv:
7642 case Instruction::URem:
7643 break;
7644 case Instruction::AShr:
7645 case Instruction::Shl:
7646 case Instruction::Xor:
7647 if (!IsConstArg)
7648 return nullptr;
7649 break;
7650 case Instruction::And:
7651 case Instruction::Or:
7652 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(BitWidth: 1))
7653 return nullptr;
7654 break;
7655 case Instruction::LShr:
7656 return getUnknown(V);
7657 default:
7658 llvm_unreachable("Unhandled binop");
7659 break;
7660 }
7661
7662 Ops.push_back(Elt: BO->LHS);
7663 Ops.push_back(Elt: BO->RHS);
7664 return nullptr;
7665 }
7666
7667 switch (U->getOpcode()) {
7668 case Instruction::Trunc:
7669 case Instruction::ZExt:
7670 case Instruction::SExt:
7671 case Instruction::PtrToAddr:
7672 case Instruction::PtrToInt:
7673 Ops.push_back(Elt: U->getOperand(i: 0));
7674 return nullptr;
7675
7676 case Instruction::BitCast:
7677 if (isSCEVable(Ty: U->getType()) && isSCEVable(Ty: U->getOperand(i: 0)->getType())) {
7678 Ops.push_back(Elt: U->getOperand(i: 0));
7679 return nullptr;
7680 }
7681 return getUnknown(V);
7682
7683 case Instruction::SDiv:
7684 case Instruction::SRem:
7685 Ops.push_back(Elt: U->getOperand(i: 0));
7686 Ops.push_back(Elt: U->getOperand(i: 1));
7687 return nullptr;
7688
7689 case Instruction::GetElementPtr:
7690 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7691 "GEP source element type must be sized");
7692 llvm::append_range(C&: Ops, R: U->operands());
7693 return nullptr;
7694
7695 case Instruction::IntToPtr:
7696 return getUnknown(V);
7697
7698 case Instruction::PHI:
7699 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7700 // relevant nodes for each of them.
7701 //
7702 // The first is just to call simplifyInstruction, and get something back
7703 // that isn't a PHI.
7704 if (Value *V = simplifyInstruction(
7705 I: cast<PHINode>(Val: U),
7706 Q: {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7707 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7708 assert(V);
7709 Ops.push_back(Elt: V);
7710 return nullptr;
7711 }
7712 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7713 // operands which all perform the same operation, but haven't been
7714 // CSE'ed for whatever reason.
7715 if (BinaryOperator *BO = getCommonInstForPHI(PN: cast<PHINode>(Val: U))) {
7716 assert(BO);
7717 Ops.push_back(Elt: BO);
7718 return nullptr;
7719 }
7720 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7721 // is equivalent to a select, and analyzes it like a select.
7722 {
7723 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7724 if (getOperandsForSelectLikePHI(DT, PN: cast<PHINode>(Val: U), Cond, LHS, RHS)) {
7725 assert(Cond);
7726 assert(LHS);
7727 assert(RHS);
7728 if (auto *CondICmp = dyn_cast<ICmpInst>(Val: Cond)) {
7729 Ops.push_back(Elt: CondICmp->getOperand(i_nocapture: 0));
7730 Ops.push_back(Elt: CondICmp->getOperand(i_nocapture: 1));
7731 }
7732 Ops.push_back(Elt: Cond);
7733 Ops.push_back(Elt: LHS);
7734 Ops.push_back(Elt: RHS);
7735 return nullptr;
7736 }
7737 }
7738 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7739 // so just construct it recursively.
7740 //
7741 // In addition to getNodeForPHI, also construct nodes which might be needed
7742 // by getRangeRef.
7743 if (RangeRefPHIAllowedOperands(DT, PHI: cast<PHINode>(Val: U))) {
7744 for (Value *V : cast<PHINode>(Val: U)->operands())
7745 Ops.push_back(Elt: V);
7746 return nullptr;
7747 }
7748 return nullptr;
7749
7750 case Instruction::Select: {
7751 // Check if U is a select that can be simplified to a SCEVUnknown.
7752 auto CanSimplifyToUnknown = [this, U]() {
7753 if (U->getType()->isIntegerTy(BitWidth: 1) || isa<ConstantInt>(Val: U->getOperand(i: 0)))
7754 return false;
7755
7756 auto *ICI = dyn_cast<ICmpInst>(Val: U->getOperand(i: 0));
7757 if (!ICI)
7758 return false;
7759 Value *LHS = ICI->getOperand(i_nocapture: 0);
7760 Value *RHS = ICI->getOperand(i_nocapture: 1);
7761 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7762 ICI->getPredicate() == CmpInst::ICMP_NE) {
7763 if (!(isa<ConstantInt>(Val: RHS) && cast<ConstantInt>(Val: RHS)->isZero()))
7764 return true;
7765 } else if (getTypeSizeInBits(Ty: LHS->getType()) >
7766 getTypeSizeInBits(Ty: U->getType()))
7767 return true;
7768 return false;
7769 };
7770 if (CanSimplifyToUnknown())
7771 return getUnknown(V: U);
7772
7773 llvm::append_range(C&: Ops, R: U->operands());
7774 return nullptr;
7775 break;
7776 }
7777 case Instruction::Call:
7778 case Instruction::Invoke:
7779 if (Value *RV = cast<CallBase>(Val: U)->getReturnedArgOperand()) {
7780 Ops.push_back(Elt: RV);
7781 return nullptr;
7782 }
7783
7784 if (auto *II = dyn_cast<IntrinsicInst>(Val: U)) {
7785 switch (II->getIntrinsicID()) {
7786 case Intrinsic::abs:
7787 Ops.push_back(Elt: II->getArgOperand(i: 0));
7788 return nullptr;
7789 case Intrinsic::umax:
7790 case Intrinsic::umin:
7791 case Intrinsic::smax:
7792 case Intrinsic::smin:
7793 case Intrinsic::usub_sat:
7794 case Intrinsic::uadd_sat:
7795 Ops.push_back(Elt: II->getArgOperand(i: 0));
7796 Ops.push_back(Elt: II->getArgOperand(i: 1));
7797 return nullptr;
7798 case Intrinsic::start_loop_iterations:
7799 case Intrinsic::annotation:
7800 case Intrinsic::ptr_annotation:
7801 Ops.push_back(Elt: II->getArgOperand(i: 0));
7802 return nullptr;
7803 default:
7804 break;
7805 }
7806 }
7807 break;
7808 }
7809
7810 return nullptr;
7811}
7812
7813const SCEV *ScalarEvolution::createSCEV(Value *V) {
7814 if (!isSCEVable(Ty: V->getType()))
7815 return getUnknown(V);
7816
7817 if (Instruction *I = dyn_cast<Instruction>(Val: V)) {
7818 // Don't attempt to analyze instructions in blocks that aren't
7819 // reachable. Such instructions don't matter, and they aren't required
7820 // to obey basic rules for definitions dominating uses which this
7821 // analysis depends on.
7822 if (!DT.isReachableFromEntry(A: I->getParent()))
7823 return getUnknown(V: PoisonValue::get(T: V->getType()));
7824 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: V))
7825 return getConstant(V: CI);
7826 else if (isa<GlobalAlias>(Val: V))
7827 return getUnknown(V);
7828 else if (!isa<ConstantExpr>(Val: V))
7829 return getUnknown(V);
7830
7831 const SCEV *LHS;
7832 const SCEV *RHS;
7833
7834 Operator *U = cast<Operator>(Val: V);
7835 if (auto BO =
7836 MatchBinaryOp(V: U, DL: getDataLayout(), AC, DT, CtxI: dyn_cast<Instruction>(Val: V))) {
7837 switch (BO->Opcode) {
7838 case Instruction::Add: {
7839 // The simple thing to do would be to just call getSCEV on both operands
7840 // and call getAddExpr with the result. However if we're looking at a
7841 // bunch of things all added together, this can be quite inefficient,
7842 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7843 // Instead, gather up all the operands and make a single getAddExpr call.
7844 // LLVM IR canonical form means we need only traverse the left operands.
7845 SmallVector<SCEVUse, 4> AddOps;
7846 do {
7847 if (BO->Op) {
7848 if (auto *OpSCEV = getExistingSCEV(V: BO->Op)) {
7849 AddOps.push_back(Elt: OpSCEV);
7850 break;
7851 }
7852
7853 // If a NUW or NSW flag can be applied to the SCEV for this
7854 // addition, then compute the SCEV for this addition by itself
7855 // with a separate call to getAddExpr. We need to do that
7856 // instead of pushing the operands of the addition onto AddOps,
7857 // since the flags are only known to apply to this particular
7858 // addition - they may not apply to other additions that can be
7859 // formed with operands from AddOps.
7860 const SCEV *RHS = getSCEV(V: BO->RHS);
7861 SCEVFlags Flags = getNoWrapFlagsFromUB(V: BO->Op);
7862 if (Flags != SCEV::FlagNone) {
7863 const SCEV *LHS = getSCEV(V: BO->LHS);
7864 if (BO->Opcode == Instruction::Sub)
7865 AddOps.push_back(Elt: getMinusSCEV(LHS, RHS, Flags));
7866 else
7867 AddOps.push_back(Elt: getAddExpr(LHS, RHS, Flags));
7868 break;
7869 }
7870 }
7871
7872 if (BO->Opcode == Instruction::Sub)
7873 AddOps.push_back(Elt: getNegativeSCEV(V: getSCEV(V: BO->RHS)));
7874 else
7875 AddOps.push_back(Elt: getSCEV(V: BO->RHS));
7876
7877 auto NewBO = MatchBinaryOp(V: BO->LHS, DL: getDataLayout(), AC, DT,
7878 CtxI: dyn_cast<Instruction>(Val: V));
7879 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7880 NewBO->Opcode != Instruction::Sub)) {
7881 AddOps.push_back(Elt: getSCEV(V: BO->LHS));
7882 break;
7883 }
7884 BO = NewBO;
7885 } while (true);
7886
7887 return getAddExpr(Ops&: AddOps);
7888 }
7889
7890 case Instruction::Mul: {
7891 SmallVector<SCEVUse, 4> MulOps;
7892 do {
7893 if (BO->Op) {
7894 if (auto *OpSCEV = getExistingSCEV(V: BO->Op)) {
7895 MulOps.push_back(Elt: OpSCEV);
7896 break;
7897 }
7898
7899 SCEVFlags Flags = getNoWrapFlagsFromUB(V: BO->Op);
7900 if (Flags != SCEV::FlagNone) {
7901 LHS = getSCEV(V: BO->LHS);
7902 RHS = getSCEV(V: BO->RHS);
7903 MulOps.push_back(Elt: getMulExpr(LHS, RHS, Flags));
7904 break;
7905 }
7906 }
7907
7908 MulOps.push_back(Elt: getSCEV(V: BO->RHS));
7909 auto NewBO = MatchBinaryOp(V: BO->LHS, DL: getDataLayout(), AC, DT,
7910 CtxI: dyn_cast<Instruction>(Val: V));
7911 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7912 MulOps.push_back(Elt: getSCEV(V: BO->LHS));
7913 break;
7914 }
7915 BO = NewBO;
7916 } while (true);
7917
7918 return getMulExpr(Ops&: MulOps);
7919 }
7920 case Instruction::UDiv:
7921 LHS = getSCEV(V: BO->LHS);
7922 RHS = getSCEV(V: BO->RHS);
7923 return getUDivExpr(LHS, RHS);
7924 case Instruction::URem:
7925 LHS = getSCEV(V: BO->LHS);
7926 RHS = getSCEV(V: BO->RHS);
7927 return getURemExpr(LHS, RHS);
7928 case Instruction::Sub: {
7929 SCEVFlags Flags = SCEV::FlagNone;
7930 if (BO->Op)
7931 Flags = getNoWrapFlagsFromUB(V: BO->Op);
7932
7933 // Try to use ptrtoaddr for subtracts with at least one ptrtoint
7934 // operand. While we don't model ptrtoint directly in SCEV, the
7935 // difference between two pointer addresses is well-defined.
7936 Value *PtrLHS = nullptr, *PtrRHS = nullptr;
7937 bool HasPtrLHS = match(V: BO->LHS, P: m_PtrToInt(Op: m_Value(V&: PtrLHS)));
7938 bool HasPtrRHS = match(V: BO->RHS, P: m_PtrToInt(Op: m_Value(V&: PtrRHS)));
7939 if (HasPtrLHS || HasPtrRHS) {
7940 // Convert a ptrtoint operand (OrigOp) to ptrtoaddr of its pointer
7941 // PtrOp. When only one side is ptrtoint (BothPtr is false), skip
7942 // SCEVUnknown pointers since wrapping them in ptrtoaddr adds no
7943 // useful structure.
7944 auto GetOp = [&](bool HasPtr, Value *PtrOp, Value *OrigOp,
7945 bool BothPtr) -> const SCEV * {
7946 if (!HasPtr)
7947 return getSCEV(V: OrigOp);
7948 const SCEV *PtrSCEV = getSCEV(V: PtrOp);
7949 if (BothPtr || !isa<SCEVUnknown>(Val: PtrSCEV)) {
7950 const SCEV *Addr = getPtrToAddrExpr(Op: PtrSCEV);
7951 if (!isa<SCEVCouldNotCompute>(Val: Addr) &&
7952 getTypeSizeInBits(Ty: OrigOp->getType()) <=
7953 getTypeSizeInBits(Ty: Addr->getType()))
7954 return getTruncateOrNoop(V: Addr, Ty: OrigOp->getType());
7955 }
7956 return getSCEV(V: OrigOp);
7957 };
7958 const SCEV *L = GetOp(HasPtrLHS, PtrLHS, BO->LHS, HasPtrRHS);
7959 const SCEV *R = GetOp(HasPtrRHS, PtrRHS, BO->RHS, HasPtrLHS);
7960 return getMinusSCEV(LHS: L, RHS: R, Flags);
7961 }
7962
7963 LHS = getSCEV(V: BO->LHS);
7964 RHS = getSCEV(V: BO->RHS);
7965 return getMinusSCEV(LHS, RHS, Flags);
7966 }
7967 case Instruction::And:
7968 // For an expression like x&255 that merely masks off the high bits,
7969 // use zext(trunc(x)) as the SCEV expression.
7970 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: BO->RHS)) {
7971 if (CI->isZero())
7972 return getSCEV(V: BO->RHS);
7973 if (CI->isMinusOne())
7974 return getSCEV(V: BO->LHS);
7975 const APInt &A = CI->getValue();
7976
7977 // Instcombine's ShrinkDemandedConstant may strip bits out of
7978 // constants, obscuring what would otherwise be a low-bits mask.
7979 // Use computeKnownBits to compute what ShrinkDemandedConstant
7980 // knew about to reconstruct a low-bits mask value.
7981 unsigned LZ = A.countl_zero();
7982 unsigned TZ = A.countr_zero();
7983 unsigned BitWidth = A.getBitWidth();
7984 KnownBits Known(BitWidth);
7985 computeKnownBits(V: BO->LHS, Known, DL: getDataLayout(), AC: &AC, CtxI: nullptr, DT: &DT);
7986
7987 APInt EffectiveMask =
7988 APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: BitWidth - LZ - TZ).shl(shiftAmt: TZ);
7989 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7990 const SCEV *MulCount = getConstant(Val: APInt::getOneBitSet(numBits: BitWidth, BitNo: TZ));
7991 const SCEV *LHS = getSCEV(V: BO->LHS);
7992 const SCEV *ShiftedLHS = nullptr;
7993 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(Val: LHS)) {
7994 if (auto *OpC = dyn_cast<SCEVConstant>(Val: LHSMul->getOperand(i: 0))) {
7995 // For an expression like (x * 8) & 8, simplify the multiply.
7996 unsigned MulZeros = OpC->getAPInt().countr_zero();
7997 unsigned GCD = std::min(a: MulZeros, b: TZ);
7998 APInt DivAmt = APInt::getOneBitSet(numBits: BitWidth, BitNo: TZ - GCD);
7999 SmallVector<SCEVUse, 4> MulOps;
8000 MulOps.push_back(Elt: getConstant(Val: OpC->getAPInt().ashr(ShiftAmt: GCD)));
8001 append_range(C&: MulOps, R: LHSMul->operands().drop_front());
8002 const SCEV *NewMul = getMulExpr(Ops&: MulOps, Flags: LHSMul->getNoWrapFlags());
8003 ShiftedLHS = getUDivExpr(LHS: NewMul, RHS: getConstant(Val: DivAmt));
8004 }
8005 }
8006 if (!ShiftedLHS)
8007 ShiftedLHS = getUDivExpr(LHS, RHS: MulCount);
8008 return getMulExpr(
8009 LHS: getZeroExtendExpr(
8010 Op: getTruncateExpr(Op: ShiftedLHS,
8011 Ty: IntegerType::get(C&: getContext(), NumBits: BitWidth - LZ - TZ)),
8012 Ty: BO->LHS->getType()),
8013 RHS: MulCount);
8014 }
8015 }
8016 // Binary `and` is a bit-wise `umin`.
8017 if (BO->LHS->getType()->isIntegerTy(BitWidth: 1)) {
8018 LHS = getSCEV(V: BO->LHS);
8019 RHS = getSCEV(V: BO->RHS);
8020 return getUMinExpr(LHS, RHS);
8021 }
8022 break;
8023
8024 case Instruction::Or:
8025 // Binary `or` is a bit-wise `umax`.
8026 if (BO->LHS->getType()->isIntegerTy(BitWidth: 1)) {
8027 LHS = getSCEV(V: BO->LHS);
8028 RHS = getSCEV(V: BO->RHS);
8029 return getUMaxExpr(LHS, RHS);
8030 }
8031 break;
8032
8033 case Instruction::Xor:
8034 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: BO->RHS)) {
8035 // If the RHS of xor is -1, then this is a not operation.
8036 if (CI->isMinusOne())
8037 return getNotSCEV(V: getSCEV(V: BO->LHS));
8038
8039 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
8040 // This is a variant of the check for xor with -1, and it handles
8041 // the case where instcombine has trimmed non-demanded bits out
8042 // of an xor with -1.
8043 if (auto *LBO = dyn_cast<BinaryOperator>(Val: BO->LHS))
8044 if (ConstantInt *LCI = dyn_cast<ConstantInt>(Val: LBO->getOperand(i_nocapture: 1)))
8045 if (LBO->getOpcode() == Instruction::And &&
8046 LCI->getValue() == CI->getValue())
8047 if (const SCEVZeroExtendExpr *Z =
8048 dyn_cast<SCEVZeroExtendExpr>(Val: getSCEV(V: BO->LHS))) {
8049 Type *UTy = BO->LHS->getType();
8050 const SCEV *Z0 = Z->getOperand();
8051 Type *Z0Ty = Z0->getType();
8052 unsigned Z0TySize = getTypeSizeInBits(Ty: Z0Ty);
8053
8054 // If C is a low-bits mask, the zero extend is serving to
8055 // mask off the high bits. Complement the operand and
8056 // re-apply the zext.
8057 if (CI->getValue().isMask(numBits: Z0TySize))
8058 return getZeroExtendExpr(Op: getNotSCEV(V: Z0), Ty: UTy);
8059
8060 // If C is a single bit, it may be in the sign-bit position
8061 // before the zero-extend. In this case, represent the xor
8062 // using an add, which is equivalent, and re-apply the zext.
8063 APInt Trunc = CI->getValue().trunc(width: Z0TySize);
8064 if (Trunc.zext(width: getTypeSizeInBits(Ty: UTy)) == CI->getValue() &&
8065 Trunc.isSignMask())
8066 return getZeroExtendExpr(Op: getAddExpr(LHS: Z0, RHS: getConstant(Val: Trunc)),
8067 Ty: UTy);
8068 }
8069 }
8070 break;
8071
8072 case Instruction::Shl:
8073 // Turn shift left of a constant amount into a multiply.
8074 if (ConstantInt *SA = dyn_cast<ConstantInt>(Val: BO->RHS)) {
8075 uint32_t BitWidth = cast<IntegerType>(Val: SA->getType())->getBitWidth();
8076
8077 // If the shift count is not less than the bitwidth, the result of
8078 // the shift is undefined. Don't try to analyze it, because the
8079 // resolution chosen here may differ from the resolution chosen in
8080 // other parts of the compiler.
8081 if (SA->getValue().uge(RHS: BitWidth))
8082 break;
8083
8084 // We can safely preserve the nuw flag in all cases. It's also safe to
8085 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
8086 // requires special handling. It can be preserved as long as we're not
8087 // left shifting by bitwidth - 1.
8088 auto Flags = SCEV::FlagNone;
8089 if (BO->Op) {
8090 auto MulFlags = getNoWrapFlagsFromUB(V: BO->Op);
8091 if (any(Val: MulFlags & SCEV::FlagNSW) &&
8092 (any(Val: MulFlags & SCEV::FlagNUW) ||
8093 SA->getValue().ult(RHS: BitWidth - 1)))
8094 Flags = Flags | SCEV::FlagNSW;
8095 if (any(Val: MulFlags & SCEV::FlagNUW))
8096 Flags = Flags | SCEV::FlagNUW;
8097 }
8098
8099 ConstantInt *X = ConstantInt::get(
8100 Context&: getContext(), V: APInt::getOneBitSet(numBits: BitWidth, BitNo: SA->getZExtValue()));
8101 return getMulExpr(LHS: getSCEV(V: BO->LHS), RHS: getConstant(V: X), Flags);
8102 }
8103 break;
8104
8105 case Instruction::AShr:
8106 // AShr X, C, where C is a constant.
8107 ConstantInt *CI = dyn_cast<ConstantInt>(Val: BO->RHS);
8108 if (!CI)
8109 break;
8110
8111 Type *OuterTy = BO->LHS->getType();
8112 uint64_t BitWidth = getTypeSizeInBits(Ty: OuterTy);
8113 // If the shift count is not less than the bitwidth, the result of
8114 // the shift is undefined. Don't try to analyze it, because the
8115 // resolution chosen here may differ from the resolution chosen in
8116 // other parts of the compiler.
8117 if (CI->getValue().uge(RHS: BitWidth))
8118 break;
8119
8120 if (CI->isZero())
8121 return getSCEV(V: BO->LHS); // shift by zero --> noop
8122
8123 uint64_t AShrAmt = CI->getZExtValue();
8124 Type *TruncTy = IntegerType::get(C&: getContext(), NumBits: BitWidth - AShrAmt);
8125
8126 Operator *L = dyn_cast<Operator>(Val: BO->LHS);
8127 const SCEV *AddTruncateExpr = nullptr;
8128 ConstantInt *ShlAmtCI = nullptr;
8129 const SCEV *AddConstant = nullptr;
8130
8131 if (L && L->getOpcode() == Instruction::Add) {
8132 // X = Shl A, n
8133 // Y = Add X, c
8134 // Z = AShr Y, m
8135 // n, c and m are constants.
8136
8137 Operator *LShift = dyn_cast<Operator>(Val: L->getOperand(i: 0));
8138 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(Val: L->getOperand(i: 1));
8139 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8140 if (AddOperandCI) {
8141 const SCEV *ShlOp0SCEV = getSCEV(V: LShift->getOperand(i: 0));
8142 ShlAmtCI = dyn_cast<ConstantInt>(Val: LShift->getOperand(i: 1));
8143 // since we truncate to TruncTy, the AddConstant should be of the
8144 // same type, so create a new Constant with type same as TruncTy.
8145 // Also, the Add constant should be shifted right by AShr amount.
8146 APInt AddOperand = AddOperandCI->getValue().ashr(ShiftAmt: AShrAmt);
8147 AddConstant = getConstant(Val: AddOperand.trunc(width: BitWidth - AShrAmt));
8148 // we model the expression as sext(add(trunc(A), c << n)), since the
8149 // sext(trunc) part is already handled below, we create a
8150 // AddExpr(TruncExp) which will be used later.
8151 AddTruncateExpr = getTruncateExpr(Op: ShlOp0SCEV, Ty: TruncTy);
8152 }
8153 }
8154 } else if (L && L->getOpcode() == Instruction::Shl) {
8155 // X = Shl A, n
8156 // Y = AShr X, m
8157 // Both n and m are constant.
8158
8159 const SCEV *ShlOp0SCEV = getSCEV(V: L->getOperand(i: 0));
8160 ShlAmtCI = dyn_cast<ConstantInt>(Val: L->getOperand(i: 1));
8161 AddTruncateExpr = getTruncateExpr(Op: ShlOp0SCEV, Ty: TruncTy);
8162 }
8163
8164 if (AddTruncateExpr && ShlAmtCI) {
8165 // We can merge the two given cases into a single SCEV statement,
8166 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8167 // a simpler case. The following code handles the two cases:
8168 //
8169 // 1) For a two-shift sext-inreg, i.e. n = m,
8170 // use sext(trunc(x)) as the SCEV expression.
8171 //
8172 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8173 // expression. We already checked that ShlAmt < BitWidth, so
8174 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8175 // ShlAmt - AShrAmt < Amt.
8176 const APInt &ShlAmt = ShlAmtCI->getValue();
8177 if (ShlAmt.ult(RHS: BitWidth) && ShlAmt.uge(RHS: AShrAmt)) {
8178 APInt Mul = APInt::getOneBitSet(numBits: BitWidth - AShrAmt,
8179 BitNo: ShlAmtCI->getZExtValue() - AShrAmt);
8180 const SCEV *CompositeExpr =
8181 getMulExpr(LHS: AddTruncateExpr, RHS: getConstant(Val: Mul));
8182 if (L->getOpcode() != Instruction::Shl)
8183 CompositeExpr = getAddExpr(LHS: CompositeExpr, RHS: AddConstant);
8184
8185 return getSignExtendExpr(Op: CompositeExpr, Ty: OuterTy);
8186 }
8187 }
8188 break;
8189 }
8190 }
8191
8192 switch (U->getOpcode()) {
8193 case Instruction::Trunc:
8194 return getTruncateExpr(Op: getSCEV(V: U->getOperand(i: 0)), Ty: U->getType());
8195
8196 case Instruction::ZExt:
8197 return getZeroExtendExpr(Op: getSCEV(V: U->getOperand(i: 0)), Ty: U->getType());
8198
8199 case Instruction::SExt:
8200 if (auto BO = MatchBinaryOp(V: U->getOperand(i: 0), DL: getDataLayout(), AC, DT,
8201 CtxI: dyn_cast<Instruction>(Val: V))) {
8202 // The NSW flag of a subtract does not always survive the conversion to
8203 // A + (-1)*B. By pushing sign extension onto its operands we are much
8204 // more likely to preserve NSW and allow later AddRec optimisations.
8205 //
8206 // NOTE: This is effectively duplicating this logic from getSignExtend:
8207 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8208 // but by that point the NSW information has potentially been lost.
8209 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8210 Type *Ty = U->getType();
8211 auto *V1 = getSignExtendExpr(Op: getSCEV(V: BO->LHS), Ty);
8212 auto *V2 = getSignExtendExpr(Op: getSCEV(V: BO->RHS), Ty);
8213 return getMinusSCEV(LHS: V1, RHS: V2, Flags: SCEV::FlagNSW);
8214 }
8215 }
8216 return getSignExtendExpr(Op: getSCEV(V: U->getOperand(i: 0)), Ty: U->getType());
8217
8218 case Instruction::BitCast:
8219 // BitCasts are no-op casts so we just eliminate the cast.
8220 if (isSCEVable(Ty: U->getType()) && isSCEVable(Ty: U->getOperand(i: 0)->getType()))
8221 return getSCEV(V: U->getOperand(i: 0));
8222 break;
8223
8224 case Instruction::PtrToAddr: {
8225 const SCEV *IntOp = getPtrToAddrExpr(Op: getSCEV(V: U->getOperand(i: 0)));
8226 if (isa<SCEVCouldNotCompute>(Val: IntOp))
8227 return getUnknown(V);
8228 return IntOp;
8229 }
8230
8231 case Instruction::PtrToInt:
8232 // SCEV only models ptrtoaddr.
8233 return getUnknown(V);
8234
8235 case Instruction::IntToPtr:
8236 // Just don't deal with inttoptr casts.
8237 return getUnknown(V);
8238
8239 case Instruction::SDiv:
8240 // If both operands are non-negative, this is just an udiv.
8241 if (isKnownNonNegative(S: getSCEV(V: U->getOperand(i: 0))) &&
8242 isKnownNonNegative(S: getSCEV(V: U->getOperand(i: 1))))
8243 return getUDivExpr(LHS: getSCEV(V: U->getOperand(i: 0)), RHS: getSCEV(V: U->getOperand(i: 1)));
8244 break;
8245
8246 case Instruction::SRem:
8247 // If both operands are non-negative, this is just an urem.
8248 if (isKnownNonNegative(S: getSCEV(V: U->getOperand(i: 0))) &&
8249 isKnownNonNegative(S: getSCEV(V: U->getOperand(i: 1))))
8250 return getURemExpr(LHS: getSCEV(V: U->getOperand(i: 0)), RHS: getSCEV(V: U->getOperand(i: 1)));
8251 break;
8252
8253 case Instruction::GetElementPtr:
8254 return createNodeForGEP(GEP: cast<GEPOperator>(Val: U));
8255
8256 case Instruction::PHI:
8257 return createNodeForPHI(PN: cast<PHINode>(Val: U));
8258
8259 case Instruction::Select:
8260 return createNodeForSelectOrPHI(V: U, Cond: U->getOperand(i: 0), TrueVal: U->getOperand(i: 1),
8261 FalseVal: U->getOperand(i: 2));
8262
8263 case Instruction::Call:
8264 case Instruction::Invoke:
8265 if (Value *RV = cast<CallBase>(Val: U)->getReturnedArgOperand())
8266 return getSCEV(V: RV);
8267
8268 if (auto *II = dyn_cast<IntrinsicInst>(Val: U)) {
8269 switch (II->getIntrinsicID()) {
8270 case Intrinsic::abs:
8271 return getAbsExpr(
8272 Op: getSCEV(V: II->getArgOperand(i: 0)),
8273 /*IsNSW=*/cast<ConstantInt>(Val: II->getArgOperand(i: 1))->isOne());
8274 case Intrinsic::umax:
8275 LHS = getSCEV(V: II->getArgOperand(i: 0));
8276 RHS = getSCEV(V: II->getArgOperand(i: 1));
8277 return getUMaxExpr(LHS, RHS);
8278 case Intrinsic::umin:
8279 LHS = getSCEV(V: II->getArgOperand(i: 0));
8280 RHS = getSCEV(V: II->getArgOperand(i: 1));
8281 return getUMinExpr(LHS, RHS);
8282 case Intrinsic::smax:
8283 LHS = getSCEV(V: II->getArgOperand(i: 0));
8284 RHS = getSCEV(V: II->getArgOperand(i: 1));
8285 return getSMaxExpr(LHS, RHS);
8286 case Intrinsic::smin:
8287 LHS = getSCEV(V: II->getArgOperand(i: 0));
8288 RHS = getSCEV(V: II->getArgOperand(i: 1));
8289 return getSMinExpr(LHS, RHS);
8290 case Intrinsic::usub_sat: {
8291 const SCEV *X = getSCEV(V: II->getArgOperand(i: 0));
8292 const SCEV *Y = getSCEV(V: II->getArgOperand(i: 1));
8293 const SCEV *ClampedY = getUMinExpr(LHS: X, RHS: Y);
8294 return getMinusSCEV(LHS: X, RHS: ClampedY, Flags: SCEV::FlagNUW);
8295 }
8296 case Intrinsic::uadd_sat: {
8297 const SCEV *X = getSCEV(V: II->getArgOperand(i: 0));
8298 const SCEV *Y = getSCEV(V: II->getArgOperand(i: 1));
8299 const SCEV *ClampedX = getUMinExpr(LHS: X, RHS: getNotSCEV(V: Y));
8300 return getAddExpr(LHS: ClampedX, RHS: Y, Flags: SCEV::FlagNUW);
8301 }
8302 case Intrinsic::start_loop_iterations:
8303 case Intrinsic::annotation:
8304 case Intrinsic::ptr_annotation:
8305 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8306 // just eqivalent to the first operand for SCEV purposes.
8307 return getSCEV(V: II->getArgOperand(i: 0));
8308 case Intrinsic::vscale:
8309 return getVScale(Ty: II->getType());
8310 default:
8311 break;
8312 }
8313 }
8314 break;
8315 }
8316
8317 return getUnknown(V);
8318}
8319
8320//===----------------------------------------------------------------------===//
8321// Iteration Count Computation Code
8322//
8323
8324const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount) {
8325 if (isa<SCEVCouldNotCompute>(Val: ExitCount))
8326 return getCouldNotCompute();
8327
8328 auto *ExitCountType = ExitCount->getType();
8329 assert(ExitCountType->isIntegerTy());
8330 auto *EvalTy = Type::getIntNTy(C&: ExitCountType->getContext(),
8331 N: 1 + ExitCountType->getScalarSizeInBits());
8332 return getTripCountFromExitCount(ExitCount, EvalTy, L: nullptr);
8333}
8334
8335const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount,
8336 Type *EvalTy,
8337 const Loop *L) {
8338 if (isa<SCEVCouldNotCompute>(Val: ExitCount))
8339 return getCouldNotCompute();
8340
8341 unsigned ExitCountSize = getTypeSizeInBits(Ty: ExitCount->getType());
8342 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8343
8344 auto CanAddOneWithoutOverflow = [&]() {
8345 ConstantRange ExitCountRange =
8346 getRangeRef(S: ExitCount, SignHint: RangeSignHint::HINT_RANGE_UNSIGNED);
8347 if (!ExitCountRange.contains(Val: APInt::getMaxValue(numBits: ExitCountSize)))
8348 return true;
8349
8350 return L && isLoopEntryGuardedByCond(L, Pred: ICmpInst::ICMP_NE, LHS: ExitCount,
8351 RHS: getMinusOne(Ty: ExitCount->getType()));
8352 };
8353
8354 // If we need to zero extend the backedge count, check if we can add one to
8355 // it prior to zero extending without overflow. Provided this is safe, it
8356 // allows better simplification of the +1.
8357 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8358 return getZeroExtendExpr(
8359 Op: getAddExpr(LHS: ExitCount, RHS: getOne(Ty: ExitCount->getType())), Ty: EvalTy);
8360
8361 // Get the total trip count from the count by adding 1. This may wrap.
8362 return getAddExpr(LHS: getTruncateOrZeroExtend(V: ExitCount, Ty: EvalTy), RHS: getOne(Ty: EvalTy));
8363}
8364
8365static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8366 if (!ExitCount)
8367 return 0;
8368
8369 ConstantInt *ExitConst = ExitCount->getValue();
8370
8371 // Guard against huge trip counts.
8372 if (ExitConst->getValue().getActiveBits() > 32)
8373 return 0;
8374
8375 // In case of integer overflow, this returns 0, which is correct.
8376 return ((unsigned)ExitConst->getZExtValue()) + 1;
8377}
8378
8379unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
8380 auto *ExitCount = dyn_cast<SCEVConstant>(Val: getBackedgeTakenCount(L, Kind: Exact));
8381 return getConstantTripCount(ExitCount);
8382}
8383
8384unsigned
8385ScalarEvolution::getSmallConstantTripCount(const Loop *L,
8386 const BasicBlock *ExitingBlock) {
8387 assert(ExitingBlock && "Must pass a non-null exiting block!");
8388 assert(L->isLoopExiting(ExitingBlock) &&
8389 "Exiting block must actually branch out of the loop!");
8390 const SCEVConstant *ExitCount =
8391 dyn_cast<SCEVConstant>(Val: getExitCount(L, ExitingBlock));
8392 return getConstantTripCount(ExitCount);
8393}
8394
8395unsigned ScalarEvolution::getSmallConstantMaxTripCount(
8396 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8397
8398 const auto *MaxExitCount =
8399 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, Predicates&: *Predicates)
8400 : getConstantMaxBackedgeTakenCount(L);
8401 return getConstantTripCount(ExitCount: dyn_cast<SCEVConstant>(Val: MaxExitCount));
8402}
8403
8404unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
8405 SmallVector<BasicBlock *, 8> ExitingBlocks;
8406 L->getExitingBlocks(ExitingBlocks);
8407
8408 // An exit with an uncomputable exit count makes the result 1.
8409 if (ExitingBlocks.empty() ||
8410 any_of(Range&: ExitingBlocks, P: [this, L](BasicBlock *ExitingBB) {
8411 return isa<SCEVCouldNotCompute>(Val: getExitCount(L, ExitingBlock: ExitingBB));
8412 }))
8413 return 1;
8414
8415 LoopGuards Guards = LoopGuards::collectOnDemand(L, SE&: *this);
8416 unsigned Res = 0;
8417 for (BasicBlock *ExitingBB : ExitingBlocks)
8418 Res = std::gcd(
8419 m: Res, n: getSmallConstantTripMultiple(ExitCount: getExitCount(L, ExitingBlock: ExitingBB), Guards));
8420 return Res;
8421}
8422
8423unsigned ScalarEvolution::getSmallConstantTripMultiple(const SCEV *ExitCount,
8424 LoopGuards &Guards) {
8425 assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Must be computable!");
8426
8427 // Get the trip count
8428 const SCEV *TCExpr =
8429 getTripCountFromExitCount(ExitCount: applyLoopGuards(Expr: ExitCount, Guards));
8430
8431 APInt Multiple = getNonZeroConstantMultiple(S: TCExpr);
8432 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8433 // the greatest power of 2 divisor less than 2^32.
8434 return Multiple.getActiveBits() > 32
8435 ? 1U << std::min(a: 31U, b: Multiple.countTrailingZeros())
8436 : (unsigned)Multiple.getZExtValue();
8437}
8438
8439unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
8440 const SCEV *ExitCount) {
8441 if (isa<SCEVCouldNotCompute>(Val: ExitCount))
8442 return 1;
8443
8444 LoopGuards Guards = LoopGuards::collectOnDemand(L, SE&: *this);
8445 return getSmallConstantTripMultiple(ExitCount, Guards);
8446}
8447
8448/// Returns the largest constant divisor of the trip count of this loop as a
8449/// normal unsigned value, if possible. This means that the actual trip count is
8450/// always a multiple of the returned value (don't forget the trip count could
8451/// very well be zero as well!).
8452///
8453/// Returns 1 if the trip count is unknown or not guaranteed to be the
8454/// multiple of a constant (which is also the case if the trip count is simply
8455/// constant, use getSmallConstantTripCount for that case), Will also return 1
8456/// if the trip count is very large (>= 2^32).
8457///
8458/// As explained in the comments for getSmallConstantTripCount, this assumes
8459/// that control exits the loop via ExitingBlock.
8460unsigned
8461ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
8462 const BasicBlock *ExitingBlock) {
8463 assert(ExitingBlock && "Must pass a non-null exiting block!");
8464 assert(L->isLoopExiting(ExitingBlock) &&
8465 "Exiting block must actually branch out of the loop!");
8466 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8467 return getSmallConstantTripMultiple(L, ExitCount);
8468}
8469
8470const SCEV *ScalarEvolution::getExitCount(const Loop *L,
8471 const BasicBlock *ExitingBlock,
8472 ExitCountKind Kind) {
8473 switch (Kind) {
8474 case Exact:
8475 return getBackedgeTakenInfo(L).getExact(ExitingBlock, SE: this);
8476 case SymbolicMaximum:
8477 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, SE: this);
8478 case ConstantMaximum:
8479 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, SE: this);
8480 };
8481 llvm_unreachable("Invalid ExitCountKind!");
8482}
8483
8484const SCEV *ScalarEvolution::getPredicatedExitCount(
8485 const Loop *L, const BasicBlock *ExitingBlock,
8486 SmallVectorImpl<const SCEVPredicate *> *Predicates, ExitCountKind Kind) {
8487 switch (Kind) {
8488 case Exact:
8489 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, SE: this,
8490 Predicates);
8491 case SymbolicMaximum:
8492 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, SE: this,
8493 Predicates);
8494 case ConstantMaximum:
8495 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, SE: this,
8496 Predicates);
8497 };
8498 llvm_unreachable("Invalid ExitCountKind!");
8499}
8500
8501const SCEV *ScalarEvolution::getPredicatedBackedgeTakenCount(
8502 const Loop *L, SmallVectorImpl<const SCEVPredicate *> &Preds) {
8503 return getPredicatedBackedgeTakenInfo(L).getExact(L, SE: this, Predicates: &Preds);
8504}
8505
8506const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
8507 ExitCountKind Kind) {
8508 switch (Kind) {
8509 case Exact:
8510 return getBackedgeTakenInfo(L).getExact(L, SE: this);
8511 case ConstantMaximum:
8512 return getBackedgeTakenInfo(L).getConstantMax(SE: this);
8513 case SymbolicMaximum:
8514 return getBackedgeTakenInfo(L).getSymbolicMax(L, SE: this);
8515 };
8516 llvm_unreachable("Invalid ExitCountKind!");
8517}
8518
8519const SCEV *ScalarEvolution::getPredicatedSymbolicMaxBackedgeTakenCount(
8520 const Loop *L, SmallVectorImpl<const SCEVPredicate *> &Preds) {
8521 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, SE: this, Predicates: &Preds);
8522}
8523
8524const SCEV *ScalarEvolution::getPredicatedConstantMaxBackedgeTakenCount(
8525 const Loop *L, SmallVectorImpl<const SCEVPredicate *> &Preds) {
8526 return getPredicatedBackedgeTakenInfo(L).getConstantMax(SE: this, Predicates: &Preds);
8527}
8528
8529bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
8530 return getBackedgeTakenInfo(L).isConstantMaxOrZero(SE: this);
8531}
8532
8533/// Push PHI nodes in the header of the given loop onto the given Worklist.
8534static void PushLoopPHIs(const Loop *L,
8535 SmallVectorImpl<Instruction *> &Worklist,
8536 SmallPtrSetImpl<Instruction *> &Visited) {
8537 BasicBlock *Header = L->getHeader();
8538
8539 // Push all Loop-header PHIs onto the Worklist stack.
8540 for (PHINode &PN : Header->phis())
8541 if (Visited.insert(Ptr: &PN).second)
8542 Worklist.push_back(Elt: &PN);
8543}
8544
8545ScalarEvolution::BackedgeTakenInfo &
8546ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8547 auto &BTI = getBackedgeTakenInfo(L);
8548 if (BTI.hasFullInfo())
8549 return BTI;
8550
8551 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(Key: L);
8552
8553 if (!Pair.second)
8554 return Pair.first->second;
8555
8556 BackedgeTakenInfo Result =
8557 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8558
8559 return PredicatedBackedgeTakenCounts.find(Val: L)->second = std::move(Result);
8560}
8561
8562ScalarEvolution::BackedgeTakenInfo &
8563ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8564 // Initially insert an invalid entry for this loop. If the insertion
8565 // succeeds, proceed to actually compute a backedge-taken count and
8566 // update the value. The temporary CouldNotCompute value tells SCEV
8567 // code elsewhere that it shouldn't attempt to request a new
8568 // backedge-taken count, which could result in infinite recursion.
8569 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8570 BackedgeTakenCounts.try_emplace(Key: L);
8571 if (!Pair.second)
8572 return Pair.first->second;
8573
8574 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8575 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8576 // must be cleared in this scope.
8577 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8578
8579 // Now that we know more about the trip count for this loop, forget any
8580 // existing SCEV values for PHI nodes in this loop since they are only
8581 // conservative estimates made without the benefit of trip count
8582 // information. This invalidation is not necessary for correctness, and is
8583 // only done to produce more precise results.
8584 if (Result.hasAnyInfo()) {
8585 // Invalidate any expression using an addrec in this loop.
8586 SmallVector<SCEVUse, 8> ToForget;
8587 auto LoopUsersIt = LoopUsers.find(Val: L);
8588 if (LoopUsersIt != LoopUsers.end())
8589 append_range(C&: ToForget, R&: LoopUsersIt->second);
8590 forgetMemoizedResults(SCEVs: ToForget);
8591
8592 // Invalidate constant-evolved loop header phis.
8593 for (PHINode &PN : L->getHeader()->phis())
8594 ConstantEvolutionLoopExitValue.erase(Val: &PN);
8595 }
8596
8597 // Re-lookup the insert position, since the call to
8598 // computeBackedgeTakenCount above could result in a
8599 // recusive call to getBackedgeTakenInfo (on a different
8600 // loop), which would invalidate the iterator computed
8601 // earlier.
8602 return BackedgeTakenCounts.find(Val: L)->second = std::move(Result);
8603}
8604
8605void ScalarEvolution::forgetAllLoops() {
8606 // This method is intended to forget all info about loops. It should
8607 // invalidate caches as if the following happened:
8608 // - The trip counts of all loops have changed arbitrarily
8609 // - Every llvm::Value has been updated in place to produce a different
8610 // result.
8611 BackedgeTakenCounts.clear();
8612 PredicatedBackedgeTakenCounts.clear();
8613 BECountUsers.clear();
8614 LoopPropertiesCache.clear();
8615 ConstantEvolutionLoopExitValue.clear();
8616 ValueExprMap.clear();
8617 ValuesAtScopes.clear();
8618 ValuesAtScopesUsers.clear();
8619 LoopDispositions.clear();
8620 BlockDispositions.clear();
8621 UnsignedRanges.clear();
8622 SignedRanges.clear();
8623 ExprValueMap.clear();
8624 HasRecMap.clear();
8625 ConstantMultipleCache.clear();
8626 PredicatedSCEVRewrites.clear();
8627 FoldCache.clear();
8628 FoldCacheUser.clear();
8629}
8630void ScalarEvolution::visitAndClearUsers(
8631 SmallVectorImpl<Instruction *> &Worklist,
8632 SmallPtrSetImpl<Instruction *> &Visited,
8633 SmallVectorImpl<SCEVUse> &ToForget) {
8634 // Nothing can be invalidated if no value has a SCEV yet.
8635 if (ValueExprMap.empty()) {
8636 Worklist.clear();
8637 return;
8638 }
8639 while (!Worklist.empty()) {
8640 Instruction *I = Worklist.pop_back_val();
8641 if (!isSCEVable(Ty: I->getType()) && !isa<WithOverflowInst>(Val: I))
8642 continue;
8643
8644 ValueExprMapType::iterator It =
8645 ValueExprMap.find_as(Val: static_cast<Value *>(I));
8646 if (It != ValueExprMap.end()) {
8647 ToForget.push_back(Elt: It->second);
8648 eraseValueFromMap(V: It->first);
8649 if (PHINode *PN = dyn_cast<PHINode>(Val: I))
8650 ConstantEvolutionLoopExitValue.erase(Val: PN);
8651 }
8652
8653 PushDefUseChildren(I, Worklist, Visited);
8654 }
8655}
8656
8657void ScalarEvolution::forgetLoop(const Loop *L) {
8658 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8659 SmallVector<Instruction *, 32> Worklist;
8660 SmallPtrSet<Instruction *, 16> Visited;
8661 SmallVector<SCEVUse, 16> ToForget;
8662
8663 // Iterate over all the loops and sub-loops to drop SCEV information.
8664 while (!LoopWorklist.empty()) {
8665 auto *CurrL = LoopWorklist.pop_back_val();
8666
8667 // Drop any stored trip count value.
8668 forgetBackedgeTakenCounts(L: CurrL, /* Predicated */ false);
8669 forgetBackedgeTakenCounts(L: CurrL, /* Predicated */ true);
8670
8671 // Drop information about predicated SCEV rewrites for this loop.
8672 PredicatedSCEVRewrites.remove_if(
8673 Pred: [&](const auto &Entry) { return Entry.first.second == CurrL; });
8674
8675 auto LoopUsersItr = LoopUsers.find(Val: CurrL);
8676 if (LoopUsersItr != LoopUsers.end())
8677 llvm::append_range(C&: ToForget, R&: LoopUsersItr->second);
8678
8679 // Drop information about expressions based on loop-header PHIs.
8680 PushLoopPHIs(L: CurrL, Worklist, Visited);
8681 visitAndClearUsers(Worklist, Visited, ToForget);
8682
8683 LoopPropertiesCache.erase(Val: CurrL);
8684 // Forget all contained loops too, to avoid dangling entries in the
8685 // ValuesAtScopes map.
8686 LoopWorklist.append(in_start: CurrL->begin(), in_end: CurrL->end());
8687 }
8688 forgetMemoizedResults(SCEVs: ToForget);
8689}
8690
8691void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
8692 forgetLoop(L: L->getOutermostLoop());
8693}
8694
8695void ScalarEvolution::forgetValue(Value *V) {
8696 Instruction *I = dyn_cast<Instruction>(Val: V);
8697 if (!I) return;
8698
8699 // Drop information about expressions based on loop-header PHIs.
8700 SmallVector<Instruction *, 16> Worklist;
8701 SmallPtrSet<Instruction *, 8> Visited;
8702 SmallVector<SCEVUse, 8> ToForget;
8703 Worklist.push_back(Elt: I);
8704 Visited.insert(Ptr: I);
8705 visitAndClearUsers(Worklist, Visited, ToForget);
8706
8707 forgetMemoizedResults(SCEVs: ToForget);
8708}
8709
8710void ScalarEvolution::forgetValues(ArrayRef<Value *> Values) {
8711 SmallVector<Instruction *, 16> Worklist;
8712 SmallPtrSet<Instruction *, 8> Visited;
8713 SmallVector<SCEVUse, 8> ToForget;
8714 for (Value *V : Values)
8715 if (auto *I = dyn_cast<Instruction>(Val: V))
8716 if (Visited.insert(Ptr: I).second)
8717 Worklist.push_back(Elt: I);
8718 visitAndClearUsers(Worklist, Visited, ToForget);
8719
8720 forgetMemoizedResults(SCEVs: ToForget);
8721}
8722
8723void ScalarEvolution::forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V) {
8724 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8725 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8726 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8727 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8728 auto InvalidateValue = [&](Value *Val) {
8729 if (!isSCEVable(Ty: Val->getType()))
8730 return;
8731 if (const SCEV *S = getExistingSCEV(V: Val)) {
8732 struct InvalidationRootCollector {
8733 Loop *L;
8734 SmallVector<SCEVUse, 8> Roots;
8735
8736 InvalidationRootCollector(Loop *L) : L(L) {}
8737
8738 bool follow(const SCEV *S) {
8739 if (auto *SU = dyn_cast<SCEVUnknown>(Val: S)) {
8740 if (auto *I = dyn_cast<Instruction>(Val: SU->getValue()))
8741 if (L->contains(Inst: I))
8742 Roots.push_back(Elt: S);
8743 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Val: S)) {
8744 if (L->contains(L: AddRec->getLoop()))
8745 Roots.push_back(Elt: S);
8746 }
8747 return true;
8748 }
8749 bool isDone() const { return false; }
8750 };
8751
8752 InvalidationRootCollector C(L);
8753 visitAll(Root: S, Visitor&: C);
8754 forgetMemoizedResults(SCEVs: C.Roots);
8755 }
8756 };
8757
8758 InvalidateValue(V);
8759
8760 // If V has a non-SCEV-able type (e.g. {i64, i1} from a with.overflow
8761 // intrinsic), its users (e.g. extractvalue) may have stale SCEV
8762 // expressions referencing loop-internal values.
8763 if (!isSCEVable(Ty: V->getType()) &&
8764 any_of(Range: V->incoming_values(), P: IsaPred<WithOverflowInst>))
8765 for (User *U : V->users())
8766 InvalidateValue(U);
8767 // Also perform the normal invalidation.
8768 forgetValue(V);
8769}
8770
8771void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8772
8773void ScalarEvolution::forgetBlockAndLoopDispositions(Value *V) {
8774 // Unless a specific value is passed to invalidation, completely clear both
8775 // caches.
8776 if (!V) {
8777 BlockDispositions.clear();
8778 LoopDispositions.clear();
8779 return;
8780 }
8781
8782 if (!isSCEVable(Ty: V->getType()))
8783 return;
8784
8785 const SCEV *S = getExistingSCEV(V);
8786 if (!S)
8787 return;
8788
8789 // Invalidate the block and loop dispositions cached for S. Dispositions of
8790 // S's users may change if S's disposition changes (i.e. a user may change to
8791 // loop-invariant, if S changes to loop invariant), so also invalidate
8792 // dispositions of S's users recursively.
8793 SmallVector<SCEVUse, 8> Worklist = {S};
8794 SmallPtrSet<const SCEV *, 8> Seen = {S};
8795 while (!Worklist.empty()) {
8796 const SCEV *Curr = Worklist.pop_back_val();
8797 bool LoopDispoRemoved = LoopDispositions.erase(Val: Curr);
8798 bool BlockDispoRemoved = BlockDispositions.erase(Val: Curr);
8799 if (!LoopDispoRemoved && !BlockDispoRemoved)
8800 continue;
8801 auto Users = SCEVUsers.find(Val: Curr);
8802 if (Users != SCEVUsers.end())
8803 for (const auto *User : Users->second)
8804 if (Seen.insert(Ptr: User).second)
8805 Worklist.push_back(Elt: User);
8806 }
8807}
8808
8809/// Get the exact loop backedge taken count considering all loop exits. A
8810/// computable result can only be returned for loops with all exiting blocks
8811/// dominating the latch. howFarToZero assumes that the limit of each loop test
8812/// is never skipped. This is a valid assumption as long as the loop exits via
8813/// that test. For precise results, it is the caller's responsibility to specify
8814/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8815const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8816 const Loop *L, ScalarEvolution *SE,
8817 SmallVectorImpl<const SCEVPredicate *> *Preds) const {
8818 // If any exits were not computable, the loop is not computable.
8819 if (!isComplete() || ExitNotTaken.empty())
8820 return SE->getCouldNotCompute();
8821
8822 const BasicBlock *Latch = L->getLoopLatch();
8823 // All exiting blocks we have collected must dominate the only backedge.
8824 if (!Latch)
8825 return SE->getCouldNotCompute();
8826
8827 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8828 // count is simply a minimum out of all these calculated exit counts.
8829 SmallVector<SCEVUse, 2> Ops;
8830 for (const auto &ENT : ExitNotTaken) {
8831 const SCEV *BECount = ENT.ExactNotTaken;
8832 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8833 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8834 "We should only have known counts for exiting blocks that dominate "
8835 "latch!");
8836
8837 Ops.push_back(Elt: BECount);
8838
8839 if (Preds)
8840 append_range(C&: *Preds, R: ENT.Predicates);
8841
8842 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8843 "Predicate should be always true!");
8844 }
8845
8846 // If an earlier exit exits on the first iteration (exit count zero), then
8847 // a later poison exit count should not propagate into the result. This are
8848 // exactly the semantics provided by umin_seq.
8849 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8850}
8851
8852const ScalarEvolution::ExitNotTakenInfo *
8853ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8854 const BasicBlock *ExitingBlock,
8855 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8856 for (const auto &ENT : ExitNotTaken)
8857 if (ENT.ExitingBlock == ExitingBlock) {
8858 if (ENT.hasAlwaysTruePredicate())
8859 return &ENT;
8860 else if (Predicates) {
8861 append_range(C&: *Predicates, R: ENT.Predicates);
8862 return &ENT;
8863 }
8864 }
8865
8866 return nullptr;
8867}
8868
8869/// getConstantMax - Get the constant max backedge taken count for the loop.
8870const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8871 ScalarEvolution *SE,
8872 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8873 if (!getConstantMax())
8874 return SE->getCouldNotCompute();
8875
8876 for (const auto &ENT : ExitNotTaken)
8877 if (!ENT.hasAlwaysTruePredicate()) {
8878 if (!Predicates)
8879 return SE->getCouldNotCompute();
8880 append_range(C&: *Predicates, R: ENT.Predicates);
8881 }
8882
8883 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8884 isa<SCEVConstant>(getConstantMax())) &&
8885 "No point in having a non-constant max backedge taken count!");
8886 return getConstantMax();
8887}
8888
8889const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8890 const Loop *L, ScalarEvolution *SE,
8891 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8892 if (!SymbolicMax) {
8893 // Form an expression for the maximum exit count possible for this loop. We
8894 // merge the max and exact information to approximate a version of
8895 // getConstantMaxBackedgeTakenCount which isn't restricted to just
8896 // constants.
8897 SmallVector<SCEVUse, 4> ExitCounts;
8898
8899 for (const auto &ENT : ExitNotTaken) {
8900 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8901 if (!isa<SCEVCouldNotCompute>(Val: ExitCount)) {
8902 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
8903 "We should only have known counts for exiting blocks that "
8904 "dominate latch!");
8905 ExitCounts.push_back(Elt: ExitCount);
8906 if (Predicates)
8907 append_range(C&: *Predicates, R: ENT.Predicates);
8908
8909 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8910 "Predicate should be always true!");
8911 }
8912 }
8913 if (ExitCounts.empty())
8914 SymbolicMax = SE->getCouldNotCompute();
8915 else
8916 SymbolicMax =
8917 SE->getUMinFromMismatchedTypes(Ops&: ExitCounts, /*Sequential*/ true);
8918 }
8919 return SymbolicMax;
8920}
8921
8922bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8923 ScalarEvolution *SE) const {
8924 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8925 return !ENT.hasAlwaysTruePredicate();
8926 };
8927 return MaxOrZero && !any_of(Range: ExitNotTaken, P: PredicateNotAlwaysTrue);
8928}
8929
8930ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
8931 : ExitLimit(E, E, E, false) {}
8932
8933ScalarEvolution::ExitLimit::ExitLimit(
8934 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8935 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8936 ArrayRef<ArrayRef<const SCEVPredicate *>> PredLists)
8937 : ExactNotTaken(E), ConstantMaxNotTaken(ConstantMaxNotTaken),
8938 SymbolicMaxNotTaken(SymbolicMaxNotTaken), MaxOrZero(MaxOrZero) {
8939 // If we prove the max count is zero, so is the symbolic bound. This happens
8940 // in practice due to differences in a) how context sensitive we've chosen
8941 // to be and b) how we reason about bounds implied by UB.
8942 if (ConstantMaxNotTaken->isZero()) {
8943 this->ExactNotTaken = E = ConstantMaxNotTaken;
8944 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8945 }
8946
8947 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
8948 !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
8949 "Exact is not allowed to be less precise than Constant Max");
8950 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
8951 !isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken)) &&
8952 "Exact is not allowed to be less precise than Symbolic Max");
8953 assert((isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken) ||
8954 !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
8955 "Symbolic Max is not allowed to be less precise than Constant Max");
8956 assert((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) ||
8957 isa<SCEVConstant>(ConstantMaxNotTaken)) &&
8958 "No point in having a non-constant max backedge taken count!");
8959 SmallPtrSet<const SCEVPredicate *, 4> SeenPreds;
8960 for (const auto PredList : PredLists)
8961 for (const auto *P : PredList) {
8962 if (SeenPreds.contains(Ptr: P))
8963 continue;
8964 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
8965 SeenPreds.insert(Ptr: P);
8966 Predicates.push_back(Elt: P);
8967 }
8968 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8969 "Backedge count should be int");
8970 assert((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) ||
8971 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8972 "Max backedge count should be int");
8973}
8974
8975ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E,
8976 const SCEV *ConstantMaxNotTaken,
8977 const SCEV *SymbolicMaxNotTaken,
8978 bool MaxOrZero,
8979 ArrayRef<const SCEVPredicate *> PredList)
8980 : ExitLimit(E, ConstantMaxNotTaken, SymbolicMaxNotTaken, MaxOrZero,
8981 ArrayRef({PredList})) {}
8982
8983/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8984/// computable exit into a persistent ExitNotTakenInfo array.
8985ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8986 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
8987 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8988 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8989 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8990
8991 ExitNotTaken.reserve(N: ExitCounts.size());
8992 std::transform(first: ExitCounts.begin(), last: ExitCounts.end(),
8993 result: std::back_inserter(x&: ExitNotTaken),
8994 unary_op: [&](const EdgeExitInfo &EEI) {
8995 BasicBlock *ExitBB = EEI.first;
8996 const ExitLimit &EL = EEI.second;
8997 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
8998 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
8999 EL.Predicates);
9000 });
9001 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
9002 isa<SCEVConstant>(ConstantMax)) &&
9003 "No point in having a non-constant max backedge taken count!");
9004}
9005
9006/// Compute the number of times the backedge of the specified loop will execute.
9007ScalarEvolution::BackedgeTakenInfo
9008ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
9009 bool AllowPredicates) {
9010 SmallVector<BasicBlock *, 8> ExitingBlocks;
9011 L->getExitingBlocks(ExitingBlocks);
9012
9013 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9014
9015 SmallVector<EdgeExitInfo, 4> ExitCounts;
9016 bool CouldComputeBECount = true;
9017 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
9018 const SCEV *MustExitMaxBECount = nullptr;
9019 const SCEV *MayExitMaxBECount = nullptr;
9020 bool MustExitMaxOrZero = false;
9021 bool IsOnlyExit = ExitingBlocks.size() == 1;
9022
9023 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
9024 // and compute maxBECount.
9025 // Do a union of all the predicates here.
9026 for (BasicBlock *ExitBB : ExitingBlocks) {
9027 // We canonicalize untaken exits to br (constant), ignore them so that
9028 // proving an exit untaken doesn't negatively impact our ability to reason
9029 // about the loop as whole.
9030 if (auto *BI = dyn_cast<CondBrInst>(Val: ExitBB->getTerminator()))
9031 if (auto *CI = dyn_cast<ConstantInt>(Val: BI->getCondition())) {
9032 bool ExitIfTrue = !L->contains(BB: BI->getSuccessor(i: 0));
9033 if (ExitIfTrue == CI->isZero())
9034 continue;
9035 }
9036
9037 ExitLimit EL = computeExitLimit(L, ExitingBlock: ExitBB, IsOnlyExit, AllowPredicates);
9038
9039 assert((AllowPredicates || EL.Predicates.empty()) &&
9040 "Predicated exit limit when predicates are not allowed!");
9041
9042 // 1. For each exit that can be computed, add an entry to ExitCounts.
9043 // CouldComputeBECount is true only if all exits can be computed.
9044 if (EL.ExactNotTaken != getCouldNotCompute())
9045 ++NumExitCountsComputed;
9046 else
9047 // We couldn't compute an exact value for this exit, so
9048 // we won't be able to compute an exact value for the loop.
9049 CouldComputeBECount = false;
9050 // Remember exit count if either exact or symbolic is known. Because
9051 // Exact always implies symbolic, only check symbolic.
9052 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
9053 ExitCounts.emplace_back(Args&: ExitBB, Args&: EL);
9054 else {
9055 assert(EL.ExactNotTaken == getCouldNotCompute() &&
9056 "Exact is known but symbolic isn't?");
9057 ++NumExitCountsNotComputed;
9058 }
9059
9060 // 2. Derive the loop's MaxBECount from each exit's max number of
9061 // non-exiting iterations. Partition the loop exits into two kinds:
9062 // LoopMustExits and LoopMayExits.
9063 //
9064 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
9065 // is a LoopMayExit. If any computable LoopMustExit is found, then
9066 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
9067 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
9068 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
9069 // any
9070 // computable EL.ConstantMaxNotTaken.
9071 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
9072 DT.dominates(A: ExitBB, B: Latch)) {
9073 if (!MustExitMaxBECount) {
9074 MustExitMaxBECount = EL.ConstantMaxNotTaken;
9075 MustExitMaxOrZero = EL.MaxOrZero;
9076 } else {
9077 MustExitMaxBECount = getUMinFromMismatchedTypes(LHS: MustExitMaxBECount,
9078 RHS: EL.ConstantMaxNotTaken);
9079 }
9080 } else if (MayExitMaxBECount != getCouldNotCompute()) {
9081 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
9082 MayExitMaxBECount = EL.ConstantMaxNotTaken;
9083 else {
9084 MayExitMaxBECount = getUMaxFromMismatchedTypes(LHS: MayExitMaxBECount,
9085 RHS: EL.ConstantMaxNotTaken);
9086 }
9087 }
9088 }
9089 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
9090 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
9091 // The loop backedge will be taken the maximum or zero times if there's
9092 // a single exit that must be taken the maximum or zero times.
9093 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9094
9095 // Remember which SCEVs are used in exit limits for invalidation purposes.
9096 // We only care about non-constant SCEVs here, so we can ignore
9097 // EL.ConstantMaxNotTaken
9098 // and MaxBECount, which must be SCEVConstant.
9099 for (const auto &Pair : ExitCounts) {
9100 if (!isa<SCEVConstant>(Val: Pair.second.ExactNotTaken))
9101 BECountUsers[Pair.second.ExactNotTaken].insert(Ptr: {L, AllowPredicates});
9102 if (!isa<SCEVConstant>(Val: Pair.second.SymbolicMaxNotTaken))
9103 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9104 Ptr: {L, AllowPredicates});
9105 }
9106 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9107 MaxBECount, MaxOrZero);
9108}
9109
9110ScalarEvolution::ExitLimit
9111ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9112 bool IsOnlyExit, bool AllowPredicates) {
9113 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9114 // If our exiting block does not dominate the latch, then its connection with
9115 // loop's exit limit may be far from trivial.
9116 const BasicBlock *Latch = L->getLoopLatch();
9117 if (!Latch || !DT.dominates(A: ExitingBlock, B: Latch))
9118 return getCouldNotCompute();
9119
9120 Instruction *Term = ExitingBlock->getTerminator();
9121 if (CondBrInst *BI = dyn_cast<CondBrInst>(Val: Term)) {
9122 bool ExitIfTrue = !L->contains(BB: BI->getSuccessor(i: 0));
9123 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9124 "It should have one successor in loop and one exit block!");
9125 // Proceed to the next level to examine the exit condition expression.
9126 return computeExitLimitFromCond(L, ExitCond: BI->getCondition(), ExitIfTrue,
9127 /*ControlsOnlyExit=*/IsOnlyExit,
9128 AllowPredicates);
9129 }
9130
9131 if (SwitchInst *SI = dyn_cast<SwitchInst>(Val: Term)) {
9132 // For switch, make sure that there is a single exit from the loop.
9133 BasicBlock *Exit = nullptr;
9134 for (auto *SBB : successors(BB: ExitingBlock))
9135 if (!L->contains(BB: SBB)) {
9136 if (Exit) // Multiple exit successors.
9137 return getCouldNotCompute();
9138 Exit = SBB;
9139 }
9140 assert(Exit && "Exiting block must have at least one exit");
9141 return computeExitLimitFromSingleExitSwitch(
9142 L, Switch: SI, ExitingBB: Exit, /*ControlsOnlyExit=*/IsSubExpr: IsOnlyExit);
9143 }
9144
9145 return getCouldNotCompute();
9146}
9147
9148ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
9149 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9150 bool AllowPredicates) {
9151 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9152 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9153 ControlsOnlyExit, AllowPredicates);
9154}
9155
9156std::optional<ScalarEvolution::ExitLimit>
9157ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9158 bool ExitIfTrue, bool ControlsOnlyExit,
9159 bool AllowPredicates) {
9160 (void)this->L;
9161 (void)this->ExitIfTrue;
9162 (void)this->AllowPredicates;
9163
9164 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9165 this->AllowPredicates == AllowPredicates &&
9166 "Variance in assumed invariant key components!");
9167 auto Itr = TripCountMap.find(Val: {ExitCond, ControlsOnlyExit});
9168 if (Itr == TripCountMap.end())
9169 return std::nullopt;
9170 return Itr->second;
9171}
9172
9173void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
9174 bool ExitIfTrue,
9175 bool ControlsOnlyExit,
9176 bool AllowPredicates,
9177 const ExitLimit &EL) {
9178 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9179 this->AllowPredicates == AllowPredicates &&
9180 "Variance in assumed invariant key components!");
9181
9182 auto InsertResult = TripCountMap.insert(KV: {{ExitCond, ControlsOnlyExit}, EL});
9183 assert(InsertResult.second && "Expected successful insertion!");
9184 (void)InsertResult;
9185 (void)ExitIfTrue;
9186}
9187
9188ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
9189 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9190 bool ControlsOnlyExit, bool AllowPredicates) {
9191
9192 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9193 AllowPredicates))
9194 return *MaybeEL;
9195
9196 ExitLimit EL = computeExitLimitFromCondImpl(
9197 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9198 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9199 return EL;
9200}
9201
9202ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
9203 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9204 bool ControlsOnlyExit, bool AllowPredicates) {
9205 // Handle BinOp conditions (And, Or).
9206 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9207 Cache, L, ExitCond, ExitIfTrue, AllowPredicates))
9208 return *LimitFromBinOp;
9209
9210 // With an icmp, it may be feasible to compute an exact backedge-taken count.
9211 // Proceed to the next level to examine the icmp.
9212 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(Val: ExitCond)) {
9213 ExitLimit EL =
9214 computeExitLimitFromICmp(L, ExitCond: ExitCondICmp, ExitIfTrue, IsSubExpr: ControlsOnlyExit);
9215 if (EL.hasFullInfo() || !AllowPredicates)
9216 return EL;
9217
9218 // Try again, but use SCEV predicates this time.
9219 return computeExitLimitFromICmp(L, ExitCond: ExitCondICmp, ExitIfTrue,
9220 IsSubExpr: ControlsOnlyExit,
9221 /*AllowPredicates=*/true);
9222 }
9223
9224 // Check for a constant condition. These are normally stripped out by
9225 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
9226 // preserve the CFG and is temporarily leaving constant conditions
9227 // in place.
9228 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: ExitCond)) {
9229 if (ExitIfTrue == !CI->getZExtValue())
9230 // The backedge is always taken.
9231 return getCouldNotCompute();
9232 // The backedge is never taken.
9233 return getZero(Ty: CI->getType());
9234 }
9235
9236 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9237 // with a constant step, we can form an equivalent icmp predicate and figure
9238 // out how many iterations will be taken before we exit.
9239 const WithOverflowInst *WO;
9240 const APInt *C;
9241 if (match(V: ExitCond, P: m_ExtractValue<1>(V: m_WithOverflowInst(I&: WO))) &&
9242 match(V: WO->getRHS(), P: m_APInt(Res&: C))) {
9243 ConstantRange NWR =
9244 ConstantRange::makeExactNoWrapRegion(BinOp: WO->getBinaryOp(), Other: *C,
9245 NoWrapKind: WO->getNoWrapKind());
9246 CmpInst::Predicate Pred;
9247 APInt NewRHSC, Offset;
9248 NWR.getEquivalentICmp(Pred, RHS&: NewRHSC, Offset);
9249 if (!ExitIfTrue)
9250 Pred = ICmpInst::getInversePredicate(pred: Pred);
9251 auto *LHS = getSCEV(V: WO->getLHS());
9252 if (Offset != 0)
9253 LHS = getAddExpr(LHS, RHS: getConstant(Val: Offset));
9254 auto EL = computeExitLimitFromICmp(L, Pred, LHS, RHS: getConstant(Val: NewRHSC),
9255 IsSubExpr: ControlsOnlyExit, AllowPredicates);
9256 if (EL.hasAnyInfo())
9257 return EL;
9258 }
9259
9260 // If it's not an integer or pointer comparison then compute it the hard way.
9261 return computeExitCountExhaustively(L, Cond: ExitCond, ExitWhen: ExitIfTrue);
9262}
9263
9264std::optional<ScalarEvolution::ExitLimit>
9265ScalarEvolution::computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache,
9266 const Loop *L,
9267 Value *ExitCond,
9268 bool ExitIfTrue,
9269 bool AllowPredicates) {
9270 // Check if the controlling expression for this loop is an And or Or.
9271 Value *Op0, *Op1;
9272 bool IsAnd;
9273 if (match(V: ExitCond, P: m_LogicalAnd(L: m_Value(V&: Op0), R: m_Value(V&: Op1))))
9274 IsAnd = true;
9275 else if (match(V: ExitCond, P: m_LogicalOr(L: m_Value(V&: Op0), R: m_Value(V&: Op1))))
9276 IsAnd = false;
9277 else
9278 return std::nullopt;
9279
9280 // A sub-condition of a non-trivial binop never solely controls the exit,
9281 // whether we exit always depends on both conditions.
9282 ExitLimit EL0 = computeExitLimitFromCondCached(
9283 Cache, L, ExitCond: Op0, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9284 ExitLimit EL1 = computeExitLimitFromCondCached(
9285 Cache, L, ExitCond: Op1, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9286
9287 // EitherMayExit is true in these two cases:
9288 // br (and Op0 Op1), loop, exit
9289 // br (or Op0 Op1), exit, loop
9290 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9291
9292 const SCEV *BECount = getCouldNotCompute();
9293 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9294 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9295 if (EitherMayExit) {
9296 bool UseSequentialUMin = !isa<BinaryOperator>(Val: ExitCond);
9297 // Both conditions must be same for the loop to continue executing.
9298 // Choose the less conservative count.
9299 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9300 EL1.ExactNotTaken != getCouldNotCompute()) {
9301 BECount = getUMinFromMismatchedTypes(LHS: EL0.ExactNotTaken, RHS: EL1.ExactNotTaken,
9302 Sequential: UseSequentialUMin);
9303 }
9304 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9305 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9306 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9307 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9308 else
9309 ConstantMaxBECount = getUMinFromMismatchedTypes(LHS: EL0.ConstantMaxNotTaken,
9310 RHS: EL1.ConstantMaxNotTaken);
9311 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9312 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9313 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9314 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9315 else
9316 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9317 LHS: EL0.SymbolicMaxNotTaken, RHS: EL1.SymbolicMaxNotTaken, Sequential: UseSequentialUMin);
9318 } else {
9319 // Both conditions must be same at the same time for the loop to exit.
9320 // For now, be conservative.
9321 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9322 BECount = EL0.ExactNotTaken;
9323 }
9324
9325 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9326 // to be more aggressive when computing BECount than when computing
9327 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9328 // and
9329 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9330 // EL1.ConstantMaxNotTaken to not.
9331 if (isa<SCEVCouldNotCompute>(Val: ConstantMaxBECount) &&
9332 !isa<SCEVCouldNotCompute>(Val: BECount))
9333 ConstantMaxBECount = getConstant(Val: getUnsignedRangeMax(S: BECount));
9334 if (isa<SCEVCouldNotCompute>(Val: SymbolicMaxBECount))
9335 SymbolicMaxBECount =
9336 isa<SCEVCouldNotCompute>(Val: BECount) ? ConstantMaxBECount : BECount;
9337 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9338 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
9339}
9340
9341ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9342 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9343 bool AllowPredicates) {
9344 // If the condition was exit on true, convert the condition to exit on false
9345 CmpPredicate Pred;
9346 if (!ExitIfTrue)
9347 Pred = ExitCond->getCmpPredicate();
9348 else
9349 Pred = ExitCond->getInverseCmpPredicate();
9350 const ICmpInst::Predicate OriginalPred = Pred;
9351
9352 const SCEV *LHS = getSCEV(V: ExitCond->getOperand(i_nocapture: 0));
9353 const SCEV *RHS = getSCEV(V: ExitCond->getOperand(i_nocapture: 1));
9354
9355 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, IsSubExpr: ControlsOnlyExit,
9356 AllowPredicates);
9357 if (EL.hasAnyInfo())
9358 return EL;
9359
9360 auto *ExhaustiveCount =
9361 computeExitCountExhaustively(L, Cond: ExitCond, ExitWhen: ExitIfTrue);
9362
9363 if (!isa<SCEVCouldNotCompute>(Val: ExhaustiveCount))
9364 return ExhaustiveCount;
9365
9366 return computeShiftCompareExitLimit(LHS: ExitCond->getOperand(i_nocapture: 0),
9367 RHS: ExitCond->getOperand(i_nocapture: 1), L, Pred: OriginalPred);
9368}
9369ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9370 const Loop *L, CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
9371 bool ControlsOnlyExit, bool AllowPredicates) {
9372
9373 // Try to evaluate any dependencies out of the loop.
9374 LHS = getSCEVAtScope(S: LHS, L);
9375 RHS = getSCEVAtScope(S: RHS, L);
9376
9377 // At this point, we would like to compute how many iterations of the
9378 // loop the predicate will return true for these inputs.
9379 if (isLoopInvariant(S: LHS, L) && !isLoopInvariant(S: RHS, L)) {
9380 // If there is a loop-invariant, force it into the RHS.
9381 std::swap(a&: LHS, b&: RHS);
9382 Pred = ICmpInst::getSwappedCmpPredicate(Pred);
9383 }
9384
9385 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9386 loopIsFiniteByAssumption(L);
9387 // Simplify the operands before analyzing them.
9388 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9389
9390 // If we have a comparison of a chrec against a constant, try to use value
9391 // ranges to answer this query.
9392 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Val&: RHS))
9393 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Val&: LHS))
9394 if (AddRec->getLoop() == L) {
9395 // Form the constant range.
9396 ConstantRange CompRange =
9397 ConstantRange::makeExactICmpRegion(Pred, Other: RHSC->getAPInt());
9398
9399 const SCEV *Ret = AddRec->getNumIterationsInRange(Range: CompRange, SE&: *this);
9400 if (!isa<SCEVCouldNotCompute>(Val: Ret)) return Ret;
9401 }
9402
9403 // If this loop must exit based on this condition (or execute undefined
9404 // behaviour), see if we can improve wrap flags. This is essentially
9405 // a must execute style proof.
9406 if (ControllingFiniteLoop && isLoopInvariant(S: RHS, L)) {
9407 // If we can prove the test sequence produced must repeat the same values
9408 // on self-wrap of the IV, then we can infer that IV doesn't self wrap
9409 // because if it did, we'd have an infinite (undefined) loop.
9410 // TODO: We can peel off any functions which are invertible *in L*. Loop
9411 // invariant terms are effectively constants for our purposes here.
9412 SCEVUse InnerLHS = LHS;
9413 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Val&: LHS))
9414 InnerLHS = ZExt->getOperand();
9415 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Val&: InnerLHS);
9416 AR && !AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9417 isKnownToBeAPowerOfTwo(S: AR->getStepRecurrence(SE&: *this), /*OrZero=*/true,
9418 /*OrNegative=*/true)) {
9419 auto Flags = AR->getNoWrapFlags();
9420 Flags = setFlags(Flags, OnFlags: SCEV::FlagNW);
9421 SmallVector<SCEVUse> Operands{AR->operands()};
9422 Flags = StrengthenNoWrapFlags(SE: this, Type: scAddRecExpr, Ops: Operands, Flags);
9423 setNoWrapFlags(AddRec: const_cast<SCEVAddRecExpr *>(AR), Flags);
9424 }
9425
9426 // For a slt/ult condition with a positive step, can we prove nsw/nuw?
9427 // From no-self-wrap, this follows trivially from the fact that every
9428 // (un)signed-wrapped, but not self-wrapped value must be LT than the
9429 // last value before (un)signed wrap. Since we know that last value
9430 // didn't exit, nor will any smaller one.
9431 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) {
9432 auto WrapType = Pred == ICmpInst::ICMP_SLT ? SCEV::FlagNSW : SCEV::FlagNUW;
9433 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Val&: LHS);
9434 AR && AR->getLoop() == L && AR->isAffine() &&
9435 !AR->getNoWrapFlags(Mask: WrapType) && AR->hasNoSelfWrap() &&
9436 isKnownPositive(S: AR->getStepRecurrence(SE&: *this))) {
9437 auto Flags = AR->getNoWrapFlags();
9438 Flags = setFlags(Flags, OnFlags: WrapType);
9439 SmallVector<SCEVUse> Operands{AR->operands()};
9440 Flags = StrengthenNoWrapFlags(SE: this, Type: scAddRecExpr, Ops: Operands, Flags);
9441 setNoWrapFlags(AddRec: const_cast<SCEVAddRecExpr *>(AR), Flags);
9442 }
9443 }
9444 }
9445
9446 switch (Pred) {
9447 case ICmpInst::ICMP_NE: { // while (X != Y)
9448 // Convert to: while (X-Y != 0)
9449 if (LHS->getType()->isPointerTy()) {
9450 LHS = getPtrToAddrExpr(Op: LHS);
9451 if (isa<SCEVCouldNotCompute>(Val: LHS))
9452 return LHS;
9453 }
9454 if (RHS->getType()->isPointerTy()) {
9455 RHS = getPtrToAddrExpr(Op: RHS);
9456 if (isa<SCEVCouldNotCompute>(Val: RHS))
9457 return RHS;
9458 }
9459 ExitLimit EL = howFarToZero(V: getMinusSCEV(LHS, RHS), L, IsSubExpr: ControlsOnlyExit,
9460 AllowPredicates);
9461 if (EL.hasAnyInfo())
9462 return EL;
9463 break;
9464 }
9465 case ICmpInst::ICMP_EQ: { // while (X == Y)
9466 // Convert to: while (X-Y == 0)
9467 if (LHS->getType()->isPointerTy()) {
9468 LHS = getPtrToAddrExpr(Op: LHS);
9469 if (isa<SCEVCouldNotCompute>(Val: LHS))
9470 return LHS;
9471 }
9472 if (RHS->getType()->isPointerTy()) {
9473 RHS = getPtrToAddrExpr(Op: RHS);
9474 if (isa<SCEVCouldNotCompute>(Val: RHS))
9475 return RHS;
9476 }
9477 ExitLimit EL = howFarToNonZero(V: getMinusSCEV(LHS, RHS), L);
9478 if (EL.hasAnyInfo()) return EL;
9479 break;
9480 }
9481 case ICmpInst::ICMP_SLE:
9482 case ICmpInst::ICMP_ULE:
9483 // Since the loop is finite, an invariant RHS cannot include the boundary
9484 // value, otherwise it would loop forever.
9485 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9486 !isLoopInvariant(S: RHS, L)) {
9487 // Otherwise, perform the addition in a wider type, to avoid overflow.
9488 // If the LHS is an addrec with the appropriate nowrap flag, the
9489 // extension will be sunk into it and the exit count can be analyzed.
9490 auto *OldType = dyn_cast<IntegerType>(Val: LHS->getType());
9491 if (!OldType)
9492 break;
9493 // Prefer doubling the bitwidth over adding a single bit to make it more
9494 // likely that we use a legal type.
9495 auto *NewType =
9496 Type::getIntNTy(C&: OldType->getContext(), N: OldType->getBitWidth() * 2);
9497 if (ICmpInst::isSigned(Pred)) {
9498 LHS = getSignExtendExpr(Op: LHS, Ty: NewType);
9499 RHS = getSignExtendExpr(Op: RHS, Ty: NewType);
9500 } else {
9501 LHS = getZeroExtendExpr(Op: LHS, Ty: NewType);
9502 RHS = getZeroExtendExpr(Op: RHS, Ty: NewType);
9503 }
9504 }
9505 RHS = getAddExpr(LHS: getOne(Ty: RHS->getType()), RHS);
9506 [[fallthrough]];
9507 case ICmpInst::ICMP_SLT:
9508 case ICmpInst::ICMP_ULT: { // while (X < Y)
9509 bool IsSigned = ICmpInst::isSigned(Pred);
9510 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, /*Invert=*/false,
9511 ControlsOnlyExit, AllowPredicates);
9512 if (EL.hasAnyInfo())
9513 return EL;
9514 break;
9515 }
9516 case ICmpInst::ICMP_SGE:
9517 case ICmpInst::ICMP_UGE:
9518 // Since the loop is finite, an invariant RHS cannot include the boundary
9519 // value, otherwise it would loop forever.
9520 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9521 !isLoopInvariant(S: RHS, L))
9522 break;
9523 RHS = getAddExpr(LHS: getMinusOne(Ty: RHS->getType()), RHS);
9524 [[fallthrough]];
9525 case ICmpInst::ICMP_SGT:
9526 case ICmpInst::ICMP_UGT: { // while (X > Y)
9527 // "X > Y" is analyzed as the equivalent "~X < ~Y".
9528 bool IsSigned = ICmpInst::isSigned(Pred);
9529 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, /*Invert=*/true,
9530 ControlsOnlyExit, AllowPredicates);
9531 if (EL.hasAnyInfo())
9532 return EL;
9533 break;
9534 }
9535 default:
9536 break;
9537 }
9538
9539 return getCouldNotCompute();
9540}
9541
9542ScalarEvolution::ExitLimit
9543ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9544 SwitchInst *Switch,
9545 BasicBlock *ExitingBlock,
9546 bool ControlsOnlyExit) {
9547 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9548
9549 // Give up if the exit is the default dest of a switch.
9550 if (Switch->getDefaultDest() == ExitingBlock)
9551 return getCouldNotCompute();
9552
9553 assert(L->contains(Switch->getDefaultDest()) &&
9554 "Default case must not exit the loop!");
9555 const SCEV *LHS = getSCEVAtScope(V: Switch->getCondition(), L);
9556 const SCEV *RHS = getConstant(V: Switch->findCaseDest(BB: ExitingBlock));
9557
9558 // while (X != Y) --> while (X-Y != 0)
9559 ExitLimit EL = howFarToZero(V: getMinusSCEV(LHS, RHS), L, IsSubExpr: ControlsOnlyExit);
9560 if (EL.hasAnyInfo())
9561 return EL;
9562
9563 return getCouldNotCompute();
9564}
9565
9566static ConstantInt *
9567EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
9568 ScalarEvolution &SE) {
9569 const SCEV *InVal = SE.getConstant(V: C);
9570 const SCEV *Val = AddRec->evaluateAtIteration(It: InVal, SE);
9571 assert(isa<SCEVConstant>(Val) &&
9572 "Evaluation of SCEV at constant didn't fold correctly?");
9573 return cast<SCEVConstant>(Val)->getValue();
9574}
9575
9576ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9577 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9578 ConstantInt *RHS = dyn_cast<ConstantInt>(Val: RHSV);
9579 if (!RHS)
9580 return getCouldNotCompute();
9581
9582 const BasicBlock *Latch = L->getLoopLatch();
9583 if (!Latch)
9584 return getCouldNotCompute();
9585
9586 const BasicBlock *Predecessor = L->getLoopPredecessor();
9587 if (!Predecessor)
9588 return getCouldNotCompute();
9589
9590 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9591 // Return LHS in OutLHS, shift_op in OutOpCode, and the shift amount in
9592 // OutShiftAmt.
9593 auto MatchPositiveShift = [](Value *V, Value *&OutLHS,
9594 Instruction::BinaryOps &OutOpCode,
9595 unsigned &OutShiftAmt) {
9596 using namespace PatternMatch;
9597
9598 ConstantInt *ShiftAmt;
9599 if (match(V, P: m_LShr(L: m_Value(V&: OutLHS), R: m_ConstantInt(CI&: ShiftAmt))))
9600 OutOpCode = Instruction::LShr;
9601 else if (match(V, P: m_AShr(L: m_Value(V&: OutLHS), R: m_ConstantInt(CI&: ShiftAmt))))
9602 OutOpCode = Instruction::AShr;
9603 else if (match(V, P: m_Shl(L: m_Value(V&: OutLHS), R: m_ConstantInt(CI&: ShiftAmt))))
9604 OutOpCode = Instruction::Shl;
9605 else
9606 return false;
9607
9608 uint64_t Amt = ShiftAmt->getValue().getLimitedValue();
9609 if (Amt == 0 || Amt >= OutLHS->getType()->getScalarSizeInBits())
9610 return false;
9611 OutShiftAmt = Amt;
9612 return true;
9613 };
9614
9615 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9616 //
9617 // loop:
9618 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9619 // %iv.shifted = lshr i32 %iv, <positive constant>
9620 //
9621 // Return true on a successful match. Return the corresponding PHI node (%iv
9622 // above) in PNOut, the opcode of the shift operation in OpCodeOut, and the
9623 // shift amount in ShiftAmtOut.
9624 auto MatchShiftRecurrence = [&](Value *V, PHINode *&PNOut,
9625 Instruction::BinaryOps &OpCodeOut,
9626 unsigned &ShiftAmtOut) {
9627 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9628
9629 {
9630 Instruction::BinaryOps OpC;
9631 Value *V;
9632 unsigned Amt;
9633
9634 // If we encounter a shift instruction, "peel off" the shift operation,
9635 // and remember that we did so. Later when we inspect %iv's backedge
9636 // value, we will make sure that the backedge value uses the same
9637 // operation.
9638 //
9639 // Note: the peeled shift operation does not have to be the same
9640 // instruction as the one feeding into the PHI's backedge value. We only
9641 // really care about it being the same *kind* of shift instruction --
9642 // that's all that is required for our later inferences to hold.
9643 if (MatchPositiveShift(LHS, V, OpC, Amt)) {
9644 PostShiftOpCode = OpC;
9645 LHS = V;
9646 }
9647 }
9648
9649 PNOut = dyn_cast<PHINode>(Val: LHS);
9650 if (!PNOut || PNOut->getParent() != L->getHeader())
9651 return false;
9652
9653 Value *BEValue = PNOut->getIncomingValueForBlock(BB: Latch);
9654 Value *OpLHS;
9655
9656 return
9657 // The backedge value for the PHI node must be a shift by a positive
9658 // amount
9659 MatchPositiveShift(BEValue, OpLHS, OpCodeOut, ShiftAmtOut) &&
9660
9661 // of the PHI node itself
9662 OpLHS == PNOut &&
9663
9664 // and the kind of shift should be match the kind of shift we peeled
9665 // off, if any.
9666 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9667 };
9668
9669 PHINode *PN;
9670 Instruction::BinaryOps OpCode;
9671 unsigned ShiftAmt;
9672 if (!MatchShiftRecurrence(LHS, PN, OpCode, ShiftAmt))
9673 return getCouldNotCompute();
9674
9675 const DataLayout &DL = getDataLayout();
9676
9677 // The key rationale for this optimization is that for some kinds of shift
9678 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9679 // within a finite number of iterations. If the condition guarding the
9680 // backedge (in the sense that the backedge is taken if the condition is true)
9681 // is false for the value the shift recurrence stabilizes to, then we know
9682 // that the backedge is taken only a finite number of times.
9683
9684 ConstantInt *StableValue = nullptr;
9685 switch (OpCode) {
9686 default:
9687 llvm_unreachable("Impossible case!");
9688
9689 case Instruction::AShr: {
9690 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9691 // bitwidth(K) iterations.
9692 Value *FirstValue = PN->getIncomingValueForBlock(BB: Predecessor);
9693 KnownBits Known = computeKnownBits(V: FirstValue, DL, AC: &AC,
9694 CtxI: Predecessor->getTerminator(), DT: &DT);
9695 auto *Ty = cast<IntegerType>(Val: RHS->getType());
9696 if (Known.isNonNegative())
9697 StableValue = ConstantInt::get(Ty, V: 0);
9698 else if (Known.isNegative())
9699 StableValue = ConstantInt::get(Ty, V: -1, IsSigned: true);
9700 else
9701 return getCouldNotCompute();
9702
9703 break;
9704 }
9705 case Instruction::LShr:
9706 case Instruction::Shl:
9707 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9708 // stabilize to 0 in at most bitwidth(K) iterations.
9709 StableValue = ConstantInt::get(Ty: cast<IntegerType>(Val: RHS->getType()), V: 0);
9710 break;
9711 }
9712
9713 auto *Result =
9714 ConstantFoldCompareInstOperands(Predicate: Pred, LHS: StableValue, RHS, DL, TLI: &TLI);
9715 assert(Result->getType()->isIntegerTy(1) &&
9716 "Otherwise cannot be an operand to a branch instruction");
9717
9718 if (Result->isNullValue()) {
9719 unsigned BitWidth = getTypeSizeInBits(Ty: RHS->getType());
9720 unsigned MaxBTC = BitWidth;
9721
9722 // For right-shift recurrences (lshr/ashr with non-negative start), we can
9723 // compute a tighter max backedge-taken count from the range of the start
9724 // value. After k shifts of ShiftAmt, value = start >> (k * ShiftAmt).
9725 // The value reaches 0 (the stable value) when k * ShiftAmt >=
9726 // activeBits(start), so max BTC = ceil(activeBits(maxStart) / ShiftAmt).
9727 if (OpCode == Instruction::LShr || OpCode == Instruction::AShr) {
9728 Value *StartValue = PN->getIncomingValueForBlock(BB: Predecessor);
9729 const SCEV *StartSCEV = getSCEV(V: StartValue);
9730 APInt MaxStart = getUnsignedRangeMax(S: StartSCEV);
9731 if (MaxStart.isStrictlyPositive()) {
9732 unsigned ActiveBits = MaxStart.getActiveBits();
9733 unsigned RangeBTC = divideCeil(Numerator: ActiveBits, Denominator: ShiftAmt);
9734 MaxBTC = std::min(a: MaxBTC, b: RangeBTC);
9735 }
9736 }
9737
9738 const SCEV *UpperBound =
9739 getConstant(Ty: getEffectiveSCEVType(Ty: RHS->getType()), V: MaxBTC);
9740 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9741 }
9742
9743 return getCouldNotCompute();
9744}
9745
9746/// Return true if we can constant fold an instruction of the specified type,
9747/// assuming that all operands were constants.
9748static bool canConstantFold(const Instruction *I,
9749 const TargetLibraryInfo *TLI) {
9750 if (isa<BinaryOperator, UnaryOperator, GEPOperator, FreezeInst, CmpInst,
9751 SelectInst, CastInst, LoadInst, ExtractElementInst, InsertElementInst,
9752 ExtractValueInst, InsertValueInst>(Val: I))
9753 return true;
9754
9755 if (const CallInst *CI = dyn_cast<CallInst>(Val: I))
9756 if (const Function *F = CI->getCalledFunction())
9757 return canConstantFoldCallTo(Call: CI, F, TLI);
9758 return false;
9759}
9760
9761/// Determine whether this instruction can constant evolve within this loop
9762/// assuming its operands can all constant evolve.
9763static bool canConstantEvolve(Instruction *I, const Loop *L,
9764 const TargetLibraryInfo *TLI) {
9765 // An instruction outside of the loop can't be derived from a loop PHI.
9766 if (!L->contains(Inst: I)) return false;
9767
9768 if (isa<PHINode>(Val: I)) {
9769 // We don't currently keep track of the control flow needed to evaluate
9770 // PHIs, so we cannot handle PHIs inside of loops.
9771 return L->getHeader() == I->getParent();
9772 }
9773
9774 // If we won't be able to constant fold this expression even if the operands
9775 // are constants, bail early.
9776 return canConstantFold(I, TLI);
9777}
9778
9779/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9780/// recursing through each instruction operand until reaching a loop header phi.
9781static PHINode *
9782getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
9783 DenseMap<Instruction *, PHINode *> &PHIMap,
9784 const TargetLibraryInfo *TLI, unsigned Depth) {
9785 if (Depth > MaxConstantEvolvingDepth)
9786 return nullptr;
9787
9788 // Otherwise, we can evaluate this instruction if all of its operands are
9789 // constant or derived from a PHI node themselves.
9790 PHINode *PHI = nullptr;
9791 for (Value *Op : UseInst->operands()) {
9792 if (isa<Constant>(Val: Op)) continue;
9793
9794 Instruction *OpInst = dyn_cast<Instruction>(Val: Op);
9795 if (!OpInst || !canConstantEvolve(I: OpInst, L, TLI))
9796 return nullptr;
9797
9798 PHINode *P = dyn_cast<PHINode>(Val: OpInst);
9799 if (!P)
9800 // If this operand is already visited, reuse the prior result.
9801 // We may have P != PHI if this is the deepest point at which the
9802 // inconsistent paths meet.
9803 P = PHIMap.lookup(Val: OpInst);
9804 if (!P) {
9805 // Recurse and memoize the results, whether a phi is found or not.
9806 // This recursive call invalidates pointers into PHIMap.
9807 P = getConstantEvolvingPHIOperands(UseInst: OpInst, L, PHIMap, TLI, Depth: Depth + 1);
9808 PHIMap[OpInst] = P;
9809 }
9810 if (!P)
9811 return nullptr; // Not evolving from PHI
9812 if (PHI && PHI != P)
9813 return nullptr; // Evolving from multiple different PHIs.
9814 PHI = P;
9815 }
9816 // This is a expression evolving from a constant PHI!
9817 return PHI;
9818}
9819
9820/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9821/// in the loop that V is derived from. We allow arbitrary operations along the
9822/// way, but the operands of an operation must either be constants or a value
9823/// derived from a constant PHI. If this expression does not fit with these
9824/// constraints, return null.
9825static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L,
9826 const TargetLibraryInfo *TLI) {
9827 Instruction *I = dyn_cast<Instruction>(Val: V);
9828 if (!I || !canConstantEvolve(I, L, TLI))
9829 return nullptr;
9830
9831 if (PHINode *PN = dyn_cast<PHINode>(Val: I))
9832 return PN;
9833
9834 // Record non-constant instructions contained by the loop.
9835 DenseMap<Instruction *, PHINode *> PHIMap;
9836 return getConstantEvolvingPHIOperands(UseInst: I, L, PHIMap, TLI, Depth: 0);
9837}
9838
9839/// EvaluateExpression - Given an expression that passes the
9840/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9841/// in the loop has the value PHIVal. If we can't fold this expression for some
9842/// reason, return null.
9843static Constant *EvaluateExpression(Value *V, const Loop *L,
9844 DenseMap<Instruction *, Constant *> &Vals,
9845 const DataLayout &DL,
9846 const TargetLibraryInfo *TLI) {
9847 // Convenient constant check, but redundant for recursive calls.
9848 if (Constant *C = dyn_cast<Constant>(Val: V)) return C;
9849 Instruction *I = dyn_cast<Instruction>(Val: V);
9850 if (!I) return nullptr;
9851
9852 if (Constant *C = Vals.lookup(Val: I)) return C;
9853
9854 // An instruction inside the loop depends on a value outside the loop that we
9855 // weren't given a mapping for, or a value such as a call inside the loop.
9856 if (!canConstantEvolve(I, L, TLI))
9857 return nullptr;
9858
9859 // An unmapped PHI can be due to a branch or another loop inside this loop,
9860 // or due to this not being the initial iteration through a loop where we
9861 // couldn't compute the evolution of this particular PHI last time.
9862 if (isa<PHINode>(Val: I)) return nullptr;
9863
9864 std::vector<Constant*> Operands(I->getNumOperands());
9865
9866 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9867 Instruction *Operand = dyn_cast<Instruction>(Val: I->getOperand(i));
9868 if (!Operand) {
9869 Operands[i] = dyn_cast<Constant>(Val: I->getOperand(i));
9870 if (!Operands[i]) return nullptr;
9871 continue;
9872 }
9873 Constant *C = EvaluateExpression(V: Operand, L, Vals, DL, TLI);
9874 Vals[Operand] = C;
9875 if (!C) return nullptr;
9876 Operands[i] = C;
9877 }
9878
9879 return ConstantFoldInstOperands(I, Ops: Operands, DL, TLI,
9880 /*AllowNonDeterministic=*/false);
9881}
9882
9883
9884// If every incoming value to PN except the one for BB is a specific Constant,
9885// return that, else return nullptr.
9886static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
9887 Constant *IncomingVal = nullptr;
9888
9889 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9890 if (PN->getIncomingBlock(i) == BB)
9891 continue;
9892
9893 auto *CurrentVal = dyn_cast<Constant>(Val: PN->getIncomingValue(i));
9894 if (!CurrentVal)
9895 return nullptr;
9896
9897 if (IncomingVal != CurrentVal) {
9898 if (IncomingVal)
9899 return nullptr;
9900 IncomingVal = CurrentVal;
9901 }
9902 }
9903
9904 return IncomingVal;
9905}
9906
9907/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9908/// in the header of its containing loop, we know the loop executes a
9909/// constant number of times, and the PHI node is just a recurrence
9910/// involving constants, fold it.
9911Constant *
9912ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9913 const APInt &BEs,
9914 const Loop *L) {
9915 auto [I, Inserted] = ConstantEvolutionLoopExitValue.try_emplace(Key: PN);
9916 if (!Inserted)
9917 return I->second;
9918
9919 if (BEs.ugt(RHS: MaxBruteForceIterations))
9920 return nullptr; // Not going to evaluate it.
9921
9922 Constant *&RetVal = I->second;
9923
9924 DenseMap<Instruction *, Constant *> CurrentIterVals;
9925 BasicBlock *Header = L->getHeader();
9926 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9927
9928 BasicBlock *Latch = L->getLoopLatch();
9929 if (!Latch)
9930 return nullptr;
9931
9932 for (PHINode &PHI : Header->phis()) {
9933 if (auto *StartCST = getOtherIncomingValue(PN: &PHI, BB: Latch))
9934 CurrentIterVals[&PHI] = StartCST;
9935 }
9936 if (!CurrentIterVals.count(Val: PN))
9937 return RetVal = nullptr;
9938
9939 Value *BEValue = PN->getIncomingValueForBlock(BB: Latch);
9940
9941 // Execute the loop symbolically to determine the exit value.
9942 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9943 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9944
9945 unsigned NumIterations = BEs.getZExtValue(); // must be in range
9946 unsigned IterationNum = 0;
9947 const DataLayout &DL = getDataLayout();
9948 for (; ; ++IterationNum) {
9949 if (IterationNum == NumIterations)
9950 return RetVal = CurrentIterVals[PN]; // Got exit value!
9951
9952 // Compute the value of the PHIs for the next iteration.
9953 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9954 DenseMap<Instruction *, Constant *> NextIterVals;
9955 Constant *NextPHI =
9956 EvaluateExpression(V: BEValue, L, Vals&: CurrentIterVals, DL, TLI: &TLI);
9957 if (!NextPHI)
9958 return nullptr; // Couldn't evaluate!
9959 NextIterVals[PN] = NextPHI;
9960
9961 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9962
9963 // Also evaluate the other PHI nodes. However, we don't get to stop if we
9964 // cease to be able to evaluate one of them or if they stop evolving,
9965 // because that doesn't necessarily prevent us from computing PN.
9966 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
9967 for (const auto &I : CurrentIterVals) {
9968 PHINode *PHI = dyn_cast<PHINode>(Val: I.first);
9969 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9970 PHIsToCompute.emplace_back(Args&: PHI, Args: I.second);
9971 }
9972 // We use two distinct loops because EvaluateExpression may invalidate any
9973 // iterators into CurrentIterVals.
9974 for (const auto &I : PHIsToCompute) {
9975 PHINode *PHI = I.first;
9976 Constant *&NextPHI = NextIterVals[PHI];
9977 if (!NextPHI) { // Not already computed.
9978 Value *BEValue = PHI->getIncomingValueForBlock(BB: Latch);
9979 NextPHI = EvaluateExpression(V: BEValue, L, Vals&: CurrentIterVals, DL, TLI: &TLI);
9980 }
9981 if (NextPHI != I.second)
9982 StoppedEvolving = false;
9983 }
9984
9985 // If all entries in CurrentIterVals == NextIterVals then we can stop
9986 // iterating, the loop can't continue to change.
9987 if (StoppedEvolving)
9988 return RetVal = CurrentIterVals[PN];
9989
9990 CurrentIterVals.swap(RHS&: NextIterVals);
9991 }
9992}
9993
9994const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9995 Value *Cond,
9996 bool ExitWhen) {
9997 PHINode *PN = getConstantEvolvingPHI(V: Cond, L, TLI: &TLI);
9998 if (!PN) return getCouldNotCompute();
9999
10000 // If the loop is canonicalized, the PHI will have exactly two entries.
10001 // That's the only form we support here.
10002 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
10003
10004 DenseMap<Instruction *, Constant *> CurrentIterVals;
10005 BasicBlock *Header = L->getHeader();
10006 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
10007
10008 BasicBlock *Latch = L->getLoopLatch();
10009 assert(Latch && "Should follow from NumIncomingValues == 2!");
10010
10011 for (PHINode &PHI : Header->phis()) {
10012 if (auto *StartCST = getOtherIncomingValue(PN: &PHI, BB: Latch))
10013 CurrentIterVals[&PHI] = StartCST;
10014 }
10015 if (!CurrentIterVals.count(Val: PN))
10016 return getCouldNotCompute();
10017
10018 // Okay, we find a PHI node that defines the trip count of this loop. Execute
10019 // the loop symbolically to determine when the condition gets a value of
10020 // "ExitWhen".
10021 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
10022 const DataLayout &DL = getDataLayout();
10023 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
10024 auto *CondVal = dyn_cast_or_null<ConstantInt>(
10025 Val: EvaluateExpression(V: Cond, L, Vals&: CurrentIterVals, DL, TLI: &TLI));
10026
10027 // Couldn't symbolically evaluate.
10028 if (!CondVal) return getCouldNotCompute();
10029
10030 if (CondVal->getValue() == uint64_t(ExitWhen)) {
10031 ++NumBruteForceTripCountsComputed;
10032 return getConstant(Ty: Type::getInt32Ty(C&: getContext()), V: IterationNum);
10033 }
10034
10035 // Update all the PHI nodes for the next iteration.
10036 DenseMap<Instruction *, Constant *> NextIterVals;
10037
10038 // Create a list of which PHIs we need to compute. We want to do this before
10039 // calling EvaluateExpression on them because that may invalidate iterators
10040 // into CurrentIterVals.
10041 SmallVector<PHINode *, 8> PHIsToCompute;
10042 for (const auto &I : CurrentIterVals) {
10043 PHINode *PHI = dyn_cast<PHINode>(Val: I.first);
10044 if (!PHI || PHI->getParent() != Header) continue;
10045 PHIsToCompute.push_back(Elt: PHI);
10046 }
10047 for (PHINode *PHI : PHIsToCompute) {
10048 Constant *&NextPHI = NextIterVals[PHI];
10049 if (NextPHI) continue; // Already computed!
10050
10051 Value *BEValue = PHI->getIncomingValueForBlock(BB: Latch);
10052 NextPHI = EvaluateExpression(V: BEValue, L, Vals&: CurrentIterVals, DL, TLI: &TLI);
10053 }
10054 CurrentIterVals.swap(RHS&: NextIterVals);
10055 }
10056
10057 // Too many iterations were needed to evaluate.
10058 return getCouldNotCompute();
10059}
10060
10061SCEVUse ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
10062 if (isa<SCEVConstant>(Val: V))
10063 return V;
10064
10065 auto &Values = ValuesAtScopes[V];
10066 // Check to see if we've folded this expression at this loop before.
10067 for (auto &LS : Values)
10068 if (LS.first == L)
10069 return LS.second ? LS.second : SCEVUse(V);
10070
10071 Values.emplace_back(Args&: L, Args: nullptr);
10072
10073 // Otherwise compute it.
10074 SCEVUse C = computeSCEVAtScope(S: V, L);
10075 for (auto &LS : reverse(C&: ValuesAtScopes[V]))
10076 if (LS.first == L) {
10077 LS.second = C;
10078 // Record the dependency under the bare expression: invalidation walks
10079 // expressions, and any use flags on C do not change which expression
10080 // this is the value at scope of.
10081 if (!isa<SCEVConstant>(Val: C))
10082 ValuesAtScopesUsers[C.getPointer()].push_back(Elt: {L, V});
10083 break;
10084 }
10085 return C;
10086}
10087
10088SCEVUse ScalarEvolution::getSCEVAtExit(const SCEV *V, const Loop *L,
10089 const BasicBlock *ExitingBlock) {
10090 SCEVUse ExitValue = getSCEVAtScope(V, L: L->getParentLoop());
10091 if (!isLoopInvariant(S: ExitValue, L)) {
10092 // If we failed to evaluate it in the outer scope, try to evaluate an
10093 // addrec for the specific exit.
10094 // TODO: Generalize this to other expressions.
10095 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
10096 if (!isa<SCEVCouldNotCompute>(Val: ExitCount))
10097 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Val: V))
10098 if (AddRec->getLoop() == L)
10099 ExitValue = AddRec->evaluateAtIteration(It: ExitCount, SE&: *this);
10100 }
10101 return ExitValue;
10102}
10103
10104/// This builds up a Constant using the ConstantExpr interface. That way, we
10105/// will return Constants for objects which aren't represented by a
10106/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
10107/// Returns NULL if the SCEV isn't representable as a Constant.
10108static Constant *BuildConstantFromSCEV(const SCEV *V) {
10109 switch (V->getSCEVType()) {
10110 case scCouldNotCompute:
10111 case scAddRecExpr:
10112 case scVScale:
10113 return nullptr;
10114 case scConstant:
10115 return cast<SCEVConstant>(Val: V)->getValue();
10116 case scUnknown:
10117 return dyn_cast<Constant>(Val: cast<SCEVUnknown>(Val: V)->getValue());
10118 case scPtrToAddr: {
10119 const SCEVPtrToAddrExpr *P2I = cast<SCEVPtrToAddrExpr>(Val: V);
10120 if (Constant *CastOp = BuildConstantFromSCEV(V: P2I->getOperand()))
10121 return ConstantExpr::getPtrToAddr(C: CastOp, Ty: P2I->getType());
10122
10123 return nullptr;
10124 }
10125 case scTruncate: {
10126 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(Val: V);
10127 if (Constant *CastOp = BuildConstantFromSCEV(V: ST->getOperand()))
10128 return ConstantExpr::getTrunc(C: CastOp, Ty: ST->getType());
10129 return nullptr;
10130 }
10131 case scAddExpr: {
10132 const SCEVAddExpr *SA = cast<SCEVAddExpr>(Val: V);
10133 Constant *C = nullptr;
10134 for (const SCEV *Op : SA->operands()) {
10135 Constant *OpC = BuildConstantFromSCEV(V: Op);
10136 if (!OpC)
10137 return nullptr;
10138 if (!C) {
10139 C = OpC;
10140 continue;
10141 }
10142 assert(!C->getType()->isPointerTy() &&
10143 "Can only have one pointer, and it must be last");
10144 if (OpC->getType()->isPointerTy()) {
10145 // The offsets have been converted to bytes. We can add bytes using
10146 // an i8 GEP.
10147 C = ConstantExpr::getPtrAdd(Ptr: OpC, Offset: C);
10148 } else {
10149 C = ConstantExpr::getAdd(C1: C, C2: OpC);
10150 }
10151 }
10152 return C;
10153 }
10154 case scMulExpr:
10155 case scSignExtend:
10156 case scZeroExtend:
10157 case scUDivExpr:
10158 case scSMaxExpr:
10159 case scUMaxExpr:
10160 case scSMinExpr:
10161 case scUMinExpr:
10162 case scSequentialUMinExpr:
10163 return nullptr;
10164 }
10165 llvm_unreachable("Unknown SCEV kind!");
10166}
10167
10168const SCEV *ScalarEvolution::getWithOperands(const SCEV *S,
10169 SmallVectorImpl<SCEVUse> &NewOps) {
10170 switch (S->getSCEVType()) {
10171 case scTruncate:
10172 case scZeroExtend:
10173 case scSignExtend:
10174 case scPtrToAddr:
10175 return getCastExpr(Kind: S->getSCEVType(), Op: NewOps[0], Ty: S->getType());
10176 case scAddRecExpr: {
10177 auto *AddRec = cast<SCEVAddRecExpr>(Val: S);
10178 return getAddRecExpr(Operands&: NewOps, L: AddRec->getLoop(), NWFlags: AddRec->getNoWrapFlags());
10179 }
10180 case scAddExpr:
10181 return getAddExpr(Ops&: NewOps, Flags: cast<SCEVAddExpr>(Val: S)->getNoWrapFlags());
10182 case scMulExpr:
10183 return getMulExpr(Ops&: NewOps, Flags: cast<SCEVMulExpr>(Val: S)->getNoWrapFlags());
10184 case scUDivExpr:
10185 return getUDivExpr(LHS: NewOps[0], RHS: NewOps[1]);
10186 case scUMaxExpr:
10187 case scSMaxExpr:
10188 case scUMinExpr:
10189 case scSMinExpr:
10190 return getMinMaxExpr(Kind: S->getSCEVType(), Ops&: NewOps);
10191 case scSequentialUMinExpr:
10192 return getSequentialMinMaxExpr(Kind: S->getSCEVType(), Ops&: NewOps);
10193 case scConstant:
10194 case scVScale:
10195 case scUnknown:
10196 return S;
10197 case scCouldNotCompute:
10198 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10199 }
10200 llvm_unreachable("Unknown SCEV kind!");
10201}
10202
10203SCEVUse ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
10204 switch (V->getSCEVType()) {
10205 case scConstant:
10206 case scVScale:
10207 return V;
10208 case scAddRecExpr: {
10209 // If this is a loop recurrence for a loop that does not contain L, then we
10210 // are dealing with the final value computed by the loop.
10211 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Val: V);
10212 // First, attempt to evaluate each operand.
10213 // Avoid performing the look-up in the common case where the specified
10214 // expression has no loop-variant portions.
10215 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
10216 SCEVUse OpAtScope = getSCEVAtScope(V: AddRec->getOperand(i), L);
10217 if (OpAtScope == AddRec->getOperand(i))
10218 continue;
10219
10220 // Okay, at least one of these operands is loop variant but might be
10221 // foldable. Build a new instance of the folded commutative expression.
10222 SmallVector<SCEVUse, 8> NewOps;
10223 NewOps.reserve(N: AddRec->getNumOperands());
10224 append_range(C&: NewOps, R: AddRec->operands().take_front(N: i));
10225 NewOps.push_back(Elt: OpAtScope);
10226 for (++i; i != e; ++i)
10227 NewOps.push_back(Elt: getSCEVAtScope(V: AddRec->getOperand(i), L));
10228
10229 const SCEV *FoldedRec = getAddRecExpr(
10230 Operands&: NewOps, L: AddRec->getLoop(), NWFlags: AddRec->getNoWrapFlags(Mask: SCEV::FlagNW));
10231 AddRec = dyn_cast<SCEVAddRecExpr>(Val: FoldedRec);
10232 // The addrec may be folded to a nonrecurrence, for example, if the
10233 // induction variable is multiplied by zero after constant folding. Go
10234 // ahead and return the folded value.
10235 if (!AddRec)
10236 return FoldedRec;
10237 break;
10238 }
10239
10240 // If the scope is outside the addrec's loop, evaluate it by using the
10241 // loop exit value of the addrec.
10242 if (!AddRec->getLoop()->contains(L)) {
10243 SCEVUse ExitValue = AddRec->getExitValue(SE&: *this);
10244 if (isa<SCEVCouldNotCompute>(Val: ExitValue))
10245 return AddRec;
10246 return ExitValue;
10247 }
10248
10249 return AddRec;
10250 }
10251 case scTruncate:
10252 case scZeroExtend:
10253 case scSignExtend:
10254 case scPtrToAddr:
10255 case scAddExpr:
10256 case scMulExpr:
10257 case scUDivExpr:
10258 case scUMaxExpr:
10259 case scSMaxExpr:
10260 case scUMinExpr:
10261 case scSMinExpr:
10262 case scSequentialUMinExpr: {
10263 ArrayRef<SCEVUse> Ops = V->operands();
10264 // Avoid performing the look-up in the common case where the specified
10265 // expression has no loop-variant portions.
10266 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
10267 SCEVUse OpAtScope = getSCEVAtScope(V: Ops[i].getPointer(), L);
10268 if (OpAtScope != Ops[i].getPointer()) {
10269 // Okay, at least one of these operands is loop variant but might be
10270 // foldable. Build a new instance of the folded commutative expression.
10271 SmallVector<SCEVUse, 8> NewOps;
10272 NewOps.reserve(N: Ops.size());
10273 append_range(C&: NewOps, R: Ops.take_front(N: i));
10274 NewOps.push_back(Elt: OpAtScope);
10275
10276 for (++i; i != e; ++i) {
10277 OpAtScope = getSCEVAtScope(V: Ops[i].getPointer(), L);
10278 NewOps.push_back(Elt: OpAtScope);
10279 }
10280
10281 return getWithOperands(S: V, NewOps);
10282 }
10283 }
10284 // If we got here, all operands are loop invariant.
10285 return V;
10286 }
10287 case scUnknown: {
10288 // If this instruction is evolved from a constant-evolving PHI, compute the
10289 // exit value from the loop without using SCEVs.
10290 const SCEVUnknown *SU = cast<SCEVUnknown>(Val: V);
10291 Instruction *I = dyn_cast<Instruction>(Val: SU->getValue());
10292 if (!I)
10293 return V; // This is some other type of SCEVUnknown, just return it.
10294
10295 if (PHINode *PN = dyn_cast<PHINode>(Val: I)) {
10296 const Loop *CurrLoop = this->LI[I->getParent()];
10297 // Looking for loop exit value.
10298 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10299 PN->getParent() == CurrLoop->getHeader()) {
10300 // Okay, there is no closed form solution for the PHI node. Check
10301 // to see if the loop that contains it has a known backedge-taken
10302 // count. If so, we may be able to force computation of the exit
10303 // value.
10304 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(L: CurrLoop);
10305 // This trivial case can show up in some degenerate cases where
10306 // the incoming IR has not yet been fully simplified.
10307 if (BackedgeTakenCount->isZero()) {
10308 Value *InitValue = nullptr;
10309 bool MultipleInitValues = false;
10310 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10311 if (!CurrLoop->contains(BB: PN->getIncomingBlock(i))) {
10312 if (!InitValue)
10313 InitValue = PN->getIncomingValue(i);
10314 else if (InitValue != PN->getIncomingValue(i)) {
10315 MultipleInitValues = true;
10316 break;
10317 }
10318 }
10319 }
10320 if (!MultipleInitValues && InitValue)
10321 return getSCEV(V: InitValue);
10322 }
10323 // Do we have a loop invariant value flowing around the backedge
10324 // for a loop which must execute the backedge?
10325 if (!isa<SCEVCouldNotCompute>(Val: BackedgeTakenCount) &&
10326 isKnownNonZero(S: BackedgeTakenCount) &&
10327 PN->getNumIncomingValues() == 2) {
10328
10329 unsigned InLoopPred =
10330 CurrLoop->contains(BB: PN->getIncomingBlock(i: 0)) ? 0 : 1;
10331 Value *BackedgeVal = PN->getIncomingValue(i: InLoopPred);
10332 if (CurrLoop->isLoopInvariant(V: BackedgeVal))
10333 return getSCEV(V: BackedgeVal);
10334 }
10335 if (auto *BTCC = dyn_cast<SCEVConstant>(Val: BackedgeTakenCount)) {
10336 // Okay, we know how many times the containing loop executes. If
10337 // this is a constant evolving PHI node, get the final value at
10338 // the specified iteration number.
10339 Constant *RV =
10340 getConstantEvolutionLoopExitValue(PN, BEs: BTCC->getAPInt(), L: CurrLoop);
10341 if (RV)
10342 return getSCEV(V: RV);
10343 }
10344 }
10345 }
10346
10347 // Okay, this is an expression that we cannot symbolically evaluate
10348 // into a SCEV. Check to see if it's possible to symbolically evaluate
10349 // the arguments into constants, and if so, try to constant propagate the
10350 // result. This is particularly useful for computing loop exit values.
10351 if (!canConstantFold(I, TLI: &TLI))
10352 return V; // This is some other type of SCEVUnknown, just return it.
10353
10354 SmallVector<Constant *, 4> Operands;
10355 Operands.reserve(N: I->getNumOperands());
10356 bool MadeImprovement = false;
10357 for (Value *Op : I->operands()) {
10358 if (Constant *C = dyn_cast<Constant>(Val: Op)) {
10359 Operands.push_back(Elt: C);
10360 continue;
10361 }
10362
10363 // If any of the operands is non-constant and if they are
10364 // non-integer and non-pointer, don't even try to analyze them
10365 // with scev techniques.
10366 if (!isSCEVable(Ty: Op->getType()))
10367 return V;
10368
10369 const SCEV *OrigV = getSCEV(V: Op);
10370 const SCEV *OpV = getSCEVAtScope(V: OrigV, L);
10371 MadeImprovement |= OrigV != OpV;
10372
10373 Constant *C = BuildConstantFromSCEV(V: OpV);
10374 if (!C)
10375 return V;
10376 assert(C->getType() == Op->getType() && "Type mismatch");
10377 Operands.push_back(Elt: C);
10378 }
10379
10380 // Check to see if getSCEVAtScope actually made an improvement.
10381 if (!MadeImprovement)
10382 return V; // This is some other type of SCEVUnknown, just return it.
10383
10384 Constant *C = nullptr;
10385 const DataLayout &DL = getDataLayout();
10386 C = ConstantFoldInstOperands(I, Ops: Operands, DL, TLI: &TLI,
10387 /*AllowNonDeterministic=*/false);
10388 if (!C)
10389 return V;
10390 return getSCEV(V: C);
10391 }
10392 case scCouldNotCompute:
10393 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10394 }
10395 llvm_unreachable("Unknown SCEV type!");
10396}
10397
10398SCEVUse ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
10399 return getSCEVAtScope(V: getSCEV(V), L);
10400}
10401
10402const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10403 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Val: S))
10404 return stripInjectiveFunctions(S: ZExt->getOperand());
10405 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Val: S))
10406 return stripInjectiveFunctions(S: SExt->getOperand());
10407 return S;
10408}
10409
10410/// Finds the minimum unsigned root of the following equation:
10411///
10412/// A * X = B (mod N)
10413///
10414/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10415/// A and B isn't important.
10416///
10417/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10418static const SCEV *
10419SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
10420 SmallVectorImpl<const SCEVPredicate *> *Predicates,
10421 ScalarEvolution &SE, const Loop *L) {
10422 uint32_t BW = A.getBitWidth();
10423 assert(BW == SE.getTypeSizeInBits(B->getType()));
10424 assert(A != 0 && "A must be non-zero.");
10425
10426 // 1. D = gcd(A, N)
10427 //
10428 // The gcd of A and N may have only one prime factor: 2. The number of
10429 // trailing zeros in A is its multiplicity
10430 uint32_t Mult2 = A.countr_zero();
10431 // D = 2^Mult2
10432
10433 // 2. Check if B is divisible by D.
10434 //
10435 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10436 // is not less than multiplicity of this prime factor for D.
10437 unsigned MinTZ = SE.getMinTrailingZeros(S: B);
10438 // Try again with the terminator of the loop predecessor for context-specific
10439 // result, if MinTZ s too small.
10440 if (MinTZ < Mult2 && L->getLoopPredecessor())
10441 MinTZ = SE.getMinTrailingZeros(S: B, CtxI: L->getLoopPredecessor()->getTerminator());
10442 if (MinTZ < Mult2) {
10443 // Check if we can prove there's no remainder using URem.
10444 const SCEV *URem =
10445 SE.getURemExpr(LHS: B, RHS: SE.getConstant(Val: APInt::getOneBitSet(numBits: BW, BitNo: Mult2)));
10446 const SCEV *Zero = SE.getZero(Ty: B->getType());
10447 if (!SE.isKnownPredicate(Pred: CmpInst::ICMP_EQ, LHS: URem, RHS: Zero)) {
10448 // Try to add a predicate ensuring B is a multiple of 1 << Mult2.
10449 if (!Predicates)
10450 return SE.getCouldNotCompute();
10451
10452 // Avoid adding a predicate that is known to be false.
10453 if (SE.isKnownPredicate(Pred: CmpInst::ICMP_NE, LHS: URem, RHS: Zero))
10454 return SE.getCouldNotCompute();
10455 Predicates->push_back(Elt: SE.getEqualPredicate(LHS: URem, RHS: Zero));
10456 }
10457 }
10458
10459 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10460 // modulo (N / D).
10461 //
10462 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10463 // (N / D) in general. The inverse itself always fits into BW bits, though,
10464 // so we immediately truncate it.
10465 APInt AD = A.lshr(shiftAmt: Mult2).trunc(width: BW - Mult2); // AD = A / D
10466 APInt I = AD.multiplicativeInverse().zext(width: BW);
10467
10468 // 4. Compute the minimum unsigned root of the equation:
10469 // I * (B / D) mod (N / D)
10470 // To simplify the computation, we factor out the divide by D:
10471 // (I * B mod N) / D
10472 const SCEV *D = SE.getConstant(Val: APInt::getOneBitSet(numBits: BW, BitNo: Mult2));
10473 return SE.getUDivExactExpr(LHS: SE.getMulExpr(LHS: B, RHS: SE.getConstant(Val: I)), RHS: D);
10474}
10475
10476/// For a given quadratic addrec, generate coefficients of the corresponding
10477/// quadratic equation, multiplied by a common value to ensure that they are
10478/// integers.
10479/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10480/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10481/// were multiplied by, and BitWidth is the bit width of the original addrec
10482/// coefficients.
10483/// This function returns std::nullopt if the addrec coefficients are not
10484/// compile- time constants.
10485static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10486GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
10487 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10488 const SCEVConstant *LC = dyn_cast<SCEVConstant>(Val: AddRec->getOperand(i: 0));
10489 const SCEVConstant *MC = dyn_cast<SCEVConstant>(Val: AddRec->getOperand(i: 1));
10490 const SCEVConstant *NC = dyn_cast<SCEVConstant>(Val: AddRec->getOperand(i: 2));
10491 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10492 << *AddRec << '\n');
10493
10494 // We currently can only solve this if the coefficients are constants.
10495 if (!LC || !MC || !NC) {
10496 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10497 return std::nullopt;
10498 }
10499
10500 APInt L = LC->getAPInt();
10501 APInt M = MC->getAPInt();
10502 APInt N = NC->getAPInt();
10503 assert(!N.isZero() && "This is not a quadratic addrec");
10504
10505 unsigned BitWidth = LC->getAPInt().getBitWidth();
10506 unsigned NewWidth = BitWidth + 1;
10507 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10508 << BitWidth << '\n');
10509 // The sign-extension (as opposed to a zero-extension) here matches the
10510 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10511 N = N.sext(width: NewWidth);
10512 M = M.sext(width: NewWidth);
10513 L = L.sext(width: NewWidth);
10514
10515 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10516 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10517 // L+M, L+2M+N, L+3M+3N, ...
10518 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10519 //
10520 // The equation Acc = 0 is then
10521 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10522 // In a quadratic form it becomes:
10523 // N n^2 + (2M-N) n + 2L = 0.
10524
10525 APInt A = N;
10526 APInt B = 2 * M - A;
10527 APInt C = 2 * L;
10528 APInt T = APInt(NewWidth, 2);
10529 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10530 << "x + " << C << ", coeff bw: " << NewWidth
10531 << ", multiplied by " << T << '\n');
10532 return std::make_tuple(args&: A, args&: B, args&: C, args&: T, args&: BitWidth);
10533}
10534
10535/// Helper function to compare optional APInts:
10536/// (a) if X and Y both exist, return min(X, Y),
10537/// (b) if neither X nor Y exist, return std::nullopt,
10538/// (c) if exactly one of X and Y exists, return that value.
10539static std::optional<APInt> MinOptional(std::optional<APInt> X,
10540 std::optional<APInt> Y) {
10541 if (X && Y) {
10542 unsigned W = std::max(a: X->getBitWidth(), b: Y->getBitWidth());
10543 APInt XW = X->sext(width: W);
10544 APInt YW = Y->sext(width: W);
10545 return XW.slt(RHS: YW) ? *X : *Y;
10546 }
10547 if (!X && !Y)
10548 return std::nullopt;
10549 return X ? *X : *Y;
10550}
10551
10552/// Helper function to truncate an optional APInt to a given BitWidth.
10553/// When solving addrec-related equations, it is preferable to return a value
10554/// that has the same bit width as the original addrec's coefficients. If the
10555/// solution fits in the original bit width, truncate it (except for i1).
10556/// Returning a value of a different bit width may inhibit some optimizations.
10557///
10558/// In general, a solution to a quadratic equation generated from an addrec
10559/// may require BW+1 bits, where BW is the bit width of the addrec's
10560/// coefficients. The reason is that the coefficients of the quadratic
10561/// equation are BW+1 bits wide (to avoid truncation when converting from
10562/// the addrec to the equation).
10563static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10564 unsigned BitWidth) {
10565 if (!X)
10566 return std::nullopt;
10567 unsigned W = X->getBitWidth();
10568 if (BitWidth > 1 && BitWidth < W && X->isIntN(N: BitWidth))
10569 return X->trunc(width: BitWidth);
10570 return X;
10571}
10572
10573/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10574/// iterations. The values L, M, N are assumed to be signed, and they
10575/// should all have the same bit widths.
10576/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10577/// where BW is the bit width of the addrec's coefficients.
10578/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10579/// returned as such, otherwise the bit width of the returned value may
10580/// be greater than BW.
10581///
10582/// This function returns std::nullopt if
10583/// (a) the addrec coefficients are not constant, or
10584/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10585/// like x^2 = 5, no integer solutions exist, in other cases an integer
10586/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10587static std::optional<APInt>
10588SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
10589 APInt A, B, C, M;
10590 unsigned BitWidth;
10591 auto T = GetQuadraticEquation(AddRec);
10592 if (!T)
10593 return std::nullopt;
10594
10595 std::tie(args&: A, args&: B, args&: C, args&: M, args&: BitWidth) = *T;
10596 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10597 std::optional<APInt> X =
10598 APIntOps::SolveQuadraticEquationWrap(A, B, C, RangeWidth: BitWidth + 1);
10599 if (!X)
10600 return std::nullopt;
10601
10602 ConstantInt *CX = ConstantInt::get(Context&: SE.getContext(), V: *X);
10603 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, C: CX, SE);
10604 if (!V->isZero())
10605 return std::nullopt;
10606
10607 return TruncIfPossible(X, BitWidth);
10608}
10609
10610/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10611/// iterations. The values M, N are assumed to be signed, and they
10612/// should all have the same bit widths.
10613/// Find the least n such that c(n) does not belong to the given range,
10614/// while c(n-1) does.
10615///
10616/// This function returns std::nullopt if
10617/// (a) the addrec coefficients are not constant, or
10618/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10619/// bounds of the range.
10620static std::optional<APInt>
10621SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
10622 const ConstantRange &Range, ScalarEvolution &SE) {
10623 assert(AddRec->getOperand(0)->isZero() &&
10624 "Starting value of addrec should be 0");
10625 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10626 << Range << ", addrec " << *AddRec << '\n');
10627 // This case is handled in getNumIterationsInRange. Here we can assume that
10628 // we start in the range.
10629 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10630 "Addrec's initial value should be in range");
10631
10632 APInt A, B, C, M;
10633 unsigned BitWidth;
10634 auto T = GetQuadraticEquation(AddRec);
10635 if (!T)
10636 return std::nullopt;
10637
10638 // Be careful about the return value: there can be two reasons for not
10639 // returning an actual number. First, if no solutions to the equations
10640 // were found, and second, if the solutions don't leave the given range.
10641 // The first case means that the actual solution is "unknown", the second
10642 // means that it's known, but not valid. If the solution is unknown, we
10643 // cannot make any conclusions.
10644 // Return a pair: the optional solution and a flag indicating if the
10645 // solution was found.
10646 auto SolveForBoundary =
10647 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10648 // Solve for signed overflow and unsigned overflow, pick the lower
10649 // solution.
10650 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10651 << Bound << " (before multiplying by " << M << ")\n");
10652 Bound *= M; // The quadratic equation multiplier.
10653
10654 std::optional<APInt> SO;
10655 if (BitWidth > 1) {
10656 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10657 "signed overflow\n");
10658 SO = APIntOps::SolveQuadraticEquationWrap(A, B, C: -Bound, RangeWidth: BitWidth);
10659 }
10660 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10661 "unsigned overflow\n");
10662 std::optional<APInt> UO =
10663 APIntOps::SolveQuadraticEquationWrap(A, B, C: -Bound, RangeWidth: BitWidth + 1);
10664
10665 auto LeavesRange = [&] (const APInt &X) {
10666 ConstantInt *C0 = ConstantInt::get(Context&: SE.getContext(), V: X);
10667 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C: C0, SE);
10668 if (Range.contains(Val: V0->getValue()))
10669 return false;
10670 // X should be at least 1, so X-1 is non-negative.
10671 ConstantInt *C1 = ConstantInt::get(Context&: SE.getContext(), V: X-1);
10672 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C: C1, SE);
10673 if (Range.contains(Val: V1->getValue()))
10674 return true;
10675 return false;
10676 };
10677
10678 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10679 // can be a solution, but the function failed to find it. We cannot treat it
10680 // as "no solution".
10681 if (!SO || !UO)
10682 return {std::nullopt, false};
10683
10684 // Check the smaller value first to see if it leaves the range.
10685 // At this point, both SO and UO must have values.
10686 std::optional<APInt> Min = MinOptional(X: SO, Y: UO);
10687 if (LeavesRange(*Min))
10688 return { Min, true };
10689 std::optional<APInt> Max = Min == SO ? UO : SO;
10690 if (LeavesRange(*Max))
10691 return { Max, true };
10692
10693 // Solutions were found, but were eliminated, hence the "true".
10694 return {std::nullopt, true};
10695 };
10696
10697 std::tie(args&: A, args&: B, args&: C, args&: M, args&: BitWidth) = *T;
10698 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10699 APInt Lower = Range.getLower().sext(width: A.getBitWidth()) - 1;
10700 APInt Upper = Range.getUpper().sext(width: A.getBitWidth());
10701 auto SL = SolveForBoundary(Lower);
10702 auto SU = SolveForBoundary(Upper);
10703 // If any of the solutions was unknown, no meaninigful conclusions can
10704 // be made.
10705 if (!SL.second || !SU.second)
10706 return std::nullopt;
10707
10708 // Claim: The correct solution is not some value between Min and Max.
10709 //
10710 // Justification: Assuming that Min and Max are different values, one of
10711 // them is when the first signed overflow happens, the other is when the
10712 // first unsigned overflow happens. Crossing the range boundary is only
10713 // possible via an overflow (treating 0 as a special case of it, modeling
10714 // an overflow as crossing k*2^W for some k).
10715 //
10716 // The interesting case here is when Min was eliminated as an invalid
10717 // solution, but Max was not. The argument is that if there was another
10718 // overflow between Min and Max, it would also have been eliminated if
10719 // it was considered.
10720 //
10721 // For a given boundary, it is possible to have two overflows of the same
10722 // type (signed/unsigned) without having the other type in between: this
10723 // can happen when the vertex of the parabola is between the iterations
10724 // corresponding to the overflows. This is only possible when the two
10725 // overflows cross k*2^W for the same k. In such case, if the second one
10726 // left the range (and was the first one to do so), the first overflow
10727 // would have to enter the range, which would mean that either we had left
10728 // the range before or that we started outside of it. Both of these cases
10729 // are contradictions.
10730 //
10731 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10732 // solution is not some value between the Max for this boundary and the
10733 // Min of the other boundary.
10734 //
10735 // Justification: Assume that we had such Max_A and Min_B corresponding
10736 // to range boundaries A and B and such that Max_A < Min_B. If there was
10737 // a solution between Max_A and Min_B, it would have to be caused by an
10738 // overflow corresponding to either A or B. It cannot correspond to B,
10739 // since Min_B is the first occurrence of such an overflow. If it
10740 // corresponded to A, it would have to be either a signed or an unsigned
10741 // overflow that is larger than both eliminated overflows for A. But
10742 // between the eliminated overflows and this overflow, the values would
10743 // cover the entire value space, thus crossing the other boundary, which
10744 // is a contradiction.
10745
10746 return TruncIfPossible(X: MinOptional(X: SL.first, Y: SU.first), BitWidth);
10747}
10748
10749ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10750 const Loop *L,
10751 bool ControlsOnlyExit,
10752 bool AllowPredicates) {
10753
10754 // This is only used for loops with a "x != y" exit test. The exit condition
10755 // is now expressed as a single expression, V = x-y. So the exit test is
10756 // effectively V != 0. We know and take advantage of the fact that this
10757 // expression only being used in a comparison by zero context.
10758
10759 SmallVector<const SCEVPredicate *> Predicates;
10760 // If the value is a constant
10761 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Val: V)) {
10762 // If the value is already zero, the branch will execute zero times.
10763 if (C->getValue()->isZero()) return C;
10764 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10765 }
10766
10767 const SCEVAddRecExpr *AddRec =
10768 dyn_cast<SCEVAddRecExpr>(Val: stripInjectiveFunctions(S: V));
10769
10770 if (!AddRec && AllowPredicates)
10771 // Try to make this an AddRec using runtime tests, in the first X
10772 // iterations of this loop, where X is the SCEV expression found by the
10773 // algorithm below.
10774 AddRec = convertSCEVToAddRecWithPredicates(S: V, L, Preds&: Predicates);
10775
10776 if (!AddRec || AddRec->getLoop() != L)
10777 return getCouldNotCompute();
10778
10779 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10780 // the quadratic equation to solve it.
10781 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10782 // We can only use this value if the chrec ends up with an exact zero
10783 // value at this index. When solving for "X*X != 5", for example, we
10784 // should not accept a root of 2.
10785 if (auto S = SolveQuadraticAddRecExact(AddRec, SE&: *this)) {
10786 const auto *R = cast<SCEVConstant>(Val: getConstant(Val: *S));
10787 return ExitLimit(R, R, R, false, Predicates);
10788 }
10789 return getCouldNotCompute();
10790 }
10791
10792 // Otherwise we can only handle this if it is affine.
10793 if (!AddRec->isAffine())
10794 return getCouldNotCompute();
10795
10796 // If this is an affine expression, the execution count of this branch is
10797 // the minimum unsigned root of the following equation:
10798 //
10799 // Start + Step*N = 0 (mod 2^BW)
10800 //
10801 // equivalent to:
10802 //
10803 // Step*N = -Start (mod 2^BW)
10804 //
10805 // where BW is the common bit width of Start and Step.
10806
10807 // Get the initial value for the loop.
10808 const SCEV *Start = getSCEVAtScope(V: AddRec->getStart(), L: L->getParentLoop());
10809 const SCEV *Step = getSCEVAtScope(V: AddRec->getOperand(i: 1), L: L->getParentLoop());
10810
10811 if (!isLoopInvariant(S: Step, L))
10812 return getCouldNotCompute();
10813
10814 LoopGuards Guards = LoopGuards::collectOnDemand(L, SE&: *this);
10815 // Specialize step for this loop so we get context sensitive facts below.
10816 const SCEV *StepWLG = applyLoopGuards(Expr: Step, Guards);
10817
10818 // For positive steps (counting up until unsigned overflow):
10819 // N = -Start/Step (as unsigned)
10820 // For negative steps (counting down to zero):
10821 // N = Start/-Step
10822 // First compute the unsigned distance from zero in the direction of Step.
10823 bool CountDown = isKnownNegative(S: StepWLG);
10824 if (!CountDown && !isKnownNonNegative(S: StepWLG))
10825 return getCouldNotCompute();
10826
10827 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(V: Start);
10828 // Handle unitary steps, which cannot wraparound.
10829 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10830 // N = Distance (as unsigned)
10831
10832 if (match(S: Step, P: m_CombineOr(Ps: m_scev_One(), Ps: m_scev_AllOnes()))) {
10833 APInt MaxBECount = getUnsignedRangeMax(S: applyLoopGuards(Expr: Distance, Guards));
10834 MaxBECount = APIntOps::umin(A: MaxBECount, B: getUnsignedRangeMax(S: Distance));
10835
10836 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10837 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10838 // case, and see if we can improve the bound.
10839 //
10840 // Explicitly handling this here is necessary because getUnsignedRange
10841 // isn't context-sensitive; it doesn't know that we only care about the
10842 // range inside the loop.
10843 const SCEV *Zero = getZero(Ty: Distance->getType());
10844 const SCEV *One = getOne(Ty: Distance->getType());
10845 const SCEV *DistancePlusOne = getAddExpr(LHS: Distance, RHS: One);
10846 if (isLoopEntryGuardedByCond(L, Pred: ICmpInst::ICMP_NE, LHS: DistancePlusOne, RHS: Zero)) {
10847 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10848 // as "unsigned_max(Distance + 1) - 1". Also apply the loop guards to
10849 // Distance + 1; the range of Distance itself may be a wrapped set even
10850 // when the guards bound Distance + 1 tightly.
10851 APInt Max = APIntOps::umin(
10852 A: getUnsignedRangeMax(S: applyLoopGuards(Expr: DistancePlusOne, Guards)),
10853 B: getUnsignedRangeMax(S: DistancePlusOne));
10854 MaxBECount = APIntOps::umin(A: MaxBECount, B: Max - 1);
10855 }
10856 return ExitLimit(Distance, getConstant(Val: MaxBECount), Distance, false,
10857 Predicates);
10858 }
10859
10860 // If the condition controls loop exit (the loop exits only if the expression
10861 // is true) and the addition is no-wrap we can use unsigned divide to
10862 // compute the backedge count. In this case, the step may not divide the
10863 // distance, but we don't care because if the condition is "missed" the loop
10864 // will have undefined behavior due to wrapping.
10865 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10866 loopHasNoAbnormalExits(L: AddRec->getLoop())) {
10867
10868 // If the stride is zero and the start is non-zero, the loop must be
10869 // infinite. In C++, most loops are finite by assumption, in which case the
10870 // step being zero implies UB must execute if the loop is entered.
10871 if (!(loopIsFiniteByAssumption(L) && isKnownNonZero(S: Start)) &&
10872 !isKnownNonZero(S: StepWLG))
10873 return getCouldNotCompute();
10874
10875 const SCEV *Exact =
10876 getUDivExpr(LHS: Distance, RHS: CountDown ? getNegativeSCEV(V: Step) : Step);
10877 const SCEV *ConstantMax = getCouldNotCompute();
10878 if (Exact != getCouldNotCompute()) {
10879 APInt MaxInt = getUnsignedRangeMax(S: applyLoopGuards(Expr: Exact, Guards));
10880 ConstantMax =
10881 getConstant(Val: APIntOps::umin(A: MaxInt, B: getUnsignedRangeMax(S: Exact)));
10882 }
10883 const SCEV *SymbolicMax =
10884 isa<SCEVCouldNotCompute>(Val: Exact) ? ConstantMax : Exact;
10885 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10886 }
10887
10888 // Solve the general equation.
10889 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Val: Step);
10890 if (!StepC || StepC->getValue()->isZero())
10891 return getCouldNotCompute();
10892 const SCEV *E = SolveLinEquationWithOverflow(
10893 A: StepC->getAPInt(), B: getNegativeSCEV(V: Start),
10894 Predicates: AllowPredicates ? &Predicates : nullptr, SE&: *this, L);
10895
10896 const SCEV *M = E;
10897 if (E != getCouldNotCompute()) {
10898 APInt MaxWithGuards = getUnsignedRangeMax(S: applyLoopGuards(Expr: E, Guards));
10899 M = getConstant(Val: APIntOps::umin(A: MaxWithGuards, B: getUnsignedRangeMax(S: E)));
10900 }
10901 auto *S = isa<SCEVCouldNotCompute>(Val: E) ? M : E;
10902 return ExitLimit(E, M, S, false, Predicates);
10903}
10904
10905ScalarEvolution::ExitLimit
10906ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10907 // Loops that look like: while (X == 0) are very strange indeed. We don't
10908 // handle them yet except for the trivial case. This could be expanded in the
10909 // future as needed.
10910
10911 // If the value is a constant, check to see if it is known to be non-zero
10912 // already. If so, the backedge will execute zero times.
10913 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Val: V)) {
10914 if (!C->getValue()->isZero())
10915 return getZero(Ty: C->getType());
10916 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10917 }
10918
10919 // We could implement others, but I really doubt anyone writes loops like
10920 // this, and if they did, they would already be constant folded.
10921 return getCouldNotCompute();
10922}
10923
10924std::pair<const BasicBlock *, const BasicBlock *>
10925ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10926 const {
10927 // If the block has a unique predecessor, then there is no path from the
10928 // predecessor to the block that does not go through the direct edge
10929 // from the predecessor to the block.
10930 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10931 return {Pred, BB};
10932
10933 // A loop's header is defined to be a block that dominates the loop.
10934 // If the header has a unique predecessor outside the loop, it must be
10935 // a block that has exactly one successor that can reach the loop.
10936 if (const Loop *L = LI.getLoopFor(BB))
10937 return {L->getLoopPredecessor(), L->getHeader()};
10938
10939 return {nullptr, BB};
10940}
10941
10942/// SCEV structural equivalence is usually sufficient for testing whether two
10943/// expressions are equal, however for the purposes of looking for a condition
10944/// guarding a loop, it can be useful to be a little more general, since a
10945/// front-end may have replicated the controlling expression.
10946static bool HasSameValue(const SCEV *A, const SCEV *B) {
10947 // Quick check to see if they are the same SCEV.
10948 if (A == B) return true;
10949
10950 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10951 // Not all instructions that are "identical" compute the same value. For
10952 // instance, two distinct alloca instructions allocating the same type are
10953 // identical and do not read memory; but compute distinct values.
10954 return A->isIdenticalTo(I: B) && (isa<BinaryOperator>(Val: A) || isa<GetElementPtrInst>(Val: A));
10955 };
10956
10957 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10958 // two different instructions with the same value. Check for this case.
10959 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(Val: A))
10960 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(Val: B))
10961 if (const Instruction *AI = dyn_cast<Instruction>(Val: AU->getValue()))
10962 if (const Instruction *BI = dyn_cast<Instruction>(Val: BU->getValue()))
10963 if (ComputesEqualValues(AI, BI))
10964 return true;
10965
10966 // Otherwise assume they may have a different value.
10967 return false;
10968}
10969
10970static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS) {
10971 const SCEV *Op0, *Op1;
10972 if (!match(S, P: m_scev_Add(Op0: m_SCEV(V&: Op0), Op1: m_SCEV(V&: Op1))))
10973 return false;
10974 if (match(S: Op0, P: m_scev_Mul(Op0: m_scev_AllOnes(), Op1: m_SCEV(V&: RHS)))) {
10975 LHS = Op1;
10976 return true;
10977 }
10978 if (match(S: Op1, P: m_scev_Mul(Op0: m_scev_AllOnes(), Op1: m_SCEV(V&: RHS)))) {
10979 LHS = Op0;
10980 return true;
10981 }
10982 return false;
10983}
10984
10985bool ScalarEvolution::SimplifyICmpOperands(CmpPredicate &Pred, SCEVUse &LHS,
10986 SCEVUse &RHS, unsigned Depth) {
10987 bool Changed = false;
10988 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10989 // '0 != 0'.
10990 auto TrivialCase = [&](bool TriviallyTrue) {
10991 LHS = RHS = getConstant(V: ConstantInt::getFalse(Context&: getContext()));
10992 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10993 return true;
10994 };
10995 // If we hit the max recursion limit bail out.
10996 if (Depth >= 3)
10997 return false;
10998
10999 const SCEV *NewLHS, *NewRHS;
11000 if (match(U: LHS, P: m_scev_c_Mul(Op0: m_SCEV(V&: NewLHS), Op1: m_SCEVVScale())) &&
11001 match(U: RHS, P: m_scev_c_Mul(Op0: m_SCEV(V&: NewRHS), Op1: m_SCEVVScale()))) {
11002 const SCEVMulExpr *LMul = cast<SCEVMulExpr>(Val&: LHS);
11003 const SCEVMulExpr *RMul = cast<SCEVMulExpr>(Val&: RHS);
11004
11005 // (X * vscale) pred (Y * vscale) ==> X pred Y
11006 // when both multiples are NSW.
11007 // (X * vscale) uicmp/eq/ne (Y * vscale) ==> X uicmp/eq/ne Y
11008 // when both multiples are NUW.
11009 if ((LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap()) ||
11010 (LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap() &&
11011 !ICmpInst::isSigned(Pred))) {
11012 LHS = NewLHS;
11013 RHS = NewRHS;
11014 Changed = true;
11015 }
11016 }
11017
11018 // Canonicalize a constant to the right side.
11019 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Val&: LHS)) {
11020 // Check for both operands constant.
11021 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Val&: RHS)) {
11022 if (!ICmpInst::compare(LHS: LHSC->getAPInt(), RHS: RHSC->getAPInt(), Pred))
11023 return TrivialCase(false);
11024 return TrivialCase(true);
11025 }
11026 // Otherwise swap the operands to put the constant on the right.
11027 std::swap(a&: LHS, b&: RHS);
11028 Pred = ICmpInst::getSwappedCmpPredicate(Pred);
11029 Changed = true;
11030 }
11031
11032 // (K + A) pred (K + B) --> A pred B
11033 // For equality, no flags are needed.
11034 // For signed, both adds must be NSW. For unsigned, both must be NUW.
11035 {
11036 const SCEVConstant *C = nullptr;
11037 if (match(U: LHS, P: m_scev_Add(Op0: m_SCEVConstant(V&: C), Op1: m_SCEV(V&: NewLHS))) &&
11038 match(U: RHS, P: m_scev_Add(Op0: m_scev_Specific(S: C), Op1: m_SCEV(V&: NewRHS)))) {
11039 const auto *LAdd = cast<SCEVAddExpr>(Val&: LHS);
11040 const auto *RAdd = cast<SCEVAddExpr>(Val&: RHS);
11041 if (ICmpInst::isEquality(P: Pred) ||
11042 (ICmpInst::isSigned(Pred) && LAdd->hasNoSignedWrap() &&
11043 RAdd->hasNoSignedWrap()) ||
11044 (ICmpInst::isUnsigned(Pred) && LAdd->hasNoUnsignedWrap() &&
11045 RAdd->hasNoUnsignedWrap())) {
11046 LHS = NewLHS;
11047 RHS = NewRHS;
11048 Changed = true;
11049 }
11050 }
11051 }
11052
11053 // (C * A) pred (C * B) --> A pred B
11054 // For equality predicates, both muls must be NUW or both must be NSW
11055 // (either suffices to make multiplication by C injective; C == 0 is
11056 // impossible because SCEV folds 0 * X to 0).
11057 // For signed ordering, C must be positive and both muls must be NSW.
11058 // For unsigned ordering, both muls must be NUW.
11059 {
11060 const SCEVConstant *C = nullptr;
11061 if (match(U: LHS, P: m_scev_Mul(Op0: m_SCEVConstant(V&: C), Op1: m_SCEV(V&: NewLHS))) &&
11062 match(U: RHS, P: m_scev_Mul(Op0: m_scev_Specific(S: C), Op1: m_SCEV(V&: NewRHS)))) {
11063 const auto *LMul = cast<SCEVMulExpr>(Val&: LHS);
11064 const auto *RMul = cast<SCEVMulExpr>(Val&: RHS);
11065 bool BothNUW = LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap();
11066 bool BothNSW = LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap();
11067 if ((ICmpInst::isEquality(P: Pred) && (BothNUW || BothNSW)) ||
11068 (ICmpInst::isSigned(Pred) && BothNSW &&
11069 C->getAPInt().isStrictlyPositive()) ||
11070 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
11071 LHS = NewLHS;
11072 RHS = NewRHS;
11073 Changed = true;
11074 }
11075 }
11076 }
11077
11078 // If we're comparing an addrec with a value which is loop-invariant in the
11079 // addrec's loop, put the addrec on the left. Also make a dominance check,
11080 // as both operands could be addrecs loop-invariant in each other's loop.
11081 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Val&: RHS)) {
11082 const Loop *L = AR->getLoop();
11083 if (isLoopInvariant(S: LHS, L) && properlyDominates(S: LHS, BB: L->getHeader())) {
11084 std::swap(a&: LHS, b&: RHS);
11085 Pred = ICmpInst::getSwappedCmpPredicate(Pred);
11086 Changed = true;
11087 }
11088 }
11089
11090 // If there's a constant operand, canonicalize comparisons with boundary
11091 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
11092 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(Val&: RHS)) {
11093 const APInt &RA = RC->getAPInt();
11094
11095 bool SimplifiedByConstantRange = false;
11096
11097 if (!ICmpInst::isEquality(P: Pred)) {
11098 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, Other: RA);
11099 if (ExactCR.isFullSet())
11100 return TrivialCase(true);
11101 if (ExactCR.isEmptySet())
11102 return TrivialCase(false);
11103
11104 APInt NewRHS;
11105 CmpInst::Predicate NewPred;
11106 if (ExactCR.getEquivalentICmp(Pred&: NewPred, RHS&: NewRHS) &&
11107 ICmpInst::isEquality(P: NewPred)) {
11108 // We were able to convert an inequality to an equality.
11109 Pred = NewPred;
11110 RHS = getConstant(Val: NewRHS);
11111 Changed = SimplifiedByConstantRange = true;
11112 }
11113 }
11114
11115 if (!SimplifiedByConstantRange) {
11116 switch (Pred) {
11117 default:
11118 break;
11119 case ICmpInst::ICMP_EQ:
11120 case ICmpInst::ICMP_NE:
11121 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
11122 if (RA.isZero() && MatchBinarySub(S: LHS, LHS, RHS))
11123 Changed = true;
11124 break;
11125
11126 // The "Should have been caught earlier!" messages refer to the fact
11127 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
11128 // should have fired on the corresponding cases, and canonicalized the
11129 // check to trivial case.
11130
11131 case ICmpInst::ICMP_UGE:
11132 assert(!RA.isMinValue() && "Should have been caught earlier!");
11133 Pred = ICmpInst::ICMP_UGT;
11134 RHS = getConstant(Val: RA - 1);
11135 Changed = true;
11136 break;
11137 case ICmpInst::ICMP_ULE:
11138 assert(!RA.isMaxValue() && "Should have been caught earlier!");
11139 Pred = ICmpInst::ICMP_ULT;
11140 RHS = getConstant(Val: RA + 1);
11141 Changed = true;
11142 break;
11143 case ICmpInst::ICMP_SGE:
11144 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
11145 Pred = ICmpInst::ICMP_SGT;
11146 RHS = getConstant(Val: RA - 1);
11147 Changed = true;
11148 break;
11149 case ICmpInst::ICMP_SLE:
11150 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
11151 Pred = ICmpInst::ICMP_SLT;
11152 RHS = getConstant(Val: RA + 1);
11153 Changed = true;
11154 break;
11155 }
11156 }
11157 }
11158
11159 // a /u b == 0 => a < b
11160 // a /u b != 0 => a >= b
11161 if (ICmpInst::isEquality(P: Pred) && RHS->isZero() &&
11162 match(U: LHS, P: m_scev_UDiv(Op0: m_SCEV(V&: LHS), Op1: m_SCEV(V&: RHS)))) {
11163 Pred = Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
11164 Changed = true;
11165 }
11166
11167 // Check for obvious equality.
11168 if (HasSameValue(A: LHS, B: RHS)) {
11169 if (ICmpInst::isTrueWhenEqual(predicate: Pred))
11170 return TrivialCase(true);
11171 if (ICmpInst::isFalseWhenEqual(predicate: Pred))
11172 return TrivialCase(false);
11173 }
11174
11175 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
11176 // adding or subtracting 1 from one of the operands.
11177 switch (Pred) {
11178 case ICmpInst::ICMP_SLE:
11179 if (!getSignedRangeMax(S: RHS).isMaxSignedValue()) {
11180 RHS = getAddExpr(LHS: getConstant(Ty: RHS->getType(), V: 1, isSigned: true), RHS,
11181 Flags: SCEV::FlagNSW);
11182 Pred = ICmpInst::ICMP_SLT;
11183 Changed = true;
11184 } else if (!getSignedRangeMin(S: LHS).isMinSignedValue()) {
11185 LHS = getAddExpr(LHS: getConstant(Ty: RHS->getType(), V: (uint64_t)-1, isSigned: true), RHS: LHS,
11186 Flags: SCEV::FlagNSW);
11187 Pred = ICmpInst::ICMP_SLT;
11188 Changed = true;
11189 }
11190 break;
11191 case ICmpInst::ICMP_SGE:
11192 if (!getSignedRangeMin(S: RHS).isMinSignedValue()) {
11193 RHS = getAddExpr(LHS: getConstant(Ty: RHS->getType(), V: (uint64_t)-1, isSigned: true), RHS,
11194 Flags: SCEV::FlagNSW);
11195 Pred = ICmpInst::ICMP_SGT;
11196 Changed = true;
11197 } else if (!getSignedRangeMax(S: LHS).isMaxSignedValue()) {
11198 LHS = getAddExpr(LHS: getConstant(Ty: RHS->getType(), V: 1, isSigned: true), RHS: LHS,
11199 Flags: SCEV::FlagNSW);
11200 Pred = ICmpInst::ICMP_SGT;
11201 Changed = true;
11202 }
11203 break;
11204 case ICmpInst::ICMP_ULE:
11205 if (!getUnsignedRangeMax(S: RHS).isMaxValue()) {
11206 RHS = getAddExpr(LHS: getConstant(Ty: RHS->getType(), V: 1, isSigned: true), RHS,
11207 Flags: SCEV::FlagNUW);
11208 Pred = ICmpInst::ICMP_ULT;
11209 Changed = true;
11210 } else if (!getUnsignedRangeMin(S: LHS).isMinValue()) {
11211 LHS = getAddExpr(LHS: getConstant(Ty: RHS->getType(), V: (uint64_t)-1, isSigned: true), RHS: LHS);
11212 Pred = ICmpInst::ICMP_ULT;
11213 Changed = true;
11214 }
11215 break;
11216 case ICmpInst::ICMP_UGE:
11217 // If RHS is an op we can fold the -1, try that first.
11218 // Otherwise prefer LHS to preserve the nuw flag.
11219 if ((isa<SCEVConstant>(Val: RHS) ||
11220 (isa<SCEVAddExpr, SCEVAddRecExpr>(Val: RHS) &&
11221 isa<SCEVConstant>(Val: cast<SCEVNAryExpr>(Val&: RHS)->getOperand(i: 0)))) &&
11222 !getUnsignedRangeMin(S: RHS).isMinValue()) {
11223 RHS = getAddExpr(LHS: getConstant(Ty: RHS->getType(), V: (uint64_t)-1, isSigned: true), RHS);
11224 Pred = ICmpInst::ICMP_UGT;
11225 Changed = true;
11226 } else if (!getUnsignedRangeMax(S: LHS).isMaxValue()) {
11227 LHS = getAddExpr(LHS: getConstant(Ty: RHS->getType(), V: 1, isSigned: true), RHS: LHS,
11228 Flags: SCEV::FlagNUW);
11229 Pred = ICmpInst::ICMP_UGT;
11230 Changed = true;
11231 } else if (!getUnsignedRangeMin(S: RHS).isMinValue()) {
11232 RHS = getAddExpr(LHS: getConstant(Ty: RHS->getType(), V: (uint64_t)-1, isSigned: true), RHS);
11233 Pred = ICmpInst::ICMP_UGT;
11234 Changed = true;
11235 }
11236 break;
11237 default:
11238 break;
11239 }
11240
11241 // TODO: More simplifications are possible here.
11242
11243 // Recursively simplify until we either hit a recursion limit or nothing
11244 // changes.
11245 if (Changed)
11246 (void)SimplifyICmpOperands(Pred, LHS, RHS, Depth: Depth + 1);
11247
11248 return Changed;
11249}
11250
11251bool ScalarEvolution::isKnownNegative(const SCEV *S) {
11252 return getSignedRangeMax(S).isNegative();
11253}
11254
11255bool ScalarEvolution::isKnownPositive(const SCEV *S) {
11256 return getSignedRangeMin(S).isStrictlyPositive();
11257}
11258
11259bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
11260 return !getSignedRangeMin(S).isNegative();
11261}
11262
11263bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
11264 return !getSignedRangeMax(S).isStrictlyPositive();
11265}
11266
11267bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
11268 // Query push down for cases where the unsigned range is
11269 // less than sufficient.
11270 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(Val: S))
11271 return isKnownNonZero(S: SExt->getOperand(i: 0));
11272 return getUnsignedRangeMin(S) != 0;
11273}
11274
11275bool ScalarEvolution::isKnownToBeAPowerOfTwo(const SCEV *S, bool OrZero,
11276 bool OrNegative) {
11277 auto NonRecursive = [OrNegative](const SCEV *S) {
11278 if (auto *C = dyn_cast<SCEVConstant>(Val: S))
11279 return C->getAPInt().isPowerOf2() ||
11280 (OrNegative && C->getAPInt().isNegatedPowerOf2());
11281
11282 // vscale is a power-of-two.
11283 return isa<SCEVVScale>(Val: S);
11284 };
11285
11286 if (NonRecursive(S))
11287 return true;
11288
11289 auto *Mul = dyn_cast<SCEVMulExpr>(Val: S);
11290 if (!Mul)
11291 return false;
11292 return all_of(Range: Mul->operands(), P: NonRecursive) && (OrZero || isKnownNonZero(S));
11293}
11294
11295bool ScalarEvolution::isKnownMultipleOf(
11296 const SCEV *S, uint64_t M,
11297 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
11298 if (M == 0)
11299 return false;
11300 if (M == 1)
11301 return true;
11302
11303 // For a constant, check that "S % M == 0".
11304 if (auto *Cst = dyn_cast<SCEVConstant>(Val: S)) {
11305 APInt C = Cst->getAPInt();
11306 return C.urem(RHS: M) == 0;
11307 }
11308
11309 // Basic tests have failed.
11310 // Check "S % M == 0" at compile time and record runtime Assumptions.
11311 auto *STy = dyn_cast<IntegerType>(Val: S->getType());
11312 const SCEV *SmodM =
11313 getURemExpr(LHS: S, RHS: getConstant(V: ConstantInt::get(Ty: STy, V: M, IsSigned: false)));
11314 const SCEV *Zero = getZero(Ty: STy);
11315
11316 // Check whether "S % M == 0" is known at compile time.
11317 if (isKnownPredicate(Pred: ICmpInst::ICMP_EQ, LHS: SmodM, RHS: Zero))
11318 return true;
11319
11320 // Check whether "S % M != 0" is known at compile time.
11321 if (isKnownPredicate(Pred: ICmpInst::ICMP_NE, LHS: SmodM, RHS: Zero))
11322 return false;
11323
11324 if (!Predicates)
11325 return false;
11326
11327 // Look through Add and AddRec expressions with nuw to improve the
11328 // precision of added predicates. S is a multiple of M if S starts with a
11329 // multiple of M and at every iteration step S only adds multiples of M.
11330 if (isa<SCEVAddExpr, SCEVAddRecExpr>(Val: S) &&
11331 cast<SCEVNAryExpr>(Val: S)->hasNoUnsignedWrap() &&
11332 all_of(Range: S->operands(),
11333 P: [&](SCEVUse Op) { return isKnownMultipleOf(S: Op, M, Predicates); }))
11334 return true;
11335
11336 // Similarly, look through Mul with nuw, where any operand being a
11337 // known-multiple is sufficient.
11338 if (auto *Mul = dyn_cast<SCEVMulExpr>(Val: S))
11339 if (Mul->hasNoUnsignedWrap() && any_of(Range: S->operands(), P: [&](SCEVUse Op) {
11340 return isKnownMultipleOf(S: Op, M, Predicates);
11341 }))
11342 return true;
11343
11344 // Similarly, look through MinMax, with no wrapping arithmetic to consider.
11345 if (isa<SCEVMinMaxExpr>(Val: S) && all_of(Range: S->operands(), P: [&](SCEVUse Op) {
11346 return isKnownMultipleOf(S: Op, M, Predicates);
11347 }))
11348 return true;
11349
11350 const SCEVPredicate *P = getComparePredicate(Pred: ICmpInst::ICMP_EQ, LHS: SmodM, RHS: Zero);
11351
11352 // Detect redundant predicates.
11353 for (auto *A : *Predicates)
11354 if (A->implies(N: P, SE&: *this))
11355 return true;
11356
11357 // Only record non-redundant predicates.
11358 Predicates->push_back(Elt: P);
11359 return true;
11360}
11361
11362bool ScalarEvolution::haveSameSign(const SCEV *S1, const SCEV *S2) {
11363 return ((isKnownNonNegative(S: S1) && isKnownNonNegative(S: S2)) ||
11364 (isKnownNegative(S: S1) && isKnownNegative(S: S2)));
11365}
11366
11367std::pair<const SCEV *, const SCEV *>
11368ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
11369 // Compute SCEV on entry of loop L.
11370 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, SE&: *this);
11371 if (Start == getCouldNotCompute())
11372 return { Start, Start };
11373 // Compute post increment SCEV for loop L.
11374 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, SE&: *this);
11375 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
11376 return { Start, PostInc };
11377}
11378
11379bool ScalarEvolution::isKnownViaInduction(CmpPredicate Pred, SCEVUse LHS,
11380 SCEVUse RHS) {
11381 // First collect all loops.
11382 SmallPtrSet<const Loop *, 8> LoopsUsed;
11383 getUsedLoops(S: LHS, LoopsUsed);
11384 getUsedLoops(S: RHS, LoopsUsed);
11385
11386 if (LoopsUsed.empty())
11387 return false;
11388
11389 // Domination relationship must be a linear order on collected loops.
11390#ifndef NDEBUG
11391 for (const auto *L1 : LoopsUsed)
11392 for (const auto *L2 : LoopsUsed)
11393 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
11394 DT.dominates(L2->getHeader(), L1->getHeader())) &&
11395 "Domination relationship is not a linear order");
11396#endif
11397
11398 const Loop *MDL =
11399 *llvm::max_element(Range&: LoopsUsed, C: [&](const Loop *L1, const Loop *L2) {
11400 return DT.properlyDominates(A: L1->getHeader(), B: L2->getHeader());
11401 });
11402
11403 // Get init and post increment value for LHS.
11404 auto SplitLHS = SplitIntoInitAndPostInc(L: MDL, S: LHS);
11405 // if LHS contains unknown non-invariant SCEV then bail out.
11406 if (SplitLHS.first == getCouldNotCompute())
11407 return false;
11408 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
11409 // Get init and post increment value for RHS.
11410 auto SplitRHS = SplitIntoInitAndPostInc(L: MDL, S: RHS);
11411 // if RHS contains unknown non-invariant SCEV then bail out.
11412 if (SplitRHS.first == getCouldNotCompute())
11413 return false;
11414 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
11415 // It is possible that init SCEV contains an invariant load but it does
11416 // not dominate MDL and is not available at MDL loop entry, so we should
11417 // check it here.
11418 if (!isAvailableAtLoopEntry(S: SplitLHS.first, L: MDL) ||
11419 !isAvailableAtLoopEntry(S: SplitRHS.first, L: MDL))
11420 return false;
11421
11422 // It seems backedge guard check is faster than entry one so in some cases
11423 // it can speed up whole estimation by short circuit
11424 return isLoopBackedgeGuardedByCond(L: MDL, Pred, LHS: SplitLHS.second,
11425 RHS: SplitRHS.second) &&
11426 isLoopEntryGuardedByCond(L: MDL, Pred, LHS: SplitLHS.first, RHS: SplitRHS.first);
11427}
11428
11429bool ScalarEvolution::isKnownPredicate(CmpPredicate Pred, SCEVUse LHS,
11430 SCEVUse RHS) {
11431 // Canonicalize the inputs first.
11432 (void)SimplifyICmpOperands(Pred, LHS, RHS);
11433
11434 return isKnownViaInduction(Pred, LHS, RHS) ||
11435 isKnownPredicateViaSplitting(Pred, LHS, RHS) ||
11436 isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
11437}
11438
11439std::optional<bool> ScalarEvolution::evaluatePredicate(CmpPredicate Pred,
11440 const SCEV *LHS,
11441 const SCEV *RHS) {
11442 if (isKnownPredicate(Pred, LHS, RHS))
11443 return true;
11444 if (isKnownPredicate(Pred: ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11445 return false;
11446 return std::nullopt;
11447}
11448
11449bool ScalarEvolution::isKnownPredicateAt(CmpPredicate Pred, const SCEV *LHS,
11450 const SCEV *RHS,
11451 const Instruction *CtxI) {
11452 // TODO: Analyze guards and assumes from Context's block.
11453 return isKnownPredicate(Pred, LHS, RHS) ||
11454 isBasicBlockEntryGuardedByCond(BB: CtxI->getParent(), Pred, LHS, RHS);
11455}
11456
11457std::optional<bool>
11458ScalarEvolution::evaluatePredicateAt(CmpPredicate Pred, const SCEV *LHS,
11459 const SCEV *RHS, const Instruction *CtxI) {
11460 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
11461 if (KnownWithoutContext)
11462 return KnownWithoutContext;
11463
11464 if (isBasicBlockEntryGuardedByCond(BB: CtxI->getParent(), Pred, LHS, RHS))
11465 return true;
11466 if (isBasicBlockEntryGuardedByCond(
11467 BB: CtxI->getParent(), Pred: ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11468 return false;
11469 return std::nullopt;
11470}
11471
11472bool ScalarEvolution::isKnownOnEveryIteration(CmpPredicate Pred,
11473 const SCEVAddRecExpr *LHS,
11474 const SCEV *RHS) {
11475 const Loop *L = LHS->getLoop();
11476 return isLoopEntryGuardedByCond(L, Pred, LHS: LHS->getStart(), RHS) &&
11477 isLoopBackedgeGuardedByCond(L, Pred, LHS: LHS->getPostIncExpr(SE&: *this), RHS);
11478}
11479
11480std::optional<ScalarEvolution::MonotonicPredicateType>
11481ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
11482 ICmpInst::Predicate Pred) {
11483 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
11484
11485#ifndef NDEBUG
11486 // Verify an invariant: inverting the predicate should turn a monotonically
11487 // increasing change to a monotonically decreasing one, and vice versa.
11488 if (Result) {
11489 auto ResultSwapped =
11490 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11491
11492 assert(*ResultSwapped != *Result &&
11493 "monotonicity should flip as we flip the predicate");
11494 }
11495#endif
11496
11497 return Result;
11498}
11499
11500std::optional<ScalarEvolution::MonotonicPredicateType>
11501ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11502 ICmpInst::Predicate Pred) {
11503 // A zero step value for LHS means the induction variable is essentially a
11504 // loop invariant value. We don't really depend on the predicate actually
11505 // flipping from false to true (for increasing predicates, and the other way
11506 // around for decreasing predicates), all we care about is that *if* the
11507 // predicate changes then it only changes from false to true.
11508 //
11509 // A zero step value in itself is not very useful, but there may be places
11510 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11511 // as general as possible.
11512
11513 // Only handle LE/LT/GE/GT predicates.
11514 if (!ICmpInst::isRelational(P: Pred))
11515 return std::nullopt;
11516
11517 bool IsGreater = ICmpInst::isGE(P: Pred) || ICmpInst::isGT(P: Pred);
11518 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11519 "Should be greater or less!");
11520
11521 // Check that AR does not wrap.
11522 if (ICmpInst::isUnsigned(Pred)) {
11523 if (!LHS->hasNoUnsignedWrap())
11524 return std::nullopt;
11525 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
11526 }
11527 assert(ICmpInst::isSigned(Pred) &&
11528 "Relational predicate is either signed or unsigned!");
11529 if (!LHS->hasNoSignedWrap())
11530 return std::nullopt;
11531
11532 const SCEV *Step = LHS->getStepRecurrence(SE&: *this);
11533
11534 if (isKnownNonNegative(S: Step))
11535 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
11536
11537 if (isKnownNonPositive(S: Step))
11538 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
11539
11540 return std::nullopt;
11541}
11542
11543std::optional<ScalarEvolution::LoopInvariantPredicate>
11544ScalarEvolution::getLoopInvariantPredicate(CmpPredicate Pred, const SCEV *LHS,
11545 const SCEV *RHS, const Loop *L,
11546 const Instruction *CtxI) {
11547 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11548 if (!isLoopInvariant(S: RHS, L)) {
11549 if (!isLoopInvariant(S: LHS, L))
11550 return std::nullopt;
11551
11552 std::swap(a&: LHS, b&: RHS);
11553 Pred = ICmpInst::getSwappedCmpPredicate(Pred);
11554 }
11555
11556 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(Val: LHS);
11557 if (!ArLHS || ArLHS->getLoop() != L)
11558 return std::nullopt;
11559
11560 auto MonotonicType = getMonotonicPredicateType(LHS: ArLHS, Pred);
11561 if (!MonotonicType)
11562 return std::nullopt;
11563 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11564 // true as the loop iterates, and the backedge is control dependent on
11565 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11566 //
11567 // * if the predicate was false in the first iteration then the predicate
11568 // is never evaluated again, since the loop exits without taking the
11569 // backedge.
11570 // * if the predicate was true in the first iteration then it will
11571 // continue to be true for all future iterations since it is
11572 // monotonically increasing.
11573 //
11574 // For both the above possibilities, we can replace the loop varying
11575 // predicate with its value on the first iteration of the loop (which is
11576 // loop invariant).
11577 //
11578 // A similar reasoning applies for a monotonically decreasing predicate, by
11579 // replacing true with false and false with true in the above two bullets.
11580 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
11581 auto P = Increasing ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
11582
11583 if (isLoopBackedgeGuardedByCond(L, Pred: P, LHS, RHS))
11584 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(),
11585 RHS);
11586
11587 if (!CtxI)
11588 return std::nullopt;
11589 // Try to prove via context.
11590 // TODO: Support other cases.
11591 switch (Pred) {
11592 default:
11593 break;
11594 case ICmpInst::ICMP_ULE:
11595 case ICmpInst::ICMP_ULT: {
11596 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11597 // Given preconditions
11598 // (1) ArLHS does not cross the border of positive and negative parts of
11599 // range because of:
11600 // - Positive step; (TODO: lift this limitation)
11601 // - nuw - does not cross zero boundary;
11602 // - nsw - does not cross SINT_MAX boundary;
11603 // (2) ArLHS <s RHS
11604 // (3) RHS >=s 0
11605 // we can replace the loop variant ArLHS <u RHS condition with loop
11606 // invariant Start(ArLHS) <u RHS.
11607 //
11608 // Because of (1) there are two options:
11609 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11610 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11611 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11612 // Because of (2) ArLHS <u RHS is trivially true.
11613 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11614 // We can strengthen this to Start(ArLHS) <u RHS.
11615 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11616 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11617 isKnownPositive(S: ArLHS->getStepRecurrence(SE&: *this)) &&
11618 isKnownNonNegative(S: RHS) &&
11619 isKnownPredicateAt(Pred: SignFlippedPred, LHS: ArLHS, RHS, CtxI))
11620 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(),
11621 RHS);
11622 }
11623 }
11624
11625 return std::nullopt;
11626}
11627
11628std::optional<ScalarEvolution::LoopInvariantPredicate>
11629ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
11630 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11631 const Instruction *CtxI, const SCEV *MaxIter) {
11632 if (auto LIP = getLoopInvariantExitCondDuringFirstIterationsImpl(
11633 Pred, LHS, RHS, L, CtxI, MaxIter))
11634 return LIP;
11635 if (auto *UMin = dyn_cast<SCEVUMinExpr>(Val: MaxIter))
11636 // Number of iterations expressed as UMIN isn't always great for expressing
11637 // the value on the last iteration. If the straightforward approach didn't
11638 // work, try the following trick: if the a predicate is invariant for X, it
11639 // is also invariant for umin(X, ...). So try to find something that works
11640 // among subexpressions of MaxIter expressed as umin.
11641 for (SCEVUse Op : UMin->operands())
11642 if (auto LIP = getLoopInvariantExitCondDuringFirstIterationsImpl(
11643 Pred, LHS, RHS, L, CtxI, MaxIter: Op))
11644 return LIP;
11645 return std::nullopt;
11646}
11647
11648std::optional<ScalarEvolution::LoopInvariantPredicate>
11649ScalarEvolution::getLoopInvariantExitCondDuringFirstIterationsImpl(
11650 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11651 const Instruction *CtxI, const SCEV *MaxIter) {
11652 // Try to prove the following set of facts:
11653 // - The predicate is monotonic in the iteration space.
11654 // - If the check does not fail on the 1st iteration:
11655 // - No overflow will happen during first MaxIter iterations;
11656 // - It will not fail on the MaxIter'th iteration.
11657 // If the check does fail on the 1st iteration, we leave the loop and no
11658 // other checks matter.
11659
11660 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11661 if (!isLoopInvariant(S: RHS, L)) {
11662 if (!isLoopInvariant(S: LHS, L))
11663 return std::nullopt;
11664
11665 std::swap(a&: LHS, b&: RHS);
11666 Pred = ICmpInst::getSwappedCmpPredicate(Pred);
11667 }
11668
11669 auto *AR = dyn_cast<SCEVAddRecExpr>(Val: LHS);
11670 if (!AR || AR->getLoop() != L)
11671 return std::nullopt;
11672
11673 // Even if both are valid, we need to consistently chose the unsigned or the
11674 // signed predicate below, not mixtures of both. For now, prefer the unsigned
11675 // predicate.
11676 Pred = Pred.dropSameSign();
11677
11678 // The predicate must be relational (i.e. <, <=, >=, >).
11679 if (!ICmpInst::isRelational(P: Pred))
11680 return std::nullopt;
11681
11682 // TODO: Support steps other than +/- 1.
11683 const SCEV *Step = AR->getStepRecurrence(SE&: *this);
11684 auto *One = getOne(Ty: Step->getType());
11685 auto *MinusOne = getNegativeSCEV(V: One);
11686 if (Step != One && Step != MinusOne)
11687 return std::nullopt;
11688
11689 // Type mismatch here means that MaxIter is potentially larger than max
11690 // unsigned value in start type, which mean we cannot prove no wrap for the
11691 // indvar.
11692 if (AR->getType() != MaxIter->getType())
11693 return std::nullopt;
11694
11695 // Value of IV on suggested last iteration.
11696 const SCEV *Last = AR->evaluateAtIteration(It: MaxIter, SE&: *this);
11697 // Does it still meet the requirement?
11698 if (!isLoopBackedgeGuardedByCond(L, Pred, LHS: Last, RHS))
11699 return std::nullopt;
11700 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11701 // not exceed max unsigned value of this type), this effectively proves
11702 // that there is no wrap during the iteration. To prove that there is no
11703 // signed/unsigned wrap, we need to check that
11704 // Start <= Last for step = 1 or Start >= Last for step = -1.
11705 ICmpInst::Predicate NoOverflowPred =
11706 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
11707 if (Step == MinusOne)
11708 NoOverflowPred = ICmpInst::getSwappedPredicate(pred: NoOverflowPred);
11709 const SCEV *Start = AR->getStart();
11710 if (!isKnownPredicateAt(Pred: NoOverflowPred, LHS: Start, RHS: Last, CtxI))
11711 return std::nullopt;
11712
11713 // Everything is fine.
11714 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11715}
11716
11717bool ScalarEvolution::isKnownPredicateViaConstantRanges(CmpPredicate Pred,
11718 SCEVUse LHS,
11719 SCEVUse RHS) {
11720 if (HasSameValue(A: LHS, B: RHS))
11721 return ICmpInst::isTrueWhenEqual(predicate: Pred);
11722
11723 auto CheckRange = [&](bool IsSigned) {
11724 auto RangeLHS = IsSigned ? getSignedRange(S: LHS) : getUnsignedRange(S: LHS);
11725 auto RangeRHS = IsSigned ? getSignedRange(S: RHS) : getUnsignedRange(S: RHS);
11726 return RangeLHS.icmp(Pred, Other: RangeRHS);
11727 };
11728
11729 // The check at the top of the function catches the case where the values are
11730 // known to be equal.
11731 if (Pred == CmpInst::ICMP_EQ)
11732 return false;
11733
11734 if (Pred == CmpInst::ICMP_NE) {
11735 if (CheckRange(true) || CheckRange(false))
11736 return true;
11737 auto *Diff = getMinusSCEV(LHS, RHS);
11738 return !isa<SCEVCouldNotCompute>(Val: Diff) && isKnownNonZero(S: Diff);
11739 }
11740
11741 return CheckRange(CmpInst::isSigned(Pred));
11742}
11743
11744bool ScalarEvolution::isKnownPredicateViaNoOverflow(CmpPredicate Pred,
11745 SCEVUse LHS, SCEVUse RHS) {
11746 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11747 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11748 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11749 // OutC1 and OutC2.
11750 auto MatchBinaryAddToConst = [this](SCEVUse X, SCEVUse Y, APInt &OutC1,
11751 APInt &OutC2, SCEVFlags ExpectedFlags) {
11752 SCEVUse XNonConstOp, XConstOp;
11753 SCEVUse YNonConstOp, YConstOp;
11754 SCEVFlags XFlagsPresent;
11755 SCEVFlags YFlagsPresent;
11756
11757 // Use nullptr for 0, to avoid creating a zero SCEV.
11758 if (!splitBinaryAdd(Expr: X, L&: XConstOp, R&: XNonConstOp, Flags&: XFlagsPresent)) {
11759 XConstOp = nullptr;
11760 XNonConstOp = X;
11761 XFlagsPresent = ExpectedFlags;
11762 }
11763 if (XConstOp && !isa<SCEVConstant>(Val: XConstOp))
11764 return false;
11765
11766 if (!splitBinaryAdd(Expr: Y, L&: YConstOp, R&: YNonConstOp, Flags&: YFlagsPresent)) {
11767 YConstOp = nullptr;
11768 YNonConstOp = Y;
11769 YFlagsPresent = ExpectedFlags;
11770 }
11771
11772 if (YNonConstOp != XNonConstOp)
11773 return false;
11774
11775 if (YConstOp && !isa<SCEVConstant>(Val: YConstOp))
11776 return false;
11777
11778 // When matching ADDs with NUW flags (and unsigned predicates), only the
11779 // second ADD (with the larger constant) requires NUW.
11780 if ((YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11781 return false;
11782 if (ExpectedFlags != SCEV::FlagNUW &&
11783 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) {
11784 return false;
11785 }
11786
11787 OutC1 = XConstOp ? cast<SCEVConstant>(Val&: XConstOp)->getAPInt()
11788 : APInt::getZero(numBits: getTypeSizeInBits(Ty: X->getType()));
11789 OutC2 = YConstOp ? cast<SCEVConstant>(Val&: YConstOp)->getAPInt()
11790 : APInt::getZero(numBits: getTypeSizeInBits(Ty: Y->getType()));
11791
11792 return true;
11793 };
11794
11795 APInt C1;
11796 APInt C2;
11797
11798 switch (Pred) {
11799 default:
11800 break;
11801
11802 case ICmpInst::ICMP_SGE:
11803 std::swap(a&: LHS, b&: RHS);
11804 [[fallthrough]];
11805 case ICmpInst::ICMP_SLE:
11806 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11807 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(RHS: C2))
11808 return true;
11809
11810 break;
11811
11812 case ICmpInst::ICMP_SGT:
11813 std::swap(a&: LHS, b&: RHS);
11814 [[fallthrough]];
11815 case ICmpInst::ICMP_SLT:
11816 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11817 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(RHS: C2))
11818 return true;
11819
11820 break;
11821
11822 case ICmpInst::ICMP_UGE:
11823 std::swap(a&: LHS, b&: RHS);
11824 [[fallthrough]];
11825 case ICmpInst::ICMP_ULE:
11826 // (X + C1) u<= (X + C2)<nuw> for C1 u<= C2.
11827 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(RHS: C2))
11828 return true;
11829
11830 break;
11831
11832 case ICmpInst::ICMP_UGT:
11833 std::swap(a&: LHS, b&: RHS);
11834 [[fallthrough]];
11835 case ICmpInst::ICMP_ULT:
11836 // (X + C1) u< (X + C2)<nuw> if C1 u< C2.
11837 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(RHS: C2))
11838 return true;
11839 break;
11840 }
11841
11842 return false;
11843}
11844
11845bool ScalarEvolution::isKnownPredicateViaSplitting(CmpPredicate Pred,
11846 SCEVUse LHS, SCEVUse RHS) {
11847 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11848 return false;
11849
11850 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11851 // the stack can result in exponential time complexity.
11852 SaveAndRestore Restore(ProvingSplitPredicate, true);
11853
11854 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11855 //
11856 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11857 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11858 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11859 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11860 // use isKnownPredicate later if needed.
11861 return isKnownNonNegative(S: RHS) &&
11862 isKnownPredicate(Pred: CmpInst::ICMP_SGE, LHS, RHS: getZero(Ty: LHS->getType())) &&
11863 isKnownPredicate(Pred: CmpInst::ICMP_SLT, LHS, RHS);
11864}
11865
11866bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
11867 const SCEV *LHS, const SCEV *RHS) {
11868 // No need to even try if we know the module has no guards.
11869 if (!HasGuards)
11870 return false;
11871
11872 return any_of(Range: *BB, P: [&](const Instruction &I) {
11873 using namespace llvm::PatternMatch;
11874
11875 Value *Condition;
11876 return match(V: &I, P: m_Intrinsic<Intrinsic::experimental_guard>(
11877 Ops: m_Value(V&: Condition))) &&
11878 isImpliedCond(Pred, LHS, RHS, FoundCondValue: Condition, Inverse: false);
11879 });
11880}
11881
11882/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11883/// protected by a conditional between LHS and RHS. This is used to
11884/// to eliminate casts.
11885bool ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
11886 CmpPredicate Pred,
11887 const SCEV *LHS,
11888 const SCEV *RHS) {
11889 // Interpret a null as meaning no loop, where there is obviously no guard
11890 // (interprocedural conditions notwithstanding). Do not bother about
11891 // unreachable loops.
11892 if (!L || !DT.isReachableFromEntry(A: L->getHeader()))
11893 return true;
11894
11895 if (VerifyIR)
11896 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11897 "This cannot be done on broken IR!");
11898
11899
11900 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11901 return true;
11902
11903 BasicBlock *Latch = L->getLoopLatch();
11904 if (!Latch)
11905 return false;
11906
11907 CondBrInst *LoopContinuePredicate =
11908 dyn_cast<CondBrInst>(Val: Latch->getTerminator());
11909 if (LoopContinuePredicate &&
11910 isImpliedCond(Pred, LHS, RHS, FoundCondValue: LoopContinuePredicate->getCondition(),
11911 Inverse: LoopContinuePredicate->getSuccessor(i: 0) != L->getHeader()))
11912 return true;
11913
11914 // We don't want more than one activation of the following loops on the stack
11915 // -- that can lead to O(n!) time complexity.
11916 if (WalkingBEDominatingConds)
11917 return false;
11918
11919 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11920
11921 // See if we can exploit a trip count to prove the predicate.
11922 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11923 const SCEV *LatchBECount = BETakenInfo.getExact(ExitingBlock: Latch, SE: this);
11924 if (LatchBECount != getCouldNotCompute()) {
11925 // We know that Latch branches back to the loop header exactly
11926 // LatchBECount times. This means the backdege condition at Latch is
11927 // equivalent to "{0,+,1} u< LatchBECount".
11928 Type *Ty = LatchBECount->getType();
11929 auto NoWrapFlags = SCEVFlags(SCEV::FlagNUW | SCEV::FlagNW);
11930 const SCEV *LoopCounter =
11931 getAddRecExpr(Start: getZero(Ty), Step: getOne(Ty), L, Flags: NoWrapFlags);
11932 if (isImpliedCond(Pred, LHS, RHS, FoundPred: ICmpInst::ICMP_ULT, FoundLHS: LoopCounter,
11933 FoundRHS: LatchBECount))
11934 return true;
11935 }
11936
11937 // Check conditions due to any @llvm.assume intrinsics.
11938 for (auto &AssumeVH : AC.assumptions()) {
11939 if (!AssumeVH)
11940 continue;
11941 auto *CI = cast<CallInst>(Val&: AssumeVH);
11942 if (!DT.dominates(Def: CI, User: Latch->getTerminator()))
11943 continue;
11944
11945 if (isImpliedCond(Pred, LHS, RHS, FoundCondValue: CI->getArgOperand(i: 0), Inverse: false))
11946 return true;
11947 }
11948
11949 if (isImpliedViaGuard(BB: Latch, Pred, LHS, RHS))
11950 return true;
11951
11952 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11953 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11954 assert(DTN && "should reach the loop header before reaching the root!");
11955
11956 BasicBlock *BB = DTN->getBlock();
11957 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11958 return true;
11959
11960 BasicBlock *PBB = BB->getSinglePredecessor();
11961 if (!PBB)
11962 continue;
11963
11964 CondBrInst *ContBr = dyn_cast<CondBrInst>(Val: PBB->getTerminator());
11965 if (!ContBr || ContBr->getSuccessor(i: 0) == ContBr->getSuccessor(i: 1))
11966 continue;
11967
11968 // If we have an edge `E` within the loop body that dominates the only
11969 // latch, the condition guarding `E` also guards the backedge. This
11970 // reasoning works only for loops with a single latch.
11971 // We're constructively (and conservatively) enumerating edges within the
11972 // loop body that dominate the latch. The dominator tree better agree
11973 // with us on this:
11974 assert(DT.dominates(BasicBlockEdge(PBB, BB), Latch) && "should be!");
11975 if (isImpliedCond(Pred, LHS, RHS, FoundCondValue: ContBr->getCondition(),
11976 Inverse: BB != ContBr->getSuccessor(i: 0)))
11977 return true;
11978 }
11979
11980 return false;
11981}
11982
11983bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
11984 CmpPredicate Pred,
11985 const SCEV *LHS,
11986 const SCEV *RHS) {
11987 // Do not bother proving facts for unreachable code.
11988 if (!DT.isReachableFromEntry(A: BB))
11989 return true;
11990 if (VerifyIR)
11991 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
11992 "This cannot be done on broken IR!");
11993
11994 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
11995 // the facts (a >= b && a != b) separately. A typical situation is when the
11996 // non-strict comparison is known from ranges and non-equality is known from
11997 // dominating predicates. If we are proving strict comparison, we always try
11998 // to prove non-equality and non-strict comparison separately.
11999 CmpPredicate NonStrictPredicate = ICmpInst::getNonStrictCmpPredicate(Pred);
12000 const bool ProvingStrictComparison =
12001 Pred != NonStrictPredicate.dropSameSign();
12002 bool ProvedNonStrictComparison = false;
12003 bool ProvedNonEquality = false;
12004
12005 auto SplitAndProve = [&](std::function<bool(CmpPredicate)> Fn) -> bool {
12006 if (!ProvedNonStrictComparison)
12007 ProvedNonStrictComparison = Fn(NonStrictPredicate);
12008 if (!ProvedNonEquality)
12009 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
12010 if (ProvedNonStrictComparison && ProvedNonEquality)
12011 return true;
12012 return false;
12013 };
12014
12015 if (ProvingStrictComparison) {
12016 auto ProofFn = [&](CmpPredicate P) {
12017 return isKnownViaNonRecursiveReasoning(Pred: P, LHS, RHS);
12018 };
12019 if (SplitAndProve(ProofFn))
12020 return true;
12021 }
12022
12023 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
12024 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
12025 const Instruction *CtxI = &BB->front();
12026 if (isImpliedCond(Pred, LHS, RHS, FoundCondValue: Condition, Inverse, Context: CtxI))
12027 return true;
12028 if (ProvingStrictComparison) {
12029 auto ProofFn = [&](CmpPredicate P) {
12030 return isImpliedCond(Pred: P, LHS, RHS, FoundCondValue: Condition, Inverse, Context: CtxI);
12031 };
12032 if (SplitAndProve(ProofFn))
12033 return true;
12034 }
12035 return false;
12036 };
12037
12038 // Starting at the block's predecessor, climb up the predecessor chain, as long
12039 // as there are predecessors that can be found that have unique successors
12040 // leading to the original block.
12041 const Loop *ContainingLoop = LI.getLoopFor(BB);
12042 const BasicBlock *PredBB;
12043 if (ContainingLoop && ContainingLoop->getHeader() == BB)
12044 PredBB = ContainingLoop->getLoopPredecessor();
12045 else
12046 PredBB = BB->getSinglePredecessor();
12047 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
12048 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(BB: Pair.first)) {
12049 const CondBrInst *BlockEntryPredicate =
12050 dyn_cast<CondBrInst>(Val: Pair.first->getTerminator());
12051 if (!BlockEntryPredicate)
12052 continue;
12053
12054 if (ProveViaCond(BlockEntryPredicate->getCondition(),
12055 BlockEntryPredicate->getSuccessor(i: 0) != Pair.second))
12056 return true;
12057 }
12058
12059 // Check conditions due to any @llvm.assume intrinsics.
12060 for (auto &AssumeVH : AC.assumptions()) {
12061 if (!AssumeVH)
12062 continue;
12063 auto *CI = cast<CallInst>(Val&: AssumeVH);
12064 if (!DT.dominates(Def: CI, BB))
12065 continue;
12066
12067 if (ProveViaCond(CI->getArgOperand(i: 0), false))
12068 return true;
12069 }
12070
12071 // Check conditions due to any @llvm.experimental.guard intrinsics.
12072 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
12073 M: F.getParent(), id: Intrinsic::experimental_guard);
12074 if (GuardDecl)
12075 for (const auto *GU : GuardDecl->users())
12076 if (const auto *Guard = dyn_cast<IntrinsicInst>(Val: GU))
12077 if (Guard->getFunction() == BB->getParent() && DT.dominates(Def: Guard, BB))
12078 if (ProveViaCond(Guard->getArgOperand(i: 0), false))
12079 return true;
12080 return false;
12081}
12082
12083bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, CmpPredicate Pred,
12084 const SCEV *LHS,
12085 const SCEV *RHS) {
12086 // Interpret a null as meaning no loop, where there is obviously no guard
12087 // (interprocedural conditions notwithstanding).
12088 if (!L)
12089 return false;
12090
12091 // Both LHS and RHS must be available at loop entry.
12092 assert(isAvailableAtLoopEntry(LHS, L) &&
12093 "LHS is not available at Loop Entry");
12094 assert(isAvailableAtLoopEntry(RHS, L) &&
12095 "RHS is not available at Loop Entry");
12096
12097 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
12098 return true;
12099
12100 return isBasicBlockEntryGuardedByCond(BB: L->getHeader(), Pred, LHS, RHS);
12101}
12102
12103bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12104 const SCEV *RHS,
12105 const Value *FoundCondValue, bool Inverse,
12106 const Instruction *CtxI) {
12107 // False conditions implies anything. Do not bother analyzing it further.
12108 if (FoundCondValue ==
12109 ConstantInt::getBool(Context&: FoundCondValue->getContext(), V: Inverse))
12110 return true;
12111
12112 if (!PendingLoopPredicates.insert(Ptr: FoundCondValue).second)
12113 return false;
12114
12115 llvm::scope_exit ClearOnExit(
12116 [&]() { PendingLoopPredicates.erase(Ptr: FoundCondValue); });
12117
12118 // Recursively handle And and Or conditions.
12119 const Value *Op0, *Op1;
12120 if (match(V: FoundCondValue, P: m_LogicalAnd(L: m_Value(V&: Op0), R: m_Value(V&: Op1)))) {
12121 if (!Inverse)
12122 return isImpliedCond(Pred, LHS, RHS, FoundCondValue: Op0, Inverse, CtxI) ||
12123 isImpliedCond(Pred, LHS, RHS, FoundCondValue: Op1, Inverse, CtxI);
12124 } else if (match(V: FoundCondValue, P: m_LogicalOr(L: m_Value(V&: Op0), R: m_Value(V&: Op1)))) {
12125 if (Inverse)
12126 return isImpliedCond(Pred, LHS, RHS, FoundCondValue: Op0, Inverse, CtxI) ||
12127 isImpliedCond(Pred, LHS, RHS, FoundCondValue: Op1, Inverse, CtxI);
12128 }
12129
12130 const ICmpInst *ICI = dyn_cast<ICmpInst>(Val: FoundCondValue);
12131 if (!ICI) return false;
12132
12133 // Now that we found a conditional branch that dominates the loop or controls
12134 // the loop latch. Check to see if it is the comparison we are looking for.
12135 CmpPredicate FoundPred;
12136 if (Inverse)
12137 FoundPred = ICI->getInverseCmpPredicate();
12138 else
12139 FoundPred = ICI->getCmpPredicate();
12140
12141 const SCEV *FoundLHS = getSCEV(V: ICI->getOperand(i_nocapture: 0));
12142 const SCEV *FoundRHS = getSCEV(V: ICI->getOperand(i_nocapture: 1));
12143
12144 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context: CtxI);
12145}
12146
12147bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12148 const SCEV *RHS, CmpPredicate FoundPred,
12149 const SCEV *FoundLHS, const SCEV *FoundRHS,
12150 const Instruction *CtxI) {
12151 // Balance the types.
12152 if (getTypeSizeInBits(Ty: LHS->getType()) <
12153 getTypeSizeInBits(Ty: FoundLHS->getType())) {
12154 // For unsigned and equality predicates, try to prove that both found
12155 // operands fit into narrow unsigned range. If so, try to prove facts in
12156 // narrow types.
12157 if (!CmpInst::isSigned(Pred: FoundPred) && !FoundLHS->getType()->isPointerTy() &&
12158 !FoundRHS->getType()->isPointerTy()) {
12159 auto *NarrowType = LHS->getType();
12160 auto *WideType = FoundLHS->getType();
12161 auto BitWidth = getTypeSizeInBits(Ty: NarrowType);
12162 const SCEV *MaxValue = getZeroExtendExpr(
12163 Op: getConstant(Val: APInt::getMaxValue(numBits: BitWidth)), Ty: WideType);
12164 if (isKnownViaNonRecursiveReasoning(Pred: ICmpInst::ICMP_ULE, LHS: FoundLHS,
12165 RHS: MaxValue) &&
12166 isKnownViaNonRecursiveReasoning(Pred: ICmpInst::ICMP_ULE, LHS: FoundRHS,
12167 RHS: MaxValue)) {
12168 const SCEV *TruncFoundLHS = getTruncateExpr(Op: FoundLHS, Ty: NarrowType);
12169 const SCEV *TruncFoundRHS = getTruncateExpr(Op: FoundRHS, Ty: NarrowType);
12170 // We cannot preserve samesign after truncation.
12171 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred: FoundPred.dropSameSign(),
12172 FoundLHS: TruncFoundLHS, FoundRHS: TruncFoundRHS, CtxI))
12173 return true;
12174 }
12175 }
12176
12177 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
12178 return false;
12179 if (CmpInst::isSigned(Pred)) {
12180 LHS = getSignExtendExpr(Op: LHS, Ty: FoundLHS->getType());
12181 RHS = getSignExtendExpr(Op: RHS, Ty: FoundLHS->getType());
12182 } else {
12183 LHS = getZeroExtendExpr(Op: LHS, Ty: FoundLHS->getType());
12184 RHS = getZeroExtendExpr(Op: RHS, Ty: FoundLHS->getType());
12185 }
12186 } else if (getTypeSizeInBits(Ty: LHS->getType()) >
12187 getTypeSizeInBits(Ty: FoundLHS->getType())) {
12188 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
12189 return false;
12190 if (CmpInst::isSigned(Pred: FoundPred)) {
12191 FoundLHS = getSignExtendExpr(Op: FoundLHS, Ty: LHS->getType());
12192 FoundRHS = getSignExtendExpr(Op: FoundRHS, Ty: LHS->getType());
12193 } else {
12194 FoundLHS = getZeroExtendExpr(Op: FoundLHS, Ty: LHS->getType());
12195 FoundRHS = getZeroExtendExpr(Op: FoundRHS, Ty: LHS->getType());
12196 }
12197 }
12198 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
12199 FoundRHS, CtxI);
12200}
12201
12202bool ScalarEvolution::isImpliedCondBalancedTypes(
12203 CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, CmpPredicate FoundPred,
12204 SCEVUse FoundLHS, SCEVUse FoundRHS, const Instruction *CtxI) {
12205 assert(getTypeSizeInBits(LHS->getType()) ==
12206 getTypeSizeInBits(FoundLHS->getType()) &&
12207 "Types should be balanced!");
12208 // Canonicalize the query to match the way instcombine will have
12209 // canonicalized the comparison.
12210 if (SimplifyICmpOperands(Pred, LHS, RHS))
12211 if (LHS == RHS)
12212 return CmpInst::isTrueWhenEqual(predicate: Pred);
12213 if (SimplifyICmpOperands(Pred&: FoundPred, LHS&: FoundLHS, RHS&: FoundRHS))
12214 if (FoundLHS == FoundRHS)
12215 return CmpInst::isFalseWhenEqual(predicate: FoundPred);
12216
12217 // Check to see if we can make the LHS or RHS match.
12218 if (LHS == FoundRHS || RHS == FoundLHS) {
12219 if (isa<SCEVConstant>(Val: RHS)) {
12220 std::swap(a&: FoundLHS, b&: FoundRHS);
12221 FoundPred = ICmpInst::getSwappedCmpPredicate(Pred: FoundPred);
12222 } else {
12223 std::swap(a&: LHS, b&: RHS);
12224 Pred = ICmpInst::getSwappedCmpPredicate(Pred);
12225 }
12226 }
12227
12228 // Check whether the found predicate is the same as the desired predicate.
12229 if (auto P = CmpPredicate::getMatching(A: FoundPred, B: Pred))
12230 return isImpliedCondOperands(Pred: *P, LHS, RHS, FoundLHS, FoundRHS, Context: CtxI);
12231
12232 // Check whether swapping the found predicate makes it the same as the
12233 // desired predicate.
12234 if (auto P = CmpPredicate::getMatching(
12235 A: ICmpInst::getSwappedCmpPredicate(Pred: FoundPred), B: Pred)) {
12236 // We can write the implication
12237 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
12238 // using one of the following ways:
12239 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
12240 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
12241 // Both require swapping the operands of one condition. Don't do this if it
12242 // would break canonical constant/addrec ordering.
12243 if (!isa<SCEVConstant>(Val: RHS) && !isa<SCEVAddRecExpr>(Val: LHS))
12244 return isImpliedCondOperands(Pred: ICmpInst::getSwappedCmpPredicate(Pred: *P), LHS: RHS,
12245 RHS: LHS, FoundLHS, FoundRHS, Context: CtxI);
12246 if (!isa<SCEVConstant>(Val: FoundRHS) && !isa<SCEVAddRecExpr>(Val: FoundLHS))
12247 return isImpliedCondOperands(Pred: *P, LHS, RHS, FoundLHS: FoundRHS, FoundRHS: FoundLHS, Context: CtxI);
12248
12249 return false;
12250 }
12251
12252 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
12253 CmpInst::Predicate P2) {
12254 assert(P1 != P2 && "Handled earlier!");
12255 return CmpInst::isRelational(P: P2) &&
12256 P1 == ICmpInst::getFlippedSignednessPredicate(Pred: P2);
12257 };
12258 if (IsSignFlippedPredicate(Pred, FoundPred)) {
12259 // Unsigned comparison is the same as signed comparison when both the
12260 // operands are non-negative or negative.
12261 if (haveSameSign(S1: FoundLHS, S2: FoundRHS))
12262 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context: CtxI);
12263 // Create local copies that we can freely swap and canonicalize our
12264 // conditions to "le/lt".
12265 CmpPredicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
12266 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
12267 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
12268 if (ICmpInst::isGT(P: CanonicalPred) || ICmpInst::isGE(P: CanonicalPred)) {
12269 CanonicalPred = ICmpInst::getSwappedCmpPredicate(Pred: CanonicalPred);
12270 CanonicalFoundPred = ICmpInst::getSwappedCmpPredicate(Pred: CanonicalFoundPred);
12271 std::swap(a&: CanonicalLHS, b&: CanonicalRHS);
12272 std::swap(a&: CanonicalFoundLHS, b&: CanonicalFoundRHS);
12273 }
12274 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
12275 "Must be!");
12276 assert((ICmpInst::isLT(CanonicalFoundPred) ||
12277 ICmpInst::isLE(CanonicalFoundPred)) &&
12278 "Must be!");
12279 if (ICmpInst::isSigned(Pred: CanonicalPred) && isKnownNonNegative(S: CanonicalRHS))
12280 // Use implication:
12281 // x <u y && y >=s 0 --> x <s y.
12282 // If we can prove the left part, the right part is also proven.
12283 return isImpliedCondOperands(Pred: CanonicalFoundPred, LHS: CanonicalLHS,
12284 RHS: CanonicalRHS, FoundLHS: CanonicalFoundLHS,
12285 FoundRHS: CanonicalFoundRHS);
12286 if (ICmpInst::isUnsigned(Pred: CanonicalPred) && isKnownNegative(S: CanonicalRHS))
12287 // Use implication:
12288 // x <s y && y <s 0 --> x <u y.
12289 // If we can prove the left part, the right part is also proven.
12290 return isImpliedCondOperands(Pred: CanonicalFoundPred, LHS: CanonicalLHS,
12291 RHS: CanonicalRHS, FoundLHS: CanonicalFoundLHS,
12292 FoundRHS: CanonicalFoundRHS);
12293 }
12294
12295 // Check if we can make progress by sharpening ranges.
12296 if (FoundPred == ICmpInst::ICMP_NE &&
12297 (isa<SCEVConstant>(Val: FoundLHS) || isa<SCEVConstant>(Val: FoundRHS))) {
12298
12299 const SCEVConstant *C = nullptr;
12300 const SCEV *V = nullptr;
12301
12302 if (isa<SCEVConstant>(Val: FoundLHS)) {
12303 C = cast<SCEVConstant>(Val&: FoundLHS);
12304 V = FoundRHS;
12305 } else {
12306 C = cast<SCEVConstant>(Val&: FoundRHS);
12307 V = FoundLHS;
12308 }
12309
12310 // The guarding predicate tells us that C != V. If the known range
12311 // of V is [C, t), we can sharpen the range to [C + 1, t). The
12312 // range we consider has to correspond to same signedness as the
12313 // predicate we're interested in folding.
12314
12315 APInt Min = ICmpInst::isSigned(Pred) ?
12316 getSignedRangeMin(S: V) : getUnsignedRangeMin(S: V);
12317
12318 if (Min == C->getAPInt()) {
12319 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
12320 // This is true even if (Min + 1) wraps around -- in case of
12321 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
12322
12323 APInt SharperMin = Min + 1;
12324
12325 switch (Pred) {
12326 case ICmpInst::ICMP_SGE:
12327 case ICmpInst::ICMP_UGE:
12328 // We know V `Pred` SharperMin. If this implies LHS `Pred`
12329 // RHS, we're done.
12330 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS: V, FoundRHS: getConstant(Val: SharperMin),
12331 Context: CtxI))
12332 return true;
12333 [[fallthrough]];
12334
12335 case ICmpInst::ICMP_SGT:
12336 case ICmpInst::ICMP_UGT:
12337 // We know from the range information that (V `Pred` Min ||
12338 // V == Min). We know from the guarding condition that !(V
12339 // == Min). This gives us
12340 //
12341 // V `Pred` Min || V == Min && !(V == Min)
12342 // => V `Pred` Min
12343 //
12344 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
12345
12346 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS: V, FoundRHS: getConstant(Val: Min), Context: CtxI))
12347 return true;
12348 break;
12349
12350 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
12351 case ICmpInst::ICMP_SLE:
12352 case ICmpInst::ICMP_ULE:
12353 if (isImpliedCondOperands(Pred: ICmpInst::getSwappedCmpPredicate(Pred), LHS: RHS,
12354 RHS: LHS, FoundLHS: V, FoundRHS: getConstant(Val: SharperMin), Context: CtxI))
12355 return true;
12356 [[fallthrough]];
12357
12358 case ICmpInst::ICMP_SLT:
12359 case ICmpInst::ICMP_ULT:
12360 if (isImpliedCondOperands(Pred: ICmpInst::getSwappedCmpPredicate(Pred), LHS: RHS,
12361 RHS: LHS, FoundLHS: V, FoundRHS: getConstant(Val: Min), Context: CtxI))
12362 return true;
12363 break;
12364
12365 default:
12366 // No change
12367 break;
12368 }
12369 }
12370 }
12371
12372 // Check whether the actual condition is beyond sufficient.
12373 if (FoundPred == ICmpInst::ICMP_EQ)
12374 if (ICmpInst::isTrueWhenEqual(predicate: Pred))
12375 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context: CtxI))
12376 return true;
12377 if (Pred == ICmpInst::ICMP_NE)
12378 if (!ICmpInst::isTrueWhenEqual(predicate: FoundPred))
12379 if (isImpliedCondOperands(Pred: FoundPred, LHS, RHS, FoundLHS, FoundRHS, Context: CtxI))
12380 return true;
12381
12382 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12383 return true;
12384
12385 // Otherwise assume the worst.
12386 return false;
12387}
12388
12389bool ScalarEvolution::splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
12390 SCEVFlags &Flags) {
12391 if (!match(U: Expr, P: m_scev_Add(Op0: m_SCEV(V&: L), Op1: m_SCEV(V&: R))))
12392 return false;
12393
12394 Flags = cast<SCEVAddExpr>(Val&: Expr)->getNoWrapFlags();
12395 return true;
12396}
12397
12398std::optional<APInt>
12399ScalarEvolution::computeConstantDifference(const SCEV *More, const SCEV *Less) {
12400 // We avoid subtracting expressions here because this function is usually
12401 // fairly deep in the call stack (i.e. is called many times).
12402
12403 unsigned BW = getTypeSizeInBits(Ty: More->getType());
12404 APInt Diff(BW, 0);
12405 APInt DiffMul(BW, 1);
12406 // Try various simplifications to reduce the difference to a constant. Limit
12407 // the number of allowed simplifications to keep compile-time low.
12408 for (unsigned I = 0; I < 8; ++I) {
12409 if (More == Less)
12410 return Diff;
12411
12412 // Reduce addrecs with identical steps to their start value.
12413 if (isa<SCEVAddRecExpr>(Val: Less) && isa<SCEVAddRecExpr>(Val: More)) {
12414 const auto *LAR = cast<SCEVAddRecExpr>(Val: Less);
12415 const auto *MAR = cast<SCEVAddRecExpr>(Val: More);
12416
12417 if (LAR->getLoop() != MAR->getLoop())
12418 return std::nullopt;
12419
12420 // We look at affine expressions only; not for correctness but to keep
12421 // getStepRecurrence cheap.
12422 if (!LAR->isAffine() || !MAR->isAffine())
12423 return std::nullopt;
12424
12425 if (LAR->getStepRecurrence(SE&: *this) != MAR->getStepRecurrence(SE&: *this))
12426 return std::nullopt;
12427
12428 Less = LAR->getStart();
12429 More = MAR->getStart();
12430 continue;
12431 }
12432
12433 // Try to match a common constant multiply.
12434 auto MatchConstMul =
12435 [](const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12436 const APInt *C;
12437 const SCEV *Op;
12438 if (match(S, P: m_scev_Mul(Op0: m_scev_APInt(C), Op1: m_SCEV(V&: Op))))
12439 return {{Op, *C}};
12440 return std::nullopt;
12441 };
12442 if (auto MatchedMore = MatchConstMul(More)) {
12443 if (auto MatchedLess = MatchConstMul(Less)) {
12444 if (MatchedMore->second == MatchedLess->second) {
12445 More = MatchedMore->first;
12446 Less = MatchedLess->first;
12447 DiffMul *= MatchedMore->second;
12448 continue;
12449 }
12450 }
12451 }
12452
12453 // Try to cancel out common factors in two add expressions.
12454 SmallDenseMap<const SCEV *, int, 8> Multiplicity;
12455 auto Add = [&](const SCEV *S, int Mul) {
12456 if (auto *C = dyn_cast<SCEVConstant>(Val: S)) {
12457 if (Mul == 1) {
12458 Diff += C->getAPInt() * DiffMul;
12459 } else {
12460 assert(Mul == -1);
12461 Diff -= C->getAPInt() * DiffMul;
12462 }
12463 } else
12464 Multiplicity[S] += Mul;
12465 };
12466 auto Decompose = [&](const SCEV *S, int Mul) {
12467 if (isa<SCEVAddExpr>(Val: S)) {
12468 for (const SCEV *Op : S->operands())
12469 Add(Op, Mul);
12470 } else
12471 Add(S, Mul);
12472 };
12473 Decompose(More, 1);
12474 Decompose(Less, -1);
12475
12476 // Check whether all the non-constants cancel out, or reduce to new
12477 // More/Less values.
12478 const SCEV *NewMore = nullptr, *NewLess = nullptr;
12479 for (const auto &[S, Mul] : Multiplicity) {
12480 if (Mul == 0)
12481 continue;
12482 if (Mul == 1) {
12483 if (NewMore)
12484 return std::nullopt;
12485 NewMore = S;
12486 } else if (Mul == -1) {
12487 if (NewLess)
12488 return std::nullopt;
12489 NewLess = S;
12490 } else
12491 return std::nullopt;
12492 }
12493
12494 // Values stayed the same, no point in trying further.
12495 if (NewMore == More || NewLess == Less)
12496 return std::nullopt;
12497
12498 More = NewMore;
12499 Less = NewLess;
12500
12501 // Reduced to constant.
12502 if (!More && !Less)
12503 return Diff;
12504
12505 // Left with variable on only one side, bail out.
12506 if (!More || !Less)
12507 return std::nullopt;
12508 }
12509
12510 // Did not reduce to constant.
12511 return std::nullopt;
12512}
12513
12514bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12515 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12516 const SCEV *FoundRHS, const Instruction *CtxI) {
12517 // Try to recognize the following pattern:
12518 //
12519 // FoundRHS = ...
12520 // ...
12521 // loop:
12522 // FoundLHS = {Start,+,W}
12523 // context_bb: // Basic block from the same loop
12524 // known(Pred, FoundLHS, FoundRHS)
12525 //
12526 // If some predicate is known in the context of a loop, it is also known on
12527 // each iteration of this loop, including the first iteration. Therefore, in
12528 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12529 // prove the original pred using this fact.
12530 if (!CtxI)
12531 return false;
12532 const BasicBlock *ContextBB = CtxI->getParent();
12533 // Make sure AR varies in the context block.
12534 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Val: FoundLHS)) {
12535 const Loop *L = AR->getLoop();
12536 const auto *Latch = L->getLoopLatch();
12537 // Make sure that context belongs to the loop and executes on 1st iteration
12538 // (if it ever executes at all).
12539 if (!L->contains(BB: ContextBB) || !Latch || !DT.dominates(A: ContextBB, B: Latch))
12540 return false;
12541 if (!isAvailableAtLoopEntry(S: FoundRHS, L: AR->getLoop()))
12542 return false;
12543 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS: AR->getStart(), FoundRHS);
12544 }
12545
12546 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Val: FoundRHS)) {
12547 const Loop *L = AR->getLoop();
12548 const auto *Latch = L->getLoopLatch();
12549 // Make sure that context belongs to the loop and executes on 1st iteration
12550 // (if it ever executes at all).
12551 if (!L->contains(BB: ContextBB) || !Latch || !DT.dominates(A: ContextBB, B: Latch))
12552 return false;
12553 if (!isAvailableAtLoopEntry(S: FoundLHS, L: AR->getLoop()))
12554 return false;
12555 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS: AR->getStart());
12556 }
12557
12558 return false;
12559}
12560
12561bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred,
12562 const SCEV *LHS,
12563 const SCEV *RHS,
12564 const SCEV *FoundLHS,
12565 const SCEV *FoundRHS) {
12566 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12567 return false;
12568
12569 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(Val: LHS);
12570 if (!AddRecLHS)
12571 return false;
12572
12573 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(Val: FoundLHS);
12574 if (!AddRecFoundLHS)
12575 return false;
12576
12577 // We'd like to let SCEV reason about control dependencies, so we constrain
12578 // both the inequalities to be about add recurrences on the same loop. This
12579 // way we can use isLoopEntryGuardedByCond later.
12580
12581 const Loop *L = AddRecFoundLHS->getLoop();
12582 if (L != AddRecLHS->getLoop())
12583 return false;
12584
12585 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12586 //
12587 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12588 // ... (2)
12589 //
12590 // Informal proof for (2), assuming (1) [*]:
12591 //
12592 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12593 //
12594 // Then
12595 //
12596 // FoundLHS s< FoundRHS s< INT_MIN - C
12597 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12598 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12599 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12600 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12601 // <=> FoundLHS + C s< FoundRHS + C
12602 //
12603 // [*]: (1) can be proved by ruling out overflow.
12604 //
12605 // [**]: This can be proved by analyzing all the four possibilities:
12606 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12607 // (A s>= 0, B s>= 0).
12608 //
12609 // Note:
12610 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12611 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12612 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12613 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12614 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12615 // C)".
12616
12617 std::optional<APInt> LDiff = computeConstantDifference(More: LHS, Less: FoundLHS);
12618 if (!LDiff)
12619 return false;
12620 std::optional<APInt> RDiff = computeConstantDifference(More: RHS, Less: FoundRHS);
12621 if (!RDiff || *LDiff != *RDiff)
12622 return false;
12623
12624 if (LDiff->isMinValue())
12625 return true;
12626
12627 APInt FoundRHSLimit;
12628
12629 if (Pred == CmpInst::ICMP_ULT) {
12630 FoundRHSLimit = -(*RDiff);
12631 } else {
12632 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12633 FoundRHSLimit = APInt::getSignedMinValue(numBits: getTypeSizeInBits(Ty: RHS->getType())) - *RDiff;
12634 }
12635
12636 // Try to prove (1) or (2), as needed.
12637 return isAvailableAtLoopEntry(S: FoundRHS, L) &&
12638 isLoopEntryGuardedByCond(L, Pred, LHS: FoundRHS,
12639 RHS: getConstant(Val: FoundRHSLimit));
12640}
12641
12642bool ScalarEvolution::isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS,
12643 const SCEV *RHS, const SCEV *FoundLHS,
12644 const SCEV *FoundRHS, unsigned Depth) {
12645 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12646
12647 llvm::scope_exit ClearOnExit([&]() {
12648 if (LPhi) {
12649 bool Erased = PendingMerges.erase(Ptr: LPhi);
12650 assert(Erased && "Failed to erase LPhi!");
12651 (void)Erased;
12652 }
12653 if (RPhi) {
12654 bool Erased = PendingMerges.erase(Ptr: RPhi);
12655 assert(Erased && "Failed to erase RPhi!");
12656 (void)Erased;
12657 }
12658 });
12659
12660 // Find respective Phis and check that they are not being pending.
12661 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(Val: LHS))
12662 if (auto *Phi = dyn_cast<PHINode>(Val: LU->getValue())) {
12663 if (!PendingMerges.insert(Ptr: Phi).second)
12664 return false;
12665 LPhi = Phi;
12666 }
12667 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(Val: RHS))
12668 if (auto *Phi = dyn_cast<PHINode>(Val: RU->getValue())) {
12669 // If we detect a loop of Phi nodes being processed by this method, for
12670 // example:
12671 //
12672 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12673 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12674 //
12675 // we don't want to deal with a case that complex, so return conservative
12676 // answer false.
12677 if (!PendingMerges.insert(Ptr: Phi).second)
12678 return false;
12679 RPhi = Phi;
12680 }
12681
12682 // If none of LHS, RHS is a Phi, nothing to do here.
12683 if (!LPhi && !RPhi)
12684 return false;
12685
12686 // If there is a SCEVUnknown Phi we are interested in, make it left.
12687 if (!LPhi) {
12688 std::swap(a&: LHS, b&: RHS);
12689 std::swap(a&: FoundLHS, b&: FoundRHS);
12690 std::swap(a&: LPhi, b&: RPhi);
12691 Pred = ICmpInst::getSwappedCmpPredicate(Pred);
12692 }
12693
12694 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12695 const BasicBlock *LBB = LPhi->getParent();
12696 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(Val: RHS);
12697
12698 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12699 return isKnownViaNonRecursiveReasoning(Pred, LHS: S1, RHS: S2) ||
12700 isImpliedCondOperandsViaRanges(Pred, LHS: S1, RHS: S2, FoundPred: Pred, FoundLHS, FoundRHS) ||
12701 isImpliedViaOperations(Pred, LHS: S1, RHS: S2, FoundLHS, FoundRHS, Depth);
12702 };
12703
12704 if (RPhi && RPhi->getParent() == LBB) {
12705 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12706 // If we compare two Phis from the same block, and for each entry block
12707 // the predicate is true for incoming values from this block, then the
12708 // predicate is also true for the Phis.
12709 for (const BasicBlock *IncBB : predecessors(BB: LBB)) {
12710 const SCEV *L = getSCEV(V: LPhi->getIncomingValueForBlock(BB: IncBB));
12711 const SCEV *R = getSCEV(V: RPhi->getIncomingValueForBlock(BB: IncBB));
12712 if (!ProvedEasily(L, R))
12713 return false;
12714 }
12715 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12716 // Case two: RHS is also a Phi from the same basic block, and it is an
12717 // AddRec. It means that there is a loop which has both AddRec and Unknown
12718 // PHIs, for it we can compare incoming values of AddRec from above the loop
12719 // and latch with their respective incoming values of LPhi.
12720 // TODO: Generalize to handle loops with many inputs in a header.
12721 if (LPhi->getNumIncomingValues() != 2) return false;
12722
12723 auto *RLoop = RAR->getLoop();
12724 auto *Predecessor = RLoop->getLoopPredecessor();
12725 assert(Predecessor && "Loop with AddRec with no predecessor?");
12726 const SCEV *L1 = getSCEV(V: LPhi->getIncomingValueForBlock(BB: Predecessor));
12727 if (!ProvedEasily(L1, RAR->getStart()))
12728 return false;
12729 auto *Latch = RLoop->getLoopLatch();
12730 assert(Latch && "Loop with AddRec with no latch?");
12731 const SCEV *L2 = getSCEV(V: LPhi->getIncomingValueForBlock(BB: Latch));
12732 if (!ProvedEasily(L2, RAR->getPostIncExpr(SE&: *this)))
12733 return false;
12734 } else {
12735 // In all other cases go over inputs of LHS and compare each of them to RHS,
12736 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12737 // At this point RHS is either a non-Phi, or it is a Phi from some block
12738 // different from LBB.
12739 for (const BasicBlock *IncBB : predecessors(BB: LBB)) {
12740 // Check that RHS is available in this block.
12741 if (!dominates(S: RHS, BB: IncBB))
12742 return false;
12743 const SCEV *L = getSCEV(V: LPhi->getIncomingValueForBlock(BB: IncBB));
12744 // Make sure L does not refer to a value from a potentially previous
12745 // iteration of a loop.
12746 if (!properlyDominates(S: L, BB: LBB))
12747 return false;
12748 // Addrecs are considered to properly dominate their loop, so are missed
12749 // by the previous check. Discard any values that have computable
12750 // evolution in this loop.
12751 if (auto *Loop = LI.getLoopFor(BB: LBB))
12752 if (hasComputableLoopEvolution(S: L, L: Loop))
12753 return false;
12754 if (!ProvedEasily(L, RHS))
12755 return false;
12756 }
12757 }
12758 return true;
12759}
12760
12761bool ScalarEvolution::isImpliedCondOperandsViaShift(CmpPredicate Pred,
12762 const SCEV *LHS,
12763 const SCEV *RHS,
12764 const SCEV *FoundLHS,
12765 const SCEV *FoundRHS) {
12766 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12767 // sure that we are dealing with same LHS.
12768 if (RHS == FoundRHS) {
12769 std::swap(a&: LHS, b&: RHS);
12770 std::swap(a&: FoundLHS, b&: FoundRHS);
12771 Pred = ICmpInst::getSwappedCmpPredicate(Pred);
12772 }
12773 if (LHS != FoundLHS)
12774 return false;
12775
12776 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(Val: FoundRHS);
12777 if (!SUFoundRHS)
12778 return false;
12779
12780 Value *Shiftee, *ShiftValue;
12781
12782 using namespace PatternMatch;
12783 if (match(V: SUFoundRHS->getValue(),
12784 P: m_LShr(L: m_Value(V&: Shiftee), R: m_Value(V&: ShiftValue)))) {
12785 auto *ShifteeS = getSCEV(V: Shiftee);
12786 // Prove one of the following:
12787 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12788 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12789 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12790 // ---> LHS <s RHS
12791 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12792 // ---> LHS <=s RHS
12793 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12794 return isKnownPredicate(Pred: ICmpInst::ICMP_ULE, LHS: ShifteeS, RHS);
12795 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12796 if (isKnownNonNegative(S: ShifteeS))
12797 return isKnownPredicate(Pred: ICmpInst::ICMP_SLE, LHS: ShifteeS, RHS);
12798 }
12799
12800 return false;
12801}
12802
12803bool ScalarEvolution::isImpliedCondOperandsViaMatchingDiff(
12804 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12805 const SCEV *FoundRHS) {
12806 // Only valid for equality predicates: (A == B) implies (C == D) when
12807 // the SCEV difference A - B equals C - D (they check the same
12808 // underlying relationship at every iteration).
12809 if (!ICmpInst::isEquality(P: Pred))
12810 return false;
12811
12812 // Restrict to cases involving loop recurrences - that's where this
12813 // pattern arises (correlated IV comparisons). This avoids calling
12814 // getMinusSCEV on arbitrary non-loop expressions.
12815 if ((!isa<SCEVAddRecExpr>(Val: LHS) && !isa<SCEVAddRecExpr>(Val: RHS)) ||
12816 (!isa<SCEVAddRecExpr>(Val: FoundLHS) && !isa<SCEVAddRecExpr>(Val: FoundRHS)))
12817 return false;
12818
12819 // AddRecs from different loops can never produce matching differences.
12820 const SCEVAddRecExpr *QueryAddRec = dyn_cast<SCEVAddRecExpr>(Val: LHS);
12821 if (!QueryAddRec)
12822 QueryAddRec = cast<SCEVAddRecExpr>(Val: RHS);
12823 const SCEVAddRecExpr *FoundAddRec = dyn_cast<SCEVAddRecExpr>(Val: FoundLHS);
12824 if (!FoundAddRec)
12825 FoundAddRec = cast<SCEVAddRecExpr>(Val: FoundRHS);
12826 if (QueryAddRec->getLoop() != FoundAddRec->getLoop())
12827 return false;
12828
12829 // If the strides differ, the differences can never match.
12830 if (QueryAddRec->getStepRecurrence(SE&: *this) !=
12831 FoundAddRec->getStepRecurrence(SE&: *this))
12832 return false;
12833
12834 // Compute differences. For pointer-typed operands sharing the same base,
12835 // getMinusSCEV strips the common base and returns an integer SCEV.
12836 // For example, {base,+,8} - (base+8*n) = {-8n,+,8}
12837 const SCEV *FoundDiff = getMinusSCEV(LHS: FoundLHS, RHS: FoundRHS);
12838 if (isa<SCEVCouldNotCompute>(Val: FoundDiff))
12839 return false;
12840
12841 const SCEV *Diff = getMinusSCEV(LHS, RHS);
12842 if (isa<SCEVCouldNotCompute>(Val: Diff))
12843 return false;
12844
12845 return Diff == FoundDiff;
12846}
12847
12848bool ScalarEvolution::isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
12849 const SCEV *RHS,
12850 const SCEV *FoundLHS,
12851 const SCEV *FoundRHS,
12852 const Instruction *CtxI) {
12853 return isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred: Pred, FoundLHS,
12854 FoundRHS) ||
12855 isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS,
12856 FoundRHS) ||
12857 isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS) ||
12858 isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12859 CtxI) ||
12860 isImpliedCondOperandsViaMatchingDiff(Pred, LHS, RHS, FoundLHS,
12861 FoundRHS) ||
12862 isImpliedCondOperandsHelper(Pred, LHS, RHS, FoundLHS, FoundRHS);
12863}
12864
12865/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12866template <typename MinMaxExprType>
12867static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12868 const SCEV *Candidate) {
12869 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12870 if (!MinMaxExpr)
12871 return false;
12872
12873 return is_contained(MinMaxExpr->operands(), Candidate);
12874}
12875
12876static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
12877 CmpPredicate Pred, const SCEV *LHS,
12878 const SCEV *RHS) {
12879 // If both sides are affine addrecs for the same loop, with equal
12880 // steps, and we know the recurrences don't wrap, then we only
12881 // need to check the predicate on the starting values.
12882
12883 if (!ICmpInst::isRelational(P: Pred))
12884 return false;
12885
12886 const SCEV *LStart, *RStart, *Step;
12887 const Loop *L;
12888 if (!match(S: LHS,
12889 P: m_scev_AffineAddRec(Op0: m_SCEV(V&: LStart), Op1: m_SCEV(V&: Step), L: m_Loop(L))) ||
12890 !match(S: RHS, P: m_scev_AffineAddRec(Op0: m_SCEV(V&: RStart), Op1: m_scev_Specific(S: Step),
12891 L: m_SpecificLoop(L))))
12892 return false;
12893 const SCEVAddRecExpr *LAR = cast<SCEVAddRecExpr>(Val: LHS);
12894 const SCEVAddRecExpr *RAR = cast<SCEVAddRecExpr>(Val: RHS);
12895 SCEVFlags NW = ICmpInst::isSigned(Pred) ? SCEV::FlagNSW : SCEV::FlagNUW;
12896 if (!LAR->getNoWrapFlags(Mask: NW) || !RAR->getNoWrapFlags(Mask: NW))
12897 return false;
12898
12899 return SE.isKnownPredicate(Pred, LHS: LStart, RHS: RStart);
12900}
12901
12902/// Is LHS `Pred` RHS true because one of them is an AddRec that is known not to
12903/// go below its own start value?
12904static bool IsKnownPredicateViaAddRecMonotonicity(ScalarEvolution &SE,
12905 CmpPredicate Pred,
12906 const SCEV *LHS,
12907 const SCEV *RHS) {
12908 // Normalize to (AddRec Pred Start).
12909 if (!isa<SCEVAddRecExpr>(Val: LHS) && isa<SCEVAddRecExpr>(Val: RHS)) {
12910 Pred = ICmpInst::getSwappedCmpPredicate(Pred);
12911 std::swap(a&: LHS, b&: RHS);
12912 }
12913
12914 // The recurrence is equal to Start in the first iteration, so only the
12915 // non-strict predicate holds.
12916 if (Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE)
12917 return false;
12918
12919 const auto *AR = dyn_cast<SCEVAddRecExpr>(Val: LHS);
12920 if (!AR || AR->getStart() != RHS)
12921 return false;
12922
12923 return SE.getMonotonicPredicateType(LHS: AR, Pred) ==
12924 ScalarEvolution::MonotonicallyIncreasing;
12925}
12926
12927/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12928/// expression?
12929static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, CmpPredicate Pred,
12930 const SCEV *LHS, const SCEV *RHS) {
12931 switch (Pred) {
12932 default:
12933 return false;
12934
12935 case ICmpInst::ICMP_SGE:
12936 std::swap(a&: LHS, b&: RHS);
12937 [[fallthrough]];
12938 case ICmpInst::ICMP_SLE:
12939 return
12940 // min(A, ...) <= A
12941 IsMinMaxConsistingOf<SCEVSMinExpr>(MaybeMinMaxExpr: LHS, Candidate: RHS) ||
12942 // A <= max(A, ...)
12943 IsMinMaxConsistingOf<SCEVSMaxExpr>(MaybeMinMaxExpr: RHS, Candidate: LHS);
12944
12945 case ICmpInst::ICMP_UGE:
12946 std::swap(a&: LHS, b&: RHS);
12947 [[fallthrough]];
12948 case ICmpInst::ICMP_ULE:
12949 return
12950 // min(A, ...) <= A
12951 // FIXME: what about umin_seq?
12952 IsMinMaxConsistingOf<SCEVUMinExpr>(MaybeMinMaxExpr: LHS, Candidate: RHS) ||
12953 // A <= max(A, ...)
12954 IsMinMaxConsistingOf<SCEVUMaxExpr>(MaybeMinMaxExpr: RHS, Candidate: LHS);
12955
12956 case ICmpInst::ICMP_UGT:
12957 std::swap(a&: LHS, b&: RHS);
12958 [[fallthrough]];
12959 case ICmpInst::ICMP_ULT:
12960 // umin(Ops) u<= each Op, so proving Op u< RHS for any Op proves
12961 // umin(Ops) u< RHS.
12962 //
12963 // Use computeConstantDifference instead of the more powerful
12964 // isKnownPredicate to keep this check cheap: isKnownPredicateViaMinOrMax
12965 // is called from isKnownViaNonRecursiveReasoning, so recursing into
12966 // the full predicate prover would be expensive.
12967 if (const auto *Min = dyn_cast<SCEVUMinExpr>(Val: LHS)) {
12968 for (SCEVUse Op : Min->operands()) {
12969 std::optional<APInt> Diff = SE.computeConstantDifference(More: RHS, Less: Op);
12970 // When Op and RHS share a common base differing by a
12971 // constant offset D (RHS - Op = D), Op u< RHS holds iff D != 0 and
12972 // RHS >= D (unsigned), i.e. the subtraction doesn't underflow.
12973 if (Diff && !Diff->isZero() && SE.getUnsignedRangeMin(S: RHS).uge(RHS: *Diff))
12974 return true;
12975 }
12976 }
12977 return false;
12978 }
12979
12980 llvm_unreachable("covered switch fell through?!");
12981}
12982
12983bool ScalarEvolution::isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
12984 const SCEV *RHS,
12985 const SCEV *FoundLHS,
12986 const SCEV *FoundRHS,
12987 unsigned Depth) {
12988 assert(getTypeSizeInBits(LHS->getType()) ==
12989 getTypeSizeInBits(RHS->getType()) &&
12990 "LHS and RHS have different sizes?");
12991 assert(getTypeSizeInBits(FoundLHS->getType()) ==
12992 getTypeSizeInBits(FoundRHS->getType()) &&
12993 "FoundLHS and FoundRHS have different sizes?");
12994 // We want to avoid hurting the compile time with analysis of too big trees.
12995 if (Depth > MaxSCEVOperationsImplicationDepth)
12996 return false;
12997
12998 // We only want to work with GT comparison so far.
12999 if (ICmpInst::isLT(P: Pred)) {
13000 Pred = ICmpInst::getSwappedCmpPredicate(Pred);
13001 std::swap(a&: LHS, b&: RHS);
13002 std::swap(a&: FoundLHS, b&: FoundRHS);
13003 }
13004
13005 CmpInst::Predicate P = Pred.getPreferredSignedPredicate();
13006
13007 // For unsigned, try to reduce it to corresponding signed comparison.
13008 if (P == ICmpInst::ICMP_UGT)
13009 // We can replace unsigned predicate with its signed counterpart if all
13010 // involved values are non-negative.
13011 // TODO: We could have better support for unsigned.
13012 if (isKnownNonNegative(S: FoundLHS) && isKnownNonNegative(S: FoundRHS)) {
13013 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
13014 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
13015 // use this fact to prove that LHS and RHS are non-negative.
13016 const SCEV *MinusOne = getMinusOne(Ty: LHS->getType());
13017 if (isImpliedCondOperands(Pred: ICmpInst::ICMP_SGT, LHS, RHS: MinusOne, FoundLHS,
13018 FoundRHS) &&
13019 isImpliedCondOperands(Pred: ICmpInst::ICMP_SGT, LHS: RHS, RHS: MinusOne, FoundLHS,
13020 FoundRHS))
13021 P = ICmpInst::ICMP_SGT;
13022 }
13023
13024 if (P != ICmpInst::ICMP_SGT)
13025 return false;
13026
13027 auto GetOpFromSExt = [&](const SCEV *S) -> const SCEV * {
13028 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(Val: S))
13029 return Ext->getOperand();
13030 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
13031 // the constant in some cases.
13032 return S;
13033 };
13034
13035 // Acquire values from extensions.
13036 auto *OrigLHS = LHS;
13037 auto *OrigFoundLHS = FoundLHS;
13038 LHS = GetOpFromSExt(LHS);
13039 FoundLHS = GetOpFromSExt(FoundLHS);
13040
13041 // Is the SGT predicate can be proved trivially or using the found context.
13042 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
13043 return isKnownViaNonRecursiveReasoning(Pred: ICmpInst::ICMP_SGT, LHS: S1, RHS: S2) ||
13044 isImpliedViaOperations(Pred: ICmpInst::ICMP_SGT, LHS: S1, RHS: S2, FoundLHS: OrigFoundLHS,
13045 FoundRHS, Depth: Depth + 1);
13046 };
13047
13048 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(Val: LHS)) {
13049 // We want to avoid creation of any new non-constant SCEV. Since we are
13050 // going to compare the operands to RHS, we should be certain that we don't
13051 // need any size extensions for this. So let's decline all cases when the
13052 // sizes of types of LHS and RHS do not match.
13053 // TODO: Maybe try to get RHS from sext to catch more cases?
13054 if (getTypeSizeInBits(Ty: LHS->getType()) != getTypeSizeInBits(Ty: RHS->getType()))
13055 return false;
13056
13057 // Should not overflow.
13058 if (!LHSAddExpr->hasNoSignedWrap())
13059 return false;
13060
13061 SCEVUse LL = LHSAddExpr->getOperand(i: 0);
13062 SCEVUse LR = LHSAddExpr->getOperand(i: 1);
13063 auto *MinusOne = getMinusOne(Ty: RHS->getType());
13064
13065 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
13066 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
13067 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
13068 };
13069 // Try to prove the following rule:
13070 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
13071 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
13072 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
13073 return true;
13074 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(Val: LHS)) {
13075 Value *LL, *LR;
13076 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
13077
13078 using namespace llvm::PatternMatch;
13079
13080 if (match(V: LHSUnknownExpr->getValue(), P: m_SDiv(L: m_Value(V&: LL), R: m_Value(V&: LR)))) {
13081 // Rules for division.
13082 // We are going to perform some comparisons with Denominator and its
13083 // derivative expressions. In general case, creating a SCEV for it may
13084 // lead to a complex analysis of the entire graph, and in particular it
13085 // can request trip count recalculation for the same loop. This would
13086 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
13087 // this, we only want to create SCEVs that are constants in this section.
13088 // So we bail if Denominator is not a constant.
13089 if (!isa<ConstantInt>(Val: LR))
13090 return false;
13091
13092 auto *Denominator = cast<SCEVConstant>(Val: getSCEV(V: LR));
13093
13094 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
13095 // then a SCEV for the numerator already exists and matches with FoundLHS.
13096 auto *Numerator = getExistingSCEV(V: LL);
13097 if (!Numerator || Numerator->getType() != FoundLHS->getType())
13098 return false;
13099
13100 // Make sure that the numerator matches with FoundLHS and the denominator
13101 // is positive.
13102 if (!HasSameValue(A: Numerator, B: FoundLHS) || !isKnownPositive(S: Denominator))
13103 return false;
13104
13105 auto *DTy = Denominator->getType();
13106 auto *FRHSTy = FoundRHS->getType();
13107 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
13108 // One of types is a pointer and another one is not. We cannot extend
13109 // them properly to a wider type, so let us just reject this case.
13110 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
13111 // to avoid this check.
13112 return false;
13113
13114 // Given that:
13115 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
13116 auto *WTy = getWiderType(T1: DTy, T2: FRHSTy);
13117 auto *DenominatorExt = getNoopOrSignExtend(V: Denominator, Ty: WTy);
13118 auto *FoundRHSExt = getNoopOrSignExtend(V: FoundRHS, Ty: WTy);
13119
13120 // Try to prove the following rule:
13121 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
13122 // For example, given that FoundLHS > 2. It means that FoundLHS is at
13123 // least 3. If we divide it by Denominator < 4, we will have at least 1.
13124 auto *DenomMinusTwo = getMinusSCEV(LHS: DenominatorExt, RHS: getConstant(Ty: WTy, V: 2));
13125 if (isKnownNonPositive(S: RHS) &&
13126 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
13127 return true;
13128
13129 // Try to prove the following rule:
13130 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
13131 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
13132 // If we divide it by Denominator > 2, then:
13133 // 1. If FoundLHS is negative, then the result is 0.
13134 // 2. If FoundLHS is non-negative, then the result is non-negative.
13135 // Anyways, the result is non-negative.
13136 auto *MinusOne = getMinusOne(Ty: WTy);
13137 auto *NegDenomMinusOne = getMinusSCEV(LHS: MinusOne, RHS: DenominatorExt);
13138 if (isKnownNegative(S: RHS) &&
13139 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
13140 return true;
13141 }
13142 }
13143
13144 // If our expression contained SCEVUnknown Phis, and we split it down and now
13145 // need to prove something for them, try to prove the predicate for every
13146 // possible incoming values of those Phis.
13147 if (isImpliedViaMerge(Pred, LHS: OrigLHS, RHS, FoundLHS: OrigFoundLHS, FoundRHS, Depth: Depth + 1))
13148 return true;
13149
13150 return false;
13151}
13152
13153static bool isKnownPredicateExtendIdiom(CmpPredicate Pred, const SCEV *LHS,
13154 const SCEV *RHS) {
13155 // zext x u<= sext x, sext x s<= zext x
13156 const SCEV *Op;
13157 switch (Pred) {
13158 case ICmpInst::ICMP_SGE:
13159 std::swap(a&: LHS, b&: RHS);
13160 [[fallthrough]];
13161 case ICmpInst::ICMP_SLE: {
13162 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
13163 return match(S: LHS, P: m_scev_SExt(Op0: m_SCEV(V&: Op))) &&
13164 match(S: RHS, P: m_scev_ZExt(Op0: m_scev_Specific(S: Op)));
13165 }
13166 case ICmpInst::ICMP_UGE:
13167 std::swap(a&: LHS, b&: RHS);
13168 [[fallthrough]];
13169 case ICmpInst::ICMP_ULE: {
13170 // If operand >=u 0 then ZExt == SExt. If operand <u 0 then ZExt <u SExt.
13171 return match(S: LHS, P: m_scev_ZExt(Op0: m_SCEV(V&: Op))) &&
13172 match(S: RHS, P: m_scev_SExt(Op0: m_scev_Specific(S: Op)));
13173 }
13174 default:
13175 return false;
13176 };
13177 llvm_unreachable("unhandled case");
13178}
13179
13180bool ScalarEvolution::isKnownViaNonRecursiveReasoning(CmpPredicate Pred,
13181 SCEVUse LHS,
13182 SCEVUse RHS) {
13183 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
13184 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
13185 IsKnownPredicateViaMinOrMax(SE&: *this, Pred, LHS, RHS) ||
13186 IsKnownPredicateViaAddRecStart(SE&: *this, Pred, LHS, RHS) ||
13187 IsKnownPredicateViaAddRecMonotonicity(SE&: *this, Pred, LHS, RHS) ||
13188 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
13189}
13190
13191bool ScalarEvolution::isImpliedCondOperandsHelper(CmpPredicate Pred,
13192 const SCEV *LHS,
13193 const SCEV *RHS,
13194 const SCEV *FoundLHS,
13195 const SCEV *FoundRHS) {
13196 switch (Pred) {
13197 default:
13198 llvm_unreachable("Unexpected CmpPredicate value!");
13199 case ICmpInst::ICMP_EQ:
13200 case ICmpInst::ICMP_NE:
13201 if (HasSameValue(A: LHS, B: FoundLHS) && HasSameValue(A: RHS, B: FoundRHS))
13202 return true;
13203 break;
13204 case ICmpInst::ICMP_SLT:
13205 case ICmpInst::ICMP_SLE:
13206 if (isKnownViaNonRecursiveReasoning(Pred: ICmpInst::ICMP_SLE, LHS, RHS: FoundLHS) &&
13207 isKnownViaNonRecursiveReasoning(Pred: ICmpInst::ICMP_SGE, LHS: RHS, RHS: FoundRHS))
13208 return true;
13209 break;
13210 case ICmpInst::ICMP_SGT:
13211 case ICmpInst::ICMP_SGE:
13212 if (isKnownViaNonRecursiveReasoning(Pred: ICmpInst::ICMP_SGE, LHS, RHS: FoundLHS) &&
13213 isKnownViaNonRecursiveReasoning(Pred: ICmpInst::ICMP_SLE, LHS: RHS, RHS: FoundRHS))
13214 return true;
13215 break;
13216 case ICmpInst::ICMP_ULT:
13217 case ICmpInst::ICMP_ULE:
13218 if (isKnownViaNonRecursiveReasoning(Pred: ICmpInst::ICMP_ULE, LHS, RHS: FoundLHS) &&
13219 isKnownViaNonRecursiveReasoning(Pred: ICmpInst::ICMP_UGE, LHS: RHS, RHS: FoundRHS))
13220 return true;
13221 break;
13222 case ICmpInst::ICMP_UGT:
13223 case ICmpInst::ICMP_UGE:
13224 if (isKnownViaNonRecursiveReasoning(Pred: ICmpInst::ICMP_UGE, LHS, RHS: FoundLHS) &&
13225 isKnownViaNonRecursiveReasoning(Pred: ICmpInst::ICMP_ULE, LHS: RHS, RHS: FoundRHS))
13226 return true;
13227 break;
13228 }
13229
13230 // Maybe it can be proved via operations?
13231 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
13232 return true;
13233
13234 return false;
13235}
13236
13237bool ScalarEvolution::isImpliedCondOperandsViaRanges(
13238 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, CmpPredicate FoundPred,
13239 const SCEV *FoundLHS, const SCEV *FoundRHS) {
13240 if (!isa<SCEVConstant>(Val: RHS) || !isa<SCEVConstant>(Val: FoundRHS))
13241 // The restriction on `FoundRHS` be lifted easily -- it exists only to
13242 // reduce the compile time impact of this optimization.
13243 return false;
13244
13245 std::optional<APInt> Addend = computeConstantDifference(More: LHS, Less: FoundLHS);
13246 if (!Addend)
13247 return false;
13248
13249 const APInt &ConstFoundRHS = cast<SCEVConstant>(Val: FoundRHS)->getAPInt();
13250
13251 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
13252 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
13253 ConstantRange FoundLHSRange =
13254 ConstantRange::makeExactICmpRegion(Pred: FoundPred, Other: ConstFoundRHS);
13255
13256 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
13257 ConstantRange LHSRange = FoundLHSRange.add(Other: ConstantRange(*Addend));
13258
13259 // We can also compute the range of values for `LHS` that satisfy the
13260 // consequent, "`LHS` `Pred` `RHS`":
13261 const APInt &ConstRHS = cast<SCEVConstant>(Val: RHS)->getAPInt();
13262 // The antecedent implies the consequent if every value of `LHS` that
13263 // satisfies the antecedent also satisfies the consequent.
13264 return LHSRange.icmp(Pred, Other: ConstRHS);
13265}
13266
13267bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
13268 bool IsSigned, bool Invert) {
13269 assert(isKnownPositive(Stride) && "Positive stride expected!");
13270
13271 unsigned BitWidth = getTypeSizeInBits(Ty: RHS->getType());
13272 const SCEV *One = getOne(Ty: Stride->getType());
13273
13274 if (IsSigned) {
13275 APInt MaxRHS = getRangeMax(S: RHS, /*IsSigned=*/true, Invert);
13276 APInt MaxValue = APInt::getSignedMaxValue(numBits: BitWidth);
13277 APInt MaxStrideMinusOne = getSignedRangeMax(S: getMinusSCEV(LHS: Stride, RHS: One));
13278
13279 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
13280 return (std::move(MaxValue) - MaxStrideMinusOne).slt(RHS: MaxRHS);
13281 }
13282
13283 APInt MaxRHS = getRangeMax(S: RHS, /*IsSigned=*/false, Invert);
13284 APInt MaxValue = APInt::getMaxValue(numBits: BitWidth);
13285 APInt MaxStrideMinusOne = getUnsignedRangeMax(S: getMinusSCEV(LHS: Stride, RHS: One));
13286
13287 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
13288 return (std::move(MaxValue) - MaxStrideMinusOne).ult(RHS: MaxRHS);
13289}
13290
13291const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) {
13292 // umin(N, 1) + floor((N - umin(N, 1)) / D)
13293 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
13294 // expression fixes the case of N=0.
13295 const SCEV *MinNOne = getUMinExpr(LHS: N, RHS: getOne(Ty: N->getType()));
13296 const SCEV *NMinusOne = getMinusSCEV(LHS: N, RHS: MinNOne);
13297 return getAddExpr(LHS: MinNOne, RHS: getUDivExpr(LHS: NMinusOne, RHS: D));
13298}
13299
13300const SCEV *
13301ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, const SCEV *Stride,
13302 const SCEV *End, unsigned BitWidth,
13303 bool IsSigned, bool Invert) {
13304 // The logic in this function assumes we can represent a positive stride.
13305 // If we can't, the backedge-taken count must be zero.
13306 if (IsSigned && BitWidth == 1)
13307 return getZero(Ty: Stride->getType());
13308
13309 // This code below only been closely audited for negative strides in the
13310 // unsigned comparison case, it may be correct for signed comparison, but
13311 // that needs to be established.
13312 if (IsSigned && isKnownNegative(S: Stride))
13313 return getCouldNotCompute();
13314
13315 // Calculate the maximum backedge count based on the range of values
13316 // permitted by Start, End, and Stride. If Invert is true, both Start and End
13317 // need inverting. Stride was already negated by the caller.
13318 APInt MinStart = getRangeMin(S: Start, IsSigned, Invert);
13319
13320 APInt MinStride =
13321 IsSigned ? getSignedRangeMin(S: Stride) : getUnsignedRangeMin(S: Stride);
13322
13323 // We assume either the stride is positive, or the backedge-taken count
13324 // is zero. So force StrideForMaxBECount to be at least one.
13325 APInt One(BitWidth, 1);
13326 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(A: One, B: MinStride)
13327 : APIntOps::umax(A: One, B: MinStride);
13328
13329 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(numBits: BitWidth)
13330 : APInt::getMaxValue(numBits: BitWidth);
13331 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
13332
13333 // Although End can be a MAX expression we estimate MaxEnd considering only
13334 // the case End = RHS of the loop termination condition. This is safe because
13335 // in the other case (End - Start) is zero, leading to a zero maximum backedge
13336 // taken count.
13337 APInt MaxEnd = getRangeMax(S: End, IsSigned, Invert);
13338 MaxEnd =
13339 IsSigned ? APIntOps::smin(A: MaxEnd, B: Limit) : APIntOps::umin(A: MaxEnd, B: Limit);
13340
13341 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
13342 MaxEnd = IsSigned ? APIntOps::smax(A: MaxEnd, B: MinStart)
13343 : APIntOps::umax(A: MaxEnd, B: MinStart);
13344
13345 APInt Delta = MaxEnd - MinStart;
13346
13347 // Try to refine Delta in case End - Start (or Start - End if Invert) gives a
13348 // tighter bound after folding.
13349 const SCEV *DeltaExpr =
13350 Invert ? getMinusSCEV(LHS: Start, RHS: End) : getMinusSCEV(LHS: End, RHS: Start);
13351 Delta = APIntOps::umin(A: Delta, B: getUnsignedRangeMax(S: DeltaExpr));
13352
13353 return getUDivCeilSCEV(N: getConstant(Val: Delta), D: getConstant(Val: StrideForMaxBECount));
13354}
13355
13356ScalarEvolution::ExitLimit
13357ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
13358 const Loop *L, bool IsSigned, bool Invert,
13359 bool ControlsOnlyExit, bool AllowPredicates) {
13360 SmallVector<const SCEVPredicate *> Predicates;
13361
13362 LoopGuards Guards = LoopGuards::collectOnDemand(L, SE&: *this);
13363
13364 // FIXME: Extend the non-invariant RHS analysis to greater-than comparisons.
13365 if (Invert && !isLoopInvariant(S: RHS, L))
13366 return getCouldNotCompute();
13367
13368 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(Val: LHS);
13369 bool PredicatedIV = false;
13370 // FIXME: Generalize the NUW inference below to decreasing IVs.
13371 if (!IV && !Invert) {
13372 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Val: LHS)) {
13373 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Val: ZExt->getOperand());
13374 if (AR && AR->getLoop() == L && AR->isAffine()) {
13375 auto canProveNUW = [&]() {
13376 // We can use the comparison to infer no-wrap flags only if it fully
13377 // controls the loop exit.
13378 if (!ControlsOnlyExit)
13379 return false;
13380
13381 if (!isLoopInvariant(S: RHS, L))
13382 return false;
13383
13384 if (!isKnownNonZero(S: AR->getStepRecurrence(SE&: *this)))
13385 // We need the sequence defined by AR to strictly increase in the
13386 // unsigned integer domain for the logic below to hold.
13387 return false;
13388
13389 const unsigned InnerBitWidth = getTypeSizeInBits(Ty: AR->getType());
13390 const unsigned OuterBitWidth = getTypeSizeInBits(Ty: RHS->getType());
13391 // If RHS <=u Limit, then there must exist a value V in the sequence
13392 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
13393 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
13394 // overflow occurs. This limit also implies that a signed comparison
13395 // (in the wide bitwidth) is equivalent to an unsigned comparison as
13396 // the high bits on both sides must be zero.
13397 APInt StrideMax = getUnsignedRangeMax(S: AR->getStepRecurrence(SE&: *this));
13398 APInt Limit = APInt::getMaxValue(numBits: InnerBitWidth) - (StrideMax - 1);
13399 Limit = Limit.zext(width: OuterBitWidth);
13400 return getUnsignedRangeMax(S: applyLoopGuards(Expr: RHS, Guards)).ule(RHS: Limit);
13401 };
13402 auto Flags = AR->getNoWrapFlags();
13403 if (!hasFlags(Flags, TestFlags: SCEV::FlagNUW) && canProveNUW())
13404 Flags = setFlags(Flags, OnFlags: SCEV::FlagNUW);
13405
13406 setNoWrapFlags(AddRec: const_cast<SCEVAddRecExpr *>(AR), Flags);
13407 if (AR->hasNoUnsignedWrap()) {
13408 // Emulate what getZeroExtendExpr would have done during construction
13409 // if we'd been able to infer the fact just above at that time.
13410 const SCEV *Step = AR->getStepRecurrence(SE&: *this);
13411 Type *Ty = ZExt->getType();
13412 const SCEV *S = getAddRecExpr(
13413 Start: getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, SE: this, Depth: 0),
13414 Step: getZeroExtendExpr(Op: Step, Ty, Depth: 0), L, Flags: AR->getNoWrapFlags());
13415 IV = dyn_cast<SCEVAddRecExpr>(Val: S);
13416 }
13417 }
13418 }
13419 }
13420
13421 if (!IV && AllowPredicates) {
13422 // Try to make this an AddRec using runtime tests, in the first X
13423 // iterations of this loop, where X is the SCEV expression found by the
13424 // algorithm below.
13425 IV = convertSCEVToAddRecWithPredicates(S: LHS, L, Preds&: Predicates);
13426 PredicatedIV = true;
13427 }
13428
13429 // Avoid weird loops
13430 if (!IV || IV->getLoop() != L || !IV->isAffine())
13431 return getCouldNotCompute();
13432
13433 // A precondition of this method is that the condition being analyzed
13434 // reaches an exiting branch which dominates the latch. Given that, we can
13435 // assume that an increment which violates the nowrap specification and
13436 // produces poison must cause undefined behavior when the resulting poison
13437 // value is branched upon and thus we can conclude that the backedge is
13438 // taken no more often than would be required to produce that poison value.
13439 // Note that a well defined loop can exit on the iteration which violates
13440 // the nowrap specification if there is another exit (either explicit or
13441 // implicit/exceptional) which causes the loop to execute before the
13442 // exiting instruction we're analyzing would trigger UB.
13443 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13444 bool NoWrap = ControlsOnlyExit && any(Val: IV->getNoWrapFlags(Mask: WrapType));
13445 // Reverse the ordering for greater-than comparisons.
13446 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
13447 if (Invert)
13448 Cond = ICmpInst::getSwappedPredicate(pred: Cond);
13449
13450 // The step of ~IV is the negated step of IV.
13451 const SCEV *Stride = IV->getStepRecurrence(SE&: *this);
13452 if (Invert)
13453 Stride = getNegativeSCEV(V: Stride);
13454 const SCEV *GuardedStride = Stride;
13455
13456 // Whether the IV may reach the maximum (or minimum if inverted) value
13457 // before the exit is taken.
13458 bool IVMayOverflow = true;
13459
13460 bool PositiveStride = isKnownPositive(S: Stride);
13461 // A dominating guard may prove the stride positive.
13462 if (!PositiveStride) {
13463 const SCEV *LoopGuardedStride = applyLoopGuards(Expr: Stride, Guards);
13464 if (isKnownPositive(S: LoopGuardedStride)) {
13465 GuardedStride = LoopGuardedStride;
13466 PositiveStride = true;
13467 // Encode the context-sensitive stride > 0 fact into the expression
13468 Stride = getUMaxExpr(LHS: Stride, RHS: getOne(Ty: Stride->getType()));
13469 }
13470 }
13471
13472 // Avoid negative or zero stride values.
13473 if (!PositiveStride) {
13474 // FIXME: Generalize the unknown-stride analysis to decreasing IVs.
13475 if (Invert)
13476 return getCouldNotCompute();
13477
13478 // We can compute the correct backedge taken count for loops with unknown
13479 // strides if we can prove that the loop is not an infinite loop with side
13480 // effects. Here's the loop structure we are trying to handle -
13481 //
13482 // i = start
13483 // do {
13484 // A[i] = i;
13485 // i += s;
13486 // } while (i < end);
13487 //
13488 // The backedge taken count for such loops is evaluated as -
13489 // (max(end, start + stride) - start - 1) /u stride
13490 //
13491 // The additional preconditions that we need to check to prove correctness
13492 // of the above formula is as follows -
13493 //
13494 // a) IV is either nuw or nsw depending upon signedness (indicated by the
13495 // NoWrap flag).
13496 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13497 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13498 // no side effects within the loop) or a predicate is added to ensure
13499 // stride is positive.
13500 // c) loop has a single static exit (with no abnormal exits)
13501 //
13502 // Precondition a) implies that if the stride is negative, this is a single
13503 // trip loop. The backedge taken count formula reduces to zero in this case.
13504 //
13505 // Precondition b) and c) combine to imply that if rhs is invariant in L,
13506 // then a zero stride means the backedge can't be taken without executing
13507 // undefined behavior.
13508 //
13509 // The positive stride case is the same as isKnownPositive(Stride) returning
13510 // true (original behavior of the function).
13511 //
13512 if (PredicatedIV || !NoWrap || !loopHasNoAbnormalExits(L))
13513 return getCouldNotCompute();
13514
13515 if (!loopIsFiniteByAssumption(L)) {
13516 // If the loop may be infinite, add a predicate ensuring Stride is
13517 // positive, to guarantee forward progress.
13518 if (!AllowPredicates || !isLoopInvariant(S: Stride, L))
13519 return getCouldNotCompute();
13520
13521 const SCEV *Zero = getZero(Ty: Stride->getType());
13522 const SCEVPredicate *P =
13523 getComparePredicate(Pred: ICmpInst::ICMP_SGT, LHS: Stride, RHS: Zero);
13524 Predicates.push_back(Elt: P);
13525 // When the predicate holds (Stride > 0), umax(Stride, 1) == Stride,
13526 // so the result is unchanged. To prevent div by zero.
13527 Stride = getUMaxExpr(LHS: Stride, RHS: getOne(Ty: Stride->getType()));
13528 } else if (!isKnownNonZero(S: Stride)) {
13529 // If we have a step of zero, and RHS isn't invariant in L, we don't know
13530 // if it might eventually be greater than start and if so, on which
13531 // iteration. We can't even produce a useful upper bound.
13532 if (!isLoopInvariant(S: RHS, L))
13533 return getCouldNotCompute();
13534
13535 // We allow a potentially zero stride, but we need to divide by stride
13536 // below. Since the loop can't be infinite and this check must control
13537 // the sole exit, we can infer the exit must be taken on the first
13538 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
13539 // we know the numerator in the divides below must be zero, so we can
13540 // pick an arbitrary non-zero value for the denominator (e.g. stride)
13541 // and produce the right result.
13542 // FIXME: Handle the case where Stride is poison?
13543 auto wouldZeroStrideBeUB = [&]() {
13544 // Proof by contradiction. Suppose the stride were zero. If we can
13545 // prove that the backedge *is* taken on the first iteration, then since
13546 // we know this condition controls the sole exit, we must have an
13547 // infinite loop. We can't have a (well defined) infinite loop per
13548 // check just above.
13549 // Note: The (Start - Stride) term is used to get the start' term from
13550 // (start' + stride,+,stride). Remember that we only care about the
13551 // result of this expression when stride == 0 at runtime.
13552 auto *StartIfZero = getMinusSCEV(LHS: IV->getStart(), RHS: Stride);
13553 return isLoopEntryGuardedByCond(L, Pred: Cond, LHS: StartIfZero, RHS);
13554 };
13555 if (!wouldZeroStrideBeUB()) {
13556 Stride = getUMaxExpr(LHS: Stride, RHS: getOne(Ty: Stride->getType()));
13557 }
13558 }
13559 } else {
13560 // Avoid proven overflow cases: this will ensure that the backedge taken
13561 // count will not generate any unsigned overflow.
13562 IVMayOverflow = canIVOverflowOnLT(RHS, Stride: GuardedStride, IsSigned, Invert) &&
13563 canIVOverflowOnLT(RHS: applyLoopGuards(Expr: RHS, Guards),
13564 Stride: GuardedStride, IsSigned, Invert);
13565 if (IVMayOverflow && !NoWrap)
13566 return getCouldNotCompute();
13567 }
13568
13569 // On all paths just preceeding, we established the following invariant:
13570 // IV can be assumed not to overflow up to and including the exiting
13571 // iteration. We proved this in one of two ways:
13572 // 1) We can show overflow doesn't occur before the exiting iteration
13573 // 1a) canIVOverflowOnLT, and b) step of one
13574 // 2) We can show that if overflow occurs, the loop must execute UB
13575 // before any possible exit.
13576 // Note that we have not yet proved RHS invariant (in general).
13577
13578 const SCEV *Start = IV->getStart();
13579
13580 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
13581 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
13582 // Use integer-typed versions for actual computation; we can't subtract
13583 // pointers in general.
13584 const SCEV *OrigStart = Start;
13585 const SCEV *OrigRHS = RHS;
13586 if (Start->getType()->isPointerTy()) {
13587 Start = getPtrToAddrExpr(Op: Start);
13588 if (isa<SCEVCouldNotCompute>(Val: Start))
13589 return Start;
13590 }
13591 if (RHS->getType()->isPointerTy()) {
13592 RHS = getPtrToAddrExpr(Op: RHS);
13593 if (isa<SCEVCouldNotCompute>(Val: RHS))
13594 return RHS;
13595 }
13596
13597 const SCEV *End = nullptr, *BECount = getCouldNotCompute(),
13598 *BECountIfBackedgeTaken = getCouldNotCompute();
13599 if (!isLoopInvariant(S: RHS, L)) {
13600 assert(!Invert && "RHS must be loop-invariant for Invert");
13601 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(Val: RHS);
13602 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13603 any(Val: RHSAddRec->getNoWrapFlags())) {
13604 // The structure of loop we are trying to calculate backedge count of:
13605 //
13606 // left = left_start
13607 // right = right_start
13608 //
13609 // while(left < right){
13610 // ... do something here ...
13611 // left += s1; // stride of left is s1 (s1 > 0)
13612 // right += s2; // stride of right is s2 (s2 < 0)
13613 // }
13614 //
13615
13616 const SCEV *RHSStart = RHSAddRec->getStart();
13617 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(SE&: *this);
13618
13619 // If Stride - RHSStride is positive and does not overflow, we can write
13620 // backedge count as ->
13621 // ceil((End - Start) /u (Stride - RHSStride))
13622 // Where, End = max(RHSStart, Start)
13623
13624 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13625 if (isKnownNegative(S: RHSStride) &&
13626 willNotOverflow(BinOp: Instruction::Sub, /*Signed=*/true, LHS: Stride,
13627 RHS: RHSStride)) {
13628
13629 const SCEV *Denominator = getMinusSCEV(LHS: Stride, RHS: RHSStride);
13630 if (isKnownPositive(S: Denominator)) {
13631 End = IsSigned ? getSMaxExpr(LHS: RHSStart, RHS: Start)
13632 : getUMaxExpr(LHS: RHSStart, RHS: Start);
13633
13634 // We can do this because End >= Start, as End = max(RHSStart, Start)
13635 const SCEV *Delta = getMinusSCEV(LHS: End, RHS: Start);
13636
13637 BECount = getUDivCeilSCEV(N: Delta, D: Denominator);
13638 BECountIfBackedgeTaken =
13639 getUDivCeilSCEV(N: getMinusSCEV(LHS: RHSStart, RHS: Start), D: Denominator);
13640 }
13641 }
13642 }
13643 } else {
13644 // Let End = max(RHS,Start). We use the expression (End-Start)/Stride to
13645 // describe the backedge count: if the backedge is taken at least once then
13646 // End is RHS, and if not End is Start so we get a backedge count of zero.
13647 // Inverted, End is min(RHS, Start).
13648 //
13649 // AddingStrideMinusOneMayOverflow has the following preconditions:
13650 //
13651 // 1. Start <= End, signed if IsSigned (inverted: End <= Start)
13652 // 2. The index variable doesn't overflow.
13653 //
13654 // Therefore, we know N exists such that
13655 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13656 // doesn't overflow.
13657 //
13658 // Using this information, try to prove whether the addition in
13659 // "(End - Start) + (Stride - 1)" has unsigned overflow.
13660 //
13661 // If the IV cannot overflow, RHS is at least Stride - 1 below the maximum
13662 // value, so the distance End - Start is at most UMAX - (Stride - 1) and
13663 // the (Stride - 1) addition below cannot overflow.
13664 const SCEV *One = getOne(Ty: Stride->getType());
13665 bool AddingStrideMinusOneMayOverflow = IVMayOverflow && [&] {
13666 if (isKnownToBeAPowerOfTwo(S: Stride)) {
13667 // Suppose Stride is a power of two, and Start/End are unsigned
13668 // integers. Let UMAX be the largest representable unsigned
13669 // integer.
13670 //
13671 // By the preconditions of this function, we know
13672 // "(Start + Stride * N) >= End", and this doesn't overflow.
13673 // As a formula:
13674 //
13675 // End <= (Start + Stride * N) <= UMAX
13676 //
13677 // Subtracting Start from all the terms:
13678 //
13679 // End - Start <= Stride * N <= UMAX - Start
13680 //
13681 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13682 //
13683 // End - Start <= Stride * N <= UMAX
13684 //
13685 // Stride * N is a multiple of Stride. Therefore,
13686 //
13687 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13688 //
13689 // Since Stride is a power of two, UMAX + 1 is divisible by
13690 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13691 // write:
13692 //
13693 // End - Start <= Stride * N <= UMAX - Stride - 1
13694 //
13695 // Dropping the middle term:
13696 //
13697 // End - Start <= UMAX - Stride - 1
13698 //
13699 // Adding Stride - 1 to both sides:
13700 //
13701 // (End - Start) + (Stride - 1) <= UMAX
13702 //
13703 // In other words, the addition doesn't have unsigned overflow.
13704 //
13705 // A similar proof works if we treat Start/End as signed values.
13706 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13707 // to use signed max instead of unsigned max. Note that we're
13708 // trying to prove a lack of unsigned overflow in either case.
13709 // Inverted: "Start - End <= Stride * N <= Start - MIN <= UMAX", same.
13710 return false;
13711 }
13712 if (!Invert && (Start == Stride || Start == getMinusSCEV(LHS: Stride, RHS: One))) {
13713 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13714 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13715 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13716 // 1 <s End.
13717 //
13718 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13719 // End.
13720 //
13721 // Both need Start to be the smaller value, so neither applies inverted.
13722 return false;
13723 }
13724 return true;
13725 }();
13726
13727 // If inverted, the analyzed values are complements: "~V - Offset" is "~(V +
13728 // Offset)" and "~To - ~From" is "From - To".
13729 auto StepBack = [&](const SCEV *V, const SCEV *Offset) -> const SCEV * {
13730 if (Invert)
13731 return getAddExpr(LHS: V, RHS: Offset);
13732 return getMinusSCEV(LHS: V, RHS: Offset);
13733 };
13734 auto Distance = [&](const SCEV *From, const SCEV *To) {
13735 return Invert ? getMinusSCEV(LHS: From, RHS: To) : getMinusSCEV(LHS: To, RHS: From);
13736 };
13737
13738 const SCEV *OrigPrevStart = StepBack(OrigStart, Stride);
13739 assert(isAvailableAtLoopEntry(OrigPrevStart, L) && "Must be!");
13740 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13741 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13742 // Can we prove Start - Stride < RHS, and either Start - Stride < Start or
13743 // (via !AddingStrideMinusOneMayOverflow) that (RHS - Start) + (Stride - 1)
13744 // does not overflow?
13745 if ((!AddingStrideMinusOneMayOverflow ||
13746 isLoopEntryGuardedByCond(L, Pred: Cond, LHS: OrigPrevStart, RHS: OrigStart)) &&
13747 isLoopEntryGuardedByCond(L, Pred: Cond, LHS: OrigPrevStart, RHS: OrigRHS)) {
13748 // In this case, we can use a refined formula for computing backedge
13749 // taken count. The general formula remains:
13750 // "End-Start /uceiling Stride"
13751 // We want to use the alternate formula:
13752 // "((RHS - 1) - (Start - Stride)) /u Stride"
13753 // Let's do a quick case analysis to show these are equivalent under
13754 // our preconditions. When inverted, the proof uses complemented Start,
13755 // RHS and End; Stride remains positive.
13756 // * For RHS <= Start (End is Start), the backedge-taken count must be
13757 // zero. Together with the precondition "Start - Stride < RHS", we have
13758 // "Start - Stride < RHS <= Start". Subtracting Start - Stride from
13759 // all sides we get "0 < RHS - (Start - Stride) <= Stride".
13760 // Subtracting 1 we get "0 <= (RHS - 1) - (Start - Stride) < Stride".
13761 // So dividing that by Stride gives zero.
13762 //
13763 // * For RHS > Start (End is RHS), the backedge count must be
13764 // "RHS-Start /uceil Stride", so it is sufficient to show that the
13765 // numerator "((RHS - 1) - (Start - Stride))" does not overflow.
13766 //
13767 // If "Start - Stride < Start" holds, we have
13768 // "RHS > Start > Start - Stride". As such
13769 // "RHS - (Start - Stride) - 1" does not overflow, which is the
13770 // reassociated numerator.
13771 //
13772 // Otherwise !AddingStrideMinusOneMayOverflow guarantees that
13773 // "(End - Start) + (Stride - 1)" does not overflow unsigned. Here
13774 // "End" is "RHS", as "RHS > Start", so this is the reassociated
13775 // numerator. Neither sub-term wraps unsigned: "RHS - Start"
13776 // due to "RHS > Start", and "Stride - 1", as Stride is non-zero.
13777 const SCEV *Numerator =
13778 getMinusSCEV(LHS: Distance(StepBack(Start, Stride), RHS), RHS: One);
13779 BECount = getUDivExpr(LHS: Numerator, RHS: Stride);
13780 }
13781
13782 if (isa<SCEVCouldNotCompute>(Val: BECount)) {
13783 auto canProveRHSIsAtOrBeyondStart = [&]() {
13784 // Inverted, the claim is "Start >= RHS". Reverse the comparisons below
13785 // by swapping their operands rather than their predicates:
13786 // isLoopEntryGuardedByCond is sensitive to operand order and loses the
13787 // proof if the IV bound moves to the other side.
13788 auto SwapIfInverted = [&](const SCEV *A, const SCEV *B) {
13789 return Invert ? std::pair(B, A) : std::pair(A, B);
13790 };
13791
13792 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13793 const SCEV *GuardedRHS = applyLoopGuards(Expr: OrigRHS, Guards);
13794 const SCEV *GuardedStart = applyLoopGuards(Expr: OrigStart, Guards);
13795 if (Invert)
13796 std::swap(a&: GuardedRHS, b&: GuardedStart);
13797
13798 auto [GELHS, GERHS] = SwapIfInverted(OrigRHS, OrigStart);
13799 if (isLoopEntryGuardedByCond(L, Pred: CondGE, LHS: GELHS, RHS: GERHS) ||
13800 isKnownPredicate(Pred: CondGE, LHS: GuardedRHS, RHS: GuardedStart))
13801 return true;
13802
13803 // (RHS > Start - 1) implies RHS >= Start.
13804 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13805 // "Start - 1" doesn't overflow.
13806 // * For signed comparison, if Start - 1 does overflow, it's equal
13807 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13808 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13809 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13810 //
13811 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13812 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13813 auto [GTLHS, GTRHS] = SwapIfInverted(OrigRHS, StepBack(OrigStart, One));
13814 return isLoopEntryGuardedByCond(L, Pred: CondGT, LHS: GTLHS, RHS: GTRHS);
13815 };
13816
13817 // If we know that RHS >= Start in the context of loop, then we know
13818 // that max(RHS, Start) = RHS at this point.
13819 if (canProveRHSIsAtOrBeyondStart()) {
13820 End = RHS;
13821 } else {
13822 // If RHS < Start, the backedge will be taken zero times. So in
13823 // general, we can write the backedge-taken count as:
13824 //
13825 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13826 //
13827 // We convert it to the following to make it more convenient for SCEV:
13828 //
13829 // ceil(max(RHS, Start) - Start) / Stride
13830 //
13831 // Inverted, this is ceil(Start - min(RHS, Start)) / Stride.
13832 if (Invert)
13833 End = IsSigned ? getSMinExpr(LHS: RHS, RHS: Start) : getUMinExpr(LHS: RHS, RHS: Start);
13834 else
13835 End = IsSigned ? getSMaxExpr(LHS: RHS, RHS: Start) : getUMaxExpr(LHS: RHS, RHS: Start);
13836
13837 // See what would happen if we assume the backedge is taken. This is
13838 // used to compute MaxBECount.
13839 BECountIfBackedgeTaken = getUDivCeilSCEV(N: Distance(Start, RHS), D: Stride);
13840 }
13841
13842 const SCEV *Delta = Distance(Start, End);
13843 if (!AddingStrideMinusOneMayOverflow) {
13844 // floor((D + (S - 1)) / S)
13845 // We prefer this formulation if it's legal because it's fewer
13846 // operations.
13847 BECount =
13848 getUDivExpr(LHS: getAddExpr(LHS: Delta, RHS: getMinusSCEV(LHS: Stride, RHS: One)), RHS: Stride);
13849 } else {
13850 BECount = getUDivCeilSCEV(N: Delta, D: Stride);
13851 }
13852 }
13853 }
13854
13855 const SCEV *ConstantMaxBECount;
13856 bool MaxOrZero = false;
13857 if (isa<SCEVConstant>(Val: BECount)) {
13858 ConstantMaxBECount = BECount;
13859 } else {
13860 ConstantMaxBECount = computeMaxBECountForLT(
13861 Start, Stride, End: RHS, BitWidth: getTypeSizeInBits(Ty: LHS->getType()), IsSigned,
13862 Invert);
13863 // If we know exactly how many times the backedge will be taken if it's
13864 // taken at least once, then the backedge count will either be that or
13865 // zero. If that count exceeds the range-based bound, the backedge can
13866 // never be taken.
13867 const APInt *IfTaken, *RangeMax;
13868 if (match(S: BECountIfBackedgeTaken, P: m_scev_APInt(C&: IfTaken))) {
13869 if (match(S: ConstantMaxBECount, P: m_scev_APInt(C&: RangeMax)) &&
13870 IfTaken->ugt(RHS: *RangeMax)) {
13871 ConstantMaxBECount = getZero(Ty: BECountIfBackedgeTaken->getType());
13872 } else {
13873 ConstantMaxBECount = BECountIfBackedgeTaken;
13874 MaxOrZero = true;
13875 }
13876 }
13877 }
13878
13879 if (isa<SCEVCouldNotCompute>(Val: ConstantMaxBECount) &&
13880 !isa<SCEVCouldNotCompute>(Val: BECount))
13881 ConstantMaxBECount = getConstant(Val: getUnsignedRangeMax(S: BECount));
13882
13883 const SCEV *SymbolicMaxBECount =
13884 isa<SCEVCouldNotCompute>(Val: BECount) ? ConstantMaxBECount : BECount;
13885 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13886 Predicates);
13887}
13888
13889const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
13890 ScalarEvolution &SE) const {
13891 if (Range.isFullSet()) // Infinite loop.
13892 return SE.getCouldNotCompute();
13893
13894 // If the start is a non-zero constant, shift the range to simplify things.
13895 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Val: getStart()))
13896 if (!SC->getValue()->isZero()) {
13897 SmallVector<SCEVUse, 4> Operands(operands());
13898 Operands[0] = SE.getZero(Ty: SC->getType());
13899 const SCEV *Shifted = SE.getAddRecExpr(Operands, L: getLoop(),
13900 NWFlags: getNoWrapFlags(Mask: FlagNW));
13901 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Val: Shifted))
13902 return ShiftedAddRec->getNumIterationsInRange(
13903 Range: Range.subtract(CI: SC->getAPInt()), SE);
13904 // This is strange and shouldn't happen.
13905 return SE.getCouldNotCompute();
13906 }
13907
13908 // The only time we can solve this is when we have all constant indices.
13909 // Otherwise, we cannot determine the overflow conditions.
13910 if (!all_of(Range: operands(), P: IsaPred<SCEVConstant>))
13911 return SE.getCouldNotCompute();
13912
13913 // Okay at this point we know that all elements of the chrec are constants and
13914 // that the start element is zero.
13915
13916 // First check to see if the range contains zero. If not, the first
13917 // iteration exits.
13918 unsigned BitWidth = SE.getTypeSizeInBits(Ty: getType());
13919 if (!Range.contains(Val: APInt(BitWidth, 0)))
13920 return SE.getZero(Ty: getType());
13921
13922 if (isAffine()) {
13923 // If this is an affine expression then we have this situation:
13924 // Solve {0,+,A} in Range === Ax in Range
13925
13926 // We know that zero is in the range. If A is positive then we know that
13927 // the upper value of the range must be the first possible exit value.
13928 // If A is negative then the lower of the range is the last possible loop
13929 // value. Also note that we already checked for a full range.
13930 APInt A = cast<SCEVConstant>(Val: getOperand(i: 1))->getAPInt();
13931 APInt End = A.sge(RHS: 1) ? (Range.getUpper() - 1) : Range.getLower();
13932
13933 // The exit value should be (End+A)/A.
13934 APInt ExitVal = (End + A).udiv(RHS: A);
13935 ConstantInt *ExitValue = ConstantInt::get(Context&: SE.getContext(), V: ExitVal);
13936
13937 // Evaluate at the exit value. If we really did fall out of the valid
13938 // range, then we computed our trip count, otherwise wrap around or other
13939 // things must have happened.
13940 ConstantInt *Val = EvaluateConstantChrecAtConstant(AddRec: this, C: ExitValue, SE);
13941 if (Range.contains(Val: Val->getValue()))
13942 return SE.getCouldNotCompute(); // Something strange happened
13943
13944 // Ensure that the previous value is in the range.
13945 assert(Range.contains(
13946 EvaluateConstantChrecAtConstant(this,
13947 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
13948 "Linear scev computation is off in a bad way!");
13949 return SE.getConstant(V: ExitValue);
13950 }
13951
13952 if (isQuadratic()) {
13953 if (auto S = SolveQuadraticAddRecRange(AddRec: this, Range, SE))
13954 return SE.getConstant(Val: *S);
13955 }
13956
13957 return SE.getCouldNotCompute();
13958}
13959
13960const SCEVAddRecExpr *
13961SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
13962 assert(getNumOperands() > 1 && "AddRec with zero step?");
13963 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
13964 // but in this case we cannot guarantee that the value returned will be an
13965 // AddRec because SCEV does not have a fixed point where it stops
13966 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
13967 // may happen if we reach arithmetic depth limit while simplifying. So we
13968 // construct the returned value explicitly.
13969 SmallVector<SCEVUse, 3> Ops;
13970 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
13971 // (this + Step) is {A+B,+,B+C,+...,+,N}.
13972 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
13973 Ops.push_back(Elt: SE.getAddExpr(LHS: getOperand(i), RHS: getOperand(i: i + 1)));
13974 // We know that the last operand is not a constant zero (otherwise it would
13975 // have been popped out earlier). This guarantees us that if the result has
13976 // the same last operand, then it will also not be popped out, meaning that
13977 // the returned value will be an AddRec.
13978 const SCEV *Last = getOperand(i: getNumOperands() - 1);
13979 assert(!Last->isZero() && "Recurrency with zero step?");
13980 Ops.push_back(Elt: Last);
13981 return cast<SCEVAddRecExpr>(Val: SE.getAddRecExpr(Operands&: Ops, L: getLoop(), NWFlags: SCEV::FlagNone));
13982}
13983
13984// Return true when S contains at least an undef value.
13985bool ScalarEvolution::containsUndefs(const SCEV *S) const {
13986 return SCEVExprContains(
13987 Root: S, Pred: [](const SCEV *S) { return match(S, P: m_scev_UndefOrPoison()); });
13988}
13989
13990// Return true when S contains a value that is a nullptr.
13991bool ScalarEvolution::containsErasedValue(const SCEV *S) const {
13992 return SCEVExprContains(Root: S, Pred: [](const SCEV *S) {
13993 if (const auto *SU = dyn_cast<SCEVUnknown>(Val: S))
13994 return SU->getValue() == nullptr;
13995 return false;
13996 });
13997}
13998
13999/// Return the size of an element read or written by Inst.
14000const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
14001 if (!isa<LoadInst, StoreInst>(Val: Inst))
14002 return nullptr;
14003 Type *ETy = getEffectiveSCEVType(Ty: getLoadStorePointerOperand(V: Inst)->getType());
14004 return getSizeOfExpr(IntTy: ETy, AllocTy: getLoadStoreType(I: Inst));
14005}
14006
14007//===----------------------------------------------------------------------===//
14008// SCEVCallbackVH Class Implementation
14009//===----------------------------------------------------------------------===//
14010
14011void ScalarEvolution::SCEVCallbackVH::deleted() {
14012 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14013 if (PHINode *PN = dyn_cast<PHINode>(Val: getValPtr()))
14014 SE->ConstantEvolutionLoopExitValue.erase(Val: PN);
14015 SE->eraseValueFromMap(V: getValPtr());
14016 // this now dangles!
14017}
14018
14019void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
14020 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14021
14022 // Forget all the expressions associated with users of the old value,
14023 // so that future queries will recompute the expressions using the new
14024 // value.
14025 SE->forgetValue(V: getValPtr());
14026 // this now dangles!
14027}
14028
14029ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
14030 : CallbackVH(V), SE(se) {}
14031
14032//===----------------------------------------------------------------------===//
14033// ScalarEvolution Class Implementation
14034//===----------------------------------------------------------------------===//
14035
14036ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
14037 AssumptionCache &AC, DominatorTree &DT,
14038 LoopInfo &LI)
14039 : F(F), DL(F.getDataLayout()), TLI(TLI), AC(AC), DT(DT), LI(LI),
14040 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
14041 LoopDispositions(64), BlockDispositions(64) {
14042 // To use guards for proving predicates, we need to scan every instruction in
14043 // relevant basic blocks, and not just terminators. Doing this is a waste of
14044 // time if the IR does not actually contain any calls to
14045 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
14046 //
14047 // This pessimizes the case where a pass that preserves ScalarEvolution wants
14048 // to _add_ guards to the module when there weren't any before, and wants
14049 // ScalarEvolution to optimize based on those guards. For now we prefer to be
14050 // efficient in lieu of being smart in that rather obscure case.
14051
14052 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
14053 M: F.getParent(), id: Intrinsic::experimental_guard);
14054 HasGuards = GuardDecl && !GuardDecl->use_empty();
14055}
14056
14057ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
14058 : F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC),
14059 DT(Arg.DT), LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
14060 ValueExprMap(std::move(Arg.ValueExprMap)),
14061 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
14062 PendingMerges(std::move(Arg.PendingMerges)),
14063 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
14064 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
14065 PredicatedBackedgeTakenCounts(
14066 std::move(Arg.PredicatedBackedgeTakenCounts)),
14067 BECountUsers(std::move(Arg.BECountUsers)),
14068 ConstantEvolutionLoopExitValue(
14069 std::move(Arg.ConstantEvolutionLoopExitValue)),
14070 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
14071 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
14072 LoopDispositions(std::move(Arg.LoopDispositions)),
14073 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
14074 BlockDispositions(std::move(Arg.BlockDispositions)),
14075 SCEVUsers(std::move(Arg.SCEVUsers)),
14076 UnsignedRanges(std::move(Arg.UnsignedRanges)),
14077 SignedRanges(std::move(Arg.SignedRanges)),
14078 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
14079 UniquePreds(std::move(Arg.UniquePreds)),
14080 SCEVAllocator(std::move(Arg.SCEVAllocator)),
14081 ConstantSCEVs(std::move(Arg.ConstantSCEVs)),
14082 LoopUsers(std::move(Arg.LoopUsers)),
14083 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
14084 FirstUnknown(Arg.FirstUnknown),
14085 NextUnknownOrderID(Arg.NextUnknownOrderID) {
14086 Arg.FirstUnknown = nullptr;
14087}
14088
14089ScalarEvolution::~ScalarEvolution() {
14090 // Iterate through all the SCEVUnknown instances and call their
14091 // destructors, so that they release their references to their values.
14092 for (SCEVUnknown *U = FirstUnknown; U;) {
14093 SCEVUnknown *Tmp = U;
14094 U = U->Next;
14095 Tmp->~SCEVUnknown();
14096 }
14097 FirstUnknown = nullptr;
14098
14099 ExprValueMap.clear();
14100 ValueExprMap.clear();
14101 HasRecMap.clear();
14102 BackedgeTakenCounts.clear();
14103 PredicatedBackedgeTakenCounts.clear();
14104
14105 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
14106 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
14107 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
14108 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
14109}
14110
14111bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
14112 return !isa<SCEVCouldNotCompute>(Val: getBackedgeTakenCount(L));
14113}
14114
14115/// When printing a top-level SCEV for trip counts, it's helpful to include
14116/// a type for constants which are otherwise hard to disambiguate.
14117static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
14118 if (isa<SCEVConstant>(Val: S))
14119 OS << *S->getType() << " ";
14120 OS << *S;
14121}
14122
14123static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
14124 const Loop *L) {
14125 // Print all inner loops first
14126 for (Loop *I : *L)
14127 PrintLoopInfo(OS, SE, L: I);
14128
14129 OS << "Loop ";
14130 L->getHeader()->printAsOperand(O&: OS, /*PrintType=*/false);
14131 OS << ": ";
14132
14133 SmallVector<BasicBlock *, 8> ExitingBlocks;
14134 L->getExitingBlocks(ExitingBlocks);
14135 if (ExitingBlocks.size() != 1)
14136 OS << "<multiple exits> ";
14137
14138 auto *BTC = SE->getBackedgeTakenCount(L);
14139 if (!isa<SCEVCouldNotCompute>(Val: BTC)) {
14140 OS << "backedge-taken count is ";
14141 PrintSCEVWithTypeHint(OS, S: BTC);
14142 } else
14143 OS << "Unpredictable backedge-taken count.";
14144 OS << "\n";
14145
14146 if (ExitingBlocks.size() > 1)
14147 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14148 OS << " exit count for " << ExitingBlock->getName() << ": ";
14149 const SCEV *EC = SE->getExitCount(L, ExitingBlock);
14150 PrintSCEVWithTypeHint(OS, S: EC);
14151 if (isa<SCEVCouldNotCompute>(Val: EC)) {
14152 // Retry with predicates.
14153 SmallVector<const SCEVPredicate *> Predicates;
14154 EC = SE->getPredicatedExitCount(L, ExitingBlock, Predicates: &Predicates);
14155 if (!isa<SCEVCouldNotCompute>(Val: EC)) {
14156 OS << "\n predicated exit count for " << ExitingBlock->getName()
14157 << ": ";
14158 PrintSCEVWithTypeHint(OS, S: EC);
14159 OS << "\n Predicates:\n";
14160 for (const auto *P : Predicates)
14161 P->print(OS, Depth: 4);
14162 }
14163 }
14164 OS << "\n";
14165 }
14166
14167 OS << "Loop ";
14168 L->getHeader()->printAsOperand(O&: OS, /*PrintType=*/false);
14169 OS << ": ";
14170
14171 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
14172 if (!isa<SCEVCouldNotCompute>(Val: ConstantBTC)) {
14173 OS << "constant max backedge-taken count is ";
14174 PrintSCEVWithTypeHint(OS, S: ConstantBTC);
14175 if (SE->isBackedgeTakenCountMaxOrZero(L))
14176 OS << ", actual taken count either this or zero.";
14177 } else {
14178 OS << "Unpredictable constant max backedge-taken count. ";
14179 }
14180
14181 OS << "\n"
14182 "Loop ";
14183 L->getHeader()->printAsOperand(O&: OS, /*PrintType=*/false);
14184 OS << ": ";
14185
14186 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
14187 if (!isa<SCEVCouldNotCompute>(Val: SymbolicBTC)) {
14188 OS << "symbolic max backedge-taken count is ";
14189 PrintSCEVWithTypeHint(OS, S: SymbolicBTC);
14190 if (SE->isBackedgeTakenCountMaxOrZero(L))
14191 OS << ", actual taken count either this or zero.";
14192 } else {
14193 OS << "Unpredictable symbolic max backedge-taken count. ";
14194 }
14195 OS << "\n";
14196
14197 if (ExitingBlocks.size() > 1)
14198 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14199 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
14200 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
14201 Kind: ScalarEvolution::SymbolicMaximum);
14202 PrintSCEVWithTypeHint(OS, S: ExitBTC);
14203 if (isa<SCEVCouldNotCompute>(Val: ExitBTC)) {
14204 // Retry with predicates.
14205 SmallVector<const SCEVPredicate *> Predicates;
14206 ExitBTC = SE->getPredicatedExitCount(L, ExitingBlock, Predicates: &Predicates,
14207 Kind: ScalarEvolution::SymbolicMaximum);
14208 if (!isa<SCEVCouldNotCompute>(Val: ExitBTC)) {
14209 OS << "\n predicated symbolic max exit count for "
14210 << ExitingBlock->getName() << ": ";
14211 PrintSCEVWithTypeHint(OS, S: ExitBTC);
14212 OS << "\n Predicates:\n";
14213 for (const auto *P : Predicates)
14214 P->print(OS, Depth: 4);
14215 }
14216 }
14217 OS << "\n";
14218 }
14219
14220 SmallVector<const SCEVPredicate *, 4> Preds;
14221 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
14222 if (PBT != BTC) {
14223 OS << "Loop ";
14224 L->getHeader()->printAsOperand(O&: OS, /*PrintType=*/false);
14225 OS << ": ";
14226 if (!isa<SCEVCouldNotCompute>(Val: PBT)) {
14227 OS << "Predicated backedge-taken count is ";
14228 PrintSCEVWithTypeHint(OS, S: PBT);
14229 } else
14230 OS << "Unpredictable predicated backedge-taken count.";
14231 OS << "\n";
14232 OS << " Predicates:\n";
14233 for (const auto *P : Preds)
14234 P->print(OS, Depth: 4);
14235 }
14236 Preds.clear();
14237
14238 auto *PredConstantMax =
14239 SE->getPredicatedConstantMaxBackedgeTakenCount(L, Preds);
14240 if (PredConstantMax != ConstantBTC) {
14241 OS << "Loop ";
14242 L->getHeader()->printAsOperand(O&: OS, /*PrintType=*/false);
14243 OS << ": ";
14244 if (!isa<SCEVCouldNotCompute>(Val: PredConstantMax)) {
14245 OS << "Predicated constant max backedge-taken count is ";
14246 PrintSCEVWithTypeHint(OS, S: PredConstantMax);
14247 } else
14248 OS << "Unpredictable predicated constant max backedge-taken count.";
14249 OS << "\n";
14250 OS << " Predicates:\n";
14251 for (const auto *P : Preds)
14252 P->print(OS, Depth: 4);
14253 }
14254 Preds.clear();
14255
14256 auto *PredSymbolicMax =
14257 SE->getPredicatedSymbolicMaxBackedgeTakenCount(L, Preds);
14258 if (SymbolicBTC != PredSymbolicMax) {
14259 OS << "Loop ";
14260 L->getHeader()->printAsOperand(O&: OS, /*PrintType=*/false);
14261 OS << ": ";
14262 if (!isa<SCEVCouldNotCompute>(Val: PredSymbolicMax)) {
14263 OS << "Predicated symbolic max backedge-taken count is ";
14264 PrintSCEVWithTypeHint(OS, S: PredSymbolicMax);
14265 } else
14266 OS << "Unpredictable predicated symbolic max backedge-taken count.";
14267 OS << "\n";
14268 OS << " Predicates:\n";
14269 for (const auto *P : Preds)
14270 P->print(OS, Depth: 4);
14271 }
14272
14273 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
14274 OS << "Loop ";
14275 L->getHeader()->printAsOperand(O&: OS, /*PrintType=*/false);
14276 OS << ": ";
14277 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
14278 }
14279}
14280
14281namespace llvm {
14282// Note: these overloaded operators need to be in the llvm namespace for them
14283// to be resolved correctly. If we put them outside the llvm namespace, the
14284//
14285// OS << ": " << SE.getLoopDisposition(SV, InnerL);
14286//
14287// code below "breaks" and start printing raw enum values as opposed to the
14288// string values.
14289static raw_ostream &operator<<(raw_ostream &OS,
14290 ScalarEvolution::LoopDisposition LD) {
14291 switch (LD) {
14292 case ScalarEvolution::LoopVariant:
14293 OS << "Variant";
14294 break;
14295 case ScalarEvolution::LoopInvariant:
14296 OS << "Invariant";
14297 break;
14298 case ScalarEvolution::LoopUniform:
14299 OS << "Uniform";
14300 break;
14301 case ScalarEvolution::LoopComputable:
14302 OS << "Computable";
14303 break;
14304 }
14305 return OS;
14306}
14307
14308static raw_ostream &operator<<(raw_ostream &OS,
14309 llvm::ScalarEvolution::BlockDisposition BD) {
14310 switch (BD) {
14311 case ScalarEvolution::DoesNotDominateBlock:
14312 OS << "DoesNotDominate";
14313 break;
14314 case ScalarEvolution::DominatesBlock:
14315 OS << "Dominates";
14316 break;
14317 case ScalarEvolution::ProperlyDominatesBlock:
14318 OS << "ProperlyDominates";
14319 break;
14320 }
14321 return OS;
14322}
14323} // namespace llvm
14324
14325void ScalarEvolution::print(raw_ostream &OS) const {
14326 // ScalarEvolution's implementation of the print method is to print
14327 // out SCEV values of all instructions that are interesting. Doing
14328 // this potentially causes it to create new SCEV objects though,
14329 // which technically conflicts with the const qualifier. This isn't
14330 // observable from outside the class though, so casting away the
14331 // const isn't dangerous.
14332 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14333
14334 if (ClassifyExpressions) {
14335 OS << "Classifying expressions for: ";
14336 F.printAsOperand(O&: OS, /*PrintType=*/false);
14337 OS << "\n";
14338 for (Instruction &I : instructions(F))
14339 if (isSCEVable(Ty: I.getType()) && !isa<CmpInst>(Val: I)) {
14340 OS << I << '\n';
14341 OS << " --> ";
14342 const SCEV *SV = SE.getSCEV(V: &I);
14343 SV->print(OS);
14344 if (!isa<SCEVCouldNotCompute>(Val: SV)) {
14345 OS << " U: ";
14346 SE.getUnsignedRange(S: SV).print(OS);
14347 OS << " S: ";
14348 SE.getSignedRange(S: SV).print(OS);
14349 }
14350
14351 const Loop *L = LI.getLoopFor(BB: I.getParent());
14352
14353 SCEVUse AtUse = SE.getSCEVAtScope(V: SV, L);
14354 if (AtUse != SV) {
14355 OS << " --> ";
14356 OS << AtUse;
14357 if (!isa<SCEVCouldNotCompute>(Val: AtUse)) {
14358 OS << " U: ";
14359 SE.getUnsignedRange(S: AtUse).print(OS);
14360 OS << " S: ";
14361 SE.getSignedRange(S: AtUse).print(OS);
14362 }
14363 }
14364
14365 if (L) {
14366 OS << "\t\t" "Exits: ";
14367 SCEVUse ExitValue = SE.getSCEVAtScope(V: SV, L: L->getParentLoop());
14368 if (!SE.isLoopInvariant(S: ExitValue, L)) {
14369 OS << "<<Unknown>>";
14370 } else {
14371 OS << ExitValue;
14372 }
14373
14374 ListSeparator LS(", ", "\t\tLoopDispositions: { ");
14375 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
14376 OS << LS;
14377 Iter->getHeader()->printAsOperand(O&: OS, /*PrintType=*/false);
14378 OS << ": " << SE.getLoopDisposition(S: SV, L: Iter);
14379 }
14380
14381 for (const auto *InnerL : depth_first(G: L)) {
14382 if (InnerL == L)
14383 continue;
14384 OS << LS;
14385 InnerL->getHeader()->printAsOperand(O&: OS, /*PrintType=*/false);
14386 OS << ": " << SE.getLoopDisposition(S: SV, L: InnerL);
14387 }
14388
14389 OS << " }";
14390 }
14391
14392 OS << "\n";
14393 }
14394 }
14395
14396 OS << "Determining loop execution counts for: ";
14397 F.printAsOperand(O&: OS, /*PrintType=*/false);
14398 OS << "\n";
14399 for (Loop *I : LI)
14400 PrintLoopInfo(OS, SE: &SE, L: I);
14401}
14402
14403ScalarEvolution::LoopDisposition
14404ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
14405 if (isa<SCEVConstant>(Val: S))
14406 return LoopInvariant;
14407
14408 auto &Values = LoopDispositions[S];
14409 for (auto &V : Values) {
14410 if (V.getPointer() == L)
14411 return V.getInt();
14412 }
14413 Values.emplace_back(Args&: L, Args: LoopVariant);
14414 LoopDisposition D = computeLoopDisposition(S, L);
14415 auto &Values2 = LoopDispositions[S];
14416 for (auto &V : llvm::reverse(C&: Values2)) {
14417 if (V.getPointer() == L) {
14418 V.setInt(D);
14419 break;
14420 }
14421 }
14422 return D;
14423}
14424
14425ScalarEvolution::LoopDisposition
14426ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
14427 switch (S->getSCEVType()) {
14428 case scConstant:
14429 case scVScale:
14430 return LoopInvariant;
14431 case scAddRecExpr: {
14432 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(Val: S);
14433
14434 // If L is the addrec's loop, it's computable.
14435 if (AR->getLoop() == L)
14436 return LoopComputable;
14437
14438 // Add recurrences are never invariant in the function-body (null loop).
14439 if (!L)
14440 return LoopVariant;
14441
14442 // Everything that is not defined at loop entry is variant.
14443 if (DT.dominates(A: L->getHeader(), B: AR->getLoop()->getHeader())) {
14444 if (L->contains(L: AR->getLoop()) &&
14445 llvm::all_of(Range: AR->operands(),
14446 P: [&](const SCEV *Op) { return isLoopUniform(S: Op, L); }))
14447 return LoopUniform;
14448
14449 return LoopVariant;
14450 }
14451 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
14452 " dominate the contained loop's header?");
14453
14454 // This recurrence is invariant w.r.t. L if AR's loop contains L.
14455 if (AR->getLoop()->contains(L))
14456 return LoopInvariant;
14457
14458 // This recurrence is variant w.r.t. L if any of its operands
14459 // are variant.
14460 for (SCEVUse Op : AR->operands())
14461 if (!isLoopInvariant(S: Op, L))
14462 return LoopVariant;
14463
14464 // Otherwise it's loop-invariant.
14465 return LoopInvariant;
14466 }
14467 case scTruncate:
14468 case scZeroExtend:
14469 case scSignExtend:
14470 case scPtrToAddr:
14471 case scAddExpr:
14472 case scMulExpr:
14473 case scUDivExpr:
14474 case scUMaxExpr:
14475 case scSMaxExpr:
14476 case scUMinExpr:
14477 case scSMinExpr:
14478 case scSequentialUMinExpr: {
14479 bool HasVarying = false;
14480 bool HasUniform = false;
14481 for (SCEVUse Op : S->operands()) {
14482 LoopDisposition D = getLoopDisposition(S: Op, L);
14483 if (D == LoopVariant)
14484 return LoopVariant;
14485 if (D == LoopComputable)
14486 HasVarying = true;
14487 if (D == LoopUniform)
14488 HasUniform = true;
14489 }
14490 return HasVarying ? (HasUniform ? LoopVariant : LoopComputable)
14491 : (HasUniform ? LoopUniform : LoopInvariant);
14492 }
14493 case scUnknown:
14494 // All non-instruction values are loop invariant. All instructions are loop
14495 // invariant if they are not contained in the specified loop.
14496 // Instructions are never considered invariant in the function body
14497 // (null loop) because they are defined within the "loop".
14498 if (auto *I = dyn_cast<Instruction>(Val: cast<SCEVUnknown>(Val: S)->getValue()))
14499 return (L && !L->contains(Inst: I)) ? LoopInvariant : LoopVariant;
14500 return LoopInvariant;
14501 case scCouldNotCompute:
14502 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14503 }
14504 llvm_unreachable("Unknown SCEV kind!");
14505}
14506
14507bool ScalarEvolution::isLoopUniform(const SCEV *S, const Loop *L) {
14508 LoopDisposition D = getLoopDisposition(S, L);
14509 return D == LoopUniform || D == LoopInvariant;
14510}
14511
14512bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
14513 return getLoopDisposition(S, L) == LoopInvariant;
14514}
14515
14516bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
14517 return getLoopDisposition(S, L) == LoopComputable;
14518}
14519
14520ScalarEvolution::BlockDisposition
14521ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14522 if (isa<SCEVConstant>(Val: S))
14523 return ProperlyDominatesBlock;
14524
14525 auto &Values = BlockDispositions[S];
14526 for (auto &V : Values) {
14527 if (V.getPointer() == BB)
14528 return V.getInt();
14529 }
14530 Values.emplace_back(Args&: BB, Args: DoesNotDominateBlock);
14531 BlockDisposition D = computeBlockDisposition(S, BB);
14532 auto &Values2 = BlockDispositions[S];
14533 for (auto &V : llvm::reverse(C&: Values2)) {
14534 if (V.getPointer() == BB) {
14535 V.setInt(D);
14536 break;
14537 }
14538 }
14539 return D;
14540}
14541
14542ScalarEvolution::BlockDisposition
14543ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14544 switch (S->getSCEVType()) {
14545 case scConstant:
14546 case scVScale:
14547 return ProperlyDominatesBlock;
14548 case scAddRecExpr: {
14549 // This uses a "dominates" query instead of "properly dominates" query
14550 // to test for proper dominance too, because the instruction which
14551 // produces the addrec's value is a PHI, and a PHI effectively properly
14552 // dominates its entire containing block.
14553 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(Val: S);
14554 if (!DT.dominates(A: AR->getLoop()->getHeader(), B: BB))
14555 return DoesNotDominateBlock;
14556
14557 // Fall through into SCEVNAryExpr handling.
14558 [[fallthrough]];
14559 }
14560 case scTruncate:
14561 case scZeroExtend:
14562 case scSignExtend:
14563 case scPtrToAddr:
14564 case scAddExpr:
14565 case scMulExpr:
14566 case scUDivExpr:
14567 case scUMaxExpr:
14568 case scSMaxExpr:
14569 case scUMinExpr:
14570 case scSMinExpr:
14571 case scSequentialUMinExpr: {
14572 bool Proper = true;
14573 for (const SCEV *NAryOp : S->operands()) {
14574 BlockDisposition D = getBlockDisposition(S: NAryOp, BB);
14575 if (D == DoesNotDominateBlock)
14576 return DoesNotDominateBlock;
14577 if (D == DominatesBlock)
14578 Proper = false;
14579 }
14580 return Proper ? ProperlyDominatesBlock : DominatesBlock;
14581 }
14582 case scUnknown:
14583 if (Instruction *I =
14584 dyn_cast<Instruction>(Val: cast<SCEVUnknown>(Val: S)->getValue())) {
14585 if (I->getParent() == BB)
14586 return DominatesBlock;
14587 if (DT.properlyDominates(A: I->getParent(), B: BB))
14588 return ProperlyDominatesBlock;
14589 return DoesNotDominateBlock;
14590 }
14591 return ProperlyDominatesBlock;
14592 case scCouldNotCompute:
14593 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14594 }
14595 llvm_unreachable("Unknown SCEV kind!");
14596}
14597
14598bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14599 return getBlockDisposition(S, BB) >= DominatesBlock;
14600}
14601
14602bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
14603 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
14604}
14605
14606void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14607 bool Predicated) {
14608 auto &BECounts =
14609 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14610 auto It = BECounts.find(Val: L);
14611 if (It != BECounts.end()) {
14612 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14613 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14614 if (!isa<SCEVConstant>(Val: S)) {
14615 auto UserIt = BECountUsers.find(Val: S);
14616 assert(UserIt != BECountUsers.end());
14617 UserIt->second.erase(Ptr: {L, Predicated});
14618 }
14619 }
14620 }
14621 BECounts.erase(I: It);
14622 }
14623}
14624
14625void ScalarEvolution::forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs) {
14626 SmallPtrSet<const SCEV *, 8> ToForget(llvm::from_range, SCEVs);
14627 SmallVector<SCEVUse, 8> Worklist(ToForget.begin(), ToForget.end());
14628
14629 while (!Worklist.empty()) {
14630 const SCEV *Curr = Worklist.pop_back_val();
14631 auto Users = SCEVUsers.find(Val: Curr);
14632 if (Users != SCEVUsers.end())
14633 for (const auto *User : Users->second)
14634 if (ToForget.insert(Ptr: User).second)
14635 Worklist.push_back(Elt: User);
14636 }
14637
14638 for (const auto *S : ToForget)
14639 forgetMemoizedResultsImpl(S);
14640
14641 PredicatedSCEVRewrites.remove_if(
14642 Pred: [&](const auto &Entry) { return ToForget.count(Ptr: Entry.first.first); });
14643}
14644
14645void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14646 LoopDispositions.erase(Val: S);
14647 BlockDispositions.erase(Val: S);
14648 UnsignedRanges.erase(Val: S);
14649 SignedRanges.erase(Val: S);
14650 HasRecMap.erase(Val: S);
14651 ConstantMultipleCache.erase(Val: S);
14652
14653 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Val: S)) {
14654 UnsignedWrapViaInductionTried.erase(Ptr: AR);
14655 SignedWrapViaInductionTried.erase(Ptr: AR);
14656 }
14657
14658 auto ExprIt = ExprValueMap.find(Val: S);
14659 if (ExprIt != ExprValueMap.end()) {
14660 for (Value *V : ExprIt->second) {
14661 auto ValueIt = ValueExprMap.find_as(Val: V);
14662 if (ValueIt != ValueExprMap.end())
14663 ValueExprMap.erase(I: ValueIt);
14664 }
14665 ExprValueMap.erase(I: ExprIt);
14666 }
14667
14668 auto ScopeIt = ValuesAtScopes.find(Val: S);
14669 if (ScopeIt != ValuesAtScopes.end()) {
14670 for (const auto &Pair : ScopeIt->second)
14671 if (!isa_and_nonnull<SCEVConstant>(Val: Pair.second))
14672 llvm::erase(C&: ValuesAtScopesUsers[Pair.second.getPointer()],
14673 V: std::make_pair(x: Pair.first, y&: S));
14674 ValuesAtScopes.erase(I: ScopeIt);
14675 }
14676
14677 auto ScopeUserIt = ValuesAtScopesUsers.find(Val: S);
14678 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14679 for (const auto &Pair : ScopeUserIt->second)
14680 // The recorded value at scope is a use of S, which may carry no-wrap
14681 // flags that are not part of this key.
14682 llvm::erase_if(C&: ValuesAtScopes[Pair.second], P: [&](const auto &LS) {
14683 return LS.first == Pair.first && LS.second.getPointer() == S;
14684 });
14685 ValuesAtScopesUsers.erase(I: ScopeUserIt);
14686 }
14687
14688 auto BEUsersIt = BECountUsers.find(Val: S);
14689 if (BEUsersIt != BECountUsers.end()) {
14690 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14691 auto Copy = BEUsersIt->second;
14692 for (const auto &Pair : Copy)
14693 forgetBackedgeTakenCounts(L: Pair.getPointer(), Predicated: Pair.getInt());
14694 BECountUsers.erase(I: BEUsersIt);
14695 }
14696
14697 auto FoldUser = FoldCacheUser.find(Val: S);
14698 if (FoldUser != FoldCacheUser.end())
14699 for (auto &KV : FoldUser->second)
14700 FoldCache.erase(Val: KV);
14701 FoldCacheUser.erase(Val: S);
14702}
14703
14704void
14705ScalarEvolution::getUsedLoops(const SCEV *S,
14706 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14707 struct FindUsedLoops {
14708 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14709 : LoopsUsed(LoopsUsed) {}
14710 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14711 bool follow(const SCEV *S) {
14712 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Val: S))
14713 LoopsUsed.insert(Ptr: AR->getLoop());
14714 return true;
14715 }
14716
14717 bool isDone() const { return false; }
14718 };
14719
14720 FindUsedLoops F(LoopsUsed);
14721 SCEVTraversal<FindUsedLoops>(F).visitAll(Root: S);
14722}
14723
14724void ScalarEvolution::getReachableBlocks(
14725 SmallPtrSetImpl<BasicBlock *> &Reachable, Function &F) {
14726 SmallVector<BasicBlock *> Worklist;
14727 Worklist.push_back(Elt: &F.getEntryBlock());
14728 while (!Worklist.empty()) {
14729 BasicBlock *BB = Worklist.pop_back_val();
14730 if (!Reachable.insert(Ptr: BB).second)
14731 continue;
14732
14733 Value *Cond;
14734 BasicBlock *TrueBB, *FalseBB;
14735 if (match(V: BB->getTerminator(), P: m_Br(C: m_Value(V&: Cond), T: m_BasicBlock(V&: TrueBB),
14736 F: m_BasicBlock(V&: FalseBB)))) {
14737 if (auto *C = dyn_cast<ConstantInt>(Val: Cond)) {
14738 Worklist.push_back(Elt: C->isOne() ? TrueBB : FalseBB);
14739 continue;
14740 }
14741
14742 if (auto *Cmp = dyn_cast<ICmpInst>(Val: Cond)) {
14743 const SCEV *L = getSCEV(V: Cmp->getOperand(i_nocapture: 0));
14744 const SCEV *R = getSCEV(V: Cmp->getOperand(i_nocapture: 1));
14745 if (isKnownPredicateViaConstantRanges(Pred: Cmp->getCmpPredicate(), LHS: L, RHS: R)) {
14746 Worklist.push_back(Elt: TrueBB);
14747 continue;
14748 }
14749 if (isKnownPredicateViaConstantRanges(Pred: Cmp->getInverseCmpPredicate(), LHS: L,
14750 RHS: R)) {
14751 Worklist.push_back(Elt: FalseBB);
14752 continue;
14753 }
14754 }
14755 }
14756
14757 append_range(C&: Worklist, R: successors(BB));
14758 }
14759}
14760
14761void ScalarEvolution::verify() const {
14762 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14763 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14764
14765 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14766
14767 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14768 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14769 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14770
14771 const SCEV *visitConstant(const SCEVConstant *Constant) {
14772 return SE.getConstant(Val: Constant->getAPInt());
14773 }
14774
14775 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14776 return SE.getUnknown(V: Expr->getValue());
14777 }
14778
14779 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14780 return SE.getCouldNotCompute();
14781 }
14782 };
14783
14784 SCEVMapper SCM(SE2);
14785 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14786 SE2.getReachableBlocks(Reachable&: ReachableBlocks, F);
14787
14788 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14789 if (containsUndefs(S: Old) || containsUndefs(S: New)) {
14790 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14791 // not propagate undef aggressively). This means we can (and do) fail
14792 // verification in cases where a transform makes a value go from "undef"
14793 // to "undef+1" (say). The transform is fine, since in both cases the
14794 // result is "undef", but SCEV thinks the value increased by 1.
14795 return nullptr;
14796 }
14797
14798 // Unless VerifySCEVStrict is set, we only compare constant deltas.
14799 const SCEV *Delta = SE2.getMinusSCEV(LHS: Old, RHS: New);
14800 if (!VerifySCEVStrict && !isa<SCEVConstant>(Val: Delta))
14801 return nullptr;
14802
14803 return Delta;
14804 };
14805
14806 while (!LoopStack.empty()) {
14807 auto *L = LoopStack.pop_back_val();
14808 llvm::append_range(C&: LoopStack, R&: *L);
14809
14810 // Only verify BECounts in reachable loops. For an unreachable loop,
14811 // any BECount is legal.
14812 if (!ReachableBlocks.contains(Ptr: L->getHeader()))
14813 continue;
14814
14815 // Only verify cached BECounts. Computing new BECounts may change the
14816 // results of subsequent SCEV uses.
14817 auto It = BackedgeTakenCounts.find(Val: L);
14818 if (It == BackedgeTakenCounts.end())
14819 continue;
14820
14821 auto *CurBECount =
14822 SCM.visit(S: It->second.getExact(L, SE: const_cast<ScalarEvolution *>(this)));
14823 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14824
14825 if (CurBECount == SE2.getCouldNotCompute() ||
14826 NewBECount == SE2.getCouldNotCompute()) {
14827 // NB! This situation is legal, but is very suspicious -- whatever pass
14828 // change the loop to make a trip count go from could not compute to
14829 // computable or vice-versa *should have* invalidated SCEV. However, we
14830 // choose not to assert here (for now) since we don't want false
14831 // positives.
14832 continue;
14833 }
14834
14835 if (SE.getTypeSizeInBits(Ty: CurBECount->getType()) >
14836 SE.getTypeSizeInBits(Ty: NewBECount->getType()))
14837 NewBECount = SE2.getZeroExtendExpr(Op: NewBECount, Ty: CurBECount->getType());
14838 else if (SE.getTypeSizeInBits(Ty: CurBECount->getType()) <
14839 SE.getTypeSizeInBits(Ty: NewBECount->getType()))
14840 CurBECount = SE2.getZeroExtendExpr(Op: CurBECount, Ty: NewBECount->getType());
14841
14842 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14843 if (Delta && !Delta->isZero()) {
14844 dbgs() << "Trip Count for " << *L << " Changed!\n";
14845 dbgs() << "Old: " << *CurBECount << "\n";
14846 dbgs() << "New: " << *NewBECount << "\n";
14847 dbgs() << "Delta: " << *Delta << "\n";
14848 std::abort();
14849 }
14850 }
14851
14852 // Collect all valid loops currently in LoopInfo.
14853 SmallPtrSet<Loop *, 32> ValidLoops;
14854 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14855 while (!Worklist.empty()) {
14856 Loop *L = Worklist.pop_back_val();
14857 if (ValidLoops.insert(Ptr: L).second)
14858 Worklist.append(in_start: L->begin(), in_end: L->end());
14859 }
14860 for (const auto &KV : ValueExprMap) {
14861#ifndef NDEBUG
14862 // Check for SCEV expressions referencing invalid/deleted loops.
14863 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14864 assert(ValidLoops.contains(AR->getLoop()) &&
14865 "AddRec references invalid loop");
14866 }
14867#endif
14868
14869 // Check that the value is also part of the reverse map.
14870 auto It = ExprValueMap.find(Val: KV.second);
14871 if (It == ExprValueMap.end() || !It->second.contains(key: KV.first)) {
14872 dbgs() << "Value " << *KV.first
14873 << " is in ValueExprMap but not in ExprValueMap\n";
14874 std::abort();
14875 }
14876
14877 if (auto *I = dyn_cast<Instruction>(Val: &*KV.first)) {
14878 if (!ReachableBlocks.contains(Ptr: I->getParent()))
14879 continue;
14880 const SCEV *OldSCEV = SCM.visit(S: KV.second);
14881 const SCEV *NewSCEV = SE2.getSCEV(V: I);
14882 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14883 if (Delta && !Delta->isZero()) {
14884 dbgs() << "SCEV for value " << *I << " changed!\n"
14885 << "Old: " << *OldSCEV << "\n"
14886 << "New: " << *NewSCEV << "\n"
14887 << "Delta: " << *Delta << "\n";
14888 std::abort();
14889 }
14890 }
14891 }
14892
14893 for (const auto &KV : ExprValueMap) {
14894 for (Value *V : KV.second) {
14895 const SCEV *S = ValueExprMap.lookup(Val: V);
14896 if (!S) {
14897 dbgs() << "Value " << *V
14898 << " is in ExprValueMap but not in ValueExprMap\n";
14899 std::abort();
14900 }
14901 if (S != KV.first) {
14902 dbgs() << "Value " << *V << " mapped to " << *S << " rather than "
14903 << *KV.first << "\n";
14904 std::abort();
14905 }
14906 }
14907 }
14908
14909 // Verify integrity of SCEV users.
14910 for (const auto &S : UniqueSCEVs) {
14911 for (SCEVUse Op : S.operands()) {
14912 // We do not store dependencies of constants.
14913 if (isa<SCEVConstant>(Val: Op))
14914 continue;
14915 auto It = SCEVUsers.find(Val: Op);
14916 if (It != SCEVUsers.end() && It->second.count(Ptr: &S))
14917 continue;
14918 dbgs() << "Use of operand " << *Op << " by user " << S
14919 << " is not being tracked!\n";
14920 std::abort();
14921 }
14922 }
14923
14924 // Verify integrity of ValuesAtScopes users.
14925 for (const auto &ValueAndVec : ValuesAtScopes) {
14926 const SCEV *Value = ValueAndVec.first;
14927 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14928 const Loop *L = LoopAndValueAtScope.first;
14929 SCEVUse ValueAtScope = LoopAndValueAtScope.second;
14930 if (!isa<SCEVConstant>(Val: ValueAtScope)) {
14931 auto It = ValuesAtScopesUsers.find(Val: ValueAtScope.getPointer());
14932 if (It != ValuesAtScopesUsers.end() &&
14933 is_contained(Range: It->second, Element: std::make_pair(x&: L, y&: Value)))
14934 continue;
14935 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14936 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14937 std::abort();
14938 }
14939 }
14940 }
14941
14942 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14943 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14944 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14945 const Loop *L = LoopAndValue.first;
14946 const SCEV *Value = LoopAndValue.second;
14947 assert(!isa<SCEVConstant>(Value));
14948 auto It = ValuesAtScopes.find(Val: Value);
14949 // The recorded value at scope may carry no-wrap flags that are not part
14950 // of the key it is recorded under.
14951 if (It != ValuesAtScopes.end() && any_of(Range: It->second, P: [&](const auto &LS) {
14952 return LS.first == L && LS.second.getPointer() == ValueAtScope;
14953 }))
14954 continue;
14955 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14956 << *ValueAtScope << " missing in ValuesAtScopes\n";
14957 std::abort();
14958 }
14959 }
14960
14961 // Verify integrity of BECountUsers.
14962 auto VerifyBECountUsers = [&](bool Predicated) {
14963 auto &BECounts =
14964 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14965 for (const auto &LoopAndBEInfo : BECounts) {
14966 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
14967 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14968 if (!isa<SCEVConstant>(Val: S)) {
14969 auto UserIt = BECountUsers.find(Val: S);
14970 if (UserIt != BECountUsers.end() &&
14971 UserIt->second.contains(Ptr: { LoopAndBEInfo.first, Predicated }))
14972 continue;
14973 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
14974 << " missing from BECountUsers\n";
14975 std::abort();
14976 }
14977 }
14978 }
14979 }
14980 };
14981 VerifyBECountUsers(/* Predicated */ false);
14982 VerifyBECountUsers(/* Predicated */ true);
14983
14984 // Verify intergity of loop disposition cache.
14985 for (auto &[S, Values] : LoopDispositions) {
14986 for (auto [Loop, CachedDisposition] : Values) {
14987 const auto RecomputedDisposition = SE2.getLoopDisposition(S, L: Loop);
14988 if (CachedDisposition != RecomputedDisposition) {
14989 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
14990 << " is incorrect: cached " << CachedDisposition << ", actual "
14991 << RecomputedDisposition << "\n";
14992 std::abort();
14993 }
14994 }
14995 }
14996
14997 // Verify integrity of the block disposition cache.
14998 for (auto &[S, Values] : BlockDispositions) {
14999 for (auto [BB, CachedDisposition] : Values) {
15000 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
15001 if (CachedDisposition != RecomputedDisposition) {
15002 dbgs() << "Cached disposition of " << *S << " for block %"
15003 << BB->getName() << " is incorrect: cached " << CachedDisposition
15004 << ", actual " << RecomputedDisposition << "\n";
15005 std::abort();
15006 }
15007 }
15008 }
15009
15010 // Verify FoldCache/FoldCacheUser caches.
15011 for (auto [FoldID, Expr] : FoldCache) {
15012 auto I = FoldCacheUser.find(Val: Expr);
15013 if (I == FoldCacheUser.end()) {
15014 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
15015 << "!\n";
15016 std::abort();
15017 }
15018 if (!is_contained(Range: I->second, Element: FoldID)) {
15019 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
15020 std::abort();
15021 }
15022 }
15023 for (auto [Expr, IDs] : FoldCacheUser) {
15024 for (auto &FoldID : IDs) {
15025 const SCEV *S = FoldCache.lookup(Val: FoldID);
15026 if (!S) {
15027 dbgs() << "Missing entry in FoldCache for expression " << *Expr
15028 << "!\n";
15029 std::abort();
15030 }
15031 if (S != Expr) {
15032 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: " << *S
15033 << " != " << *Expr << "!\n";
15034 std::abort();
15035 }
15036 }
15037 }
15038
15039 // Verify that ConstantMultipleCache computations are correct. We check that
15040 // cached multiples and recomputed multiples are multiples of each other to
15041 // verify correctness. It is possible that a recomputed multiple is different
15042 // from the cached multiple due to strengthened no wrap flags or changes in
15043 // KnownBits computations.
15044 for (auto [S, Multiple] : ConstantMultipleCache) {
15045 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
15046 if ((Multiple != 0 && RecomputedMultiple != 0 &&
15047 Multiple.urem(RHS: RecomputedMultiple) != 0 &&
15048 RecomputedMultiple.urem(RHS: Multiple) != 0)) {
15049 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
15050 << *S << " : Computed " << RecomputedMultiple
15051 << " but cache contains " << Multiple << "!\n";
15052 std::abort();
15053 }
15054 }
15055}
15056
15057bool ScalarEvolution::invalidate(
15058 Function &F, const PreservedAnalyses &PA,
15059 FunctionAnalysisManager::Invalidator &Inv) {
15060 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
15061 // of its dependencies is invalidated.
15062 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
15063 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
15064 Inv.invalidate<AssumptionAnalysis>(IR&: F, PA) ||
15065 Inv.invalidate<DominatorTreeAnalysis>(IR&: F, PA) ||
15066 Inv.invalidate<LoopAnalysis>(IR&: F, PA);
15067}
15068
15069AnalysisKey ScalarEvolutionAnalysis::Key;
15070
15071ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
15072 FunctionAnalysisManager &AM) {
15073 auto &TLI = AM.getResult<TargetLibraryAnalysis>(IR&: F);
15074 auto &AC = AM.getResult<AssumptionAnalysis>(IR&: F);
15075 auto &DT = AM.getResult<DominatorTreeAnalysis>(IR&: F);
15076 auto &LI = AM.getResult<LoopAnalysis>(IR&: F);
15077 return ScalarEvolution(F, TLI, AC, DT, LI);
15078}
15079
15080PreservedAnalyses
15081ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
15082 AM.getResult<ScalarEvolutionAnalysis>(IR&: F).verify();
15083 return PreservedAnalyses::all();
15084}
15085
15086PreservedAnalyses
15087ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
15088 // For compatibility with opt's -analyze feature under legacy pass manager
15089 // which was not ported to NPM. This keeps tests using
15090 // update_analyze_test_checks.py working.
15091 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
15092 << F.getName() << "':\n";
15093 AM.getResult<ScalarEvolutionAnalysis>(IR&: F).print(OS);
15094 return PreservedAnalyses::all();
15095}
15096
15097INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
15098 "Scalar Evolution Analysis", false, true)
15099INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
15100INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
15101INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
15102INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
15103INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
15104 "Scalar Evolution Analysis", false, true)
15105
15106char ScalarEvolutionWrapperPass::ID = 0;
15107
15108ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {}
15109
15110bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
15111 SE.reset(p: new ScalarEvolution(
15112 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
15113 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
15114 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
15115 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
15116 return false;
15117}
15118
15119void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
15120
15121void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
15122 SE->print(OS);
15123}
15124
15125void ScalarEvolutionWrapperPass::verifyAnalysis() const {
15126 if (!VerifySCEV)
15127 return;
15128
15129 SE->verify();
15130}
15131
15132void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
15133 AU.setPreservesAll();
15134 AU.addRequiredTransitive<AssumptionCacheTracker>();
15135 AU.addRequiredTransitive<LoopInfoWrapperPass>();
15136 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
15137 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
15138}
15139
15140const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
15141 const SCEV *RHS) {
15142 return getComparePredicate(Pred: ICmpInst::ICMP_EQ, LHS, RHS);
15143}
15144
15145const SCEVPredicate *
15146ScalarEvolution::getComparePredicate(const ICmpInst::Predicate Pred,
15147 const SCEV *LHS, const SCEV *RHS) {
15148 FoldingSetNodeID ID;
15149 assert(LHS->getType() == RHS->getType() &&
15150 "Type mismatch between LHS and RHS");
15151 // Unique this node based on the arguments
15152 ID.AddInteger(I: SCEVPredicate::P_Compare);
15153 ID.AddInteger(I: Pred);
15154 ID.AddPointer(Ptr: LHS);
15155 ID.AddPointer(Ptr: RHS);
15156 FoldingSetInsertToken Token;
15157 if (const auto *S = UniquePreds.lookup(ID, Token))
15158 return S;
15159 SCEVComparePredicate *Eq = new (SCEVAllocator)
15160 SCEVComparePredicate(ID.Intern(Allocator&: SCEVAllocator), Pred, LHS, RHS);
15161 UniquePreds.insert(N: Eq, Token);
15162 return Eq;
15163}
15164
15165const SCEVPredicate *ScalarEvolution::getWrapPredicate(
15166 const SCEVAddRecExpr *AR,
15167 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
15168 FoldingSetNodeID ID;
15169 // Unique this node based on the arguments
15170 ID.AddInteger(I: SCEVPredicate::P_Wrap);
15171 ID.AddPointer(Ptr: AR);
15172 ID.AddInteger(I: AddedFlags);
15173 FoldingSetInsertToken Token;
15174 if (const auto *S = UniquePreds.lookup(ID, Token))
15175 return S;
15176 auto *OF = new (SCEVAllocator)
15177 SCEVWrapPredicate(ID.Intern(Allocator&: SCEVAllocator), AR, AddedFlags);
15178 UniquePreds.insert(N: OF, Token);
15179 return OF;
15180}
15181
15182namespace {
15183
15184class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
15185public:
15186
15187 /// Rewrites \p S in the context of a loop L and the SCEV predication
15188 /// infrastructure.
15189 ///
15190 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
15191 /// equivalences present in \p Pred.
15192 ///
15193 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
15194 /// \p NewPreds such that the result will be an AddRecExpr.
15195 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
15196 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15197 const SCEVPredicate *Pred) {
15198 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
15199 return Rewriter.visit(S);
15200 }
15201
15202 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15203 if (Pred) {
15204 if (auto *U = dyn_cast<SCEVUnionPredicate>(Val: Pred)) {
15205 for (const auto *Pred : U->getPredicates())
15206 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Val: Pred))
15207 if (IPred->getLHS() == Expr &&
15208 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15209 return IPred->getRHS();
15210 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Val: Pred)) {
15211 if (IPred->getLHS() == Expr &&
15212 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15213 return IPred->getRHS();
15214 }
15215 }
15216 return convertToAddRecWithPreds(Expr);
15217 }
15218
15219 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15220 const SCEV *Operand = visit(S: Expr->getOperand());
15221 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Val: Operand);
15222 if (AR && AR->getLoop() == L && AR->isAffine()) {
15223 // This couldn't be folded because the operand didn't have the nuw
15224 // flag. Add the nusw flag as an assumption that we could make.
15225 const SCEV *Step = AR->getStepRecurrence(SE);
15226 Type *Ty = Expr->getType();
15227 if (addOverflowAssumption(AR, AddedFlags: SCEVWrapPredicate::IncrementNUSW))
15228 return SE.getAddRecExpr(Start: SE.getZeroExtendExpr(Op: AR->getStart(), Ty),
15229 Step: SE.getSignExtendExpr(Op: Step, Ty), L,
15230 Flags: AR->getNoWrapFlags());
15231 }
15232 return SE.getZeroExtendExpr(Op: Operand, Ty: Expr->getType());
15233 }
15234
15235 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15236 const SCEV *Operand = visit(S: Expr->getOperand());
15237 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Val: Operand);
15238 if (AR && AR->getLoop() == L && AR->isAffine()) {
15239 // This couldn't be folded because the operand didn't have the nsw
15240 // flag. Add the nssw flag as an assumption that we could make.
15241 const SCEV *Step = AR->getStepRecurrence(SE);
15242 Type *Ty = Expr->getType();
15243 if (addOverflowAssumption(AR, AddedFlags: SCEVWrapPredicate::IncrementNSSW))
15244 return SE.getAddRecExpr(Start: SE.getSignExtendExpr(Op: AR->getStart(), Ty),
15245 Step: SE.getSignExtendExpr(Op: Step, Ty), L,
15246 Flags: AR->getNoWrapFlags());
15247 }
15248 return SE.getSignExtendExpr(Op: Operand, Ty: Expr->getType());
15249 }
15250
15251private:
15252 explicit SCEVPredicateRewriter(
15253 const Loop *L, ScalarEvolution &SE,
15254 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15255 const SCEVPredicate *Pred)
15256 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
15257
15258 bool addOverflowAssumption(const SCEVPredicate *P) {
15259 if (!NewPreds) {
15260 // Check if we've already made this assumption.
15261 return Pred && Pred->implies(N: P, SE);
15262 }
15263 NewPreds->push_back(Elt: P);
15264 return true;
15265 }
15266
15267 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
15268 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
15269 auto *A = SE.getWrapPredicate(AR, AddedFlags);
15270 return addOverflowAssumption(P: A);
15271 }
15272
15273 // If \p Expr represents a PHINode, we try to see if it can be represented
15274 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
15275 // to add this predicate as a runtime overflow check, we return the AddRec.
15276 // If \p Expr does not meet these conditions (is not a PHI node, or we
15277 // couldn't create an AddRec for it, or couldn't add the predicate), we just
15278 // return \p Expr.
15279 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
15280 if (!isa<PHINode>(Val: Expr->getValue()))
15281 return Expr;
15282 std::optional<
15283 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
15284 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(SymbolicPHI: Expr);
15285 if (!PredicatedRewrite)
15286 return Expr;
15287 for (const auto *P : PredicatedRewrite->second){
15288 // Wrap predicates from outer loops are not supported.
15289 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(Val: P)) {
15290 if (L != WP->getExpr()->getLoop())
15291 return Expr;
15292 }
15293 if (!addOverflowAssumption(P))
15294 return Expr;
15295 }
15296 return PredicatedRewrite->first;
15297 }
15298
15299 SmallVectorImpl<const SCEVPredicate *> *NewPreds;
15300 const SCEVPredicate *Pred;
15301 const Loop *L;
15302};
15303
15304} // end anonymous namespace
15305
15306const SCEV *
15307ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
15308 const SCEVPredicate &Preds) {
15309 return SCEVPredicateRewriter::rewrite(S, L, SE&: *this, NewPreds: nullptr, Pred: &Preds);
15310}
15311
15312const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
15313 const SCEV *S, const Loop *L,
15314 SmallVectorImpl<const SCEVPredicate *> &Preds) {
15315 SmallVector<const SCEVPredicate *> TransformPreds;
15316 S = SCEVPredicateRewriter::rewrite(S, L, SE&: *this, NewPreds: &TransformPreds, Pred: nullptr);
15317 auto *AddRec = dyn_cast<SCEVAddRecExpr>(Val: S);
15318
15319 if (!AddRec)
15320 return nullptr;
15321
15322 // Check if any of the transformed predicates is known to be false. In that
15323 // case, it doesn't make sense to convert to a predicated AddRec, as the
15324 // versioned loop will never execute.
15325 for (const SCEVPredicate *Pred : TransformPreds) {
15326 auto *WrapPred = dyn_cast<SCEVWrapPredicate>(Val: Pred);
15327 if (!WrapPred || WrapPred->getFlags() != SCEVWrapPredicate::IncrementNSSW)
15328 continue;
15329
15330 const SCEVAddRecExpr *AddRecToCheck = WrapPred->getExpr();
15331 const SCEV *ExitCount = getBackedgeTakenCount(L: AddRecToCheck->getLoop());
15332 if (isa<SCEVCouldNotCompute>(Val: ExitCount))
15333 continue;
15334
15335 const SCEV *Step = AddRecToCheck->getStepRecurrence(SE&: *this);
15336 if (!Step->isOne())
15337 continue;
15338
15339 ExitCount = getTruncateOrSignExtend(V: ExitCount, Ty: Step->getType());
15340 const SCEV *Add = getAddExpr(LHS: AddRecToCheck->getStart(), RHS: ExitCount);
15341 if (isKnownPredicate(Pred: CmpInst::ICMP_SLT, LHS: Add, RHS: AddRecToCheck->getStart()))
15342 return nullptr;
15343 }
15344
15345 // Since the transformation was successful, we can now transfer the SCEV
15346 // predicates.
15347 Preds.append(in_start: TransformPreds.begin(), in_end: TransformPreds.end());
15348
15349 return AddRec;
15350}
15351
15352/// SCEV predicates
15353SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
15354 SCEVPredicateKind Kind)
15355 : FastID(ID), Kind(Kind) {}
15356
15357SCEVComparePredicate::SCEVComparePredicate(const FoldingSetNodeIDRef ID,
15358 const ICmpInst::Predicate Pred,
15359 const SCEV *LHS, const SCEV *RHS)
15360 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
15361 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
15362 assert(LHS != RHS && "LHS and RHS are the same SCEV");
15363}
15364
15365bool SCEVComparePredicate::implies(const SCEVPredicate *N,
15366 ScalarEvolution &SE) const {
15367 const auto *Op = dyn_cast<SCEVComparePredicate>(Val: N);
15368
15369 if (!Op)
15370 return false;
15371
15372 if (Pred != ICmpInst::ICMP_EQ)
15373 return false;
15374
15375 return Op->LHS == LHS && Op->RHS == RHS;
15376}
15377
15378bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
15379
15380void SCEVComparePredicate::print(raw_ostream &OS, unsigned Depth) const {
15381 if (Pred == ICmpInst::ICMP_EQ)
15382 OS.indent(NumSpaces: Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
15383 else
15384 OS.indent(NumSpaces: Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
15385 << *RHS << "\n";
15386
15387}
15388
15389SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
15390 const SCEVAddRecExpr *AR,
15391 IncrementWrapFlags Flags)
15392 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
15393
15394const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
15395
15396bool SCEVWrapPredicate::implies(const SCEVPredicate *N,
15397 ScalarEvolution &SE) const {
15398 const auto *Op = dyn_cast<SCEVWrapPredicate>(Val: N);
15399 if (!Op || setFlags(Flags, OnFlags: Op->Flags) != Flags)
15400 return false;
15401
15402 if (Op->AR == AR)
15403 return true;
15404
15405 if (Flags != SCEVWrapPredicate::IncrementNSSW &&
15406 Flags != SCEVWrapPredicate::IncrementNUSW)
15407 return false;
15408
15409 const SCEV *Start = AR->getStart();
15410 const SCEV *OpStart = Op->AR->getStart();
15411 if (Start->getType()->isPointerTy() != OpStart->getType()->isPointerTy())
15412 return false;
15413
15414 // Reject pointers to different address spaces.
15415 if (Start->getType()->isPointerTy() && Start->getType() != OpStart->getType())
15416 return false;
15417
15418 // NUSW/NSSW on a wider-type AddRec does not imply the same on a
15419 // narrower-type AddRec.
15420 if (SE.getTypeSizeInBits(Ty: AR->getType()) >
15421 SE.getTypeSizeInBits(Ty: Op->AR->getType()))
15422 return false;
15423
15424 const SCEV *Step = AR->getStepRecurrence(SE);
15425 const SCEV *OpStep = Op->AR->getStepRecurrence(SE);
15426 if (!SE.isKnownPositive(S: Step) || !SE.isKnownPositive(S: OpStep))
15427 return false;
15428
15429 // If both steps are positive, this implies N, if N's start and step are
15430 // ULE/SLE (for NSUW/NSSW) than this'.
15431 Type *WiderTy = SE.getWiderType(T1: Step->getType(), T2: OpStep->getType());
15432 Step = SE.getNoopOrZeroExtend(V: Step, Ty: WiderTy);
15433 OpStep = SE.getNoopOrZeroExtend(V: OpStep, Ty: WiderTy);
15434
15435 bool IsNUW = Flags == SCEVWrapPredicate::IncrementNUSW;
15436 OpStart = IsNUW ? SE.getNoopOrZeroExtend(V: OpStart, Ty: WiderTy)
15437 : SE.getNoopOrSignExtend(V: OpStart, Ty: WiderTy);
15438 Start = IsNUW ? SE.getNoopOrZeroExtend(V: Start, Ty: WiderTy)
15439 : SE.getNoopOrSignExtend(V: Start, Ty: WiderTy);
15440 CmpInst::Predicate Pred = IsNUW ? CmpInst::ICMP_ULE : CmpInst::ICMP_SLE;
15441 return SE.isKnownPredicate(Pred, LHS: OpStep, RHS: Step) &&
15442 SE.isKnownPredicate(Pred, LHS: OpStart, RHS: Start);
15443}
15444
15445bool SCEVWrapPredicate::isAlwaysTrue() const {
15446 SCEVFlags ScevFlags = AR->getNoWrapFlags();
15447 IncrementWrapFlags IFlags = Flags;
15448
15449 if (ScalarEvolution::setFlags(Flags: ScevFlags, OnFlags: SCEV::FlagNSW) == ScevFlags)
15450 IFlags = clearFlags(Flags: IFlags, OffFlags: IncrementNSSW);
15451
15452 return IFlags == IncrementAnyWrap;
15453}
15454
15455void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
15456 OS.indent(NumSpaces: Depth) << *getExpr() << " Added Flags: ";
15457 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
15458 OS << "<nusw>";
15459 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
15460 OS << "<nssw>";
15461 OS << "\n";
15462}
15463
15464/// Union predicates don't get cached so create a dummy set ID for it.
15465SCEVUnionPredicate::SCEVUnionPredicate(ArrayRef<const SCEVPredicate *> Preds,
15466 ScalarEvolution &SE)
15467 : SCEVPredicate(FoldingSetNodeIDRef(), P_Union) {
15468 for (const auto *P : Preds)
15469 add(N: P, SE);
15470}
15471
15472bool SCEVUnionPredicate::isAlwaysTrue() const {
15473 return all_of(Range: Preds,
15474 P: [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
15475}
15476
15477bool SCEVUnionPredicate::implies(const SCEVPredicate *N,
15478 ScalarEvolution &SE) const {
15479 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(Val: N))
15480 return all_of(Range: Set->Preds, P: [this, &SE](const SCEVPredicate *I) {
15481 return this->implies(N: I, SE);
15482 });
15483
15484 if (any_of(Range: Preds,
15485 P: [N, &SE](const SCEVPredicate *I) { return I->implies(N, SE); }))
15486 return true;
15487
15488 // A wrap predicate may be implied by a wrap predicate in Preds after applying
15489 // equal predicates.
15490 const auto *NWrap = dyn_cast<SCEVWrapPredicate>(Val: N);
15491 if (!NWrap)
15492 return false;
15493 const Loop *L = NWrap->getExpr()->getLoop();
15494 return any_of(Range: Preds, P: [&](const SCEVPredicate *I) {
15495 const auto *IWrap = dyn_cast<SCEVWrapPredicate>(Val: I);
15496 if (!IWrap)
15497 return false;
15498 const auto *RewrittenAR = dyn_cast<SCEVAddRecExpr>(
15499 Val: SE.rewriteUsingPredicate(S: IWrap->getExpr(), L, Preds: *this));
15500 return RewrittenAR &&
15501 SE.getWrapPredicate(AR: RewrittenAR, AddedFlags: IWrap->getFlags())->implies(N, SE);
15502 });
15503}
15504
15505void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
15506 for (const auto *Pred : Preds)
15507 Pred->print(OS, Depth);
15508}
15509
15510void SCEVUnionPredicate::add(const SCEVPredicate *N, ScalarEvolution &SE) {
15511 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(Val: N)) {
15512 for (const auto *Pred : Set->Preds)
15513 add(N: Pred, SE);
15514 return;
15515 }
15516
15517 // Implication checks are quadratic in the number of predicates. Stop doing
15518 // them if there are many predicates, as they should be too expensive to use
15519 // anyway at that point.
15520 bool CheckImplies = Preds.size() < 16;
15521
15522 // Only add predicate if it is not already implied by this union predicate.
15523 if (CheckImplies && implies(N, SE))
15524 return;
15525
15526 // Build a new vector containing the current predicates, except the ones that
15527 // are implied by the new predicate N.
15528 SmallVector<const SCEVPredicate *> PrunedPreds;
15529 for (auto *P : Preds) {
15530 if (CheckImplies && N->implies(N: P, SE))
15531 continue;
15532 PrunedPreds.push_back(Elt: P);
15533 }
15534 Preds = std::move(PrunedPreds);
15535 Preds.push_back(Elt: N);
15536}
15537
15538PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
15539 Loop &L)
15540 : SE(SE), L(L) {
15541 SmallVector<const SCEVPredicate*, 4> Empty;
15542 Preds = std::make_unique<SCEVUnionPredicate>(args&: Empty, args&: SE);
15543}
15544
15545void ScalarEvolution::registerUser(const SCEV *User, ArrayRef<SCEVUse> Ops) {
15546 for (const SCEV *Op : Ops)
15547 // We do not expect that forgetting cached data for SCEVConstants will ever
15548 // open any prospects for sharpening or introduce any correctness issues,
15549 // so we don't bother storing their dependencies.
15550 if (!isa<SCEVConstant>(Val: Op))
15551 SCEVUsers[Op].insert(Ptr: User);
15552}
15553
15554const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
15555 const SCEV *Expr = SE.getSCEV(V);
15556 return getPredicatedSCEV(Expr);
15557}
15558
15559const SCEV *PredicatedScalarEvolution::getPredicatedSCEV(const SCEV *Expr) {
15560 RewriteEntry &Entry = RewriteMap[Expr];
15561
15562 // If we already have an entry and the version matches, return it.
15563 if (Entry.second && Generation == Entry.first)
15564 return Entry.second;
15565
15566 // We found an entry but it's stale. Rewrite the stale entry
15567 // according to the current predicate.
15568 if (Entry.second)
15569 Expr = Entry.second;
15570
15571 const SCEV *NewSCEV = SE.rewriteUsingPredicate(S: Expr, L: &L, Preds: *Preds);
15572 Entry = {Generation, NewSCEV};
15573
15574 return NewSCEV;
15575}
15576
15577const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
15578 if (!BackedgeCount) {
15579 SmallVector<const SCEVPredicate *, 4> Preds;
15580 BackedgeCount = SE.getPredicatedBackedgeTakenCount(L: &L, Preds);
15581 for (const auto *P : Preds)
15582 addPredicate(Pred: *P);
15583 }
15584 return BackedgeCount;
15585}
15586
15587const SCEV *PredicatedScalarEvolution::getSymbolicMaxBackedgeTakenCount() {
15588 if (!SymbolicMaxBackedgeCount) {
15589 SmallVector<const SCEVPredicate *, 4> Preds;
15590 SymbolicMaxBackedgeCount =
15591 SE.getPredicatedSymbolicMaxBackedgeTakenCount(L: &L, Preds);
15592 for (const auto *P : Preds)
15593 addPredicate(Pred: *P);
15594 }
15595 return SymbolicMaxBackedgeCount;
15596}
15597
15598unsigned PredicatedScalarEvolution::getSmallConstantMaxTripCount() {
15599 if (!SmallConstantMaxTripCount) {
15600 SmallVector<const SCEVPredicate *, 4> Preds;
15601 SmallConstantMaxTripCount = SE.getSmallConstantMaxTripCount(L: &L, Predicates: &Preds);
15602 for (const auto *P : Preds)
15603 addPredicate(Pred: *P);
15604 }
15605 return *SmallConstantMaxTripCount;
15606}
15607
15608void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
15609 if (Preds->implies(N: &Pred, SE))
15610 return;
15611
15612 Preds = std::make_unique<SCEVUnionPredicate>(args: Preds->getUnionWith(N: &Pred, SE));
15613 updateGeneration();
15614}
15615
15616void PredicatedScalarEvolution::addPredicates(
15617 ArrayRef<const SCEVPredicate *> Preds) {
15618 for (const SCEVPredicate *P : Preds)
15619 addPredicate(Pred: *P);
15620}
15621
15622const SCEVPredicate &PredicatedScalarEvolution::getPredicate() const {
15623 return *Preds;
15624}
15625
15626void PredicatedScalarEvolution::updateGeneration() {
15627 // If the generation number wrapped recompute everything.
15628 if (++Generation == 0) {
15629 for (auto &II : RewriteMap) {
15630 const SCEV *Rewritten = II.second.second;
15631 II.second = {Generation, SE.rewriteUsingPredicate(S: Rewritten, L: &L, Preds: *Preds)};
15632 }
15633 }
15634}
15635
15636const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(
15637 Value *V, SmallVectorImpl<const SCEVPredicate *> *ExtraPreds) {
15638 const SCEV *Expr = this->getSCEV(V);
15639 SmallVector<const SCEVPredicate *, 4> NewPreds;
15640 auto *New = SE.convertSCEVToAddRecWithPredicates(S: Expr, L: &L, Preds&: NewPreds);
15641
15642 if (!New)
15643 return nullptr;
15644
15645 if (ExtraPreds) {
15646 ExtraPreds->append(RHS: NewPreds);
15647 return New;
15648 }
15649
15650 addPredicates(Preds: NewPreds);
15651
15652 RewriteMap[SE.getSCEV(V)] = {Generation, New};
15653 return New;
15654}
15655
15656PredicatedScalarEvolution::PredicatedScalarEvolution(
15657 const PredicatedScalarEvolution &Init)
15658 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15659 Preds(std::make_unique<SCEVUnionPredicate>(args&: *Init.Preds)),
15660 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {}
15661
15662void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
15663 // For each block.
15664 for (auto *BB : L.getBlocks())
15665 for (auto &I : *BB) {
15666 if (!SE.isSCEVable(Ty: I.getType()))
15667 continue;
15668
15669 auto *Expr = SE.getSCEV(V: &I);
15670 auto II = RewriteMap.find(Val: Expr);
15671
15672 if (II == RewriteMap.end())
15673 continue;
15674
15675 // Don't print things that are not interesting.
15676 if (II->second.second == Expr)
15677 continue;
15678
15679 OS.indent(NumSpaces: Depth) << "[PSE]" << I << ":\n";
15680 OS.indent(NumSpaces: Depth + 2) << *Expr << "\n";
15681 OS.indent(NumSpaces: Depth + 2) << "--> " << *II->second.second << "\n";
15682 }
15683}
15684
15685void ScalarEvolution::LoopGuards::collectPending() {
15686 const Loop *L = PendingLoop;
15687 if (!L)
15688 return;
15689 PendingLoop = nullptr;
15690 BasicBlock *Pred = L->getLoopPredecessor();
15691 if (!Pred)
15692 return;
15693 SmallPtrSet<const BasicBlock *, 8> VisitedBlocks;
15694 collectFromBlock(SE, Guards&: *this, Block: L->getHeader(), Pred, VisitedBlocks);
15695}
15696
15697void ScalarEvolution::LoopGuards::collectFromPHI(
15698 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
15699 const PHINode &Phi, SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks,
15700 SmallDenseMap<const BasicBlock *, LoopGuards> &IncomingGuards,
15701 unsigned Depth) {
15702 if (!SE.isSCEVable(Ty: Phi.getType()))
15703 return;
15704
15705 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15706 auto GetMinMaxConst = [&](unsigned IncomingIdx) -> MinMaxPattern {
15707 const BasicBlock *InBlock = Phi.getIncomingBlock(i: IncomingIdx);
15708 if (!VisitedBlocks.insert(Ptr: InBlock).second)
15709 return {nullptr, scCouldNotCompute};
15710
15711 // Avoid analyzing unreachable blocks so that we don't get trapped
15712 // traversing cycles with ill-formed dominance or infinite cycles
15713 if (!SE.DT.isReachableFromEntry(A: InBlock))
15714 return {nullptr, scCouldNotCompute};
15715
15716 auto [G, Inserted] = IncomingGuards.try_emplace(Key: InBlock, Args: LoopGuards(SE));
15717 if (Inserted)
15718 collectFromBlock(SE, Guards&: G->second, Block: Phi.getParent(), Pred: InBlock, VisitedBlocks,
15719 Depth: Depth + 1);
15720 auto &RewriteMap = G->second.RewriteMap;
15721 if (RewriteMap.empty())
15722 return {nullptr, scCouldNotCompute};
15723 auto S = RewriteMap.find(Val: SE.getSCEV(V: Phi.getIncomingValue(i: IncomingIdx)));
15724 if (S == RewriteMap.end())
15725 return {nullptr, scCouldNotCompute};
15726 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(Val: S->second);
15727 if (!SM)
15728 return {nullptr, scCouldNotCompute};
15729 if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(Val: SM->getOperand(i: 0)))
15730 return {C0, SM->getSCEVType()};
15731 return {nullptr, scCouldNotCompute};
15732 };
15733 auto MergeMinMaxConst = [](MinMaxPattern P1,
15734 MinMaxPattern P2) -> MinMaxPattern {
15735 auto [C1, T1] = P1;
15736 auto [C2, T2] = P2;
15737 if (!C1 || !C2 || T1 != T2)
15738 return {nullptr, scCouldNotCompute};
15739 switch (T1) {
15740 case scUMaxExpr:
15741 return {C1->getAPInt().ult(RHS: C2->getAPInt()) ? C1 : C2, T1};
15742 case scSMaxExpr:
15743 return {C1->getAPInt().slt(RHS: C2->getAPInt()) ? C1 : C2, T1};
15744 case scUMinExpr:
15745 return {C1->getAPInt().ugt(RHS: C2->getAPInt()) ? C1 : C2, T1};
15746 case scSMinExpr:
15747 return {C1->getAPInt().sgt(RHS: C2->getAPInt()) ? C1 : C2, T1};
15748 default:
15749 llvm_unreachable("Trying to merge non-MinMaxExpr SCEVs.");
15750 }
15751 };
15752 auto P = GetMinMaxConst(0);
15753 for (unsigned int In = 1; In < Phi.getNumIncomingValues(); In++) {
15754 if (!P.first)
15755 break;
15756 P = MergeMinMaxConst(P, GetMinMaxConst(In));
15757 }
15758 if (P.first) {
15759 const SCEV *LHS = SE.getSCEV(V: const_cast<PHINode *>(&Phi));
15760 SmallVector<SCEVUse, 2> Ops({P.first, LHS});
15761 const SCEV *RHS = SE.getMinMaxExpr(Kind: P.second, Ops);
15762 Guards.RewriteMap.insert(KV: {LHS, RHS});
15763 }
15764}
15765
15766// Return a new SCEV that modifies \p Expr to the closest number divides by
15767// \p Divisor and less or equal than Expr. For now, only handle constant
15768// Expr.
15769static const SCEV *getPreviousSCEVDivisibleByDivisor(const SCEV *Expr,
15770 const APInt &DivisorVal,
15771 ScalarEvolution &SE) {
15772 const APInt *ExprVal;
15773 if (!match(S: Expr, P: m_scev_APInt(C&: ExprVal)) || ExprVal->isNegative() ||
15774 DivisorVal.isNonPositive())
15775 return Expr;
15776 APInt Rem = ExprVal->urem(RHS: DivisorVal);
15777 // return the SCEV: Expr - Expr % Divisor
15778 return SE.getConstant(Val: *ExprVal - Rem);
15779}
15780
15781// Return a new SCEV that modifies \p Expr to the closest number divides by
15782// \p Divisor and greater or equal than Expr. For now, only handle constant
15783// Expr.
15784static const SCEV *getNextSCEVDivisibleByDivisor(const SCEV *Expr,
15785 const APInt &DivisorVal,
15786 ScalarEvolution &SE) {
15787 const APInt *ExprVal;
15788 if (!match(S: Expr, P: m_scev_APInt(C&: ExprVal)) || ExprVal->isNegative() ||
15789 DivisorVal.isNonPositive())
15790 return Expr;
15791 APInt Rem = ExprVal->urem(RHS: DivisorVal);
15792 if (Rem.isZero())
15793 return Expr;
15794 // return the SCEV: Expr + Divisor - Expr % Divisor
15795 return SE.getConstant(Val: *ExprVal + DivisorVal - Rem);
15796}
15797
15798static bool collectDivisibilityInformation(
15799 ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS,
15800 DenseMap<const SCEV *, const SCEV *> &DivInfo,
15801 DenseMap<const SCEV *, APInt> &Multiples, ScalarEvolution &SE) {
15802 // If we have LHS == 0, check if LHS is computing a property of some unknown
15803 // SCEV %v which we can rewrite %v to express explicitly.
15804 if (Predicate != CmpInst::ICMP_EQ || !match(S: RHS, P: m_scev_Zero()))
15805 return false;
15806 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15807 // explicitly express that.
15808 const SCEVUnknown *URemLHS = nullptr;
15809 const SCEV *URemRHS = nullptr;
15810 if (!match(S: LHS, P: m_scev_URem(LHS: m_SCEVUnknown(V&: URemLHS), RHS: m_SCEV(V&: URemRHS), SE)))
15811 return false;
15812
15813 const SCEV *Multiple =
15814 SE.getMulExpr(LHS: SE.getUDivExpr(LHS: URemLHS, RHS: URemRHS), RHS: URemRHS);
15815 DivInfo[URemLHS] = Multiple;
15816 if (auto *C = dyn_cast<SCEVConstant>(Val: URemRHS))
15817 Multiples[URemLHS] = C->getAPInt();
15818 return true;
15819}
15820
15821// Check if the condition is a divisibility guard (A % B == 0).
15822static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS,
15823 ScalarEvolution &SE) {
15824 const SCEV *X, *Y;
15825 return match(S: LHS, P: m_scev_URem(LHS: m_SCEV(V&: X), RHS: m_SCEV(V&: Y), SE)) && RHS->isZero();
15826}
15827
15828// Apply divisibility by \p Divisor on MinMaxExpr with constant values,
15829// recursively. This is done by aligning up/down the constant value to the
15830// Divisor.
15831static const SCEV *applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr,
15832 APInt Divisor,
15833 ScalarEvolution &SE) {
15834 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
15835 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
15836 // the non-constant operand and in \p LHS the constant operand.
15837 auto IsMinMaxSCEVWithNonNegativeConstant =
15838 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
15839 const SCEV *&RHS) {
15840 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Val: Expr)) {
15841 if (MinMax->getNumOperands() != 2)
15842 return false;
15843 if (auto *C = dyn_cast<SCEVConstant>(Val: MinMax->getOperand(i: 0))) {
15844 if (C->getAPInt().isNegative())
15845 return false;
15846 SCTy = MinMax->getSCEVType();
15847 LHS = MinMax->getOperand(i: 0);
15848 RHS = MinMax->getOperand(i: 1);
15849 return true;
15850 }
15851 }
15852 return false;
15853 };
15854
15855 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15856 SCEVTypes SCTy;
15857 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15858 MinMaxRHS))
15859 return MinMaxExpr;
15860 auto IsMin = isa<SCEVSMinExpr>(Val: MinMaxExpr) || isa<SCEVUMinExpr>(Val: MinMaxExpr);
15861 assert(SE.isKnownNonNegative(MinMaxLHS) && "Expected non-negative operand!");
15862 auto *DivisibleExpr =
15863 IsMin ? getPreviousSCEVDivisibleByDivisor(Expr: MinMaxLHS, DivisorVal: Divisor, SE)
15864 : getNextSCEVDivisibleByDivisor(Expr: MinMaxLHS, DivisorVal: Divisor, SE);
15865 SmallVector<SCEVUse> Ops = {
15866 applyDivisibilityOnMinMaxExpr(MinMaxExpr: MinMaxRHS, Divisor, SE), DivisibleExpr};
15867 return SE.getMinMaxExpr(Kind: SCTy, Ops);
15868}
15869
15870void ScalarEvolution::LoopGuards::collectFromBlock(
15871 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
15872 const BasicBlock *Block, const BasicBlock *Pred,
15873 SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks, unsigned Depth) {
15874
15875 assert(SE.DT.isReachableFromEntry(Block) && SE.DT.isReachableFromEntry(Pred));
15876
15877 SmallVector<SCEVUse> ExprsToRewrite;
15878 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
15879 const SCEV *RHS,
15880 DenseMap<const SCEV *, const SCEV *> &RewriteMap,
15881 const LoopGuards &DivGuards) {
15882 // WARNING: It is generally unsound to apply any wrap flags to the proposed
15883 // replacement SCEV which isn't directly implied by the structure of that
15884 // SCEV. In particular, using contextual facts to imply flags is *NOT*
15885 // legal. See the scoping rules for flags in the header to understand why.
15886
15887 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15888 // and \p FromRewritten are the same (i.e. there has been no rewrite
15889 // registered for \p From), then puts this value in the list of rewritten
15890 // expressions.
15891 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15892 const SCEV *To) {
15893 if (From == FromRewritten)
15894 ExprsToRewrite.push_back(Elt: From);
15895 RewriteMap[From] = To;
15896 };
15897
15898 // Checks whether \p S has already been rewritten. In that case returns the
15899 // existing rewrite because we want to chain further rewrites onto the
15900 // already rewritten value. Otherwise returns \p S.
15901 auto GetMaybeRewritten = [&](const SCEV *S) {
15902 return RewriteMap.lookup_or(Val: S, Default&: S);
15903 };
15904
15905 // Check for a condition of the form (-C1 + X < C2). InstCombine will
15906 // create this form when combining two checks of the form (X u< C2 + C1) and
15907 // (X >=u C1).
15908 auto MatchRangeCheckIdiom = [&](ICmpInst::Predicate Pred,
15909 const SCEV *MatchLHS,
15910 const SCEV *MatchRHS) {
15911 const SCEVConstant *C1;
15912 const SCEVUnknown *LHSUnknown;
15913 auto *C2 = dyn_cast<SCEVConstant>(Val: MatchRHS);
15914 if (!match(S: MatchLHS,
15915 P: m_scev_Add(Op0: m_SCEVConstant(V&: C1), Op1: m_SCEVUnknown(V&: LHSUnknown))) ||
15916 !C2)
15917 return false;
15918
15919 auto ExactRegion =
15920 ConstantRange::makeExactICmpRegion(Pred, Other: C2->getAPInt())
15921 .sub(Other: C1->getAPInt());
15922
15923 // Tighten the raw range with what we already know about LHSUnknown
15924 // from prior guards recorded in RewriteMap, or from SCEV's own range
15925 // analysis.
15926 const SCEV *RewrittenLHS = GetMaybeRewritten(LHSUnknown);
15927 ExactRegion = ExactRegion.intersectWith(CR: SE.getUnsignedRange(S: RewrittenLHS),
15928 Type: ConstantRange::Unsigned);
15929
15930 // Bail if the guard is inconsistent with prior facts, or if the range
15931 // is still not a monotonic non-wrapping interval after tightening.
15932 if (ExactRegion.isEmptySet() || ExactRegion.isWrappedSet() ||
15933 ExactRegion.isFullSet())
15934 return false;
15935
15936 const SCEV *RegionMin = SE.getConstant(Val: ExactRegion.getUnsignedMin());
15937 const SCEV *RegionMax = SE.getConstant(Val: ExactRegion.getUnsignedMax());
15938 const SCEV *ClampedLHS =
15939 SE.getUMaxExpr(LHS: RegionMin, RHS: SE.getUMinExpr(LHS: RewrittenLHS, RHS: RegionMax));
15940 AddRewrite(LHSUnknown, RewrittenLHS, ClampedLHS);
15941 return true;
15942 };
15943 if (MatchRangeCheckIdiom(Predicate, LHS, RHS))
15944 return;
15945
15946 // Do not apply information for constants or if RHS contains an AddRec.
15947 if (isa<SCEVConstant>(Val: LHS) || SE.containsAddRecurrence(S: RHS))
15948 return;
15949
15950 // If RHS is SCEVUnknown, make sure the information is applied to it.
15951 if (!isa<SCEVUnknown>(Val: LHS) && isa<SCEVUnknown>(Val: RHS)) {
15952 std::swap(a&: LHS, b&: RHS);
15953 Predicate = CmpInst::getSwappedPredicate(pred: Predicate);
15954 }
15955
15956 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
15957 // Apply divisibility information when computing the constant multiple.
15958 const APInt &DividesBy =
15959 SE.getConstantMultiple(S: DivGuards.rewrite(Expr: RewrittenLHS));
15960
15961 // Collect rewrites for LHS and its transitive operands based on the
15962 // condition.
15963 // For min/max expressions, also apply the guard to its operands:
15964 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
15965 // 'min(a, b) > c' -> '(a > c) and (b > c)',
15966 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
15967 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
15968
15969 // We cannot express strict predicates in SCEV, so instead we replace them
15970 // with non-strict ones against plus or minus one of RHS depending on the
15971 // predicate.
15972 const SCEV *One = SE.getOne(Ty: RHS->getType());
15973 switch (Predicate) {
15974 case CmpInst::ICMP_ULT:
15975 if (RHS->getType()->isPointerTy())
15976 return;
15977 RHS = SE.getUMaxExpr(LHS: RHS, RHS: One);
15978 [[fallthrough]];
15979 case CmpInst::ICMP_SLT: {
15980 RHS = SE.getMinusSCEV(LHS: RHS, RHS: One);
15981 RHS = getPreviousSCEVDivisibleByDivisor(Expr: RHS, DivisorVal: DividesBy, SE);
15982 break;
15983 }
15984 case CmpInst::ICMP_UGT:
15985 case CmpInst::ICMP_SGT:
15986 RHS = SE.getAddExpr(LHS: RHS, RHS: One);
15987 RHS = getNextSCEVDivisibleByDivisor(Expr: RHS, DivisorVal: DividesBy, SE);
15988 break;
15989 case CmpInst::ICMP_ULE:
15990 case CmpInst::ICMP_SLE:
15991 RHS = getPreviousSCEVDivisibleByDivisor(Expr: RHS, DivisorVal: DividesBy, SE);
15992 break;
15993 case CmpInst::ICMP_UGE:
15994 case CmpInst::ICMP_SGE:
15995 RHS = getNextSCEVDivisibleByDivisor(Expr: RHS, DivisorVal: DividesBy, SE);
15996 break;
15997 default:
15998 break;
15999 }
16000
16001 SmallVector<SCEVUse, 16> Worklist(1, LHS);
16002 SmallPtrSet<const SCEV *, 16> Visited;
16003
16004 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
16005 append_range(C&: Worklist, R: S->operands());
16006 };
16007
16008 while (!Worklist.empty()) {
16009 const SCEV *From = Worklist.pop_back_val();
16010 if (isa<SCEVConstant>(Val: From))
16011 continue;
16012 if (!Visited.insert(Ptr: From).second)
16013 continue;
16014 const SCEV *FromRewritten = GetMaybeRewritten(From);
16015 const SCEV *To = nullptr;
16016
16017 switch (Predicate) {
16018 case CmpInst::ICMP_ULT:
16019 case CmpInst::ICMP_ULE:
16020 To = SE.getUMinExpr(LHS: FromRewritten, RHS);
16021 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(Val: FromRewritten))
16022 EnqueueOperands(UMax);
16023 break;
16024 case CmpInst::ICMP_SLT:
16025 case CmpInst::ICMP_SLE:
16026 To = SE.getSMinExpr(LHS: FromRewritten, RHS);
16027 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(Val: FromRewritten))
16028 EnqueueOperands(SMax);
16029 break;
16030 case CmpInst::ICMP_UGT:
16031 case CmpInst::ICMP_UGE:
16032 To = SE.getUMaxExpr(LHS: FromRewritten, RHS);
16033 if (auto *UMin = dyn_cast<SCEVUMinExpr>(Val: FromRewritten))
16034 EnqueueOperands(UMin);
16035 break;
16036 case CmpInst::ICMP_SGT:
16037 case CmpInst::ICMP_SGE:
16038 To = SE.getSMaxExpr(LHS: FromRewritten, RHS);
16039 if (auto *SMin = dyn_cast<SCEVSMinExpr>(Val: FromRewritten))
16040 EnqueueOperands(SMin);
16041 break;
16042 case CmpInst::ICMP_EQ:
16043 if (isa<SCEVConstant>(Val: RHS))
16044 To = RHS;
16045 break;
16046 case CmpInst::ICMP_NE:
16047 if (match(S: RHS, P: m_scev_Zero())) {
16048 const SCEV *OneAlignedUp =
16049 getNextSCEVDivisibleByDivisor(Expr: One, DivisorVal: DividesBy, SE);
16050 To = SE.getUMaxExpr(LHS: FromRewritten, RHS: OneAlignedUp);
16051 } else {
16052 // LHS != RHS can be rewritten as (LHS - RHS) = UMax(1, LHS - RHS),
16053 // but creating the subtraction eagerly is expensive. Track the
16054 // inequalities in a separate map, and materialize the rewrite lazily
16055 // when encountering a suitable subtraction while re-writing.
16056 if (LHS->getType()->isPointerTy()) {
16057 LHS = SE.getPtrToAddrExpr(Op: LHS);
16058 RHS = SE.getPtrToAddrExpr(Op: RHS);
16059 if (isa<SCEVCouldNotCompute>(Val: LHS) || isa<SCEVCouldNotCompute>(Val: RHS))
16060 break;
16061 }
16062 const SCEVConstant *C;
16063 const SCEV *A, *B;
16064 if (match(S: RHS, P: m_scev_Add(Op0: m_SCEVConstant(V&: C), Op1: m_SCEV(V&: A))) &&
16065 match(S: LHS, P: m_scev_Add(Op0: m_scev_Specific(S: C), Op1: m_SCEV(V&: B)))) {
16066 RHS = A;
16067 LHS = B;
16068 }
16069 if (LHS > RHS)
16070 std::swap(a&: LHS, b&: RHS);
16071 Guards.NotEqual.insert(V: {LHS, RHS});
16072 continue;
16073 }
16074 break;
16075 default:
16076 break;
16077 }
16078
16079 if (To)
16080 AddRewrite(From, FromRewritten, To);
16081 }
16082 };
16083
16084 SmallVector<PointerIntPair<Value *, 1, bool>> Terms;
16085 // First, collect information from assumptions dominating the loop.
16086 for (auto &AssumeVH : SE.AC.assumptions()) {
16087 if (!AssumeVH)
16088 continue;
16089 auto *AssumeI = cast<CallInst>(Val&: AssumeVH);
16090 if (!SE.DT.dominates(Def: AssumeI, BB: Block))
16091 continue;
16092 Terms.emplace_back(Args: AssumeI->getOperand(i_nocapture: 0), Args: true);
16093 }
16094
16095 // Second, collect information from llvm.experimental.guards dominating the loop.
16096 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
16097 M: SE.F.getParent(), id: Intrinsic::experimental_guard);
16098 if (GuardDecl)
16099 for (const auto *GU : GuardDecl->users())
16100 if (const auto *Guard = dyn_cast<IntrinsicInst>(Val: GU))
16101 if (Guard->getFunction() == Block->getParent() &&
16102 SE.DT.dominates(Def: Guard, BB: Block))
16103 Terms.emplace_back(Args: Guard->getArgOperand(i: 0), Args: true);
16104
16105 // Third, collect conditions from dominating branches. Starting at the loop
16106 // predecessor, climb up the predecessor chain, as long as there are
16107 // predecessors that can be found that have unique successors leading to the
16108 // original header.
16109 // TODO: share this logic with isLoopEntryGuardedByCond.
16110 unsigned NumCollectedConditions = 0;
16111 VisitedBlocks.insert(Ptr: Block);
16112 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred, Block);
16113 for (; Pair.first;
16114 Pair = SE.getPredecessorWithUniqueSuccessorForBB(BB: Pair.first)) {
16115 VisitedBlocks.insert(Ptr: Pair.second);
16116 const CondBrInst *LoopEntryPredicate =
16117 dyn_cast<CondBrInst>(Val: Pair.first->getTerminator());
16118 if (!LoopEntryPredicate)
16119 continue;
16120
16121 Terms.emplace_back(Args: LoopEntryPredicate->getCondition(),
16122 Args: LoopEntryPredicate->getSuccessor(i: 0) == Pair.second);
16123 NumCollectedConditions++;
16124
16125 // If we are recursively collecting guards stop after 2
16126 // conditions to limit compile-time impact for now.
16127 if (Depth > 0 && NumCollectedConditions == 2)
16128 break;
16129 }
16130 // Finally, if we stopped climbing the predecessor chain because
16131 // there wasn't a unique one to continue, try to collect conditions
16132 // for PHINodes by recursively following all of their incoming
16133 // blocks and try to merge the found conditions to build a new one
16134 // for the Phi.
16135 if (Pair.second->hasNPredecessorsOrMore(N: 2) &&
16136 Depth < MaxLoopGuardCollectionDepth) {
16137 SmallDenseMap<const BasicBlock *, LoopGuards> IncomingGuards;
16138 for (auto &Phi : Pair.second->phis())
16139 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards, Depth);
16140 }
16141
16142 // Now apply the information from the collected conditions to
16143 // Guards.RewriteMap. Conditions are processed in reverse order, so the
16144 // earliest conditions is processed first, except guards with divisibility
16145 // information, which are moved to the back. This ensures the SCEVs with the
16146 // shortest dependency chains are constructed first.
16147 SmallVector<std::tuple<CmpInst::Predicate, const SCEV *, const SCEV *>>
16148 GuardsToProcess;
16149 for (auto [Term, EnterIfTrue] : reverse(C&: Terms)) {
16150 SmallVector<Value *, 8> Worklist;
16151 SmallPtrSet<Value *, 8> Visited;
16152 Worklist.push_back(Elt: Term);
16153 while (!Worklist.empty()) {
16154 Value *Cond = Worklist.pop_back_val();
16155 if (!Visited.insert(Ptr: Cond).second)
16156 continue;
16157
16158 if (auto *Cmp = dyn_cast<ICmpInst>(Val: Cond)) {
16159 auto Predicate =
16160 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
16161 const auto *LHS = SE.getSCEV(V: Cmp->getOperand(i_nocapture: 0));
16162 const auto *RHS = SE.getSCEV(V: Cmp->getOperand(i_nocapture: 1));
16163 // If LHS is a constant, apply information to the other expression.
16164 // TODO: If LHS is not a constant, check if using CompareSCEVComplexity
16165 // can improve results.
16166 if (isa<SCEVConstant>(Val: LHS)) {
16167 std::swap(a&: LHS, b&: RHS);
16168 Predicate = CmpInst::getSwappedPredicate(pred: Predicate);
16169 }
16170 GuardsToProcess.emplace_back(Args&: Predicate, Args&: LHS, Args&: RHS);
16171 continue;
16172 }
16173
16174 Value *L, *R;
16175 if (EnterIfTrue ? match(V: Cond, P: m_LogicalAnd(L: m_Value(V&: L), R: m_Value(V&: R)))
16176 : match(V: Cond, P: m_LogicalOr(L: m_Value(V&: L), R: m_Value(V&: R)))) {
16177 Worklist.push_back(Elt: L);
16178 Worklist.push_back(Elt: R);
16179 }
16180 }
16181 }
16182
16183 // Process divisibility guards in reverse order to populate DivGuards early.
16184 DenseMap<const SCEV *, APInt> Multiples;
16185 LoopGuards DivGuards(SE);
16186 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess) {
16187 if (!isDivisibilityGuard(LHS, RHS, SE))
16188 continue;
16189 collectDivisibilityInformation(Predicate, LHS, RHS, DivInfo&: DivGuards.RewriteMap,
16190 Multiples, SE);
16191 }
16192
16193 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess)
16194 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap, DivGuards);
16195
16196 // Apply divisibility information last. This ensures it is applied to the
16197 // outermost expression after other rewrites for the given value.
16198 for (const auto &[K, Divisor] : Multiples) {
16199 const SCEV *DivisorSCEV = SE.getConstant(Val: Divisor);
16200 Guards.RewriteMap[K] =
16201 SE.getMulExpr(LHS: SE.getUDivExpr(LHS: applyDivisibilityOnMinMaxExpr(
16202 MinMaxExpr: Guards.rewrite(Expr: K), Divisor, SE),
16203 RHS: DivisorSCEV),
16204 RHS: DivisorSCEV);
16205 ExprsToRewrite.push_back(Elt: K);
16206 }
16207
16208 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
16209 // the replacement expressions are contained in the ranges of the replaced
16210 // expressions.
16211 Guards.PreserveNUW = true;
16212 Guards.PreserveNSW = true;
16213 for (const SCEV *Expr : ExprsToRewrite) {
16214 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16215 Guards.PreserveNUW &=
16216 SE.getUnsignedRange(S: Expr).contains(CR: SE.getUnsignedRange(S: RewriteTo));
16217 Guards.PreserveNSW &=
16218 SE.getSignedRange(S: Expr).contains(CR: SE.getSignedRange(S: RewriteTo));
16219 }
16220
16221 // Now that all rewrite information is collect, rewrite the collected
16222 // expressions with the information in the map. This applies information to
16223 // sub-expressions.
16224 if (ExprsToRewrite.size() > 1) {
16225 for (const SCEV *Expr : ExprsToRewrite) {
16226 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16227 Guards.RewriteMap.erase(Val: Expr);
16228 Guards.RewriteMap.insert(KV: {Expr, Guards.rewrite(Expr: RewriteTo)});
16229 }
16230 }
16231}
16232
16233const SCEV *ScalarEvolution::LoopGuards::rewrite(const SCEV *Expr) const {
16234 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
16235 /// in the map. It skips AddRecExpr because we cannot guarantee that the
16236 /// replacement is loop invariant in the loop of the AddRec.
16237 class SCEVLoopGuardRewriter
16238 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
16239 const DenseMap<const SCEV *, const SCEV *> &Map;
16240 const SmallDenseSet<std::pair<const SCEV *, const SCEV *>> &NotEqual;
16241
16242 SCEVFlags FlagMask = SCEV::FlagNone;
16243
16244 public:
16245 SCEVLoopGuardRewriter(ScalarEvolution &SE,
16246 const ScalarEvolution::LoopGuards &Guards)
16247 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap),
16248 NotEqual(Guards.NotEqual) {
16249 if (Guards.PreserveNUW)
16250 FlagMask = ScalarEvolution::setFlags(Flags: FlagMask, OnFlags: SCEV::FlagNUW);
16251 if (Guards.PreserveNSW)
16252 FlagMask = ScalarEvolution::setFlags(Flags: FlagMask, OnFlags: SCEV::FlagNSW);
16253 }
16254
16255 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
16256
16257 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
16258 return Map.lookup_or(Val: Expr, Default&: Expr);
16259 }
16260
16261 const SCEV *visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr) {
16262 if (const SCEV *S = Map.lookup(Val: Expr))
16263 return S;
16264 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitPtrToAddrExpr(
16265 Expr);
16266 }
16267
16268 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
16269 if (const SCEV *S = Map.lookup(Val: Expr))
16270 return S;
16271
16272 // If we didn't find the extact ZExt expr in the map, check if there's
16273 // an entry for a smaller ZExt we can use instead.
16274 Type *Ty = Expr->getType();
16275 const SCEV *Op = Expr->getOperand(i: 0);
16276 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
16277 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
16278 Bitwidth > Op->getType()->getScalarSizeInBits()) {
16279 Type *NarrowTy = IntegerType::get(C&: SE.getContext(), NumBits: Bitwidth);
16280 auto *NarrowExt = SE.getZeroExtendExpr(Op, Ty: NarrowTy);
16281 if (const SCEV *S = Map.lookup(Val: NarrowExt))
16282 return SE.getZeroExtendExpr(Op: S, Ty);
16283 Bitwidth = Bitwidth / 2;
16284 }
16285
16286 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr(
16287 Expr);
16288 }
16289
16290 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
16291 if (const SCEV *S = Map.lookup(Val: Expr))
16292 return S;
16293 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitSignExtendExpr(
16294 Expr);
16295 }
16296
16297 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
16298 if (const SCEV *S = Map.lookup(Val: Expr))
16299 return S;
16300 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitUMinExpr(Expr);
16301 }
16302
16303 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
16304 if (const SCEV *S = Map.lookup(Val: Expr))
16305 return S;
16306 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitSMinExpr(Expr);
16307 }
16308
16309 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
16310 if (const SCEV *S = Map.lookup(Val: Expr))
16311 return S;
16312
16313 // Helper to check if S is a subtraction (A - B) where A != B, and if so,
16314 // return UMax(S, 1).
16315 auto RewriteSubtraction = [&](const SCEV *S) -> const SCEV * {
16316 SCEVUse LHS, RHS;
16317 if (MatchBinarySub(S, LHS, RHS)) {
16318 if (LHS > RHS)
16319 std::swap(a&: LHS, b&: RHS);
16320 if (NotEqual.contains(V: {LHS, RHS})) {
16321 const SCEV *OneAlignedUp = getNextSCEVDivisibleByDivisor(
16322 Expr: SE.getOne(Ty: S->getType()), DivisorVal: SE.getConstantMultiple(S), SE);
16323 return SE.getUMaxExpr(LHS: OneAlignedUp, RHS: S);
16324 }
16325 }
16326 return nullptr;
16327 };
16328
16329 // Check if Expr itself is a subtraction pattern with guard info.
16330 if (const SCEV *Rewritten = RewriteSubtraction(Expr))
16331 return Rewritten;
16332
16333 // Trip count expressions sometimes consist of adding 3 operands, i.e.
16334 // (Const + A + B). There may be guard info for A + B, and if so, apply
16335 // it.
16336 // TODO: Could more generally apply guards to Add sub-expressions.
16337 if (isa<SCEVConstant>(Val: Expr->getOperand(i: 0))) {
16338 if (Expr->getNumOperands() == 3) {
16339 const SCEV *Add =
16340 SE.getAddExpr(LHS: Expr->getOperand(i: 1), RHS: Expr->getOperand(i: 2));
16341 if (const SCEV *Rewritten = RewriteSubtraction(Add))
16342 return SE.getAddExpr(
16343 LHS: Expr->getOperand(i: 0), RHS: Rewritten,
16344 Flags: ScalarEvolution::maskFlags(Flags: Expr->getNoWrapFlags(), Mask: FlagMask));
16345 if (const SCEV *S = Map.lookup(Val: Add))
16346 return SE.getAddExpr(LHS: Expr->getOperand(i: 0), RHS: S);
16347 }
16348
16349 // For expressions of the form (Const + A), check if we have guard info
16350 // for (Const + 1 + A), and rewrite to ((Const + 1 + A) - 1). This makes
16351 // sure we don't lose information when rewriting expressions based on
16352 // back-edge taken counts in some cases.
16353 if (Expr->getNumOperands() == 2) {
16354 const SCEV *S = nullptr;
16355 // Handle (-1 + 1 + A) without constructing SCEVs.
16356 if (match(U: Expr->getOperand(i: 0), P: m_scev_AllOnes())) {
16357 S = Map.lookup(Val: Expr->getOperand(i: 1));
16358 } else {
16359 const SCEV *NewC =
16360 SE.getAddExpr(LHS: Expr->getOperand(i: 0), RHS: SE.getOne(Ty: Expr->getType()));
16361 S = Map.lookup(Val: SE.getAddExpr(LHS: NewC, RHS: Expr->getOperand(i: 1)));
16362 }
16363 if (S)
16364 return SE.getAddExpr(LHS: S, RHS: SE.getMinusOne(Ty: Expr->getType()));
16365 }
16366 }
16367 SmallVector<SCEVUse, 2> Operands;
16368 bool Changed = false;
16369 for (SCEVUse Op : Expr->operands()) {
16370 Operands.push_back(
16371 Elt: SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visit(S: Op));
16372 Changed |= Op != Operands.back();
16373 }
16374 // We are only replacing operands with equivalent values, so transfer the
16375 // flags from the original expression.
16376 return !Changed ? Expr
16377 : SE.getAddExpr(Ops&: Operands,
16378 Flags: ScalarEvolution::maskFlags(
16379 Flags: Expr->getNoWrapFlags(), Mask: FlagMask));
16380 }
16381
16382 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
16383 SmallVector<SCEVUse, 2> Operands;
16384 bool Changed = false;
16385 for (SCEVUse Op : Expr->operands()) {
16386 Operands.push_back(
16387 Elt: SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visit(S: Op));
16388 Changed |= Op != Operands.back();
16389 }
16390 // We are only replacing operands with equivalent values, so transfer the
16391 // flags from the original expression.
16392 return !Changed ? Expr
16393 : SE.getMulExpr(Ops&: Operands,
16394 Flags: ScalarEvolution::maskFlags(
16395 Flags: Expr->getNoWrapFlags(), Mask: FlagMask));
16396 }
16397 };
16398
16399 if (RewriteMap.empty() && NotEqual.empty())
16400 return Expr;
16401
16402 SCEVLoopGuardRewriter Rewriter(SE, *this);
16403 return Rewriter.visit(S: Expr);
16404}
16405
16406const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
16407 LoopGuards Guards = LoopGuards::collectOnDemand(L, SE&: *this);
16408 return applyLoopGuards(Expr, Guards);
16409}
16410
16411const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr,
16412 LoopGuards &Guards) {
16413 // Loop guards never rewrite constants and AddRecs, so there is no need to
16414 // collect pending guards for them.
16415 if (isa<SCEVConstant, SCEVAddRecExpr>(Val: Expr))
16416 return Expr;
16417 if (Guards.PendingLoop)
16418 Guards.collectPending();
16419 return Guards.rewrite(Expr);
16420}
16421